forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompletionCache.ts
More file actions
166 lines (149 loc) · 5.52 KB
/
completionCache.ts
File metadata and controls
166 lines (149 loc) · 5.52 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
import chalk from 'chalk'
import { mkdir, readFile, writeFile } from 'fs/promises'
import { homedir } from 'os'
import { dirname, join } from 'path'
import { pathToFileURL } from 'url'
import { color } from '../components/design-system/color.js'
import { supportsHyperlinks } from '../ink/supports-hyperlinks.js'
import { logForDebugging } from './debug.js'
import { isENOENT } from './errors.js'
import { execFileNoThrow } from './execFileNoThrow.js'
import { logError } from './log.js'
import type { ThemeName } from './theme.js'
const EOL = '\n'
type ShellInfo = {
name: string
rcFile: string
cacheFile: string
completionLine: string
shellFlag: string
}
function detectShell(): ShellInfo | null {
const shell = process.env.SHELL || ''
const home = homedir()
const claudeDir = join(home, '.claude')
if (shell.endsWith('/zsh') || shell.endsWith('/zsh.exe')) {
const cacheFile = join(claudeDir, 'completion.zsh')
return {
name: 'zsh',
rcFile: join(home, '.zshrc'),
cacheFile,
completionLine: `[[ -f "${cacheFile}" ]] && source "${cacheFile}"`,
shellFlag: 'zsh',
}
}
if (shell.endsWith('/bash') || shell.endsWith('/bash.exe')) {
const cacheFile = join(claudeDir, 'completion.bash')
return {
name: 'bash',
rcFile: join(home, '.bashrc'),
cacheFile,
completionLine: `[ -f "${cacheFile}" ] && source "${cacheFile}"`,
shellFlag: 'bash',
}
}
if (shell.endsWith('/fish') || shell.endsWith('/fish.exe')) {
const xdg = process.env.XDG_CONFIG_HOME || join(home, '.config')
const cacheFile = join(claudeDir, 'completion.fish')
return {
name: 'fish',
rcFile: join(xdg, 'fish', 'config.fish'),
cacheFile,
completionLine: `[ -f "${cacheFile}" ] && source "${cacheFile}"`,
shellFlag: 'fish',
}
}
return null
}
function formatPathLink(filePath: string): string {
if (!supportsHyperlinks()) {
return filePath
}
const fileUrl = pathToFileURL(filePath).href
return `\x1b]8;;${fileUrl}\x07${filePath}\x1b]8;;\x07`
}
/**
* Generate and cache the completion script, then add a source line to the
* shell's rc file. Returns a user-facing status message.
*/
export async function setupShellCompletion(theme: ThemeName): Promise<string> {
const shell = detectShell()
if (!shell) {
return ''
}
// Ensure the cache directory exists
try {
await mkdir(dirname(shell.cacheFile), { recursive: true })
} catch (e: unknown) {
logError(e)
return `${EOL}${color('warning', theme)(`Could not write ${shell.name} completion cache`)}${EOL}${chalk.dim(`Run manually: claude completion ${shell.shellFlag} > ${shell.cacheFile}`)}${EOL}`
}
// Generate the completion script by writing directly to the cache file.
// Using --output avoids piping through stdout where process.exit() can
// truncate output before the pipe buffer drains.
const claudeBin = process.argv[1] || 'claude'
const result = await execFileNoThrow(claudeBin, [
'completion',
shell.shellFlag,
'--output',
shell.cacheFile,
])
if (result.code !== 0) {
return `${EOL}${color('warning', theme)(`Could not generate ${shell.name} shell completions`)}${EOL}${chalk.dim(`Run manually: claude completion ${shell.shellFlag} > ${shell.cacheFile}`)}${EOL}`
}
// Check if rc file already sources completions
let existing = ''
try {
existing = await readFile(shell.rcFile, { encoding: 'utf-8' })
if (
existing.includes('claude completion') ||
existing.includes(shell.cacheFile)
) {
return `${EOL}${color('success', theme)(`Shell completions updated for ${shell.name}`)}${EOL}${chalk.dim(`See ${formatPathLink(shell.rcFile)}`)}${EOL}`
}
} catch (e: unknown) {
if (!isENOENT(e)) {
logError(e)
return `${EOL}${color('warning', theme)(`Could not install ${shell.name} shell completions`)}${EOL}${chalk.dim(`Add this to ${formatPathLink(shell.rcFile)}:`)}${EOL}${chalk.dim(shell.completionLine)}${EOL}`
}
}
// Append source line to rc file
try {
const configDir = dirname(shell.rcFile)
await mkdir(configDir, { recursive: true })
const separator = existing && !existing.endsWith('\n') ? '\n' : ''
const content = `${existing}${separator}\n# Claude Code shell completions\n${shell.completionLine}\n`
await writeFile(shell.rcFile, content, { encoding: 'utf-8' })
return `${EOL}${color('success', theme)(`Installed ${shell.name} shell completions`)}${EOL}${chalk.dim(`Added to ${formatPathLink(shell.rcFile)}`)}${EOL}${chalk.dim(`Run: source ${shell.rcFile}`)}${EOL}`
} catch (error) {
logError(error)
return `${EOL}${color('warning', theme)(`Could not install ${shell.name} shell completions`)}${EOL}${chalk.dim(`Add this to ${formatPathLink(shell.rcFile)}:`)}${EOL}${chalk.dim(shell.completionLine)}${EOL}`
}
}
/**
* Regenerate cached shell completion scripts in ~/.claude/.
* Called after `claude update` so completions stay in sync with the new binary.
*/
export async function regenerateCompletionCache(): Promise<void> {
const shell = detectShell()
if (!shell) {
return
}
logForDebugging(`update: Regenerating ${shell.name} completion cache`)
const claudeBin = process.argv[1] || 'claude'
const result = await execFileNoThrow(claudeBin, [
'completion',
shell.shellFlag,
'--output',
shell.cacheFile,
])
if (result.code !== 0) {
logForDebugging(
`update: Failed to regenerate ${shell.name} completion cache`,
)
return
}
logForDebugging(
`update: Regenerated ${shell.name} completion cache at ${shell.cacheFile}`,
)
}