Skip to content

Commit ddf9006

Browse files
author
pbj
committed
feat: Include Confirmation dialogue if a file is about to be overwritten
- 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
1 parent 80803eb commit ddf9006

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

main.go

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"github.com/beevik/etree"
1818
in "github.com/charmbracelet/freeze/input"
1919
"github.com/charmbracelet/freeze/svg"
20+
"github.com/charmbracelet/huh"
2021
"github.com/charmbracelet/lipgloss"
2122
"github.com/charmbracelet/log"
2223
"github.com/charmbracelet/x/exp/term/ansi"
@@ -133,6 +134,36 @@ func main() {
133134
config.Output = defaultOutputFilename
134135
}
135136

137+
istty := isatty.IsTerminal(os.Stdout.Fd())
138+
139+
// Check if file already exists
140+
if _, err := os.Stat(config.Output); err == nil && istty {
141+
var confirm bool
142+
var newOutputFilename string
143+
144+
confirmOverwriteForm :=
145+
huh.NewConfirm().
146+
Title(fmt.Sprintf("'%s' already exists. Would you like to overwrite this file?", config.Output)).
147+
Value(&confirm)
148+
149+
newOutputFileNameForm := huh.NewInput().
150+
Title("Enter new output filename to use").
151+
Value(&newOutputFilename)
152+
153+
err = confirmOverwriteForm.Run()
154+
if err != nil {
155+
printErrorFatal("could not retrive overwrite confirmation", err)
156+
}
157+
158+
if !confirm {
159+
err := newOutputFileNameForm.Run()
160+
if err != nil {
161+
printErrorFatal("could not retrieve new output filename to use", err)
162+
}
163+
config.Output = newOutputFilename
164+
}
165+
}
166+
136167
scale = 1
137168
if autoHeight && autoWidth && strings.HasSuffix(config.Output, ".png") {
138169
scale = 4
@@ -386,8 +417,6 @@ func main() {
386417
}
387418
}
388419

389-
istty := isatty.IsTerminal(os.Stdout.Fd())
390-
391420
switch {
392421
case strings.HasSuffix(config.Output, ".png"):
393422
// use libsvg conversion.

0 commit comments

Comments
 (0)