-
-
Notifications
You must be signed in to change notification settings - Fork 895
Expand file tree
/
Copy pathshellutil.go
More file actions
709 lines (620 loc) · 19.7 KB
/
shellutil.go
File metadata and controls
709 lines (620 loc) · 19.7 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package shellutil
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/wavetermdev/waveterm/pkg/util/envutil"
"github.com/wavetermdev/waveterm/pkg/util/utilfn"
"github.com/wavetermdev/waveterm/pkg/utilds"
"github.com/wavetermdev/waveterm/pkg/wavebase"
"github.com/wavetermdev/waveterm/pkg/waveobj"
"github.com/wavetermdev/waveterm/pkg/wconfig"
)
var (
//go:embed shellintegration/zsh_zprofile.sh
ZshStartup_Zprofile string
//go:embed shellintegration/zsh_zshrc.sh
ZshStartup_Zshrc string
//go:embed shellintegration/zsh_zlogin.sh
ZshStartup_Zlogin string
//go:embed shellintegration/zsh_zshenv.sh
ZshStartup_Zshenv string
//go:embed shellintegration/bash_bashrc.sh
BashStartup_Bashrc string
//go:embed shellintegration/bash_preexec.sh
BashStartup_Preexec string
//go:embed shellintegration/fish_wavefish.sh
FishStartup_Wavefish string
//go:embed shellintegration/pwsh_wavepwsh.sh
PwshStartup_wavepwsh string
ZshExtendedHistoryPattern = regexp.MustCompile(`^: [0-9]+:`)
)
const DefaultTermType = "xterm-256color"
const DefaultTermRows = 24
const DefaultTermCols = 80
var cachedMacUserShell string
var macUserShellOnce = &sync.Once{}
var userShellRegexp = regexp.MustCompile(`^UserShell: (.*)$`)
var gitBashCache = utilds.MakeSyncCache(findInstalledGitBash)
const DefaultShellPath = "/bin/bash"
const (
ShellType_bash = "bash"
ShellType_zsh = "zsh"
ShellType_fish = "fish"
ShellType_pwsh = "pwsh"
ShellType_unknown = "unknown"
)
const (
// there must be no spaces in these integration dir paths
ZshIntegrationDir = "shell/zsh"
BashIntegrationDir = "shell/bash"
PwshIntegrationDir = "shell/pwsh"
FishIntegrationDir = "shell/fish"
WaveHomeBinDir = "bin"
ZshHistoryFileName = ".zsh_history"
)
func DetectLocalShellPath() string {
if runtime.GOOS == "windows" {
if pwshPath, lpErr := exec.LookPath("pwsh"); lpErr == nil {
return pwshPath
}
if powershellPath, lpErr := exec.LookPath("powershell"); lpErr == nil {
return powershellPath
}
return "powershell.exe"
}
shellPath := GetMacUserShell()
if shellPath == "" {
shellPath = os.Getenv("SHELL")
}
if shellPath == "" {
return DefaultShellPath
}
return shellPath
}
func GetMacUserShell() string {
if runtime.GOOS != "darwin" {
return ""
}
macUserShellOnce.Do(func() {
cachedMacUserShell = internalMacUserShell()
})
return cachedMacUserShell
}
// dscl . -read /Users/[username] UserShell
// defaults to /bin/bash
func internalMacUserShell() string {
osUser, err := user.Current()
if err != nil {
return DefaultShellPath
}
ctx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second)
defer cancelFn()
userStr := "/Users/" + osUser.Username
out, err := exec.CommandContext(ctx, "dscl", ".", "-read", userStr, "UserShell").CombinedOutput()
if err != nil {
return DefaultShellPath
}
outStr := strings.TrimSpace(string(out))
m := userShellRegexp.FindStringSubmatch(outStr)
if m == nil {
return DefaultShellPath
}
return m[1]
}
func hasDirPart(dir string, part string) bool {
dir = filepath.Clean(dir)
part = strings.ToLower(part)
for {
base := strings.ToLower(filepath.Base(dir))
if base == part {
return true
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
return false
}
func FindGitBash(config *wconfig.FullConfigType, rescan bool) string {
if runtime.GOOS != "windows" {
return ""
}
if config != nil && config.Settings.TermGitBashPath != "" {
return config.Settings.TermGitBashPath
}
path, _ := gitBashCache.Get(rescan)
return path
}
func findInstalledGitBash() (string, error) {
// Try PATH first (skip system32, and only accept if in a Git directory)
pathEnv := os.Getenv("PATH")
pathDirs := filepath.SplitList(pathEnv)
for _, dir := range pathDirs {
dir = strings.Trim(dir, `"`)
if hasDirPart(dir, "system32") {
continue
}
if !hasDirPart(dir, "git") {
continue
}
bashPath := filepath.Join(dir, "bash.exe")
if _, err := os.Stat(bashPath); err == nil {
return bashPath, nil
}
}
// Try scoop location
userProfile := os.Getenv("USERPROFILE")
if userProfile != "" {
scoopPath := filepath.Join(userProfile, "scoop", "apps", "git", "current", "bin", "bash.exe")
if _, err := os.Stat(scoopPath); err == nil {
return scoopPath, nil
}
}
// Try LocalAppData\programs\git\bin
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData != "" {
localPath := filepath.Join(localAppData, "programs", "git", "bin", "bash.exe")
if _, err := os.Stat(localPath); err == nil {
return localPath, nil
}
}
// Try C:\Program Files\Git\bin
programFilesPath := filepath.Join("C:\\", "Program Files", "Git", "bin", "bash.exe")
if _, err := os.Stat(programFilesPath); err == nil {
return programFilesPath, nil
}
return "", nil
}
func DefaultTermSize() waveobj.TermSize {
return waveobj.TermSize{Rows: DefaultTermRows, Cols: DefaultTermCols}
}
func WaveshellLocalEnvVars(termType string) map[string]string {
rtn := make(map[string]string)
if termType != "" {
rtn["TERM"] = termType
}
// these are not necessary since they should be set with the swap token, but no harm in setting them here
rtn["TERM_PROGRAM"] = "waveterm"
rtn["WAVETERM"], _ = os.Executable()
rtn["WAVETERM_VERSION"] = wavebase.WaveVersion
rtn["WAVETERM_WSHBINDIR"] = filepath.Join(wavebase.GetWaveDataDir(), WaveHomeBinDir)
return rtn
}
func UpdateCmdEnv(cmd *exec.Cmd, envVars map[string]string) {
if len(envVars) == 0 {
return
}
found := make(map[string]bool)
var newEnv []string
for _, envStr := range cmd.Env {
envKey := GetEnvStrKey(envStr)
newEnvVal, ok := envVars[envKey]
if ok {
found[envKey] = true
if newEnvVal != "" {
newEnv = append(newEnv, envKey+"="+newEnvVal)
}
} else {
newEnv = append(newEnv, envStr)
}
}
for envKey, envVal := range envVars {
if found[envKey] {
continue
}
newEnv = append(newEnv, envKey+"="+envVal)
}
cmd.Env = newEnv
}
func GetEnvStrKey(envStr string) string {
eqIdx := strings.Index(envStr, "=")
if eqIdx == -1 {
return envStr
}
return envStr[0:eqIdx]
}
var initStartupFilesOnce = &sync.Once{}
// in a Once block so it can be called multiple times
// we run it at startup, but also before launching local shells so we know everything is initialized before starting the shell
func InitCustomShellStartupFiles() error {
var err error
initStartupFilesOnce.Do(func() {
err = initCustomShellStartupFilesInternal()
})
return err
}
func GetLocalBashRcFileOverride() string {
return filepath.Join(wavebase.GetWaveDataDir(), BashIntegrationDir, ".bashrc")
}
func GetLocalWaveFishFilePath() string {
return filepath.Join(wavebase.GetWaveDataDir(), FishIntegrationDir, "wave.fish")
}
func GetLocalWavePowershellEnv() string {
return filepath.Join(wavebase.GetWaveDataDir(), PwshIntegrationDir, "wavepwsh.ps1")
}
func GetLocalZshZDotDir() string {
return filepath.Join(wavebase.GetWaveDataDir(), ZshIntegrationDir)
}
func HasWaveZshHistory() (bool, int64) {
zshDir := GetLocalZshZDotDir()
historyFile := filepath.Join(zshDir, ZshHistoryFileName)
fileInfo, err := os.Stat(historyFile)
if err != nil {
return false, 0
}
return true, fileInfo.Size()
}
func GetBlockZshHistoryDir(blockId string) string {
zshDir := GetLocalZshZDotDir()
return filepath.Join(zshDir, "history", blockId)
}
func CleanupBlockZshHistory(blockId string) error {
histDir := GetBlockZshHistoryDir(blockId)
err := os.RemoveAll(histDir)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("error removing block history dir %s: %w", histDir, err)
}
log.Printf("cleaned up block zsh history dir: %s\n", histDir)
return nil
}
// getPerBlockHistoryFiles returns a list of per-block .zsh_history file paths
func getPerBlockHistoryFiles() []string {
zshDir := GetLocalZshZDotDir()
historyBaseDir := filepath.Join(zshDir, "history")
entries, err := os.ReadDir(historyBaseDir)
if err != nil {
return nil
}
var files []string
for _, entry := range entries {
if !entry.IsDir() {
continue
}
histFile := filepath.Join(historyBaseDir, entry.Name(), ZshHistoryFileName)
if _, err := os.Stat(histFile); err == nil {
files = append(files, histFile)
}
}
return files
}
func IsExtendedZshHistoryFile(fileName string) (bool, error) {
file, err := os.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
defer file.Close()
buf := make([]byte, 1024)
n, err := file.Read(buf)
if err != nil {
return false, err
}
content := string(buf[:n])
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
return ZshExtendedHistoryPattern.MatchString(line), nil
}
return false, nil
}
func GetLocalWshBinaryPath(version string, goos string, goarch string) (string, error) {
ext := ""
if goarch == "amd64" {
goarch = "x64"
}
if goarch == "aarch64" {
goarch = "arm64"
}
if goos == "windows" {
ext = ".exe"
}
if !wavebase.SupportedWshBinaries[fmt.Sprintf("%s-%s", goos, goarch)] {
return "", fmt.Errorf("unsupported wsh platform: %s-%s", goos, goarch)
}
baseName := fmt.Sprintf("wsh-%s-%s.%s%s", version, goos, goarch, ext)
return filepath.Join(wavebase.GetWaveAppBinPath(), baseName), nil
}
// absWshBinDir must be an absolute, expanded path (no ~ or $HOME, etc.)
// it will be hard-quoted appropriately for the shell
func InitRcFiles(waveHome string, absWshBinDir string) error {
// ensure directories exist
zshDir := filepath.Join(waveHome, ZshIntegrationDir)
err := wavebase.CacheEnsureDir(zshDir, ZshIntegrationDir, 0755, ZshIntegrationDir)
if err != nil {
return err
}
bashDir := filepath.Join(waveHome, BashIntegrationDir)
err = wavebase.CacheEnsureDir(bashDir, BashIntegrationDir, 0755, BashIntegrationDir)
if err != nil {
return err
}
fishDir := filepath.Join(waveHome, FishIntegrationDir)
err = wavebase.CacheEnsureDir(fishDir, FishIntegrationDir, 0755, FishIntegrationDir)
if err != nil {
return err
}
pwshDir := filepath.Join(waveHome, PwshIntegrationDir)
err = wavebase.CacheEnsureDir(pwshDir, PwshIntegrationDir, 0755, PwshIntegrationDir)
if err != nil {
return err
}
var pathSep string
if runtime.GOOS == "windows" {
pathSep = ";"
} else {
pathSep = ":"
}
params := map[string]string{
"WSHBINDIR": HardQuote(absWshBinDir),
"WSHBINDIR_PWSH": HardQuotePowerShell(absWshBinDir),
"PATHSEP": pathSep,
}
// write files to directory
err = utilfn.WriteTemplateToFile(filepath.Join(zshDir, ".zprofile"), ZshStartup_Zprofile, params)
if err != nil {
return fmt.Errorf("error writing zsh-integration .zprofile: %v", err)
}
err = utilfn.WriteTemplateToFile(filepath.Join(zshDir, ".zshrc"), ZshStartup_Zshrc, params)
if err != nil {
return fmt.Errorf("error writing zsh-integration .zshrc: %v", err)
}
err = utilfn.WriteTemplateToFile(filepath.Join(zshDir, ".zlogin"), ZshStartup_Zlogin, params)
if err != nil {
return fmt.Errorf("error writing zsh-integration .zlogin: %v", err)
}
err = utilfn.WriteTemplateToFile(filepath.Join(zshDir, ".zshenv"), ZshStartup_Zshenv, params)
if err != nil {
return fmt.Errorf("error writing zsh-integration .zshenv: %v", err)
}
err = utilfn.WriteTemplateToFile(filepath.Join(bashDir, ".bashrc"), BashStartup_Bashrc, params)
if err != nil {
return fmt.Errorf("error writing bash-integration .bashrc: %v", err)
}
err = os.WriteFile(filepath.Join(bashDir, "bash_preexec.sh"), []byte(BashStartup_Preexec), 0644)
if err != nil {
return fmt.Errorf("error writing bash-integration bash_preexec.sh: %v", err)
}
err = utilfn.WriteTemplateToFile(filepath.Join(fishDir, "wave.fish"), FishStartup_Wavefish, params)
if err != nil {
return fmt.Errorf("error writing fish-integration wave.fish: %v", err)
}
err = utilfn.WriteTemplateToFile(filepath.Join(pwshDir, "wavepwsh.ps1"), PwshStartup_wavepwsh, params)
if err != nil {
return fmt.Errorf("error writing pwsh-integration wavepwsh.ps1: %v", err)
}
return nil
}
func initCustomShellStartupFilesInternal() error {
log.Printf("initializing wsh and shell startup files\n")
waveDataHome := wavebase.GetWaveDataDir()
binDir := filepath.Join(waveDataHome, WaveHomeBinDir)
err := InitRcFiles(waveDataHome, binDir)
if err != nil {
return err
}
err = wavebase.CacheEnsureDir(binDir, WaveHomeBinDir, 0755, WaveHomeBinDir)
if err != nil {
return err
}
// copy the correct binary to bin
wshFullPath, err := GetLocalWshBinaryPath(wavebase.WaveVersion, runtime.GOOS, runtime.GOARCH)
if err != nil {
log.Printf("error (non-fatal), could not resolve wsh binary path: %v\n", err)
}
if _, err := os.Stat(wshFullPath); err != nil {
log.Printf("error (non-fatal), could not resolve wsh binary %q: %v\n", wshFullPath, err)
return nil
}
wshDstPath := filepath.Join(binDir, "wsh")
if runtime.GOOS == "windows" {
wshDstPath = wshDstPath + ".exe"
}
err = utilfn.AtomicRenameCopy(wshDstPath, wshFullPath, 0755)
if err != nil {
return fmt.Errorf("error copying wsh binary to bin: %v", err)
}
wshBaseName := filepath.Base(wshFullPath)
log.Printf("wsh binary successfully copied from %q to %q\n", wshBaseName, wshDstPath)
return nil
}
func GetShellTypeFromShellPath(shellPath string) string {
shellBase := filepath.Base(shellPath)
if strings.Contains(shellBase, "bash") {
return ShellType_bash
}
if strings.Contains(shellBase, "zsh") {
return ShellType_zsh
}
if strings.Contains(shellBase, "fish") {
return ShellType_fish
}
if strings.Contains(shellBase, "pwsh") || strings.Contains(shellBase, "powershell") {
return ShellType_pwsh
}
return ShellType_unknown
}
var (
bashVersionRegexp = regexp.MustCompile(`\bversion\s+(\d+\.\d+)`)
zshVersionRegexp = regexp.MustCompile(`\bzsh\s+(\d+\.\d+)`)
fishVersionRegexp = regexp.MustCompile(`\bversion\s+(\d+\.\d+)`)
pwshVersionRegexp = regexp.MustCompile(`(?:PowerShell\s+)?(\d+\.\d+)`)
)
func DetectShellTypeAndVersion() (string, string, error) {
shellPath := DetectLocalShellPath()
return DetectShellTypeAndVersionFromPath(shellPath)
}
func DetectShellTypeAndVersionFromPath(shellPath string) (string, string, error) {
shellType := GetShellTypeFromShellPath(shellPath)
if shellType == ShellType_unknown {
return shellType, "", fmt.Errorf("unknown shell type: %s", shellPath)
}
shellBase := filepath.Base(shellPath)
if shellType == ShellType_pwsh && strings.Contains(shellBase, "powershell") && !strings.Contains(shellBase, "pwsh") {
return "powershell", "", nil
}
version, err := getShellVersion(shellPath, shellType)
if err != nil {
return shellType, "", err
}
return shellType, version, nil
}
func getShellVersion(shellPath string, shellType string) (string, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second)
defer cancelFn()
var cmd *exec.Cmd
var versionRegex *regexp.Regexp
switch shellType {
case ShellType_bash:
cmd = exec.CommandContext(ctx, shellPath, "--version")
versionRegex = bashVersionRegexp
case ShellType_zsh:
cmd = exec.CommandContext(ctx, shellPath, "--version")
versionRegex = zshVersionRegexp
case ShellType_fish:
cmd = exec.CommandContext(ctx, shellPath, "--version")
versionRegex = fishVersionRegexp
case ShellType_pwsh:
cmd = exec.CommandContext(ctx, shellPath, "--version")
versionRegex = pwshVersionRegexp
default:
return "", fmt.Errorf("unsupported shell type: %s", shellType)
}
output, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("failed to get version for %s: %w", shellType, err)
}
outputStr := strings.TrimSpace(string(output))
matches := versionRegex.FindStringSubmatch(outputStr)
if len(matches) < 2 {
return "", fmt.Errorf("failed to parse version from output: %q", outputStr)
}
return matches[1], nil
}
func FixupWaveZshHistory() error {
if runtime.GOOS != "darwin" {
return nil
}
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error getting home directory: %w", err)
}
realHistFile := filepath.Join(homeDir, ".zsh_history")
// Collect all history files to merge (legacy wave history + per-block histories)
var histFilesToMerge []string
// Check for legacy wave zsh history file
zshDir := GetLocalZshZDotDir()
waveHistFile := filepath.Join(zshDir, ZshHistoryFileName)
if fileInfo, err := os.Stat(waveHistFile); err == nil && fileInfo.Size() > 0 {
histFilesToMerge = append(histFilesToMerge, waveHistFile)
} else if err == nil && fileInfo.Size() == 0 {
// remove empty file
os.Remove(waveHistFile)
}
// Collect per-block history files
perBlockFiles := getPerBlockHistoryFiles()
histFilesToMerge = append(histFilesToMerge, perBlockFiles...)
if len(histFilesToMerge) == 0 {
return nil
}
log.Printf("merging %d wave zsh history file(s) into ~/.zsh_history\n", len(histFilesToMerge))
isExtended, err := IsExtendedZshHistoryFile(realHistFile)
if err != nil {
return fmt.Errorf("error checking if history is extended: %w", err)
}
hasExtendedStr := "false"
if isExtended {
hasExtendedStr = "true"
}
// Build fc -RI commands for each history file
var fcCommands string
for _, hf := range histFilesToMerge {
quotedFile := utilfn.ShellQuote(hf, true, -1)
fcCommands += fmt.Sprintf("\t\tfc -RI %s\n", quotedFile)
}
script := fmt.Sprintf(`
HISTFILE=~/.zsh_history
HISTSIZE=999999
SAVEHIST=999999
has_extended_history=%s
[[ $has_extended_history == true ]] && setopt EXTENDED_HISTORY
fc -RI
%s fc -W
`, hasExtendedStr, fcCommands)
ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelFn()
cmd := exec.CommandContext(ctx, "zsh", "-f", "-i", "-c", script)
cmd.Stdin = nil
envStr := envutil.SliceToEnv(os.Environ())
envStr = envutil.RmEnv(envStr, "ZDOTDIR")
cmd.Env = envutil.EnvToSlice(envStr)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error executing zsh history fixup script: %w, output: %s", err, string(output))
}
// Clean up merged history files
for _, hf := range histFilesToMerge {
err = os.Remove(hf)
if err != nil {
log.Printf("error removing wave zsh history file %s: %v\n", hf, err)
}
}
// Remove empty per-block history directories
historyBaseDir := filepath.Join(zshDir, "history")
entries, err := os.ReadDir(historyBaseDir)
if err == nil {
for _, entry := range entries {
if entry.IsDir() {
blockDir := filepath.Join(historyBaseDir, entry.Name())
os.Remove(blockDir) // only removes if empty
}
}
}
log.Printf("successfully merged %d wave zsh history file(s) into ~/.zsh_history\n", len(histFilesToMerge))
return nil
}
func GetTerminalResetSeq() string {
resetSeq := "\x1b[0m" // reset attributes
resetSeq += "\x1b[?25h" // show cursor
resetSeq += "\x1b[?1l" // normal cursor keys
resetSeq += "\x1b[?7h" // wraparound on
resetSeq += "\x1b[?45l" // reverse wraparound off
resetSeq += "\x1b[?66l" // application keypad off (DECNKM)
resetSeq += "\x1b[4l" // insert mode off (IRM)
resetSeq += "\x1b[?9l" // X10 mouse tracking off
resetSeq += "\x1b[?1000l" // disable Send Mouse X & Y on button press
resetSeq += "\x1b[?1002l" // disable Use Cell Motion Mouse Tracking
resetSeq += "\x1b[?1003l" // disable Use All Motion Mouse Tracking
resetSeq += "\x1b[?1004l" // disable Send FocusIn/FocusOut events
resetSeq += "\x1b[?1006l" // disable Enable SGR Mouse Mode
resetSeq += "\x1b[?1007l" // disable Enable Alternate Scroll Mode
resetSeq += "\x1b[?2004l" // disable bracketed paste mode
resetSeq += "\x1b[?2026l" // synchronized output off
resetSeq += FormatOSC(16162, "R") // disable alternate screen mode
return resetSeq
}
func FormatOSC(oscNum int, parts ...string) string {
if len(parts) == 0 {
return fmt.Sprintf("\x1b]%d\x07", oscNum)
}
return fmt.Sprintf("\x1b]%d;%s\x07", oscNum, strings.Join(parts, ";"))
}