Skip to content

Commit

Permalink
feat: preserve file permission when write formatted files (#1636)
Browse files Browse the repository at this point in the history
test: add a test case to validate permission equal
  • Loading branch information
hohobilly authored Aug 9, 2023
1 parent f05ccdc commit 9f128b4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ func (f *Format) format(path string) error {
}

func write(path string, contents []byte) error {
originalFileInfo, err := os.Stat(path)
if err != nil {
return err
}
f, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path))
if err != nil {
return err
Expand All @@ -118,5 +122,8 @@ func write(path string, contents []byte) error {
if err := f.Close(); err != nil {
return err
}
if err := os.Chmod(f.Name(), originalFileInfo.Mode()); err != nil {
return err
}
return os.Rename(f.Name(), path)
}
21 changes: 21 additions & 0 deletions format/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ func TestFormat_Format(t *testing.T) {
assert.True(t, fx.isFormatted("api/api.go"))
}

func TestFormat_PermissionsPreserved(t *testing.T) {
fx := setup(t)

originalFileInfo, err := os.Stat(filepath.Join(fx.basedir, "main.go"))
if err != nil {
t.Fatal(err)
}

assert.NoError(t, New().Build(&Config{SearchDir: fx.basedir}))
assert.True(t, permissionsEqual(t, filepath.Join(fx.basedir, "main.go"), originalFileInfo.Mode()))
assert.True(t, permissionsEqual(t, filepath.Join(fx.basedir, "api/api.go"), originalFileInfo.Mode()))
}

func TestFormat_ExcludeDir(t *testing.T) {
fx := setup(t)
assert.NoError(t, New().Build(&Config{
Expand Down Expand Up @@ -96,6 +109,14 @@ func (fx *fixture) isFormatted(file string) bool {
return !bytes.Equal(testFiles[file], contents)
}

func permissionsEqual(t *testing.T, path string, expectedMode os.FileMode) bool {
fileInfo, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
return expectedMode == fileInfo.Mode()
}

var testFiles = map[string][]byte{
"api/api.go": []byte(`package api
Expand Down

0 comments on commit 9f128b4

Please sign in to comment.