idtools.go 1.5 KB

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