-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_bootstrap.go
More file actions
86 lines (75 loc) · 1.86 KB
/
Copy pathconfig_bootstrap.go
File metadata and controls
86 lines (75 loc) · 1.86 KB
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
package contexting
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
func ensureStarterConfigPrompt(path string, autoCreate bool) (bool, error) {
if path == "" {
return false, nil
}
if _, err := os.Stat(path); err == nil {
return false, nil
} else if !os.IsNotExist(err) {
return false, fmt.Errorf("check config path %s: %w", path, err)
}
if autoCreate {
return true, writeStarterConfig(path, false)
}
if !isInteractiveTerminal() {
return false, nil
}
ok, err := askYesNo(fmt.Sprintf("Config file %q not found. Create starter config now? [Y/n]: ", path), true)
if err != nil {
return false, err
}
if !ok {
return false, nil
}
if err := writeStarterConfig(path, false); err != nil {
return false, err
}
LogInfof("Created starter config at %s", path)
return true, nil
}
func writeStarterConfig(path string, force bool) error {
if !force {
if _, err := os.Stat(path); err == nil {
return fmt.Errorf("config already exists: %s", path)
} else if !os.IsNotExist(err) {
return fmt.Errorf("check config path %s: %w", path, err)
}
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return fmt.Errorf("create config directory: %w", err)
}
return writeFileAtomic(path, []byte(starterConfigTemplate), 0o644)
}
func askYesNo(prompt string, defaultYes bool) (bool, error) {
fmt.Print(prompt)
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
return false, fmt.Errorf("read prompt input: %w", err)
}
value := strings.ToLower(strings.TrimSpace(input))
if value == "" {
return defaultYes, nil
}
if value == "y" || value == "yes" {
return true, nil
}
if value == "n" || value == "no" {
return false, nil
}
return defaultYes, nil
}
func isInteractiveTerminal() bool {
fi, err := os.Stdin.Stat()
if err != nil {
return false
}
return (fi.Mode() & os.ModeCharDevice) != 0
}