Repository navigation
Expand file tree
/
Copy pathinit.go
More file actions
415 lines (364 loc) · 11.5 KB
/
Copy pathinit.go
File metadata and controls
415 lines (364 loc) · 11.5 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
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
404
405
406
407
408
409
410
411
412
413
414
415
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
// Supported shells for init command.
var supportedShells = map[string]bool{
"bash": true,
"zsh": true,
"powershell": true,
"pwsh": true, // alias for powershell
}
// Init command flags.
var (
initDryRun bool
initUninstall bool
initNoPrompt bool
)
func init() {
initFlagSet := flag.NewFlagSet("init", flag.ContinueOnError)
initFlagSet.BoolVar(&initDryRun, "dry-run", false, "Preview changes without modifying files")
initFlagSet.BoolVar(&initUninstall, "uninstall", false, "Remove wt configuration from shell")
initFlagSet.BoolVar(&initNoPrompt, "no-prompt", false, "Skip activation instructions")
registerCommand(&command{
name: "init",
short: "Initialize shell integration",
long: `Add wt shell integration to your shell configuration.
Automatically detects your shell and updates the appropriate config file:
- bash: ~/.bashrc
- zsh: ~/.zshrc (or $ZDOTDIR/.zshrc if ZDOTDIR is set)
- powershell: $PROFILE (Windows only)
The configuration is wrapped in markers so it can be safely updated or removed.
Examples:
wt init # Auto-detect shell and configure
wt init bash # Configure for bash specifically
wt init --dry-run # Preview changes without modifying files
wt init --uninstall # Remove wt configuration from shell`,
usage: "[shell]",
flags: initFlagSet,
run: func(args []string) error {
if len(args) > 1 {
return fmt.Errorf("accepts at most 1 arg, got %d", len(args))
}
shell := detectShell(args)
if shell == "" {
return fmt.Errorf("could not detect shell. Please specify: wt
8000
init bash|zsh|powershell")
}
// PowerShell init is only supported on Windows because wt shellenv
// only outputs PowerShell code when running on Windows
if shell == "powershell" && runtime.GOOS != "windows" {
return fmt.Errorf("PowerShell shell integration is only supported on Windows. On macOS/Linux, use: wt init bash or wt init zsh")
}
configPath := getShellConfigPath(shell)
if configPath == "" {
return fmt.Errorf("could not determine config file for %s", shell)
}
operation := "install"
status := "installed"
if initDryRun {
status = "planned"
}
if initUninstall {
operation = "uninstall"
status = "removed"
if initDryRun {
status = "planned"
}
if err := removeShellConfig(configPath, shell, initDryRun); err != nil {
return err
}
if isJSONOutput() {
return emitJSONSuccess("init", map[string]any{
"status": status,
"operation": operation,
"shell": shell,
"config_path": configPath,
"dry_run": initDryRun,
})
}
return nil
}
if err := installShellConfig(configPath, shell, initDryRun, initNoPrompt); err != nil {
return err
}
if isJSONOutput() {
return emitJSONSuccess("init", map[string]any{
"status": status,
"operation": operation,
"shell": shell,
"config_path": configPath,
"dry_run": initDryRun,
})
}
return nil
},
})
}
const (
markerStart = "# >>> wt initialize >>>"
markerEnd = "# <<< wt initialize <<<"
)
// rejectSymlink returns an error if the given path is a symlink.
// This prevents symlink attacks where writing to a symlinked rc file
// would modify the symlink target (e.g., a system file).
func rejectSymlink(path string) error {
info, err := os.Lstat(path)
if os.IsNotExist(err) {
return nil // file doesn't exist yet, safe to create
}
if err != nil {
return fmt.Errorf("failed to check %s: %w", path, err)
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("refusing to modify %s: file is a symlink", path)
}
return nil
}
// detectShell determines which shell to configure based on args or environment.
func detectShell(args []string) string {
// 1. Explicit argument
if len(args) > 0 {
shell := strings.ToLower(args[0])
if supportedShells[shell] {
if shell == "pwsh" {
return "powershell"
}
return shell
}
fmt.Fprintf(os.Stderr, "Warning: unknown shell '%s', attempting auto-detection\n", args[0])
}
// 2. On Windows, default to PowerShell
if runtime.GOOS == "windows" {
return "powershell"
}
// 3. Check $SHELL environment variable
shellEnv := os.Getenv("SHELL")
if strings.Contains(shellEnv, "zsh") {
return "zsh"
}
if strings.Contains(shellEnv, "bash") {
return "bash"
}
// 4. Default to bash on Unix
return "bash"
}
// getShellConfigPath returns the path to the shell configuration file.
func getShellConfigPath(shell string) string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
switch shell {
case "bash":
// Prefer .bashrc, fall back to .bash_profile on macOS
bashrc := filepath.Join(home, ".bashrc")
if _, err := os.Stat(bashrc); err == nil {
return bashrc
}
if runtime.GOOS == "darwin" {
return filepath.Join(home, ".bash_profile")
}
return bashrc
case "zsh":
// Respect ZDOTDIR if set: zsh reads its startup files from $ZDOTDIR (default: $HOME).
// This avoids writing to the wrong (potentially unused or broken) ~/.zshrc.
if zdotdir := strings.TrimSpace(os.Getenv("ZDOTDIR")); zdotdir != "" {
if !filepath.IsAbs(zdotdir) {
zdotdir = filepath.Join(home, zdotdir)
}
return filepath.Join(filepath.Clean(zdotdir), ".zshrc")
}
return filepath.Join(home, ".zshrc")
case "powershell":
// Check $PROFILE env var first (works for both Windows PowerShell 5.1 and PowerShell Core)
if profile := os.Getenv("PROFILE"); profile != "" {
return profile
}
if runtime.GOOS == "windows" {
// Default to Windows PowerShell 5.1 path (more common)
// Windows PowerShell 5.1: Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
// PowerShell Core 7+: Documents\PowerShell\Microsoft.PowerShell_profile.ps1
docs := filepath.Join(home, "Documents", "WindowsPowerShell")
if err := os.MkdirAll(docs, 0755); err == nil {
return filepath.Join(docs, "Microsoft.PowerShell_profile.ps1")
}
}
// Unix PowerShell Core
return filepath.Join(home, ".config", "powershell", "Microsoft.PowerShell_profile.ps1")
}
return ""
}
// getShellConfigContent returns the shell configuration block to add.
func getShellConfigContent(shell string) string {
switch shell {
case "bash", "zsh":
return fmt.Sprintf(`%s
eval "$(wt shellenv)"
%s`, markerStart, markerEnd)
case "powershell":
return fmt.Sprintf(`%s
Invoke-Expression (& wt shellenv)
%s`, markerStart, markerEnd)
}
return ""
}
// successPrefix returns a checkmark or "[ok]" depending on terminal support.
func successPrefix() string {
// Check if we're in a terminal that likely supports Unicode
// Most modern terminals do, but CI environments and some Windows consoles may not
if os.Getenv("CI") != "" || os.Getenv("TERM") == "dumb" {
return "[ok]"
}
return "✓"
}
// installShellConfig adds or updates shell configuration.
func installShellConfig(configPath, shell string, dryRun, noPrompt bool) error {
jsonMode := isJSONOutput()
content := getShellConfigContent(shell)
if content == "" {
return fmt.Errorf("unsupported shell: %s", shell)
}
// Reject symlinks to prevent writing through to unintended files
if err := rejectSymlink(configPath); err != nil {
return err
}
// Read existing config
existing, err := os.ReadFile(configPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to read %s: %w", configPath, err)
}
existingStr := string(existing)
// Check if already configured.
if strings.Contains(existingStr, markerStart) { //nolint:nestif // update-or-append logic is inherently branchy
// Update existing configuration
startIdx := strings.Index(existingStr, markerStart)
endIdx := strings.Index(existingStr, markerEnd)
if endIdx > startIdx {
endIdx += len(markerEnd)
newContent := existingStr[:startIdx] + content + existingStr[endIdx:]
if dryRun {
if !jsonMode {
fmt.Printf("Would update %s (already configured, updating)\n\n", configPath)
fmt.Println("New configuration block:")
fmt.Println(content)
}
return nil
}
if err := os.WriteFile(configPath, []byte(newContent), 0644); err != nil { //nolint:gosec // shell config should be world-readable
return fmt.Errorf("failed to write %s: %w", configPath, err)
}
if !jsonMode {
fmt.Printf("%s Updated wt configuration in %s\n", successPrefix(), configPath)
}
return nil
}
}
// Append new configuration
if dryRun {
if !jsonMode {
fmt.Printf("Would append to %s:\n\n", configPath)
fmt.Println(content)
fmt.Println()
fmt.Println("To apply, run: wt init")
}
return nil
}
// Ensure directory exists
if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
// Append to file
f, err := os.OpenFile(configPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open %s: %w", configPath, err)
}
defer f.Close()
// Add newline before if file doesn't end with one
if len(existing) > 0 && existing[len(existing)-1] != '\n' {
if _, err := f.WriteString("\n"); err != nil {
return err
}
}
if _, err := f.WriteString("\n" + content + "\n"); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
if !jsonMode {
fmt.Printf("%s Added wt shell integration to %s\n", successPrefix(), configPath)
if !noPrompt {
fmt.Println()
fmt.Println("To activate, run:")
switch shell {
case "bash":
fmt.Printf(" source %s\n", configPath)
case "zsh":
fmt.Printf(" source %s\n", configPath)
case "powershell":
fmt.Println(" . $PROFILE")
}
fmt.Println()
fmt.Println("Or start a new shell session.")
}
}
return nil
}
// removeShellConfig removes the wt configuration block from shell config.
func removeShellConfig(configPath, shell string, dryRun bool) error {
_ = shell
jsonMode := isJSONOutput()
// Reject symlinks to prevent writing through to unintended files
if err := rejectSymlink(configPath); err != nil {
return err
}
existing, err := os.ReadFile(configPath)
if os.IsNotExist(err) {
if !jsonMode {
fmt.Println("No configuration found to remove.")
}
return nil
}
if err != nil {
return fmt.Errorf("failed to read %s: %w", configPath, err)
}
existingStr := string(existing)
if !strings.Contains(existingStr, markerStart) {
if !jsonMode {
fmt.Println("No wt configuration found in", configPath)
}
return nil
}
startIdx := strings.Index(existingStr, markerStart)
endIdx := strings.Index(existingStr, markerEnd)
if endIdx <= startIdx {
return fmt.Errorf("malformed configuration markers in %s", configPath)
}
endIdx += len(markerEnd)
// Count newlines before the marker to preserve original formatting
// We only remove the single newline we added before the marker
before := existingStr[:startIdx]
after := existingStr[endIdx:]
// Remove trailing newline from before (the one we added)
if strings.HasSuffix(before, "\n\n") {
before = before[:len(before)-1]
}
// Remove leading newline from after (the one we added)
after = strings.TrimPrefix(after, "\n")
newContent := before + after
if dryRun {
if !jsonMode {
fmt.Printf("Would remove wt configuration from %s\n", configPath)
}
return nil
}
if err := os.WriteFile(configPath, []byte(newContent), 0644); err != nil { //nolint:gosec // shell config should be world-readable
return fmt.Errorf("failed to write %s: %w", configPath, err)
}
if !jsonMode {
fmt.Printf("%s Removed wt configuration from %s\n", successPrefix(), configPath)
}
return nil
}