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

Use os.Copy over os.Rename to avoid os restrictions #7

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
44 changes: 43 additions & 1 deletion bufisk.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ func downloadBufToFilePath(ctx context.Context, bufVersion string, bufFilePath s
if err != nil {
return fmt.Errorf("could not download buf (are you sure %q is a valid release version?): %w", bufVersion, err)
}
defer func() {
// Cleanup temp file, if it exists.
if err := os.Remove(tempFilePath); err != nil && !errors.Is(err, os.ErrNotExist) && retErr == nil {
retErr = fmt.Errorf("failed to cleanup temp file %q: %w", tempFilePath, err)
}
}()
// We could return the temporary *os.File from downloadTemp but oh well.
bufFileData, err := os.ReadFile(tempFilePath)
if err != nil {
Expand Down Expand Up @@ -271,8 +277,44 @@ func moveFileToPath(fromFilePath string, toFilePath string) error {
if err := os.MkdirAll(filepath.Dir(toFilePath), 0700); err != nil {
return err
}
// Try to use os.Rename if possible, but it doesn't work across devices.
// This will replace any other file atomically.
return os.Rename(fromFilePath, toFilePath)
if err := os.Rename(fromFilePath, toFilePath); err == nil {
return nil
}
// Otherwise, copy and remove.
if err := copyFileToPath(fromFilePath, toFilePath); err != nil {
return err
}
return os.Remove(fromFilePath)
}

func copyFileToPath(fromFilePath string, toFilePath string) (retErr error) {
if err := os.MkdirAll(filepath.Dir(toFilePath), 0700); err != nil {
return err
}
fromFile, err := os.Open(fromFilePath)
if err != nil {
return err
}
defer func() {
if err := fromFile.Close(); err != nil && retErr == nil {
retErr = err
}
}()
toFile, err := os.Create(toFilePath)
if err != nil {
return err
}
defer func() {
if err := toFile.Close(); err != nil && retErr == nil {
retErr = err
}
}()
if _, err := io.Copy(toFile, fromFile); err != nil {
return err
}
return nil
}

func getFileURL(bufVersion string, fileName string) string {
Expand Down