wanna-goon/recover.go

65 lines
2.3 KiB
Go

package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Merith-TK/utils/debug"
)
// restoreFiles is a duplicate function that performs the same operation as in `main.go`.
// It restores files from the `.wanna-goon` directory back to their original locations.
func restoreFiles() error {
debug.SetTitle("Restore") // Set the debug title to "Restore"
defer debug.ResetTitle() // Reset the debug title when the function exits
// Get the user's profile directory from the environment variable
userProfile := os.Getenv("USERPROFILE")
if userProfile == "" {
return fmt.Errorf("could not get USERPROFILE environment variable")
}
// Get the absolute path to the `.wanna-goon` directory
wannaGoonPath, wannaGoonErr := filepath.Abs("C:/.wanna-goon")
if wannaGoonErr != nil {
return fmt.Errorf("could not get absolute path for .wanna-goon: %v", wannaGoonErr)
}
// Walk through the `.wanna-goon` directory to restore files
err := filepath.Walk(wannaGoonPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// If the current path is a directory, recreate it in the original location
if info.IsDir() {
destPath := filepath.Join("C:/", strings.TrimPrefix(path, wannaGoonPath))
debug.Print("creating directory:", destPath)
if err := os.MkdirAll(destPath, os.ModePerm); err != nil {
return fmt.Errorf("could not create directory %s: %v", destPath, err)
}
} else {
// If the current path is a file, move it back to the original location
destPath := filepath.Join("C:/", strings.TrimPrefix(path, wannaGoonPath))
debug.Print("moving file:", path, "to:", destPath)
if err := os.Rename(path, destPath); err != nil {
return fmt.Errorf("could not move file %s to %s: %v", path, destPath, err)
}
}
return nil
})
// Handle any errors that occurred during the file restoration process
if err != nil {
return fmt.Errorf("error restoring files: %v", err)
} else {
debug.Print("files restored successfully")
// Remove the `.wanna-goon` directory after all files have been restored
if err := os.RemoveAll(wannaGoonPath); err != nil {
return fmt.Errorf("could not remove wanna-goon directory: %v", err)
}
}
return nil
}