Skip to content

Commit

Permalink
Merge pull request #841 from hairyhenderson/chmod-out-first
Browse files Browse the repository at this point in the history
Apply --chmod before opening output file
  • Loading branch information
Dave Henderson authored and GitHub committed May 14, 2020
2 parents 4afac25 + 13c6ad1 commit 892e280
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
18 changes: 18 additions & 0 deletions internal/tests/integration/basic_nonwindows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,21 @@ func (s *BasicSuite) TestOverridesOutputModeWithChmod(c *C) {
assert.Equal(c, v.content, string(content))
}
}

func (s *BasicSuite) TestAppliesChmodBeforeWrite(c *C) {
// 'broken' was created with mode 0000
out := s.tmpDir.Join("broken")
result := icmd.RunCmd(icmd.Command(GomplateBin,
"-f", s.tmpDir.Join("one"),
"-o", out,
"--chmod", "0644"), func(cmd *icmd.Cmd) {
})
result.Assert(c, icmd.Success)

info, err := os.Stat(out)
assert.NilError(c, err)
assert.Equal(c, os.FileMode(0644), info.Mode())
content, err := ioutil.ReadFile(out)
assert.NilError(c, err)
assert.Equal(c, "hi\n", string(content))
}
3 changes: 2 additions & 1 deletion internal/tests/integration/basic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ var _ = Suite(&BasicSuite{})
func (s *BasicSuite) SetUpTest(c *C) {
s.tmpDir = fs.NewDir(c, "gomplate-inttests",
fs.WithFile("one", "hi\n", fs.WithMode(0640)),
fs.WithFile("two", "hello\n"))
fs.WithFile("two", "hello\n"),
fs.WithFile("broken", "", fs.WithMode(0000)))
}

func (s *BasicSuite) TearDownTest(c *C) {
Expand Down
9 changes: 6 additions & 3 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,16 @@ func openOutFile(cfg *config.Config, filename string, mode os.FileMode, modeOver
}

func createOutFile(filename string, mode os.FileMode, modeOverride bool) (out io.WriteCloser, err error) {
if modeOverride {
err = fs.Chmod(filename, mode.Perm())
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to chmod output file '%s' with mode %q: %w", filename, mode.Perm(), err)
}
}
out, err = fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode.Perm())
if err != nil {
return out, err
}
if modeOverride {
err = fs.Chmod(filename, mode.Perm())
}
return out, err
}

Expand Down

0 comments on commit 892e280

Please sign in to comment.