Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1130 lines (1075 loc) · 33.7 KB
/
Copy pathmain.go
File metadata and controls
1130 lines (1075 loc) · 33.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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// backscroll — never lose a command's output again.
//
// Records every command you run (output, exit code, cwd, timing) into a
// local SQLite database, segmented via OSC 133 shell-integration marks,
// and makes it all searchable.
package main
import (
_ "embed"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime/debug"
"strconv"
"strings"
"time"
"golang.org/x/term"
"github.com/soren-achebe/backscroll/internal/ansi"
"github.com/soren-achebe/backscroll/internal/diff"
"github.com/soren-achebe/backscroll/internal/record"
"github.com/soren-achebe/backscroll/internal/redact"
"github.com/soren-achebe/backscroll/internal/store"
)
var version = "dev"
// resolvedVersion returns the release version stamped by goreleaser, falling
// back to the module version recorded by `go install ...@version`.
func resolvedVersion() string {
if version != "dev" {
return version
}
if bi, ok := debug.ReadBuildInfo(); ok && bi.Main.Version != "" && bi.Main.Version != "(devel)" {
return strings.TrimPrefix(bi.Main.Version, "v")
}
return version
}
//go:embed shell/backscroll.zsh
var zshInit string
//go:embed shell/backscroll.bash
var bashInit string
//go:embed shell/backscroll.fish
var fishInit string
//go:embed shell/backscroll.ps1
var pwshInit string
//go:embed shell/backscroll.tmux
var tmuxInit string
//go:embed shell/backscroll.kdl
var zellijInit string
//go:embed shell/backscroll.screen
var screenInit string
const usage = `backscroll — never lose a command's output again
Usage:
backscroll run start a recorded shell session
backscroll exec <cmd> [args] run one command and record its output,
exit code, cwd and timing — no session
needed (cron jobs, CI steps, builds).
Output passes through, exit code is
mirrored. --quiet records silently
backscroll init <bash|zsh|fish|pwsh>
print shell-integration snippet
(add: eval "$(backscroll init zsh)" to rc;
fish: backscroll init fish | source;
pwsh: backscroll init pwsh | Out-String | Invoke-Expression);
also: init tmux|zellij|screen picker binds
backscroll list [-n N] recent commands; filter with --cwd DIR,
--exit CODE|fail, --since 2h|3d|1w|DATE,
--session ID, --host NAME|local
backscroll show [id | -N] full stored output (default: last command)
-2 = one before last, etc. --raw keeps colors
backscroll last [-n N] alias for list
backscroll search <query> full-text search over commands + outputs
(same filters as list: --cwd --exit --since)
-C/-A/-B N: grep-style context lines around
each matching output line (-C 0 = matches only)
backscroll pick [query] interactive fuzzy picker (needs fzf) with
live output preview; enter = view output.
--pager for tmux/zellij popups, --print-id,
--print-cmd; same filters as list
backscroll diff <a> [b] diff two stored outputs (ids or -N offsets);
with one arg, diffs against the previous run
of the same command ("what changed?")
backscroll export [id|-N ...] share a command + its output:
--format md (default: paste into an issue),
cast (asciinema v2), json. --details folds
long md output; -o FILE writes to a file
backscroll import <source> seed the DB from history you already have:
atuin (times/exits/cwd/host), zsh, bash,
fish. Re-running only adds new entries;
--dry-run previews, [path] overrides the
default location
backscroll stats database statistics; --by cmd|cwd|exit|host|day
breaks history down (counts, fail%, total
time), same filters as list — e.g.
stats --by cmd --exit fail --since 1w
backscroll note [id|-N] <text> attach a note to a command ("this is the
one that fixed it"); notes show up in
list/show/search and are searchable.
No text prints the note, --rm removes it
backscroll prune --older 30d delete old entries
backscroll delete <id> delete one entry
backscroll redact <id|-N ...> permanently mask secrets (tokens, keys,
passwords) in stored entries; --dry-run
previews. show/search/export take --redact
backscroll sync <subcommand> cross-machine sync via a shared folder,
end-to-end encrypted, no server needed:
init <dir>, export, import, status
(backscroll sync --help for details)
backscroll mcp Model Context Protocol server over stdio:
lets AI coding agents search your history
and read command outputs. Secrets are
redacted by default (--no-redact opts out)
backscroll serve local web UI: browse + search your history
in the browser, colors preserved, diffs.
Loopback-only by default (127.0.0.1:4133);
read-only; --redact masks secrets
backscroll off | on pause / resume recording (this session)
backscroll doctor check that everything is set up correctly
backscroll doctor --reindex rebuild the full-text search index
backscroll upgrade update this binary to the latest release
(checksum-verified; --check only reports;
refuses brew/scoop/deb-managed installs)
backscroll version print version
Ignore patterns: one Go regexp per line in ~/.config/backscroll/ignore —
matching commands are never stored (see 'backscroll doctor' for the path).
Extra redact patterns: one Go regexp per line in ~/.config/backscroll/redact.
Data lives in ~/.local/share/backscroll/backscroll.db (override: $BACKSCROLL_DB).
Everything is local; nothing ever leaves your machine. The one exception is
'backscroll upgrade', which contacts github.com when — and only when — you run it.
`
func main() {
if len(os.Args) < 2 {
fmt.Print(usage)
os.Exit(0)
}
cmd, args := os.Args[1], os.Args[2:]
var err error
switch cmd {
case "run":
err = cmdRun(args)
case "exec":
err = cmdExec(args)
case "init":
err = cmdInit(args)
case "list", "last":
err = cmdList(args)
case "show":
err = cmdShow(args)
case "search":
err = cmdSearch(args)
case "pick":
err = cmdPick(args)
case "diff":
err = cmdDiff(args)
case "export":
err = cmdExport(args)
case "import":
err = cmdImport(args)
case "stats":
err = cmdStats(args)
case "prune":
err = cmdPrune(args)
case "note":
err = cmdNote(args)
case "delete":
err = cmdDelete(args)
case "redact":
err = cmdRedact(args)
case "sync":
err = cmdSync(args)
case "mcp":
err = cmdMCP(args)
case "serve", "web":
err = cmdServe(args)
case "off", "on":
err = cmdToggle(cmd)
case "doctor":
err = cmdDoctor(args)
case "upgrade":
err = cmdUpgrade(args)
case "version", "--version", "-v":
fmt.Println("backscroll", resolvedVersion())
case "help", "--help", "-h":
fmt.Print(usage)
default:
fmt.Fprintf(os.Stderr, "backscroll: unknown command %q\n\n%s", cmd, usage)
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "backscroll:", err)
os.Exit(1)
}
}
func openStore() (*store.Store, error) { return store.Open() }
func cmdRun(args []string) error {
fs := flag.NewFlagSet("run", flag.ExitOnError)
head := fs.Int("head-cap", 256<<10, "max bytes kept from start of each command's output")
tail := fs.Int("tail-cap", 1<<20, "max bytes kept from end of each command's output")
login := fs.Bool("login", false, "spawn the shell as a login shell (note: a login bash does not read ~/.bashrc)")
fs.BoolVar(login, "l", *login, "shorthand for --login")
fs.Parse(args)
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
err = record.Run(st, *head, *tail, *login)
var ee *exec.ExitError
if errors.As(err, &ee) {
st.Close()
os.Exit(ee.ExitCode()) // mirror the shell's exit status silently
}
return err
}
func cmdInit(args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: backscroll init <bash|zsh|fish|pwsh|tmux|zellij|screen>")
}
switch args[0] {
case "zsh":
fmt.Print(zshInit)
case "bash":
fmt.Print(bashInit)
case "fish":
fmt.Print(fishInit)
case "pwsh", "powershell":
fmt.Print(pwshInit)
case "tmux":
fmt.Print(tmuxInit)
case "zellij":
fmt.Print(zellijInit)
case "screen":
fmt.Print(screenInit)
default:
return fmt.Errorf("unsupported target %q (bash, zsh, fish, pwsh, tmux, zellij, screen)", args[0])
}
return nil
}
func fmtDur(d time.Duration) string {
switch {
case d < time.Second:
return fmt.Sprintf("%dms", d.Milliseconds())
case d < time.Minute:
return fmt.Sprintf("%.1fs", d.Seconds())
default:
return d.Round(time.Second).String()
}
}
// fmtSpan renders a command's wall time, or "" when the end (or start)
// is unknown — e.g. entries imported from shell history files.
func fmtSpan(c store.Command) string {
if c.EndedAt.IsZero() || c.StartedAt.IsZero() || c.StartedAt.Unix() <= 0 || c.EndedAt.Before(c.StartedAt) {
return ""
}
return fmtDur(c.EndedAt.Sub(c.StartedAt))
}
// fmtWhen renders an absolute timestamp, or "time unknown" for entries
// whose source had no timestamps (plain bash history imports).
func fmtWhen(t time.Time) string {
if t.IsZero() || t.Unix() <= 0 {
return "time unknown"
}
return t.Format("2006-01-02 15:04:05")
}
func fmtAgo(t time.Time) string {
if t.IsZero() || t.Unix() <= 0 {
return "unknown"
}
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
return fmt.Sprintf("%dm ago", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%dh ago", int(d.Hours()))
default:
return t.Format("Jan 02 15:04")
}
}
func exitStr(c store.Command) string {
if !c.ExitCode.Valid {
return "?"
}
return strconv.FormatInt(c.ExitCode.Int64, 10)
}
// filterFlags registers the shared list/search filter flags on fs and
// returns a func that builds the store.Filter after fs.Parse.
func filterFlags(fs *flag.FlagSet) func(limit int) (store.Filter, error) {
sess := fs.Int64("session", 0, "only this session id")
cwd := fs.String("cwd", "", "only commands run in `dir` (or beneath it); \".\" = current dir")
exit := fs.String("exit", "", "only exit `code` (number, or \"fail\" for any nonzero)")
since := fs.String("since", "", "only commands newer than `t` (30m, 2h, 3d, 1w, or 2006-01-02[ 15:04])")
until := fs.String("until", "", "only commands older than `t` (same forms as --since; exclusive bound)")
host := fs.String("host", "", "only commands from this `host` (synced machines; \"local\" = this machine)")
return func(limit int) (store.Filter, error) {
f := store.Filter{Session: *sess, Limit: limit, Host: *host}
if *cwd != "" {
abs, err := filepath.Abs(*cwd)
if err != nil {
return f, err
}
f.Cwd = filepath.Clean(abs)
}
switch {
case *exit == "":
case *exit == "fail" || *exit == "nonzero":
f.Failed = true
default:
n, err := strconv.ParseInt(*exit, 10, 64)
if err != nil {
return f, fmt.Errorf("--exit: want a number or \"fail\", got %q", *exit)
}
f.Exit, f.ExitSet = n, true
}
if *since != "" {
t, err := parseTimeSpec(*since)
if err != nil {
return f, fmt.Errorf("--since: %w", err)
}
f.Since = t
}
if *until != "" {
t, err := parseTimeSpec(*until)
if err != nil {
return f, fmt.Errorf("--until: %w", err)
}
f.Until = t
}
return f, nil
}
}
// splitFlags separates registered flags (with their values) from positional
// words so filters can trail the query: `search boom --since 1d` works the
// same as `search --since 1d boom`. A dash-word that is not a registered
// flag stays positional (queries may contain dashes); everything after a
// bare "--" is positional.
func splitFlags(fs *flag.FlagSet, args []string) (flags, pos []string) {
for i := 0; i < len(args); i++ {
a := args[i]
if a == "--" {
pos = append(pos, args[i+1:]...)
break
}
if strings.HasPrefix(a, "-") && a != "-" {
name := strings.TrimLeft(a, "-")
if eq := strings.IndexByte(name, '='); eq >= 0 {
name = name[:eq]
}
if fl := fs.Lookup(name); fl != nil {
flags = append(flags, a)
if !strings.Contains(a, "=") {
b, ok := fl.Value.(interface{ IsBoolFlag() bool })
if !(ok && b.IsBoolFlag()) && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
}
continue
}
}
pos = append(pos, a)
}
return flags, pos
}
// parseTimeSpec accepts a relative age (30m, 2h, 3d, 1w — d/w extend Go
// durations) or an absolute local date/time (2006-01-02, 2006-01-02 15:04).
// Relative forms mean "that long ago", so --until 2h reads "older than two
// hours" and --since 2h "newer than two hours".
func parseTimeSpec(s string) (time.Time, error) {
for _, layout := range []string{"2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02"} {
if t, err := time.ParseInLocation(layout, s, time.Local); err == nil {
return t, nil
}
}
ds := s
if n := len(s); n > 1 {
switch s[n-1] {
case 'd':
if v, err := strconv.ParseFloat(s[:n-1], 64); err == nil {
return time.Now().Add(-time.Duration(v * 24 * float64(time.Hour))), nil
}
case 'w':
if v, err := strconv.ParseFloat(s[:n-1], 64); err == nil {
return time.Now().Add(-time.Duration(v * 7 * 24 * float64(time.Hour))), nil
}
}
}
if d, err := time.ParseDuration(ds); err == nil {
return time.Now().Add(-d), nil
}
return time.Time{}, fmt.Errorf("want 30m, 2h, 3d, 1w or 2006-01-02[ 15:04], got %q", s)
}
func cmdList(args []string) error {
fs := flag.NewFlagSet("list", flag.ExitOnError)
n := fs.Int("n", 20, "number of entries")
mkFilter := filterFlags(fs)
fs.Parse(args)
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
f, err := mkFilter(*n)
if err != nil {
return err
}
cmds, err := st.List(f)
if err != nil {
return err
}
if len(cmds) == 0 {
if f.Active() {
fmt.Println("no commands match those filters")
} else {
fmt.Println("no recorded commands yet — start a session with: backscroll run")
}
return nil
}
color := term.IsTerminal(int(os.Stdout.Fd()))
for i := len(cmds) - 1; i >= 0; i-- {
c := cmds[i]
mark := "✓"
if c.ExitCode.Valid && c.ExitCode.Int64 != 0 {
mark = "✗"
}
line := fmt.Sprintf("%5d %s %-12s %8s %8s %s%s",
c.ID, mark, fmtAgo(c.StartedAt), fmtSpan(c),
humanBytes(c.OutputLen), hostTag(c, color), oneLine(c.Cmd, 80))
if color && mark == "✗" {
line = "\x1b[31m" + line + "\x1b[0m"
}
fmt.Println(line)
if c.Note != "" {
n := " ✎ " + oneLine(c.Note, 100)
if color {
n = "\x1b[33m" + n + "\x1b[0m"
}
fmt.Println(n)
}
}
return nil
}
// hostTag renders a "[host] " prefix for entries imported from another
// machine via sync ("" for local ones).
func hostTag(c store.Command, color bool) string {
if c.Local() || c.Host == "" {
return ""
}
if color {
return "\x1b[35m[" + c.Host + "]\x1b[0m "
}
return "[" + c.Host + "] "
}
func oneLine(s string, max int) string {
s = strings.ReplaceAll(s, "\n", " ⏎ ")
if len(s) > max {
s = s[:max-1] + "…"
}
return s
}
func humanBytes(n int64) string {
switch {
case n < 1<<10:
return fmt.Sprintf("%dB", n)
case n < 1<<20:
return fmt.Sprintf("%.1fKB", float64(n)/(1<<10))
default:
return fmt.Sprintf("%.1fMB", float64(n)/(1<<20))
}
}
func cmdShow(args []string) error {
fs := flag.NewFlagSet("show", flag.ExitOnError)
raw := fs.Bool("raw", false, "keep ANSI colors / control sequences")
quiet := fs.Bool("q", false, "output only, no header")
doRedact := fs.Bool("redact", false, "mask secrets (tokens, keys, passwords) in the output")
// allow "show -2" style (bare -N = Nth from last) and flags in any
// position ("show 5 -q"): split flags from positionals ourselves.
// All show flags are booleans, so this is safe.
var target int64 = -1
var flags, pos []string
for _, a := range args {
if len(a) > 1 && a[0] == '-' {
if n, err := strconv.ParseInt(a, 10, 64); err == nil {
target = n
continue
}
flags = append(flags, a)
continue
}
pos = append(pos, a)
}
fs.Parse(append(flags, pos...))
if fs.NArg() > 0 {
n, err := strconv.ParseInt(fs.Arg(0), 10, 64)
if err != nil {
return fmt.Errorf("bad id %q", fs.Arg(0))
}
target = n
}
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
c, err := st.Get(target)
if err != nil {
return fmt.Errorf("not found (%v)", err)
}
if *doRedact {
extra := redact.LoadExtra()
c.Cmd, _ = redact.String(c.Cmd, extra)
c.Note, _ = redact.String(c.Note, extra)
}
if !*quiet {
fmt.Printf("\x1b[1m$ %s\x1b[0m\n", c.Cmd)
from := ""
if !c.Local() && c.Host != "" {
from = " · from " + c.Host
}
when := fmtWhen(c.StartedAt)
took := ""
if sp := fmtSpan(*c); sp != "" {
took = " · took " + sp
}
sess := ""
if c.SessionID > 0 {
sess = fmt.Sprintf(" · session #%d", c.SessionID)
}
fmt.Printf("\x1b[2m# id %d%s · %s · cwd %s · exit %s%s · %s%s\x1b[0m\n",
c.ID, sess, when, c.Cwd, exitStr(*c),
took, humanBytes(c.OutputLen), from)
if strings.HasPrefix(c.Machine, "hist:") {
fmt.Printf("\x1b[2m# imported from shell history (%s) — no output was recorded\x1b[0m\n",
strings.TrimPrefix(c.Machine, "hist:"))
}
if c.Note != "" {
fmt.Printf("\x1b[33m# note: %s\x1b[0m\n", c.Note)
}
}
out := c.Output
if !*raw {
out = ansi.Strip(out)
}
if *doRedact {
out, _ = redact.Bytes(out, redact.LoadExtra())
}
os.Stdout.Write(out)
if len(out) > 0 && out[len(out)-1] != '\n' {
fmt.Println()
}
return nil
}
func cmdSearch(args []string) error {
fs := flag.NewFlagSet("search", flag.ExitOnError)
n := fs.Int("n", 20, "max results")
doRedact := fs.Bool("redact", false, "mask secrets in displayed commands and snippets")
ctxC := fs.Int("C", -1, "show N lines of context around each matching output line (like grep -C)")
ctxA := fs.Int("A", -1, "show N lines after each matching output line (like grep -A)")
ctxB := fs.Int("B", -1, "show N lines before each matching output line (like grep -B)")
mkFilter := filterFlags(fs)
flagArgs, posArgs := splitFlags(fs, args)
fs.Parse(flagArgs)
if len(posArgs) == 0 {
return fmt.Errorf("usage: backscroll search <query> [flags]")
}
query := strings.Join(posArgs, " ")
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
f, err := mkFilter(*n)
if err != nil {
return err
}
res, err := st.Search(query, f)
if err != nil {
return err
}
if len(res) == 0 {
fmt.Println("no matches")
return nil
}
var extra []*regexp.Regexp
if *doRedact {
extra = redact.LoadExtra()
}
ctxMode := *ctxC >= 0 || *ctxA >= 0 || *ctxB >= 0
before, after := *ctxB, *ctxA
if before < 0 {
before = max(*ctxC, 0)
}
if after < 0 {
after = max(*ctxC, 0)
}
for _, c := range res {
cmd, snip := c.Cmd, strings.TrimSpace(c.Snippet)
if *doRedact {
cmd, _ = redact.String(cmd, extra)
// drop the FTS highlight escapes first: a secret split by
// them would otherwise slip past the redaction patterns
snip, _ = redact.String(string(ansi.Strip([]byte(snip))), extra)
}
fmt.Printf("\x1b[1m%5d\x1b[0m %s exit %s %s\x1b[36m%s\x1b[0m\n",
c.ID, fmtAgo(c.StartedAt), exitStr(c), hostTag(c, true), oneLine(cmd, 70))
if ctxMode {
printSearchContext(st, c, query, before, after, *doRedact, extra)
continue
}
if snip != "" {
fmt.Printf(" %s\n", oneLine(snip, 100))
}
}
fmt.Printf("\n(%d results — `backscroll show <id>` for full output)\n", len(res))
return nil
}
// printSearchContext renders grep-style context hunks from a result's
// stored plain output under its search headline (search -A/-B/-C).
// Redaction runs on the whole text BEFORE matching and highlighting, so
// highlight escapes can never split a secret past the redact patterns.
func printSearchContext(st *store.Store, c store.Command, query string, before, after int, doRedact bool, extra []*regexp.Regexp) {
const maxHunks = 5
text, err := st.Plain(c.ID)
if err != nil || text == "" {
return
}
if doRedact {
text, _ = redact.String(text, extra)
}
hunks, shown, total := grepContext(text, query, before, after, maxHunks)
for hi, h := range hunks {
if hi > 0 {
fmt.Println(" \x1b[2m--\x1b[0m")
}
for i, ln := range h.Lines {
lineNo := h.Start + i + 1
if h.IsMatch[i] {
clipped := clipLine(ln, matchOffset(ln, query), 140)
fmt.Printf(" \x1b[32m%5d\x1b[0m:%s\n", lineNo,
highlightMatches(clipped, query, "\x1b[1;31m", "\x1b[0m"))
} else {
fmt.Printf(" \x1b[2m%5d-%s\x1b[0m\n", lineNo, clipLine(ln, 0, 140))
}
}
}
if total > shown {
fmt.Printf(" \x1b[2m(%d more matching lines — backscroll show %d | grep …)\x1b[0m\n", total-shown, c.ID)
}
}
func parseDur(s string) (time.Duration, error) {
if strings.HasSuffix(s, "d") {
n, err := strconv.Atoi(strings.TrimSuffix(s, "d"))
if err != nil {
return 0, err
}
return time.Duration(n) * 24 * time.Hour, nil
}
return time.ParseDuration(s)
}
func cmdPrune(args []string) error {
fs := flag.NewFlagSet("prune", flag.ExitOnError)
older := fs.String("older", "90d", "delete entries older than this (e.g. 30d, 12h)")
maxSize := fs.String("max-size", "", "then delete oldest entries until the DB fits under this size (e.g. 500M, 2G)")
fs.Parse(args)
olderSet := false
fs.Visit(func(f *flag.Flag) {
if f.Name == "older" {
olderSet = true
}
})
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
// With only --max-size given, don't silently apply the 90d default too.
if olderSet || *maxSize == "" {
d, err := parseDur(*older)
if err != nil {
return err
}
n, err := st.Prune(d)
if err != nil {
return err
}
fmt.Printf("deleted %d entries older than %s\n", n, *older)
}
if *maxSize != "" {
limit, err := parseSize(*maxSize)
if err != nil {
return err
}
n, err := st.PruneToSize(limit)
if err != nil {
return err
}
fmt.Printf("deleted %d oldest entries to fit under %s\n", n, *maxSize)
}
return nil
}
// parseSize parses a human size like "500M", "2G", "1.5g", "300000" (bytes).
// Suffixes K/M/G/T are binary (1024-based); an optional trailing B/iB is
// accepted ("500MB", "2GiB").
func parseSize(s string) (int64, error) {
t := strings.TrimSpace(strings.ToUpper(s))
t = strings.TrimSuffix(t, "IB")
t = strings.TrimSuffix(t, "B")
mult := int64(1)
if n := len(t); n > 0 {
switch t[n-1] {
case 'K':
mult, t = 1<<10, t[:n-1]
case 'M':
mult, t = 1<<20, t[:n-1]
case 'G':
mult, t = 1<<30, t[:n-1]
case 'T':
mult, t = 1<<40, t[:n-1]
}
}
v, err := strconv.ParseFloat(strings.TrimSpace(t), 64)
if err != nil || v < 0 {
return 0, fmt.Errorf("invalid size %q (use e.g. 500M, 2G)", s)
}
return int64(v * float64(mult)), nil
}
// cmdNote attaches a searchable annotation to a stored command:
//
// backscroll note "this fixed it" → note on the last command
// backscroll note -3 "the broken run" → note on the 3rd-from-last
// backscroll note 1052 "keeper" → note by absolute id
// backscroll note 1052 → print the note
// backscroll note 1052 --rm → remove it
func cmdNote(args []string) error {
rm := false
target := int64(-1)
targetSet := false
var words []string
for _, a := range args {
switch {
case a == "--rm" || a == "-rm":
rm = true
case a == "--help" || a == "-h":
fmt.Println("usage: backscroll note [id|-N] [text ...] | --rm")
return nil
case !targetSet && len(words) == 0 && isIntArg(a):
n, _ := strconv.ParseInt(a, 10, 64)
target = n
targetSet = true
default:
words = append(words, a)
}
}
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
c, err := st.Get(target)
if err != nil {
return fmt.Errorf("not found (%v)", err)
}
switch {
case rm:
if err := st.SetNote(c.ID, ""); err != nil {
return err
}
fmt.Printf("removed note from entry %d\n", c.ID)
case len(words) == 0:
if c.Note == "" {
fmt.Printf("entry %d has no note (add one: backscroll note %d \"text\")\n", c.ID, c.ID)
} else {
fmt.Println(c.Note)
}
default:
note := strings.Join(words, " ")
if err := st.SetNote(c.ID, note); err != nil {
return err
}
fmt.Printf("noted entry %d (%s): %s\n", c.ID, oneLine(c.Cmd, 40), note)
}
return nil
}
// isIntArg reports whether a parses as a (possibly negative) integer —
// an id or -N offset rather than note text.
func isIntArg(a string) bool {
_, err := strconv.ParseInt(a, 10, 64)
return err == nil
}
func cmdDelete(args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: backscroll delete <id>")
}
id, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return err
}
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
if err := st.Delete(id); err != nil {
return err
}
fmt.Printf("deleted entry %d\n", id)
return nil
}
// cmdRedact permanently scrubs secrets from stored entries: the command
// line, the raw output, and the search index are all rewritten in place.
func cmdRedact(args []string) error {
fs := flag.NewFlagSet("redact", flag.ExitOnError)
dry := fs.Bool("dry-run", false, "report what would be masked without changing the store")
var flags, pos []string
for _, a := range args {
if _, err := strconv.ParseInt(a, 10, 64); err == nil {
pos = append(pos, a) // ids and -N offsets, flags may interleave
continue
}
flags = append(flags, a)
}
fs.Parse(flags)
pos = append(pos, fs.Args()...)
if len(pos) == 0 {
return fmt.Errorf("usage: backscroll redact [--dry-run] <id|-N> [...]\n" +
"permanently masks secrets in stored entries (see also: show --redact, export --redact)")
}
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
extra := redact.LoadExtra()
for _, p := range pos {
n, _ := strconv.ParseInt(p, 10, 64)
c, err := st.Get(n)
if err != nil {
return fmt.Errorf("%s: not found (%v)", p, err)
}
newCmd, hitsCmd := redact.String(c.Cmd, extra)
newOut, hitsOut := redact.Bytes(c.Output, extra)
newNote, hitsNote := redact.String(c.Note, extra)
hits := hitsCmd + hitsOut + hitsNote
if hits == 0 {
fmt.Printf("entry %d: nothing to redact\n", c.ID)
continue
}
if *dry {
fmt.Printf("entry %d: would mask %d secret(s)\n", c.ID, hits)
continue
}
plain := string(ansi.Strip(newOut))
if err := st.UpdateOutput(c.ID, newCmd, newOut, plain); err != nil {
return fmt.Errorf("entry %d: %v", c.ID, err)
}
if hitsNote > 0 {
if err := st.SetNote(c.ID, newNote); err != nil {
return fmt.Errorf("entry %d: %v", c.ID, err)
}
}
fmt.Printf("entry %d: masked %d secret(s)\n", c.ID, hits)
}
return nil
}
func cmdToggle(which string) error {
if os.Getenv("BACKSCROLL_ACTIVE") == "" {
return fmt.Errorf("not inside a backscroll session (start one with: backscroll run)")
}
// The recorder watches the PTY stream, so an in-band private OSC
// sequence is all it takes — no sockets, no signals.
fmt.Printf("\x1b]6973;rec=%s\x07", which)
if which == "off" {
fmt.Println("backscroll: recording paused for this session (resume: backscroll on)")
} else {
fmt.Println("backscroll: recording resumed")
}
return nil
}
// rcFor maps $SHELL to its rc file and the hook line to add. A "" rc
// means the shell needs no snippet at all (it emits OSC 133 natively).
func rcFor(shell string) (rc string, hook string) {
home, _ := os.UserHomeDir()
base := filepath.Base(shell)
switch {
case base == "nu" || base == "nushell":
return "", "" // nushell emits OSC 133 + OSC 7 by default
case strings.Contains(shell, "zsh"):
return home + "/.zshrc", `eval "$(backscroll init zsh)"`
case strings.Contains(shell, "fish"):
return home + "/.config/fish/config.fish", `backscroll init fish | source`
default:
return home + "/.bashrc", `eval "$(backscroll init bash)"`
}
}
func cmdDoctor(args []string) error {
if len(args) == 1 && args[0] == "--reindex" {
st, err := openStore()
if err != nil {
return err
}
defer st.Close()
fmt.Println("rebuilding full-text index from stored outputs…")
if err := st.RebuildFTS(); err != nil {
return err
}
fmt.Println("done.")
return nil
}
ok := func(b bool) string {
if b {
return "\x1b[32m✓\x1b[0m"
}
return "\x1b[31m✗\x1b[0m"
}
fmt.Println("backscroll doctor")
fmt.Println("─────────────────")
fmt.Printf("version : %s\n", resolvedVersion())
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/bash"
}
fmt.Printf("shell : %s\n", shell)
inSession := os.Getenv("BACKSCROLL_ACTIVE") != ""
fmt.Printf("%s inside a backscroll session", ok(inSession))
if !inSession {
fmt.Print(" → start one: backscroll run")
}
fmt.Println()
hooked := os.Getenv("BACKSCROLL_HOOKED") != ""
rc, hookLine := rcFor(shell)
if inSession {
fmt.Printf("%s shell integration active in this session\n", ok(hooked || rc == ""))
}
rcHasHook := rc == "" // zero-config shells count as hooked
if rc == "" {
fmt.Printf("%s shell emits OSC 133 natively — zero-config, no snippet needed\n", ok(true))
} else {
if b, err := os.ReadFile(rc); err == nil {
rcHasHook = strings.Contains(string(b), "backscroll init")
}
fmt.Printf("%s rc file references backscroll (%s)", ok(rcHasHook), rc)
if !rcHasHook {
fmt.Printf("\n → add: %s", hookLine)
}
fmt.Println()
}
st, err := openStore()
fmt.Printf("%s database opens (%s)", ok(err == nil), store.DefaultPath())
if err != nil {