github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/file/backup.go (about) 1 package file 2 3 import ( 4 "os" 5 "path/filepath" 6 "strings" 7 ) 8 9 type BackupFile struct { 10 OrigFn string 11 BackupFn string 12 } 13 14 // Restore restores the original file from the backup file. 15 func (bf *BackupFile) Restore() { 16 if !FileExists(bf.BackupFn) { 17 // The caller was successful. Nothing to clean up. 18 return 19 } else { 20 // The backup remains, something went wrong, so we replace the original file. 21 _ = os.Rename(bf.BackupFn, bf.OrigFn) 22 // This may seem redundant, but it's not on some operating systems 23 _ = os.Remove(bf.BackupFn) 24 } 25 } 26 27 // Clear removes the backup file. 28 func (bf *BackupFile) Clear() { 29 if FileExists(bf.BackupFn) { 30 _ = os.Remove(bf.BackupFn) 31 } 32 } 33 34 // MakeBackup creates a backup of the original file and returns a structure that 35 // can be used to restore the original file in case of an error. 36 func MakeBackup(tmpPath, origFn string) (BackupFile, error) { 37 if !FileExists(origFn) { 38 return BackupFile{}, nil 39 } 40 41 _, name := filepath.Split(origFn) 42 pattern := strings.Replace(name, ".", ".*.", -1) 43 tmpFile, err := os.CreateTemp(tmpPath, pattern) 44 if err != nil { 45 return BackupFile{}, err 46 } 47 tmpFile.Close() 48 tmpFn := tmpFile.Name() 49 _, err = Copy(tmpFn, origFn) 50 return BackupFile{ 51 OrigFn: origFn, 52 BackupFn: tmpFn, 53 }, err 54 }