-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile_init.go
403 lines (356 loc) · 8.9 KB
/
profile_init.go
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package main
import (
"fmt"
"github.com/atotto/clipboard"
tea "github.com/charmbracelet/bubbletea"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
"time"
)
type InitModel struct {
shell string
rcFile string
err error
selected string // "a" for append, "c" for copy
forShell bool
succeeded bool
}
func (m InitModel) Init() tea.Cmd {
return nil
}
func (m InitModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "q", "ctrl+c":
return m, tea.Quit
case "a":
if err := m.appendToRC(); err != nil {
m.err = err
return m, tea.Quit
} else {
m.succeeded = true
m.selected = "a"
return m, tea.Quit
}
case "c":
if err := m.copyToClipboard(); err != nil {
m.err = err
return m, tea.Quit
}
m.succeeded = true
m.selected = "c"
return m, tea.Quit
}
}
return m, nil
}
func (m InitModel) View() string {
if m.forShell {
switch m.shell {
case "bash", "zsh":
return bashInitScript
case "fish":
return fishInitScript
default:
return fmt.Sprintf("Unsupported shell: %s\n", m.shell)
}
}
if m.err != nil {
return fmt.Sprintf("%s%s%sError:%s %v\n",
colorRed,
colorBold,
iconX,
colorReset,
m.err,
)
}
if m.succeeded {
if m.selected == "a" {
return fmt.Sprintf("%s%s%sSuccess:%s Configuration appended to %s\nPlease run\n❯ eval \"$(envman init - %s)\" \nor\n❯ source %s\nor Restart your shell\n",
colorGreen,
colorBold,
iconCheck,
colorReset,
m.rcFile,
m.shell,
m.rcFile,
)
}
if m.selected == "c" {
return fmt.Sprintf("%s%s%sSuccess:%s Configuration copied to clipboard\n",
colorGreen,
colorBold,
iconCheck,
colorReset,
)
}
}
currentUser, _ := user.Current()
currentTime := time.Now().UTC().Format("2006-01-02 15:04:05")
var sb strings.Builder
sb.WriteString(fmt.Sprintf("%s%senvman Initialization%s\n\n", colorBold, colorGreen, colorReset))
sb.WriteString(fmt.Sprintf("Shell: %s\n", m.shell))
sb.WriteString(fmt.Sprintf("RC File: %s\n", m.rcFile))
sb.WriteString(fmt.Sprintf("Current User: %s\n", currentUser.Username))
sb.WriteString(fmt.Sprintf("Current Time (UTC): %s\n\n", currentTime))
sb.WriteString("The following will be added to your shell configuration:\n\n")
sb.WriteString(fmt.Sprintf("%s%s%s\n", colorYellow, getEnvmanBlock(m.shell), colorReset))
sb.WriteString("\nOptions:\n")
sb.WriteString(fmt.Sprintf("%s[a]%s Append automatically to %s\n", colorBold, colorReset, m.rcFile))
sb.WriteString(fmt.Sprintf("%s[c]%s Copy to clipboard\n", colorBold, colorReset))
sb.WriteString(fmt.Sprintf("%s[q]%s Quit\n", colorBold, colorReset))
return sb.String()
}
func getEnvmanBlock(shell string) string {
currentTime := time.Now().UTC().Format("2006-01-02 15:04:05")
return fmt.Sprintf(`
# START >>>>>>>>>>>> envman Managed [%s] <<<<<<<<<<<<<<<
eval "$(envman init - %s)"
# END >>>>>>>>>>>> envman Managed <<<<<<<<<<<<<<<`, currentTime, shell)
}
func (m InitModel) appendToRC() error {
content := getEnvmanBlock(m.shell)
rcPath := m.rcFile
if strings.HasPrefix(rcPath, "~/") {
home := os.Getenv("HOME")
rcPath = filepath.Join(home, rcPath[2:])
}
existing, err := os.ReadFile(rcPath)
if err == nil && strings.Contains(string(existing), fmt.Sprintf(`eval "$(envman init - %s)"`, m.shell)) {
return fmt.Errorf("envman configuration already exists in %s", m.rcFile)
}
f, err := os.OpenFile(rcPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open %s: %v", m.rcFile, err)
}
defer f.Close()
if _, err := f.WriteString("\n" + content + "\n"); err != nil {
return fmt.Errorf("failed to write to %s: %v", m.rcFile, err)
}
return nil
}
func (m InitModel) copyToClipboard() error {
content := getEnvmanBlock(m.shell)
err := copyToClipboard(content)
if err != nil {
return err
}
fmt.Printf("\n%s%s%sConfiguration copied to clipboard!%s\n",
colorGreen,
colorBold,
iconCheck,
colorReset,
)
return nil
}
func copyToClipboard(content string) error {
err := clipboard.WriteAll(content)
if err != nil {
if altErr := tryAlternativeClipboard(content); altErr != nil {
fmt.Printf("\n%s%s%sClipboard access failed!%s\n",
colorYellow,
colorBold,
iconWarning,
colorReset,
)
fmt.Println("\nPlease copy this manually:")
fmt.Printf("%s%s%s\n",
colorYellow,
content,
colorReset,
)
return fmt.Errorf("failed to copy to clipboard: %v", err)
}
}
return nil
}
func tryAlternativeClipboard(content string) error {
switch runtime.GOOS {
case "darwin":
cmd := exec.Command("pbcopy")
in, err := cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
if _, err := in.Write([]byte(content)); err != nil {
return err
}
if err := in.Close(); err != nil {
return err
}
return cmd.Wait()
case "linux":
if xclipCmd := exec.Command("xclip", "-selection", "clipboard"); xclipCmd != nil {
xclipCmd.Stdin = strings.NewReader(content)
if err := xclipCmd.Run(); err == nil {
return nil
}
}
if xselCmd := exec.Command("xsel", "--clipboard", "--input"); xselCmd != nil {
xselCmd.Stdin = strings.NewReader(content)
if err := xselCmd.Run(); err == nil {
return nil
}
}
return fmt.Errorf("no clipboard mechanism available")
case "windows":
cmd := exec.Command("clip")
in, err := cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
if _, err := in.Write([]byte(content)); err != nil {
return err
}
if err := in.Close(); err != nil {
return err
}
return cmd.Wait()
}
return fmt.Errorf("unsupported platform")
}
func InitCommand(forShell bool, shell string) error {
if forShell {
switch shell {
case "bash", "zsh":
fmt.Print(bashInitScript)
case "fish":
fmt.Print(fishInitScript)
default:
return fmt.Errorf("unsupported shell: %s", shell)
}
return nil
}
model := InitModel{
shell: shell,
rcFile: getShellRC(shell),
forShell: forShell,
}
p := tea.NewProgram(model)
finalModel, err := p.Run()
if err != nil {
return fmt.Errorf("error running program: %v", err)
}
if m, ok := finalModel.(InitModel); ok && m.err != nil {
return m.err
}
return nil
}
var bashInitScript string
var fishInitScript string
func getShellRC(shell string) string {
home := os.Getenv("HOME")
switch shell {
case "bash":
if _, err := os.Stat(filepath.Join(home, ".bash_profile")); err == nil {
return "~/.bash_profile"
}
return "~/.bashrc"
case "zsh":
return "~/.zshrc"
case "fish":
return "~/.config/fish/config.fish"
default:
return "~/.profile"
}
}
func detectShell() string {
shell := os.Getenv("SHELL")
switch {
case shell == "":
return "bash" // default to bash if we can't detect
case shell == "/bin/bash" || shell == "/usr/bin/bash":
return "bash"
case shell == "/bin/zsh" || shell == "/usr/bin/zsh":
return "zsh"
case shell == "/bin/fish" || shell == "/usr/bin/fish":
return "fish"
default:
return "bash" // default to bash for unknown shells
}
}
func ensureEnvmanDirs() error {
currentUser, err := user.Current()
if err != nil {
return fmt.Errorf("failed to get current user: %v", err)
}
dirs := []string{
filepath.Join("/home", currentUser.Username, ".envman"),
filepath.Join("/home", currentUser.Username, ".envman/completions"),
}
for _, dir := range dirs {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create directory %s: %v", dir, err)
}
}
return nil
}
func init() {
envmanRoot, err := getEnvmanRoot()
if err != nil {
fmt.Println("Error getting envman root directory: ", err)
os.Exit(1)
}
bashInitScript = fmt.Sprintf(`export ENVMAN_ROOT="%s"
envman() {
local command
command="$1"
if [ "$#" -gt 0 ]; then
shift
fi
case "$command" in
load)
if [ "$#" -eq 0 ]; then
echo "Usage: envman load <profile>" >&2
return 1
fi
local profile_path="$ENVMAN_ROOT/$1.env"
if [ -f "$profile_path" ]; then
source "$profile_path"
echo "Loaded profile: $1"
else
echo "Profile not found: $1" >&2
return 1
fi
;;
*)
command envman "$command" "$@"
;;
esac
}
`, envmanRoot)
fishInitScript = fmt.Sprintf(`set -gx ENVMAN_ROOT "%s"
function envman
set -l command $argv[1]
set -e argv[1]
switch "$command"
case "load"
if test (count $argv) -eq 0
echo "Usage: envman load <profile>" >&2
return 1
end
set -l profile_path "$ENVMAN_ROOT/$argv[1].env"
if test -f "$profile_path"
source "$profile_path"
echo "Loaded profile: $argv[1]"
else
echo "Profile not found: $argv[1]" >&2
return 1
end
case '*'
command envman "$command" $argv
end
end
`, envmanRoot)
}