Skip to content

Commit

Permalink
feat: Include Confirmation dialogue if a file is about to be overwritten
Browse files Browse the repository at this point in the history
- Added in a `huh.NewConfirm` and `huh.NewInput` fields, that checks
  if the output file already exists within the given directory
- If the user selects to `overwrite` the file, execution continues as is
- If the user selects to `not overwrite` the file, an `input` field is
  provided to select a new output filename
- The `huh` forms will be rendered only if the `stdout` is a terminal
  • Loading branch information
pbj authored and prithvijj committed Sep 27, 2024
1 parent 7608512 commit 2ea8954
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/beevik/etree"
in "github.com/charmbracelet/freeze/input"
"github.com/charmbracelet/freeze/svg"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
"github.com/charmbracelet/x/ansi"
Expand Down Expand Up @@ -134,6 +135,45 @@ func main() {
config.Output = defaultOutputFilename
}

istty := isatty.IsTerminal(os.Stdout.Fd())

// Check if file already exists
if _, err := os.Stat(config.Output); err == nil && istty {
var confirm bool
var newOutputFilename string

confirmOverwriteForm :=
huh.NewConfirm().
Title(fmt.Sprintf("'%s' already exists. Would you like to overwrite this file?", config.Output)).
Value(&confirm)

newOutputFileNameForm := huh.NewInput().
Title("Enter new output filename to use").
Value(&newOutputFilename)

err = confirmOverwriteForm.Run()
if err != nil {
printErrorFatal("could not retrive overwrite confirmation", err)
}

if !confirm {
err := newOutputFileNameForm.Run()
if err != nil {
printErrorFatal("could not retrieve new output filename to use", err)
}

fileInfo, err := os.Stat(newOutputFilename)
if err != nil {
printErrorFatal("could not retrieve new output filename info", err)
}

if fileInfo.IsDir() {
printErrorFatal(fmt.Sprintf("'%s' is a directory. Hence cannot overwrite to the given filename", newOutputFilename), errors.New("could not overwrite to filename"))
}
config.Output = newOutputFilename
}
}

scale = 1
if autoHeight && autoWidth && strings.HasSuffix(config.Output, ".png") {
scale = 4
Expand Down Expand Up @@ -393,8 +433,6 @@ func main() {
}
}

istty := isatty.IsTerminal(os.Stdout.Fd())

switch {
case strings.HasSuffix(config.Output, ".png"):
// use libsvg conversion.
Expand Down

0 comments on commit 2ea8954

Please sign in to comment.