Don't overwrite files unless forced

This commit is contained in:
MrLetsplay 2023-07-13 18:15:42 +00:00
parent d75e330a26
commit 8284d77d7e
Signed by: mr
SSH Key Fingerprint: SHA256:92jBH80vpXyaZHjaIl47pjRq+Yt7XGTArqQg1V7hSqg

31
main.go
View File

@ -17,6 +17,7 @@ type config struct {
Files []file Files []file
VariableRegex string VariableRegex string
RegexGroup int RegexGroup int
ForceOverwrite bool
} }
var defaultVariableRegex = `\$\{([a-zA-Z0-9_-]+)\}` var defaultVariableRegex = `\$\{([a-zA-Z0-9_-]+)\}`
@ -62,6 +63,19 @@ func filterFile(file file, regex regexp.Regexp, regexGroup int) error {
return nil return nil
} }
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func filterFiles(config config) error { func filterFiles(config config) error {
var regexString string var regexString string
if len(config.VariableRegex) == 0 { if len(config.VariableRegex) == 0 {
@ -85,7 +99,19 @@ func filterFiles(config config) error {
} }
for _, file := range config.Files { for _, file := range config.Files {
log.Println("Filtering file:", file) if !config.ForceOverwrite {
exists, err := fileExists(file.TargetPath)
if err != nil {
return err
}
if exists {
log.Println("Skipping file:", file.Path, "->", file.TargetPath, "(already exists)")
continue
}
}
log.Println("Filtering file:", file.Path, "->", file.TargetPath)
err := filterFile(file, *regex, regexGroup) err := filterFile(file, *regex, regexGroup)
if err != nil { if err != nil {
return err return err
@ -97,6 +123,7 @@ func filterFiles(config config) error {
func main() { func main() {
configPath := flag.String("config", "config.json", "Path to config file") configPath := flag.String("config", "config.json", "Path to config file")
force := flag.Bool("force", false, "Forcibly overwrite existing files (equivalent to setting forceOverwrite to true in the config)")
flag.Parse() flag.Parse()
config, err := loadConfig(*configPath) config, err := loadConfig(*configPath)
@ -104,6 +131,8 @@ func main() {
log.Fatalln("Failed to load config:", err) log.Fatalln("Failed to load config:", err)
} }
config.ForceOverwrite = config.ForceOverwrite || *force
err = filterFiles(*config) err = filterFiles(*config)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)