Skip to content

Commit 2ea8954

Browse files
pbjprithvijj
authored andcommitted
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 7608512 commit 2ea8954

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/ansi"
@@ -134,6 +135,45 @@ func main() {
134135
config.Output = defaultOutputFilename
135136
}
136137

138+
istty := isatty.IsTerminal(os.Stdout.Fd())
139+
140+
// Check if file already exists
141+
if _, err := os.Stat(config.Output); err == nil && istty {
142+
var confirm bool
143+
var newOutputFilename string
144+
145+
confirmOverwriteForm :=
146+
huh.NewConfirm().
147+
Title(fmt.Sprintf("'%s' already exists. Would you like to overwrite this file?", config.Output)).
148+
Value(&confirm)
149+
150+
newOutputFileNameForm := huh.NewInput().
151+
Title("Enter new output filename to use").
152+
Value(&newOutputFilename)
153+
154+
err = confirmOverwriteForm.Run()
155+
if err != nil {
156+
printErrorFatal("could not retrive overwrite confirmation", err)
157+
}
158+
159+
if !confirm {
160+
err := newOutputFileNameForm.Run()
161+
if err != nil {
162+
printErrorFatal("could not retrieve new output filename to use", err)
163+
}
164+
165+
fileInfo, err := os.Stat(newOutputFilename)
166+
if err != nil {
167+
printErrorFatal("could not retrieve new output filename info", err)
168+
}
169+
170+
if fileInfo.IsDir() {
171+
printErrorFatal(fmt.Sprintf("'%s' is a directory. Hence cannot overwrite to the given filename", newOutputFilename), errors.New("could not overwrite to filename"))
172+
}
173+
config.Output = newOutputFilename
174+
}
175+
}
176+
137177
scale = 1
138178
if autoHeight && autoWidth && strings.HasSuffix(config.Output, ".png") {
139179
scale = 4
@@ -393,8 +433,6 @@ func main() {
393433
}
394434
}
395435

396-
istty := isatty.IsTerminal(os.Stdout.Fd())
397-
398436
switch {
399437
case strings.HasSuffix(config.Output, ".png"):
400438
// use libsvg conversion.

0 commit comments

Comments
 (0)