|
| 1 | +package fileutils |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | +) |
| 7 | + |
| 8 | +// MkdirAllNewAs creates a directory (include any along the path) and then modifies |
| 9 | +// ownership ONLY of newly created directories to the requested uid/gid. If the |
| 10 | +// directories along the path exist, no change of ownership will be performed |
| 11 | +func MkdirAllNewAs(path string, mode os.FileMode, ownerUID, ownerGID int) error { |
| 12 | + // make an array containing the original path asked for, plus (for mkAll == true) |
| 13 | + // all path components leading up to the complete path that don't exist before we MkdirAll |
| 14 | + // so that we can chown all of them properly at the end. If chownExisting is false, we won't |
| 15 | + // chown the full directory path if it exists |
| 16 | + var paths []string |
| 17 | + if _, err := os.Stat(path); err != nil && os.IsNotExist(err) { |
| 18 | + paths = []string{path} |
| 19 | + } else if err == nil { |
| 20 | + // nothing to do; directory path fully exists already |
| 21 | + return nil |
| 22 | + } |
| 23 | + |
| 24 | + // walk back to "/" looking for directories which do not exist |
| 25 | + // and add them to the paths array for chown after creation |
| 26 | + dirPath := path |
| 27 | + for { |
| 28 | + dirPath = filepath.Dir(dirPath) |
| 29 | + if dirPath == "/" { |
| 30 | + break |
| 31 | + } |
| 32 | + if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) { |
| 33 | + paths = append(paths, dirPath) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if err := os.MkdirAll(path, mode); err != nil && !os.IsExist(err) { |
| 38 | + return err |
| 39 | + } |
| 40 | + |
| 41 | + // even if it existed, we will chown the requested path + any subpaths that |
| 42 | + // didn't exist when we called MkdirAll |
| 43 | + for _, pathComponent := range paths { |
| 44 | + if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + } |
| 48 | + return nil |
| 49 | +} |
0 commit comments