From e3d1947626c288b19815a03b3079ce288b3be3e2 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Tue, 3 Oct 2023 22:44:22 -0700 Subject: [PATCH] MkdirAllNewAs,CopyDirectory: ensure dir perms Because of umask, sometimes newly created files and directories can have permission bits different than expected. An easy solution would be to call os.Chmod after creation -- this is how CopyFile already works. Now, let's do the same for directories. PS The alternative to that would be to temporary set umask to 0, but it is very problematic in Go as it affects other threads. Signed-off-by: Kir Kolyshkin --- fileutils.go | 11 +++++++---- idtools.go | 3 +++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/fileutils.go b/fileutils.go index 7421e62..81851c8 100644 --- a/fileutils.go +++ b/fileutils.go @@ -125,6 +125,7 @@ func CopyDirectory(source string, dest string) error { if err != nil { return nil } + destPath := filepath.Join(dest, relPath) if info.IsDir() { // Skip the source directory. @@ -138,18 +139,20 @@ func CopyDirectory(source string, dest string) error { uid := int(st.Uid) gid := int(st.Gid) - if err := os.Mkdir(filepath.Join(dest, relPath), info.Mode()); err != nil { + if err := os.Mkdir(destPath, info.Mode()); err != nil { return err } - - if err := os.Lchown(filepath.Join(dest, relPath), uid, gid); err != nil { + if err := os.Lchown(destPath, uid, gid); err != nil { + return err + } + if err := os.Chmod(destPath, info.Mode()); err != nil { return err } } return nil } - return CopyFile(path, filepath.Join(dest, relPath)) + return CopyFile(path, destPath) }) } diff --git a/idtools.go b/idtools.go index bad6539..0ae2dfb 100644 --- a/idtools.go +++ b/idtools.go @@ -49,6 +49,9 @@ func MkdirAllNewAs(path string, mode os.FileMode, ownerUID, ownerGID int) error if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil { return err } + if err := os.Chmod(pathComponent, mode); err != nil { + return err + } } return nil }