Skip to content

Commit

Permalink
feat(go): ask for confirmation before overwriting existing database
Browse files Browse the repository at this point in the history
  • Loading branch information
milanmlft committed Oct 25, 2024
1 parent 8883057 commit 04d3f3f
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions todo-go/cmd/init.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package cmd

import (
"bufio"
"fmt"
"log"
"os"
"strings"

"github.com/milanmlft/todo/todo-go/todo"
"github.com/spf13/cobra"
Expand All @@ -29,11 +31,14 @@ func init() {
}

func initRun(cmd *cobra.Command, args []string) {
// TODO: ask for confirmation to overwrite existing file
dbpath := viper.GetString("datafile")
if fileExists(dbpath) {
log.Printf("Database already exists at %s. Doing nothing.", dbpath)
return
prompt := fmt.Sprintf("Database already exists at %s. Overwrite? [y/N]", dbpath)
confirm := askForConfirmation(prompt)
if !confirm {
fmt.Println("Doing nothing.")
return
}
}
err := todo.InitialiseDB(dbpath)
if err != nil {
Expand All @@ -53,3 +58,14 @@ func fileExists(path string) bool {
fmt.Printf("Error checking file %s: %v", path, err)
return false
}

func askForConfirmation(prompt string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
}
input = strings.TrimSpace(strings.ToLower(input))
return input == "y" || input == "yes"
}

0 comments on commit 04d3f3f

Please sign in to comment.