Skip to content

Commit

Permalink
fix: remove temp file rename
Browse files Browse the repository at this point in the history
Signed-off-by: mrjoelkamp <joel.kamp@docker.com>
  • Loading branch information
mrjoelkamp committed Jun 11, 2024
1 parent 626088b commit 1a40475
Showing 1 changed file with 4 additions and 54 deletions.
58 changes: 4 additions & 54 deletions metadata/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,38 +579,6 @@ func (update *Updater) preOrderDepthFirstWalk(targetFilePath string) (*metadata.
return nil, fmt.Errorf("target %s not found", targetFilePath)
}

func moveFile(source, destination string) (err error) {
// can only safely rename on any OS if source and destination are in the same directory
if filepath.Dir(source) == filepath.Dir(destination) {
return os.Rename(source, destination)
}

inputFile, err := os.Open(source)
if err != nil {
return fmt.Errorf("couldn't open source file: %s", err)
}
defer inputFile.Close()
outputFile, err := os.Create(destination)
if err != nil {
return fmt.Errorf("couldn't open dest file: %s", err)
}
defer outputFile.Close()
c, err := io.Copy(outputFile, inputFile)
if err != nil {
return fmt.Errorf("writing to output file failed: %s", err)
}
if c <= 0 {
return fmt.Errorf("nothing copied to output file")
}
inputFile.Close()
// The copy was successful, so now delete the original file
err = os.Remove(source)
if err != nil {
return fmt.Errorf("failed removing original file: %s", err)
}
return nil
}

// persistMetadata writes metadata to disk atomically to avoid data loss
func (update *Updater) persistMetadata(roleName string, data []byte) error {
log := metadata.GetLogger()
Expand All @@ -620,34 +588,16 @@ func (update *Updater) persistMetadata(roleName string, data []byte) error {
}
// caching enabled, proceed with persisting the metadata locally
fileName := filepath.Join(update.cfg.LocalMetadataDir, fmt.Sprintf("%s.json", url.QueryEscape(roleName)))
cwd, err := os.Getwd()
if err != nil {
return err
}
// create a temporary file
file, err := os.CreateTemp(cwd, "tuf_tmp")
if err != nil {
return err
}
defer file.Close()
// write the data content to the temporary file
err = os.WriteFile(file.Name(), data, 0644)
err := os.WriteFile(fileName, data, 0644)
if err != nil {
// delete the temporary file if there was an error while writing
errRemove := os.Remove(file.Name())
// delete the file if there was an error while writing
errRemove := os.Remove(fileName)
if errRemove != nil {
log.Info("Failed to delete temporary file", "name", file.Name())
log.Info("Failed to delete file", "name", fileName)
}
return err
}

// can't move/rename an open file on windows, so close it first
file.Close()
// if all okay, rename the temporary file to the desired one
err = moveFile(file.Name(), fileName)
if err != nil {
return err
}
read, err := os.ReadFile(fileName)
if err != nil {
return err
Expand Down

0 comments on commit 1a40475

Please sign in to comment.