Repository navigation
Expand file tree
/
Copy pathpick.go
More file actions
194 lines (180 loc) · 4.74 KB
/
Copy pathpick.go
File metadata and controls
194 lines (180 loc) · 4.74 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
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"github.com/soren-achebe/backscroll/internal/ansi"
"github.com/soren-achebe/backscroll/internal/redact"
)
// cmdPick opens an interactive fuzzy picker (fzf) over recorded commands,
// with a live preview of each command's stored output. On selection the
// output is printed (or paged with --pager, handy inside a tmux popup).
func cmdPick(args []string) error {
fs := flag.NewFlagSet("pick", flag.ExitOnError)
n := fs.Int("n", 1000, "max entries offered to the picker")
pager := fs.Bool("pager", false, "view the selected output in a pager (less -R)")
raw := fs.Bool("raw", false, "keep ANSI colors / control sequences")
printID := fs.Bool("print-id", false, "print only the selected entry's id")
printCmd := fs.Bool("print-cmd", false, "print only the selected command line")
doRedact := fs.Bool("redact", false, "mask secrets (tokens, keys, passwords) in the output")
mkFilter := filterFlags(fs)
flagArgs, posArgs := splitFlags(fs, args)
fs.Parse(flagArgs)
initial := strings.Join(posArgs, " ")
fzf, err := exec.LookPath("fzf")
if err != nil {
return fmt.Errorf("'pick' needs fzf on your PATH (https://github.com/junegunn/fzf — most package managers have it)")
}
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 {
return fmt.Errorf("no recorded commands yet — start a session with: backscroll run")
}
var b strings.Builder
for _, c := range cmds { // newest first; --tiebreak=index keeps that order
mark := "\x1b[32m✓\x1b[0m"
if c.ExitCode.Valid && c.ExitCode.Int64 != 0 {
mark = "\x1b[31m✗\x1b[0m"
} else if !c.ExitCode.Valid {
mark = "?"
}
cmdText := c.Cmd
if *doRedact {
cmdText, _ = redact.String(cmdText, redact.LoadExtra())
}
fmt.Fprintf(&b, "%d\t\x1b[2m%-12s\x1b[0m %s %s%s\n",
c.ID, fmtAgo(c.StartedAt), mark, hostTag(c, true), oneLine(cmdText, 300))
}
self, err := os.Executable()
if err != nil {
self = "backscroll"
}
preview := shellQuote(self) + " show --raw"
if *doRedact {
preview += " --redact"
}
preview += " {1}"
fzfArgs := []string{
"--ansi",
"--delimiter=\t",
"--with-nth=2..",
"--no-sort",
"--tiebreak=index",
"--layout=reverse",
"--preview=" + preview,
"--preview-window=down,65%,wrap",
"--header=enter: view output · esc: cancel",
"--prompt=backscroll> ",
}
if initial != "" {
fzfArgs = append(fzfArgs, "--query="+initial)
}
pick := exec.Command(fzf, fzfArgs...)
pick.Stdin = strings.NewReader(b.String())
pick.Stderr = os.Stderr // fzf draws its UI on the tty
sel, err := pick.Output()
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) && (ee.ExitCode() == 1 || ee.ExitCode() == 130) {
return nil // no match / cancelled — not an error
}
return fmt.Errorf("fzf: %w", err)
}
idStr, _, _ := strings.Cut(strings.TrimSpace(string(sel)), "\t")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil || id <= 0 {
return nil
}
switch {
case *printID:
fmt.Println(id)
return nil
case *printCmd:
c, err := st.Get(id)
if err != nil {
return err
}
cmdText := c.Cmd
if *doRedact {
cmdText, _ = redact.String(cmdText, redact.LoadExtra())
}
fmt.Println(cmdText)
return nil
}
c, err := st.Get(id)
if err != nil {
return err
}
cmdText := c.Cmd
if *doRedact {
cmdText, _ = redact.String(cmdText, redact.LoadExtra())
}
header := fmt.Sprintf("\x1b[1m$ %s\x1b[0m\n\x1b[2m# id %d · %s · cwd %s · exit %s · took %s · %s\x1b[0m\n",
cmdText, c.ID, fmtWhen(c.StartedAt), c.Cwd, exitStr(*c),
fmtSpan(*c), humanBytes(c.OutputLen))
out := c.Output
if *pager {
*raw = true // the pager handles colors; keep them
}
if !*raw {
out = ansi.Strip(out)
}
if *doRedact {
out, _ = redact.Bytes(out, redact.LoadExtra())
}
if *pager {
return runPager(header, out)
}
fmt.Print(header)
os.Stdout.Write(out)
if len(out) > 0 && out[len(out)-1] != '\n' {
fmt.Println()
}
return nil
}
// runPager pipes header+out through $BACKSCROLL_PAGER / $PAGER / less -R.
func runPager(header string, out []byte) error {
pagerCmd := os.Getenv("BACKSCROLL_PAGER")
if pagerCmd == "" {
pagerCmd = os.Getenv("PAGER")
}
if pagerCmd == "" {
pagerCmd = "less -R"
}
p := exec.Command("sh", "-c", pagerCmd)
pw, err := p.StdinPipe()
if err != nil {
return err
}
p.Stdout = os.Stdout
p.Stderr = os.Stderr
if err := p.Start(); err != nil {
return err
}
io.WriteString(pw, header)
pw.Write(out)
if len(out) > 0 && out[len(out)-1] != '\n' {
io.WriteString(pw, "\n")
}
pw.Close()
return p.Wait()
}
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}