Skip to content

Commit

Permalink
Handle independently setting UID/GID to default
Browse files Browse the repository at this point in the history
  • Loading branch information
mbillow committed Mar 7, 2022
1 parent 6a9dbb4 commit c647b7b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
21 changes: 18 additions & 3 deletions template/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -1670,9 +1670,16 @@ func writeToFile(path, username, groupName, permissions string, args ...string)
}

// Change ownership and permissions
if username != "" || groupName != "" {
uid := 0
gid := 0
var uid int
var gid int
cu, err := user.Current()
if err != nil {
return "", err
}

if username == "" {
uid, _ = strconv.Atoi(cu.Uid)
} else {
var convErr error
u, err := user.Lookup(username)
if err != nil {
Expand All @@ -1684,7 +1691,12 @@ func writeToFile(path, username, groupName, permissions string, args ...string)
} else {
uid, _ = strconv.Atoi(u.Uid)
}
}

if groupName == "" {
gid, _ = strconv.Atoi(cu.Gid)
} else {
var convErr error
g, err := user.LookupGroup(groupName)
if err != nil {
gid, convErr = strconv.Atoi(groupName)
Expand All @@ -1694,7 +1706,10 @@ func writeToFile(path, username, groupName, permissions string, args ...string)
} else {
gid, _ = strconv.Atoi(g.Gid)
}
}

// Avoid the chown call altogether if using current user and group.
if username != "" || groupName != "" {
err = os.Chown(path, uid, gid)
if err != nil {
return "", err
Expand Down
22 changes: 22 additions & 0 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2079,6 +2079,28 @@ func Test_writeToFile(t *testing.T) {
"after",
false,
},
{
"writeToFile_provide_just_gid",
"",
"after",
"",
currentUser.Gid,
"0644",
"",
"after",
false,
},
{
"writeToFile_provide_just_uid",
"",
"after",
currentUser.Uid,
"",
"0644",
"",
"after",
false,
},
{
"writeToFile_create_directory",
"demo/testing.tmp",
Expand Down

0 comments on commit c647b7b

Please sign in to comment.