Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
358 lines (318 loc) · 12 KB
/
Copy pathmain.go
File metadata and controls
358 lines (318 loc) · 12 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
package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/creack/pty"
"golang.org/x/term"
)
// defaultExcludeDirs lists directories that hold generated or vendored files
// rather than project sources. Walking them wastes time, and on macOS it also
// wastes file descriptors: fsnotify watches through kqueue, which costs one
// descriptor per watched directory. An Xcode tree alone (DerivedData, Pods)
// reaches hundreds of thousands of directories and exhausts the system file
// table.
//
// An entry with no "/" matches any directory of that name. An entry with a "/"
// matches a relative path suffix, so ".claude/worktrees" excludes the linked
// git worktrees Claude Code creates without excluding ".claude" itself.
//
// loadGitIgnoredDirs does not cover these. It reads only the ignored entries of
// the working tree it runs in, and ".claude/worktrees" is untracked rather than
// ignored, so it never appears in that list. The walk then descends into each
// linked worktree, whose own .gitignore the outer command never consults.
var defaultExcludeDirs = []string{
// version control
".git", ".hg", ".svn",
// vendored dependencies
"vendor", "node_modules", "Pods", "Carthage", ".venv", "venv",
// build output
"DerivedData", "build", ".build", "dist", "target", ".gradle", ".next", ".nuxt",
// caches
"__pycache__", ".cache", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".terraform",
// linked git worktrees created by tooling
".claude/worktrees", ".worktrees",
}
const usage = `Usage: osc8wrap [options] <command> [args...]
<other command> | osc8wrap [options]
osc8wrap sessions [--format FMT] [query...]
osc8wrap open <id> [--print]
osc8wrap preview <id> [query...]
Subcommands:
sessions List every Claude Code session on this machine, the
ones running under osc8wrap and the finished ones,
as records for a fuzzy picker such as fzf.
Recognized only as the first non-flag argument, so
"osc8wrap -- sessions" still wraps a command that is
itself named "sessions".
See "osc8wrap sessions --help".
open <id> Open one of those sessions: jump to its window if it
is still running, or resume it with "claude --resume"
if it has finished. <id> is field 2 of a "sessions"
record. See "osc8wrap open --help".
preview <id> [query...] Render one session for a picker's preview pane.
See "osc8wrap preview --help".
Options:
--scheme=NAME URL scheme for file links (default: file)
Can also be set via OSC8WRAP_SCHEME env var
Examples: file, vscode, cursor, zed
--terminator=TYPE OSC8 string terminator (default: st)
Can also be set via OSC8WRAP_TERMINATOR env var
st: ESC \ (ECMA-48 standard)
bel: BEL 0x07 (legacy xterm)
--domains=LIST Comma-separated domains to linkify without https://
(default: github.com, env: OSC8WRAP_DOMAINS)
--github-org=NAME GitHub organization for repo#number references
Can also be set via OSC8WRAP_GITHUB_ORG
--no-resolve-basename Disable basename resolution (default: enabled)
Can also be set via OSC8WRAP_NO_RESOLVE_BASENAME=1
--exclude-dir=DIR,... Directories to exclude from search (replaces defaults)
Defaults cover version control, vendored dependencies
(node_modules, Pods, vendor), build output
(DerivedData, build, dist, target) and caches.
A name matches any directory so named; a value with a
"/" matches a relative path suffix, as in
".claude/worktrees".
Can also be set via OSC8WRAP_EXCLUDE_DIRS
OSC8WRAP_MAX_WATCHES=N Cap on directories watched for changes
(default: 10000, env var only)
On macOS each watch costs a file descriptor, so this
bounds what an unexpected tree can consume. Reaching
it prints one warning and stops adding watches; the
fix is usually --exclude-dir, not a bigger cap.
--no-symbol-links Disable symbol linking (default: enabled when scheme != file)
Can also be set via OSC8WRAP_NO_SYMBOL_LINKS=1
--debug-writes Log each Write call to a temp file (path printed to stderr)
Examples:
osc8wrap go build ./...
osc8wrap --scheme=cursor grep -rn "TODO" .
grep -rn "TODO" . | osc8wrap
osc8wrap sessions
`
func main() {
os.Exit(run())
}
func run() int {
opts, cmdArgs, sawDoubleDash := parseArgs(os.Args[1:])
if runCommand, ok := lookupSubcommand(cmdArgs, sawDoubleDash); ok {
return runCommand(cmdArgs[1:])
}
hostname, _ := os.Hostname()
cwd, _ := os.Getwd()
opts.Output = os.Stdout
opts.Cwd = cwd
opts.Hostname = hostname
scratchpad := newSessionScratchpad()
opts.Scratchpad = scratchpad
linker := NewLinker(opts)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go linker.StartIndexer(ctx)
if len(cmdArgs) == 0 {
if term.IsTerminal(int(os.Stdin.Fd())) {
fmt.Fprint(os.Stderr, usage)
return 1
}
if err := runPipeMode(linker); err != nil {
fmt.Fprintf(os.Stderr, "osc8wrap: %v\n", err)
return 1
}
return 0
}
exitCode, err := runPTYMode(linker, cmdArgs, scratchpad)
if err != nil {
fmt.Fprintf(os.Stderr, "osc8wrap: %v\n", err)
}
return exitCode
}
// subcommands maps a subcommand name to its implementation, which receives the
// arguments after the name and returns the process exit code. Every name here
// must also appear in usage; TestSubcommandsAreDocumented enforces that.
var subcommands = map[string]func([]string) int{
"sessions": runSessionsCommand,
"open": runOpenCommand,
"preview": runPreviewCommand,
}
// lookupSubcommand reports whether the boundary parseArgs found starts a
// subcommand rather than a command to wrap, and returns its implementation.
// Reusing parseArgs' boundary is what keeps the two from disagreeing: a
// mistyped option before a subcommand still produces parseArgs' "unknown
// option" error rather than being silently dropped.
//
// An explicit "--" always introduces a command, so "osc8wrap -- sessions"
// still wraps a program that is itself named "sessions".
func lookupSubcommand(cmdArgs []string, sawDoubleDash bool) (func([]string) int, bool) {
if sawDoubleDash || len(cmdArgs) == 0 {
return nil, false
}
run, ok := subcommands[cmdArgs[0]]
return run, ok
}
func parseArgs(args []string) (opts LinkerOptions, cmdArgs []string, sawDoubleDash bool) {
opts.GitHubOrg = os.Getenv("OSC8WRAP_GITHUB_ORG")
opts.Scheme = os.Getenv("OSC8WRAP_SCHEME")
opts.Terminator = os.Getenv("OSC8WRAP_TERMINATOR")
opts.Domains = []string{"github.com"}
if env := os.Getenv("OSC8WRAP_DOMAINS"); env != "" {
opts.Domains = splitComma(env)
}
opts.ResolveBasename = os.Getenv("OSC8WRAP_NO_RESOLVE_BASENAME") != "1"
opts.ExcludeDirs = defaultExcludeDirs
if env := os.Getenv("OSC8WRAP_EXCLUDE_DIRS"); env != "" {
opts.ExcludeDirs = splitComma(env)
}
// An unparsable or non-positive value leaves MaxWatches at 0, which
// NewFileIndex reads as the default. A typo must not lift the cap.
if n, err := strconv.Atoi(os.Getenv("OSC8WRAP_MAX_WATCHES")); err == nil && n > 0 {
opts.MaxWatches = n
}
noSymbolLinks := os.Getenv("OSC8WRAP_NO_SYMBOL_LINKS") == "1"
for i, arg := range args {
if v, ok := strings.CutPrefix(arg, "--scheme="); ok {
opts.Scheme = v
} else if v, ok := strings.CutPrefix(arg, "--terminator="); ok {
opts.Terminator = v
} else if v, ok := strings.CutPrefix(arg, "--domains="); ok {
opts.Domains = splitComma(v)
} else if v, ok := strings.CutPrefix(arg, "--github-org="); ok {
opts.GitHubOrg = v
} else if arg == "--no-resolve-basename" {
opts.ResolveBasename = false
} else if v, ok := strings.CutPrefix(arg, "--exclude-dir="); ok {
opts.ExcludeDirs = splitComma(v)
} else if arg == "--no-symbol-links" {
noSymbolLinks = true
} else if arg == "--debug-writes" {
opts.DebugWrites = true
} else if arg == "--" {
cmdArgs = args[i+1:]
sawDoubleDash = true
break
} else if strings.HasPrefix(arg, "-") {
fmt.Fprintf(os.Stderr, "unknown option: %s\n", arg)
fmt.Fprint(os.Stderr, usage)
os.Exit(1)
} else {
cmdArgs = args[i:]
break
}
}
scheme := opts.Scheme
if scheme == "" {
scheme = "file"
}
opts.SymbolLinks = scheme != "file" && !noSymbolLinks
return
}
func splitComma(s string) []string {
if s == "" {
return nil
}
parts := strings.Split(s, ",")
result := make([]string, 0, len(parts))
for _, p := range parts {
if t := strings.TrimSpace(p); t != "" {
result = append(result, t)
}
}
return result
}
func runPipeMode(linker *Linker) error {
if _, err := io.Copy(linker, os.Stdin); err != nil {
return err
}
return linker.Flush()
}
func runPTYMode(linker *Linker, cmdArgs []string, scratchpad *sessionScratchpad) (int, error) {
cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
ptmx, err := pty.Start(cmd)
if err != nil {
return 1, fmt.Errorf("failed to start pty: %w", err)
}
defer ptmx.Close() //nolint:errcheck
scratchpad.setChildPID(cmd.Process.Pid)
// Publishing the session is a convenience for `osc8wrap sessions`; it must
// never keep the wrapped command from running, so errors are dropped.
unregister := registerCurrentSession(cmd, cmdArgs)
defer unregister()
handleResize(ptmx)
forwardSignals(cmd)
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err == nil {
defer func() {
_, _ = os.Stdout.WriteString("\033[0m")
_ = term.Restore(int(os.Stdin.Fd()), oldState)
}()
}
go func() { _, _ = io.Copy(ptmx, os.Stdin) }()
if _, err := io.Copy(linker, ptmx); err != nil {
return 1, err
}
if err := linker.Flush(); err != nil {
return 1, err
}
_ = cmd.Wait()
if cmd.ProcessState != nil {
return cmd.ProcessState.ExitCode(), nil
}
return 0, nil
}
// registerCurrentSession records this wrapper in the session registry and
// returns the (idempotent) cleanup that removes it again. Every input is best
// effort: a session with no tty or no Ghostty surface is still worth listing,
// and a registry that cannot be written at all costs the user nothing but the
// `sessions` listing.
func registerCurrentSession(cmd *exec.Cmd, cmdArgs []string) func() {
if cmd.Process == nil {
return func() {}
}
// os.Stdout, not the pty we just created: the registry records the
// terminal emulator's own device, which is what a navigator can address.
tty, _ := ttyPath(os.Stdout)
cwd, _ := os.Getwd()
cleanup, _ := registerSession(RegistryEntry{
WrapperPID: os.Getpid(),
ChildPID: cmd.Process.Pid,
TTY: tty,
SurfaceID: ghosttySurfaceID(),
Cwd: cwd,
Command: cmdArgs,
StartedAt: time.Now(),
})
return cleanup
}
func handleResize(ptmx *os.File) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGWINCH)
go func() {
for range ch {
_ = pty.InheritSize(os.Stdin, ptmx)
}
}()
ch <- syscall.SIGWINCH
}
// forwardSignals relays SIGINT and SIGTERM to the wrapped command. Installing
// a handler disables the default terminate action, so the wrapper survives the
// signal and keeps wrapping: the registry entry must stay, and it is the
// deferred unregister on the way out (plus loadRegistry's pruning of dead
// wrapper pids) that removes it. Unregistering here would erase a live session
// from `osc8wrap sessions` for the rest of its life, since nothing
// re-registers.
func forwardSignals(cmd *exec.Cmd) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
go func() {
for sig := range ch {
if cmd.Process != nil {
_ = cmd.Process.Signal(sig)
}
}
}()
}