github.com/Benchkram/bob@v0.0.0-20220321080157-7c8f3876e225/cli/cmd_playground.go (about) 1 //go:build dev 2 // +build dev 3 4 package cli 5 6 import ( 7 "bufio" 8 "fmt" 9 "os" 10 "strconv" 11 "strings" 12 13 "github.com/logrusorgru/aurora" 14 15 "github.com/Benchkram/bob/bob" 16 "github.com/Benchkram/errz" 17 18 "github.com/spf13/cobra" 19 ) 20 21 func init() { 22 playgroundCmd.Flags().Bool("clean", false, "Delete directory content before creating the playground") 23 rootCmd.AddCommand(playgroundCmd) 24 } 25 26 var playgroundCmd = &cobra.Command{ 27 Use: "playground", 28 Short: "Create a temporary playground in the current dir", 29 Long: ``, 30 Run: func(cmd *cobra.Command, args []string) { 31 clean, err := strconv.ParseBool(cmd.Flag("clean").Value.String()) 32 errz.Fatal(err) 33 34 if clean { 35 36 wd, err := os.Getwd() 37 errz.Fatal(err) 38 if wd == "/" { 39 fmt.Println("Can't delete root '/'") 40 os.Exit(1) 41 } 42 43 homedir := os.Getenv("HOME") 44 if homedir != "" { 45 if wd == homedir { 46 fmt.Println("Can't delete home dir") 47 os.Exit(1) 48 } 49 } 50 51 reader := bufio.NewReader(os.Stdin) 52 fmt.Printf("Delete content of %q: [y/n] ", wd) 53 text, _ := reader.ReadString('\n') 54 text = strings.ToLower(text) 55 text = strings.TrimSuffix(text, "\n") 56 if text != "y" { 57 fmt.Printf("%s\n", aurora.Red("abort")) 58 os.Exit(1) 59 } 60 61 files, err := os.ReadDir(wd) 62 errz.Fatal(err) 63 for _, file := range files { 64 err = os.RemoveAll(file.Name()) 65 errz.Fatal(err) 66 } 67 } 68 69 runPlayground() 70 }, 71 } 72 73 func runPlayground() { 74 wd, err := os.Getwd() 75 errz.Fatal(err) 76 77 err = bob.CreatePlayground(wd) 78 errz.Fatal(err) 79 }