idtools_unix.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // +build !windows
  2. package idtools
  3. import (
  4. "os"
  5. "path/filepath"
  6. "github.com/docker/docker/pkg/system"
  7. )
  8. func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error {
  9. // make an array containing the original path asked for, plus (for mkAll == true)
  10. // all path components leading up to the complete path that don't exist before we MkdirAll
  11. // so that we can chown all of them properly at the end. If chownExisting is false, we won't
  12. // chown the full directory path if it exists
  13. var paths []string
  14. if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
  15. paths = []string{path}
  16. } else if err == nil && chownExisting {
  17. if err := os.Chown(path, ownerUID, ownerGID); err != nil {
  18. return err
  19. }
  20. // short-circuit--we were called with an existing directory and chown was requested
  21. return nil
  22. } else if err == nil {
  23. // nothing to do; directory path fully exists already and chown was NOT requested
  24. return nil
  25. }
  26. if mkAll {
  27. // walk back to "/" looking for directories which do not exist
  28. // and add them to the paths array for chown after creation
  29. dirPath := path
  30. for {
  31. dirPath = filepath.Dir(dirPath)
  32. if dirPath == "/" {
  33. break
  34. }
  35. if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
  36. paths = append(paths, dirPath)
  37. }
  38. }
  39. if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) {
  40. return err
  41. }
  42. } else {
  43. if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
  44. return err
  45. }
  46. }
  47. // even if it existed, we will chown the requested path + any subpaths that
  48. // didn't exist when we called MkdirAll
  49. for _, pathComponent := range paths {
  50. if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil {
  51. return err
  52. }
  53. }
  54. return nil
  55. }