1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
package prompt
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"codeberg.org/snonux/gos/internal/colour"
"codeberg.org/snonux/gos/internal/oi"
"codeberg.org/snonux/gos/internal/table"
)
var (
ErrAborted = errors.New("aborted")
ErrDeleted = errors.New("deleted")
ErrRamdomOther = errors.New("randomOther")
RandomOption = true
)
func FileAction(question, content, filePath string, includeRandomOption ...bool) (string, error) {
table.New().
WithBaseColor(colour.AttentionCol).
WithHeaderColor(colour.AckCol).
Header(question).
TextBox(content).
MustRender()
reader := bufio.NewReader(os.Stdin)
includeRandom := len(includeRandomOption) > 0 && includeRandomOption[0] == RandomOption
var randomOption string
if includeRandom {
randomOption = "/r=random other"
}
for {
fmt.Print(" ")
colour.Ackf("(y=yes/n=no/e=edit/d=delete%s):", randomOption)
input, err := reader.ReadString('\n')
if err != nil {
return "", fmt.Errorf("error reading input: %w", err)
}
switch strings.ToLower(strings.TrimSpace(input)) {
case "y", "yes":
return content, nil
case "n", "no":
return content, fmt.Errorf("%w %s", ErrAborted, filePath)
case "e", "edit":
if err := EditFile(filePath); err != nil {
return content, err
}
if content, err = oi.SlurpAndTrim(filePath); err != nil {
return content, err
}
return FileAction(question, content, filePath, includeRandomOption...)
case "d", "delete":
if err := os.Remove(filePath); err != nil {
return content, err
}
return content, fmt.Errorf("%w %s", ErrDeleted, filePath)
case "r", "random", "random other":
if includeRandom {
return content, fmt.Errorf("%w %s", ErrRamdomOther, filePath)
}
fallthrough
default:
var r string
if includeRandom {
r = "r"
}
fmt.Printf("Please respond with one of [yned%s].\n", r)
}
}
}
func EditFile(filePath string) error {
editor, ok := os.LookupEnv("EDITOR")
if !ok {
return errors.New("EDITOR environment variable is not set")
}
cmd := exec.Command(editor, filePath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
|