hopdeck 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/bin/hopdeck.js +716 -342
- package/lib/atomic.js +57 -0
- package/lib/background.js +67 -0
- package/lib/clipboard.js +41 -0
- package/lib/config.js +22 -0
- package/lib/deepsearch.js +34 -23
- package/lib/executable.js +27 -12
- package/lib/git.js +34 -2
- package/lib/history.js +273 -68
- package/lib/i18n.js +36 -4
- package/lib/image-worker.js +76 -0
- package/lib/images.js +24 -5
- package/lib/input.js +55 -0
- package/lib/links.js +16 -8
- package/lib/lru.js +39 -0
- package/lib/profile.js +48 -0
- package/lib/provider-setup.js +1 -0
- package/lib/provider.js +3 -6
- package/lib/style.js +14 -4
- package/lib/text.js +16 -5
- package/lib/textfile.js +18 -0
- package/lib/tmux.js +22 -0
- package/lib/windows-terminal.js +11 -5
- package/lib/winshell.js +21 -0
- package/lib/wsl.js +15 -0
- package/package.json +2 -1
package/lib/atomic.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { randomBytes } = require('crypto');
|
|
5
|
+
|
|
6
|
+
function writeJsonAtomic(file, value, { mode = 0o600, space, rename = fs.renameSync, platform = process.platform } = {}) {
|
|
7
|
+
const json = JSON.stringify(value, null, space);
|
|
8
|
+
writeAtomic(file, json, mode, rename, platform);
|
|
9
|
+
return Buffer.byteLength(json);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function writeAtomic(file, data, mode, rename = fs.renameSync, platform = process.platform) {
|
|
13
|
+
const temp = `${file}.${process.pid}.${randomBytes(12).toString('hex')}.tmp`;
|
|
14
|
+
const fd = fs.openSync(temp, 'wx', mode);
|
|
15
|
+
try {
|
|
16
|
+
try { fs.writeFileSync(fd, data); } finally { fs.closeSync(fd); }
|
|
17
|
+
for (let attempt = 0; ; attempt++) {
|
|
18
|
+
try { rename(temp, file); break; }
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (platform !== 'win32' || attempt >= 4 || !['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) throw error;
|
|
21
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10 * (attempt + 1));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
} catch (error) {
|
|
25
|
+
try { fs.unlinkSync(temp); } catch { /* */ }
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readJsonSafe(file, onCorrupt) {
|
|
31
|
+
let raw;
|
|
32
|
+
try { raw = fs.readFileSync(file); }
|
|
33
|
+
catch (error) { return { value: undefined, status: error.code === 'ENOENT' ? 'missing' : 'corrupt' }; }
|
|
34
|
+
try { return { value: JSON.parse(raw), status: 'ok' }; }
|
|
35
|
+
catch { onCorrupt?.(raw); return { value: undefined, status: 'corrupt' }; }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function backupCorrupt(file, bad) {
|
|
39
|
+
const prefix = path.basename(file) + '.corrupt-', dir = path.dirname(file);
|
|
40
|
+
const backups = () => fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && /^\d{13}(?:-[a-f0-9]+)?$/.test(name.slice(prefix.length))).sort().reverse();
|
|
41
|
+
const previous = backups();
|
|
42
|
+
const existing = previous.some((name) => {
|
|
43
|
+
try { return fs.readFileSync(path.join(dir, name)).equals(bad); }
|
|
44
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; return false; }
|
|
45
|
+
});
|
|
46
|
+
if (!existing) {
|
|
47
|
+
// Publish the backup atomically as well, so a partial copy never counts as a backup.
|
|
48
|
+
const timestamp = Math.max(Date.now(), Number(previous[0]?.slice(prefix.length, prefix.length + 13) || 0) + 1);
|
|
49
|
+
const dest = `${file}.corrupt-${timestamp}-${randomBytes(6).toString('hex')}`;
|
|
50
|
+
writeAtomic(dest, bad, 0o600);
|
|
51
|
+
}
|
|
52
|
+
for (const name of backups().slice(3)) {
|
|
53
|
+
try { fs.unlinkSync(path.join(dir, name)); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = { writeJsonAtomic, readJsonSafe, backupCorrupt };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function createBackground({ reload, git, poll, working, reloadMs, interval = setInterval, timeout = setTimeout,
|
|
4
|
+
cancelInterval = clearInterval, cancelTimeout = clearTimeout }) {
|
|
5
|
+
let focused = true, started = false, pollTimer, pollMs, timers = [];
|
|
6
|
+
const deferred = new Set();
|
|
7
|
+
const periodic = (fn) => { if (focused) fn(); else deferred.add(fn); };
|
|
8
|
+
function schedulePoll() {
|
|
9
|
+
if (!started || !poll) return;
|
|
10
|
+
const ms = focused || working() ? 400 : 1000;
|
|
11
|
+
if (pollTimer && ms === pollMs) return;
|
|
12
|
+
if (pollTimer) cancelTimeout(pollTimer);
|
|
13
|
+
pollMs = ms;
|
|
14
|
+
pollTimer = timeout(() => { pollTimer = null; poll(); schedulePoll(); }, ms);
|
|
15
|
+
pollTimer.unref?.();
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
get focused() { return focused; },
|
|
19
|
+
start() {
|
|
20
|
+
started = true;
|
|
21
|
+
timers = [[reload, reloadMs], [git, 4000]].filter(([fn]) => fn).map(([fn, ms]) => {
|
|
22
|
+
const timer = interval(() => periodic(fn), ms); timer.unref?.(); return timer;
|
|
23
|
+
});
|
|
24
|
+
schedulePoll();
|
|
25
|
+
},
|
|
26
|
+
focus(value) {
|
|
27
|
+
if (focused === value) return false;
|
|
28
|
+
focused = value; schedulePoll();
|
|
29
|
+
const reloaded = value && deferred.has(reload);
|
|
30
|
+
if (value) { for (const fn of deferred) fn(true); deferred.clear(); }
|
|
31
|
+
return reloaded;
|
|
32
|
+
},
|
|
33
|
+
update: schedulePoll,
|
|
34
|
+
close() {
|
|
35
|
+
started = false;
|
|
36
|
+
for (const timer of timers) cancelInterval(timer);
|
|
37
|
+
if (pollTimer) cancelTimeout(pollTimer);
|
|
38
|
+
pollTimer = null; timers = []; deferred.clear();
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function coalesceMouse(send, timeout = setTimeout, cancel = clearTimeout) {
|
|
44
|
+
let timer;
|
|
45
|
+
const queue = [];
|
|
46
|
+
const motion = ([b, , , type]) => type === 'M' && (b & 96) === 32;
|
|
47
|
+
function drain() {
|
|
48
|
+
while (queue.length && !motion(queue[0])) send(...queue.shift());
|
|
49
|
+
if (queue.length && !timer) {
|
|
50
|
+
timer = timeout(() => { timer = null; send(...queue.shift()); drain(); }, 16);
|
|
51
|
+
timer.unref?.();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const push = (...event) => {
|
|
55
|
+
const previous = queue.at(-1);
|
|
56
|
+
if (motion(event) && previous && motion(previous)) {
|
|
57
|
+
// Un arrastre que vuelve al punto inicial sigue siendo un arrastre.
|
|
58
|
+
event[4] = previous[4] || event[1] !== previous[1] || event[2] !== previous[2];
|
|
59
|
+
queue[queue.length - 1] = event;
|
|
60
|
+
} else queue.push(event);
|
|
61
|
+
drain();
|
|
62
|
+
};
|
|
63
|
+
push.close = () => { if (timer) cancel(timer); timer = null; queue.length = 0; };
|
|
64
|
+
return push;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
module.exports = { createBackground, coalesceMouse };
|
package/lib/clipboard.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const cp = require('child_process');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const { isWSL } = require('./wsl');
|
|
5
|
+
|
|
6
|
+
const supportsOsc52 = (env) => !!(env.WT_SESSION || env.KITTY_WINDOW_ID || env.WEZTERM_PANE ||
|
|
7
|
+
/^(iTerm.app|WezTerm|ghostty|vscode|tmux)$/.test(env.TERM_PROGRAM || '') ||
|
|
8
|
+
/^(xterm-kitty|xterm-ghostty|alacritty|foot(?:-extra)?|tmux(?:-256color)?)$/.test(env.TERM || ''));
|
|
9
|
+
|
|
10
|
+
/** Copia al portapapeles. OSC 52 es de mejor esfuerzo y no tiene confirmación. */
|
|
11
|
+
async function copyText(t, { platform = process.platform, env = process.env, spawn = cp.spawn, stdout = process.stdout, wsl = isWSL } = {}) {
|
|
12
|
+
if (env.HOPDECK_COPY_LOG) {
|
|
13
|
+
try { fs.appendFileSync(env.HOPDECK_COPY_LOG, JSON.stringify(t) + '\n'); return 'ok'; } catch { return 'failed'; }
|
|
14
|
+
}
|
|
15
|
+
// OSC 52 se envía siempre (sirve también por SSH); solo cuenta como copiado en terminales que se sabe que lo admiten.
|
|
16
|
+
let osc = false;
|
|
17
|
+
if (stdout.isTTY) {
|
|
18
|
+
try { stdout.write(`\x1b]52;c;${Buffer.from(t).toString('base64')}\x07`); osc = supportsOsc52(env); } catch { /* */ }
|
|
19
|
+
}
|
|
20
|
+
const run = (cmd, args, text = t, options = {}) => new Promise((resolve) => {
|
|
21
|
+
const failed = (err) => resolve(err.code === 'ENOENT' ? 'missing' : 'failed');
|
|
22
|
+
try {
|
|
23
|
+
const c = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'], ...options });
|
|
24
|
+
c.on('error', failed);
|
|
25
|
+
c.on('exit', (code) => resolve(code === 0 ? 'ok' : 'failed'));
|
|
26
|
+
c.stdin.on('error', () => {}); c.stdin.end(text);
|
|
27
|
+
} catch (err) { failed(err); }
|
|
28
|
+
});
|
|
29
|
+
const outcome = (result) => osc ? 'ok' : result;
|
|
30
|
+
if (platform === 'darwin') return outcome(await run('pbcopy', [], t, { env: { ...env, LC_ALL: '', LC_CTYPE: 'UTF-8' } }));
|
|
31
|
+
if (platform === 'win32') return outcome(await run('powershell', ['-NoProfile', '-Command', '[Console]::InputEncoding=[Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())']));
|
|
32
|
+
if (wsl({ platform, env })) return outcome(await run('clip.exe', [], Buffer.from('\uFEFF' + t, 'utf16le')));
|
|
33
|
+
if (env.WAYLAND_DISPLAY) {
|
|
34
|
+
const result = await run('wl-copy', []);
|
|
35
|
+
if (result !== 'missing') return outcome(result);
|
|
36
|
+
}
|
|
37
|
+
const result = await run('xclip', ['-selection', 'clipboard']);
|
|
38
|
+
return outcome(result === 'missing' ? await run('xsel', ['--clipboard', '--input']) : result);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { copyText };
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const os = require('os');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { readJsonSafe } = require('./atomic');
|
|
5
|
+
|
|
6
|
+
const CONFIG_FILE = process.env.HOPDECK_CONFIG || path.join(os.homedir(), '.hopdeck.json');
|
|
7
|
+
|
|
8
|
+
function memoizeConfig(read = readJsonSafe) {
|
|
9
|
+
const files = new Map();
|
|
10
|
+
return (file = CONFIG_FILE, onCorrupt) => {
|
|
11
|
+
if (!files.has(file)) {
|
|
12
|
+
let raw;
|
|
13
|
+
const result = read(file, (bytes) => { raw = bytes; });
|
|
14
|
+
files.set(file, { result, raw });
|
|
15
|
+
}
|
|
16
|
+
const { result, raw } = files.get(file);
|
|
17
|
+
if (raw !== undefined) onCorrupt?.(raw);
|
|
18
|
+
return result;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module.exports = { CONFIG_FILE, readConfig: memoizeConfig(), memoizeConfig };
|
package/lib/deepsearch.js
CHANGED
|
@@ -63,32 +63,43 @@ if (!isMainThread && workerData && workerData.deepSearch) {
|
|
|
63
63
|
* Busca `q` en `files`. `onHit(file)` se llama en cuanto se encuentra un acierto. Devuelve { done: Promise, cancel() }.
|
|
64
64
|
* Reparte los archivos (los grandes primero) entre varios hilos; si no se pueden crear hilos, busca en el hilo principal por tandas.
|
|
65
65
|
*/
|
|
66
|
-
function deepSearch(files, q, onHit, { threads } = {}) {
|
|
66
|
+
function deepSearch(files, q, onHit, { threads, stat = fs.promises.stat } = {}) {
|
|
67
67
|
let cancelled = false; const workers = [];
|
|
68
68
|
const cancel = () => { cancelled = true; for (const w of workers) { try { w.terminate(); } catch { /* */ } } };
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
let i = 0;
|
|
79
|
-
const step = () => { if (cancelled) return finish(); const t = Date.now(); while (i < list.length && Date.now() - t < 20) { const f = list[i++]; if (fileHasSync(f, q)) onHit(f); } if (i < list.length) setImmediate(step); else finish(); };
|
|
80
|
-
step();
|
|
81
|
-
};
|
|
82
|
-
for (const part of parts) {
|
|
83
|
-
if (!part.length) continue;
|
|
84
|
-
let w;
|
|
85
|
-
try { w = new Worker(__filename, { workerData: { deepSearch: true, files: part, q } }); } catch { fallback(part); continue; }
|
|
86
|
-
workers.push(w);
|
|
87
|
-
let ended = false; const end = () => { if (!ended) { ended = true; finish(); } };
|
|
88
|
-
w.on('message', (m) => { if (cancelled) return; if (m.hit) onHit(m.hit); else if (m.done) end(); });
|
|
89
|
-
w.on('error', end); w.on('exit', end);
|
|
69
|
+
const done = (async () => {
|
|
70
|
+
const sized = [];
|
|
71
|
+
for (let i = 0; i < files.length && !cancelled; i += 64) {
|
|
72
|
+
const batch = await Promise.all(files.slice(i, i + 64).map(async (entry) => {
|
|
73
|
+
const { file, size } = typeof entry === 'string' ? { file: entry } : entry;
|
|
74
|
+
if (Number.isSafeInteger(size) && size >= 0) return [file, size];
|
|
75
|
+
try { return [file, (await stat(file)).size]; } catch { return [file, 0]; }
|
|
76
|
+
}));
|
|
77
|
+
for (const entry of batch) if (entry[1] <= MAX_SIZE) sized.push(entry);
|
|
90
78
|
}
|
|
91
|
-
|
|
79
|
+
if (cancelled || !sized.length) return;
|
|
80
|
+
sized.sort((a, b) => b[1] - a[1]);
|
|
81
|
+
const n = Math.max(1, Math.min(threads || 4, os.cpus().length - 1 || 1, sized.length));
|
|
82
|
+
const parts = Array.from({ length: n }, () => []);
|
|
83
|
+
sized.forEach(([f], i) => parts[i % n].push(f));
|
|
84
|
+
return new Promise((resolve) => {
|
|
85
|
+
let left = parts.filter((p) => p.length).length;
|
|
86
|
+
const finish = () => { if (--left <= 0) resolve(); };
|
|
87
|
+
const fallback = (list) => { // sin hilos: en el hilo principal, cediendo el control entre archivos
|
|
88
|
+
let i = 0;
|
|
89
|
+
const step = () => { if (cancelled) return finish(); const t = Date.now(); while (i < list.length && Date.now() - t < 20) { const f = list[i++]; if (fileHasSync(f, q)) onHit(f); } if (i < list.length) setImmediate(step); else finish(); };
|
|
90
|
+
step();
|
|
91
|
+
};
|
|
92
|
+
for (const part of parts) {
|
|
93
|
+
if (!part.length) continue;
|
|
94
|
+
let w;
|
|
95
|
+
try { w = new Worker(__filename, { workerData: { deepSearch: true, files: part, q } }); } catch { fallback(part); continue; }
|
|
96
|
+
workers.push(w);
|
|
97
|
+
let ended = false; const end = () => { if (!ended) { ended = true; finish(); } };
|
|
98
|
+
w.on('message', (m) => { if (cancelled) return; if (m.hit) onHit(m.hit); else if (m.done) end(); });
|
|
99
|
+
w.on('error', end); w.on('exit', end);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
})();
|
|
92
103
|
return { done, cancel };
|
|
93
104
|
}
|
|
94
105
|
|
package/lib/executable.js
CHANGED
|
@@ -1,20 +1,35 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
const fs = require('fs');
|
|
3
3
|
const path = require('path');
|
|
4
|
+
const { isWSL } = require('./wsl');
|
|
4
5
|
const found = new Map();
|
|
5
|
-
function findExecutable(name, { env = process.env, platform = process.platform } = {}) {
|
|
6
|
+
function findExecutable(name, { env = process.env, platform = process.platform, stat = fs.statSync, access = fs.accessSync } = {}) {
|
|
6
7
|
const pathKey = Object.keys(env).find((k) => k.toLowerCase() === 'path') || 'PATH';
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
8
|
+
const extKey = Object.keys(env).find((k) => k.toLowerCase() === 'pathext') || 'PATHEXT';
|
|
9
|
+
const win = platform === 'win32', paths = win ? path.win32 : path.posix, wsl = isWSL({ env, platform });
|
|
10
|
+
const dirs = (env[pathKey] || '').split(win ? ';' : ':').filter(Boolean);
|
|
11
|
+
const mounted = (dir) => /^\/mnt\/[a-z](?:\/|$)/i.test(path.posix.normalize(dir));
|
|
12
|
+
const key = JSON.stringify([platform, wsl, name, env[pathKey], env[extKey]]);
|
|
13
|
+
const cache = stat === fs.statSync && access === fs.accessSync;
|
|
14
|
+
const valid = (file) => {
|
|
15
|
+
try { if (!stat(file).isFile()) return false; if (!win) access(file, fs.constants.X_OK); return true; }
|
|
16
|
+
catch { return false; }
|
|
17
|
+
};
|
|
18
|
+
const hit = cache && found.get(key);
|
|
19
|
+
if (hit && valid(hit)) return hit;
|
|
20
|
+
if (hit) found.delete(key);
|
|
21
|
+
const exts = win ? (env[extKey] || '.EXE;.CMD;.BAT').split(';').filter(Boolean).map((ext) => ext.toLowerCase()) : [''];
|
|
22
|
+
const search = (dirs, exts) => {
|
|
23
|
+
for (const dir of dirs) for (const ext of exts) {
|
|
24
|
+
const file = paths.join(dir, name + ext);
|
|
25
|
+
if (valid(file)) return file;
|
|
16
26
|
}
|
|
17
|
-
|
|
18
|
-
|
|
27
|
+
return null;
|
|
28
|
+
};
|
|
29
|
+
const file = wsl ? search(dirs.filter((d) => !mounted(d)), exts) || search(dirs.filter(mounted), exts)
|
|
30
|
+
: search(dirs, exts) || (win ? search(dirs, ['']) : null);
|
|
31
|
+
// A newly installed PATHEXT match must supersede an extensionless fallback.
|
|
32
|
+
if (file && cache && (!win || exts.includes(paths.extname(file).toLowerCase()))) found.set(key, file);
|
|
33
|
+
return file;
|
|
19
34
|
}
|
|
20
35
|
module.exports = { findExecutable };
|
package/lib/git.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// ramas recientes y la actividad de ramas (cambios de rama, ramas creadas, merges) que git guarda en su reflog.
|
|
4
4
|
// Nunca modifica el repositorio. Solo se ejecutan comandos fijos (`status`, `reflog show`, `for-each-ref`) sin shell.
|
|
5
5
|
const cp = require('child_process');
|
|
6
|
+
const fs = require('node:fs/promises');
|
|
7
|
+
const path = require('node:path');
|
|
6
8
|
|
|
7
9
|
// GIT_OPTIONAL_LOCKS=0: `status` no escribe en .git. core.fsmonitor=false: un repositorio ajeno no puede lanzar un programa
|
|
8
10
|
// propio a través de su configuración mientras lo miramos. LC_ALL=C: salida estable, sin traducir.
|
|
@@ -85,10 +87,40 @@ async function readGit(cwd) {
|
|
|
85
87
|
if (st.missing) return { ok: false, repo: true, missing: true };
|
|
86
88
|
if (!st.ok) return { ok: false, repo: !/not a git repository/i.test(st.err), err: st.err.trim().split('\n')[0] || '' };
|
|
87
89
|
const [rl, br] = await Promise.all([
|
|
88
|
-
run(cwd, ['reflog', 'show', '--all', '--date=unix', '--format=%gd%x09%gs']),
|
|
90
|
+
run(cwd, ['reflog', 'show', '--all', '-n', '200', '--date=unix', '--format=%gd%x09%gs']),
|
|
89
91
|
run(cwd, ['for-each-ref', '--sort=-committerdate', '--count=8', '--format=%(HEAD)%09%(refname:short)%09%(committerdate:unix)', 'refs/heads']),
|
|
90
92
|
]);
|
|
91
93
|
return { ok: true, repo: true, status: parseStatus(st.out), activity: rl.ok ? parseActivity(rl.out) : [], branches: br.ok ? parseBranches(br.out) : [] };
|
|
92
94
|
}
|
|
93
95
|
|
|
94
|
-
|
|
96
|
+
async function gitStamp(cwd) {
|
|
97
|
+
let dir = path.resolve(cwd);
|
|
98
|
+
while (true) {
|
|
99
|
+
const dot = path.join(dir, '.git'), st = await fs.stat(dot).catch(() => null);
|
|
100
|
+
if (st?.isDirectory()) return stamp(dot);
|
|
101
|
+
if (st?.isFile()) {
|
|
102
|
+
if (st.size > 8192) return null;
|
|
103
|
+
const target = /^gitdir: (.+)$/im.exec(await fs.readFile(dot, 'utf8').catch(() => ''));
|
|
104
|
+
return target ? stamp(path.resolve(dir, target[1].trim())) : null;
|
|
105
|
+
}
|
|
106
|
+
const parent = path.dirname(dir);
|
|
107
|
+
if (parent === dir) return null;
|
|
108
|
+
dir = parent;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function stamp(dir) {
|
|
113
|
+
const times = await Promise.all(['HEAD', 'index', 'logs/HEAD'].map(async (name) => {
|
|
114
|
+
const st = await fs.stat(path.join(dir, name)).catch(() => null);
|
|
115
|
+
return st?.mtimeMs ?? null;
|
|
116
|
+
}));
|
|
117
|
+
return JSON.stringify([dir, ...times]);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function refreshGit(cwd, previous, { now = Date.now, read = readGit, signature = gitStamp } = {}) {
|
|
121
|
+
const at = now(), key = await signature(cwd);
|
|
122
|
+
if (previous && key === previous.key && at - previous.at < 60000) return previous;
|
|
123
|
+
return { at, key, data: await read(cwd) };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = { readGit, refreshGit, gitStamp, parseStatus, parseActivity, parseBranches };
|