51 lines
1.3 KiB
JavaScript
51 lines
1.3 KiB
JavaScript
/**
|
|
* Cached `git status -sb` for the system prompt. Spawn is optional so Node tests
|
|
* can inject a runner.
|
|
*/
|
|
|
|
const TTL_MS = 30000;
|
|
|
|
const cache = { cwd: '', at: 0, text: '' };
|
|
|
|
function formatStatus(stdout, stderr) {
|
|
const body = String(stdout || '').trim() || String(stderr || '').trim();
|
|
if (!body) return '';
|
|
if (/not a git repository/i.test(body)) return '';
|
|
const lines = body.split('\n').slice(0, 40);
|
|
return '[git status]\n' + lines.join('\n');
|
|
}
|
|
|
|
async function gitStatusSb(cwd, opts) {
|
|
opts = opts || {};
|
|
if (!cwd || opts.hostWorkspace === false) return '';
|
|
if (cache.cwd === cwd && Date.now() - cache.at < (opts.ttlMs || TTL_MS)) return cache.text;
|
|
const run = opts.run;
|
|
if (typeof run !== 'function') {
|
|
cache.cwd = cwd;
|
|
cache.at = Date.now();
|
|
cache.text = '';
|
|
return '';
|
|
}
|
|
try {
|
|
const out = await run(cwd, 'git status -sb', opts.timeoutMs || 8000);
|
|
const text = formatStatus(out && out.stdout, out && out.stderr);
|
|
cache.cwd = cwd;
|
|
cache.at = Date.now();
|
|
cache.text = text;
|
|
return text;
|
|
} catch (_) {
|
|
cache.cwd = cwd;
|
|
cache.at = Date.now();
|
|
cache.text = '';
|
|
return '';
|
|
}
|
|
}
|
|
|
|
function resetCache() {
|
|
cache.cwd = '';
|
|
cache.at = 0;
|
|
cache.text = '';
|
|
}
|
|
|
|
module.exports = { TTL_MS, formatStatus, gitStatusSb, resetCache };
|