-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
…335) Splitted out of #328. --- By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. Signed-off-by: Burak Varlı <[email protected]>
- Loading branch information
Showing
3 changed files
with
43 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package util | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"io/fs" | ||
"os" | ||
) | ||
|
||
// ReplaceFile safely replaces a file with a new file by copying to a temporary location first | ||
// then renaming. | ||
func ReplaceFile(destPath string, sourcePath string, perm fs.FileMode) error { | ||
tmpDest := destPath + ".tmp" | ||
|
||
sourceFile, err := os.Open(sourcePath) | ||
if err != nil { | ||
return err | ||
} | ||
defer sourceFile.Close() | ||
|
||
destFile, err := os.OpenFile(tmpDest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) | ||
if err != nil { | ||
return err | ||
} | ||
defer destFile.Close() | ||
|
||
buf := make([]byte, 64*1024) | ||
_, err = io.CopyBuffer(destFile, sourceFile, buf) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
err = os.Rename(tmpDest, destPath) | ||
if err != nil { | ||
return fmt.Errorf("Failed to rename file %s: %w", destPath, err) | ||
} | ||
|
||
return nil | ||
} |