Skip to content

Commit 5f5cb50

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 5f5cb50

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

main.go

Lines changed: 40 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,45 @@ 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+
164+
fileInfo, err := os.Stat(newOutputFilename)
165+
if err != nil {
166+
printErrorFatal("could not retrieve new output filename info", err)
167+
}
168+
169+
if fileInfo.IsDir() {
170+
printErrorFatal(fmt.Sprintf("'%s' is a directory. Hence cannot overwrite to the given filename", newOutputFilename), errors.New("could not overwrite to filename"))
171+
}
172+
config.Output = newOutputFilename
173+
}
174+
}
175+
136176
scale = 1
137177
if autoHeight && autoWidth && strings.HasSuffix(config.Output, ".png") {
138178
scale = 4
@@ -386,8 +426,6 @@ func main() {
386426
}
387427
}
388428

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

0 commit comments

Comments
 (0)