Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preserve file permission when writing formatted files #1636

Merged
merged 1 commit into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,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 @@ -113,5 +117,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
Loading