From 1dedcd0d376f57abae5cadd38116c1aca2821330 Mon Sep 17 00:00:00 2001 From: unclejack Date: Sat, 10 May 2014 10:58:45 +0300 Subject: [PATCH] add ValidateContextDirectory to utils/utils.go This commit adds a function which can be used to ensure all contents of a directory can be accessed. This function doesn't follow symlinks to check if they're pointing to files which exist. Such symlinks can be useful later. Docker-DCO-1.1-Signed-off-by: Cristian Staretu (github: unclejack) --- utils/utils.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/utils/utils.go b/utils/utils.go index 191c85206e..c3ae4e569d 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -1067,3 +1067,40 @@ func TreeSize(dir string) (size int64, err error) { }) return } + +// ValidateContextDirectory checks if all the contents of the directory +// can be read and returns an error if some files can't be read +// symlinks which point to non-existing files don't trigger an error +func ValidateContextDirectory(srcPath string) error { + var finalError error + + filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error { + // skip this directory/file if it's not in the path, it won't get added to the context + _, err = filepath.Rel(srcPath, filePath) + if err != nil && os.IsPermission(err) { + return nil + } + + if _, err := os.Stat(filePath); err != nil && os.IsPermission(err) { + finalError = fmt.Errorf("can't stat '%s'", filePath) + return err + } + // skip checking if symlinks point to non-existing files, such symlinks can be useful + lstat, _ := os.Lstat(filePath) + if lstat.Mode()&os.ModeSymlink == os.ModeSymlink { + return err + } + + if !f.IsDir() { + currentFile, err := os.Open(filePath) + if err != nil && os.IsPermission(err) { + finalError = fmt.Errorf("no permission to read from '%s'", filePath) + return err + } else { + currentFile.Close() + } + } + return nil + }) + return finalError +}