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

Add WithSyncDirectory to optionally fsync the directory after the rename #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,12 @@ func WithReplaceOnClose() Option {
c.renameOnClose = true
})
}

// WithSyncDirectory configures renameio to fsync the directory after renaming
// the file. If that succeeds it's guaranteed the file will be in the new state
// even after a crash.
func WithSyncDirectory() Option {
return optionFunc(func(c *config) {
c.syncDirectory = true
})
}
19 changes: 18 additions & 1 deletion tempfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ type PendingFile struct {
done bool
closed bool
replaceOnClose bool
syncDirectory bool
}

// Cleanup is a no-op if CloseAtomicallyReplace succeeded, and otherwise closes
Expand Down Expand Up @@ -167,6 +168,16 @@ func (t *PendingFile) CloseAtomicallyReplace() error {
return err
}
t.done = true
if t.syncDirectory {
dh, err := os.OpenFile(filepath.Dir(t.path), os.O_WRONLY, 0)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Linux this doesn't work. (Error: open <file>: is a directory)

Simply os.Open(filepath.Dir(t.path)) does work instead.

See also:

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good point — could you add a test so that the feature is exercised in the CI pipeline?

if err != nil {
return err
}
defer dh.Close()
if err := dh.Sync(); err != nil {
return err
}
}
return nil
}

Expand Down Expand Up @@ -200,6 +211,7 @@ type config struct {
ignoreUmask bool
chmod *os.FileMode
renameOnClose bool
syncDirectory bool
}

// NewPendingFile creates a temporary file destined to atomically creating or
Expand Down Expand Up @@ -255,7 +267,12 @@ func NewPendingFile(path string, opts ...Option) (*PendingFile, error) {
}
}

return &PendingFile{File: f, path: cfg.path, replaceOnClose: cfg.renameOnClose}, nil
return &PendingFile{
File: f,
path: cfg.path,
replaceOnClose: cfg.renameOnClose,
syncDirectory: cfg.syncDirectory,
}, nil
}

// Symlink wraps os.Symlink, replacing an existing symlink with the same name
Expand Down