File size: 5,309 Bytes
064bfd6 | 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 | import chokidar, { type FSWatcher } from 'chokidar'
import { isAbsolute, join } from 'path'
import { registerCleanup } from '../cleanupRegistry.js'
import { logForDebugging } from '../debug.js'
import { errorMessage } from '../errors.js'
import {
executeCwdChangedHooks,
executeFileChangedHooks,
type HookOutsideReplResult,
} from '../hooks.js'
import { clearCwdEnvFiles } from '../sessionEnvironment.js'
import { getHooksConfigFromSnapshot } from './hooksConfigSnapshot.js'
let watcher: FSWatcher | null = null
let currentCwd: string
let dynamicWatchPaths: string[] = []
let dynamicWatchPathsSorted: string[] = []
let initialized = false
let hasEnvHooks = false
let notifyCallback: ((text: string, isError: boolean) => void) | null = null
export function setEnvHookNotifier(
cb: ((text: string, isError: boolean) => void) | null,
): void {
notifyCallback = cb
}
export function initializeFileChangedWatcher(cwd: string): void {
if (initialized) return
initialized = true
currentCwd = cwd
const config = getHooksConfigFromSnapshot()
hasEnvHooks =
(config?.CwdChanged?.length ?? 0) > 0 ||
(config?.FileChanged?.length ?? 0) > 0
if (hasEnvHooks) {
registerCleanup(async () => dispose())
}
const paths = resolveWatchPaths(config)
if (paths.length === 0) return
startWatching(paths)
}
function resolveWatchPaths(
config?: ReturnType<typeof getHooksConfigFromSnapshot>,
): string[] {
const matchers = (config ?? getHooksConfigFromSnapshot())?.FileChanged ?? []
// Matcher field: filenames to watch in cwd, pipe-separated (e.g. ".envrc|.env")
const staticPaths: string[] = []
for (const m of matchers) {
if (!m.matcher) continue
for (const name of m.matcher.split('|').map(s => s.trim())) {
if (!name) continue
staticPaths.push(isAbsolute(name) ? name : join(currentCwd, name))
}
}
// Combine static matcher paths with dynamic paths from hook output
return [...new Set([...staticPaths, ...dynamicWatchPaths])]
}
function startWatching(paths: string[]): void {
logForDebugging(`FileChanged: watching ${paths.length} paths`)
watcher = chokidar.watch(paths, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 200 },
ignorePermissionErrors: true,
})
watcher.on('change', p => handleFileEvent(p, 'change'))
watcher.on('add', p => handleFileEvent(p, 'add'))
watcher.on('unlink', p => handleFileEvent(p, 'unlink'))
}
function handleFileEvent(
path: string,
event: 'change' | 'add' | 'unlink',
): void {
logForDebugging(`FileChanged: ${event} ${path}`)
void executeFileChangedHooks(path, event)
.then(({ results, watchPaths, systemMessages }) => {
if (watchPaths.length > 0) {
updateWatchPaths(watchPaths)
}
for (const msg of systemMessages) {
notifyCallback?.(msg, false)
}
for (const r of results) {
if (!r.succeeded && r.output) {
notifyCallback?.(r.output, true)
}
}
})
.catch(e => {
const msg = errorMessage(e)
logForDebugging(`FileChanged hook failed: ${msg}`, {
level: 'error',
})
notifyCallback?.(msg, true)
})
}
export function updateWatchPaths(paths: string[]): void {
if (!initialized) return
const sorted = paths.slice().sort()
if (
sorted.length === dynamicWatchPathsSorted.length &&
sorted.every((p, i) => p === dynamicWatchPathsSorted[i])
) {
return
}
dynamicWatchPaths = paths
dynamicWatchPathsSorted = sorted
restartWatching()
}
function restartWatching(): void {
if (watcher) {
void watcher.close()
watcher = null
}
const paths = resolveWatchPaths()
if (paths.length > 0) {
startWatching(paths)
}
}
export async function onCwdChangedForHooks(
oldCwd: string,
newCwd: string,
): Promise<void> {
if (oldCwd === newCwd) return
// Re-evaluate from the current snapshot so mid-session hook changes are picked up
const config = getHooksConfigFromSnapshot()
const currentHasEnvHooks =
(config?.CwdChanged?.length ?? 0) > 0 ||
(config?.FileChanged?.length ?? 0) > 0
if (!currentHasEnvHooks) return
currentCwd = newCwd
await clearCwdEnvFiles()
const hookResult = await executeCwdChangedHooks(oldCwd, newCwd).catch(e => {
const msg = errorMessage(e)
logForDebugging(`CwdChanged hook failed: ${msg}`, {
level: 'error',
})
notifyCallback?.(msg, true)
return {
results: [] as HookOutsideReplResult[],
watchPaths: [] as string[],
systemMessages: [] as string[],
}
})
dynamicWatchPaths = hookResult.watchPaths
dynamicWatchPathsSorted = hookResult.watchPaths.slice().sort()
for (const msg of hookResult.systemMessages) {
notifyCallback?.(msg, false)
}
for (const r of hookResult.results) {
if (!r.succeeded && r.output) {
notifyCallback?.(r.output, true)
}
}
// Re-resolve matcher paths against the new cwd
if (initialized) {
restartWatching()
}
}
function dispose(): void {
if (watcher) {
void watcher.close()
watcher = null
}
dynamicWatchPaths = []
dynamicWatchPathsSorted = []
initialized = false
hasEnvHooks = false
notifyCallback = null
}
export function resetFileChangedWatcherForTesting(): void {
dispose()
}
|