retakes-cli 0.0.0-stage → 0.1.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/LICENSE +75 -0
- package/README.md +48 -2
- package/bin/retake.js +4 -0
- package/package.json +42 -4
- package/skills/retakes/SKILL.md +72 -0
- package/skills/retakes-match/SKILL.md +53 -0
- package/skills/retakes-recreate/SKILL.md +74 -0
- package/skills/retakes-watch/SKILL.md +64 -0
- package/src/adapters/generic.js +18 -0
- package/src/adapters/hyperframes.js +50 -0
- package/src/adapters/index.js +61 -0
- package/src/adapters/locate.js +7 -0
- package/src/adapters/remotion.js +28 -0
- package/src/brand.js +12 -0
- package/src/cli.js +70 -0
- package/src/commands/local.js +253 -0
- package/src/commands/remote.js +387 -0
- package/src/commands/skill.js +53 -0
- package/src/commands/video.js +120 -0
- package/src/diff.js +92 -0
- package/src/ignore.js +48 -0
- package/src/media.js +71 -0
- package/src/remote.js +120 -0
- package/src/snapshot.js +95 -0
- package/src/store.js +132 -0
- package/src/util.js +136 -0
- package/src/video/analyze.js +204 -0
- package/src/video/audio.js +180 -0
- package/src/video/ff.js +87 -0
- package/src/video/frames.js +112 -0
- package/src/video/match.js +287 -0
- package/src/video/pack.js +259 -0
- package/src/video/sheets.js +161 -0
package/src/ignore.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// A small .gitignore-style matcher: *, **, ?, trailing "/" for directories,
|
|
2
|
+
// a leading "/" (or any inner "/") anchors to the project root, "!" re-includes.
|
|
3
|
+
function globToRegExp(glob) {
|
|
4
|
+
let s = "";
|
|
5
|
+
for (let i = 0; i < glob.length; i++) {
|
|
6
|
+
const ch = glob[i];
|
|
7
|
+
if (ch === "*") {
|
|
8
|
+
if (glob[i + 1] === "*") {
|
|
9
|
+
if (glob[i + 2] === "/") {
|
|
10
|
+
s += "(?:.*/)?";
|
|
11
|
+
i += 2;
|
|
12
|
+
} else {
|
|
13
|
+
s += ".*";
|
|
14
|
+
i += 1;
|
|
15
|
+
}
|
|
16
|
+
} else s += "[^/]*";
|
|
17
|
+
} else if (ch === "?") s += "[^/]";
|
|
18
|
+
else s += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
19
|
+
}
|
|
20
|
+
return new RegExp(`^${s}$`, process.platform === "win32" || process.platform === "darwin" ? "i" : "");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function compileIgnore(patterns) {
|
|
24
|
+
const rules = [];
|
|
25
|
+
for (let raw of patterns) {
|
|
26
|
+
let p = String(raw).trim();
|
|
27
|
+
if (!p || p.startsWith("#")) continue;
|
|
28
|
+
let negate = false;
|
|
29
|
+
if (p.startsWith("!")) {
|
|
30
|
+
negate = true;
|
|
31
|
+
p = p.slice(1);
|
|
32
|
+
}
|
|
33
|
+
const dirOnly = p.endsWith("/");
|
|
34
|
+
if (dirOnly) p = p.slice(0, -1);
|
|
35
|
+
const anchored = p.startsWith("/") || p.includes("/");
|
|
36
|
+
if (p.startsWith("/")) p = p.slice(1);
|
|
37
|
+
rules.push({ negate, dirOnly, anchored, re: globToRegExp(p) });
|
|
38
|
+
}
|
|
39
|
+
return function isIgnored(rel, isDir) {
|
|
40
|
+
let ignored = false;
|
|
41
|
+
const base = rel.slice(rel.lastIndexOf("/") + 1);
|
|
42
|
+
for (const r of rules) {
|
|
43
|
+
if (r.dirOnly && !isDir) continue;
|
|
44
|
+
if (r.re.test(r.anchored ? rel : base)) ignored = !r.negate;
|
|
45
|
+
}
|
|
46
|
+
return ignored;
|
|
47
|
+
};
|
|
48
|
+
}
|
package/src/media.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
export const VIDEO_EXT = [".mp4", ".mov", ".webm", ".mkv", ".m4v"];
|
|
6
|
+
|
|
7
|
+
let ffmpegOk = null;
|
|
8
|
+
export function hasFfmpeg() {
|
|
9
|
+
if (ffmpegOk === null) {
|
|
10
|
+
const a = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" });
|
|
11
|
+
const b = spawnSync("ffprobe", ["-version"], { stdio: "ignore" });
|
|
12
|
+
ffmpegOk = a.status === 0 && b.status === 0;
|
|
13
|
+
}
|
|
14
|
+
return ffmpegOk;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function probe(file) {
|
|
18
|
+
if (!hasFfmpeg()) return {};
|
|
19
|
+
const r = spawnSync("ffprobe", ["-v", "error", "-print_format", "json", "-show_streams", "-show_format", file], { encoding: "utf8" });
|
|
20
|
+
if (r.status !== 0) return {};
|
|
21
|
+
try {
|
|
22
|
+
const j = JSON.parse(r.stdout);
|
|
23
|
+
const v = (j.streams || []).find((s) => s.codec_type === "video") || {};
|
|
24
|
+
const [num, den] = String(v.avg_frame_rate || v.r_frame_rate || "0/1").split("/").map(Number);
|
|
25
|
+
return {
|
|
26
|
+
duration: Number(j.format?.duration) || Number(v.duration) || null,
|
|
27
|
+
width: v.width || null,
|
|
28
|
+
height: v.height || null,
|
|
29
|
+
fps: den ? Math.round((num / den) * 1000) / 1000 : null,
|
|
30
|
+
hasAudio: (j.streams || []).some((s) => s.codec_type === "audio"),
|
|
31
|
+
};
|
|
32
|
+
} catch {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function run(args) {
|
|
38
|
+
const r = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { encoding: "utf8" });
|
|
39
|
+
if (r.status !== 0) throw new Error(`ffmpeg failed: ${(r.stderr || "").trim().split("\n").pop()}`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function makePoster(file, out, at) {
|
|
43
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
44
|
+
run(["-ss", String(Math.max(0, at)), "-i", file, "-frames:v", "1", "-vf", "scale='min(1280,iw)':-2", "-q:v", "3", out]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A small 540p H.264 proxy: what the web player streams, and what survives when an
|
|
48
|
+
// old full-quality render is pruned on the free tier.
|
|
49
|
+
export function makePreview(file, out) {
|
|
50
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
51
|
+
run([
|
|
52
|
+
"-i", file,
|
|
53
|
+
"-vf", "scale=-2:'min(540,ih)'",
|
|
54
|
+
"-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p",
|
|
55
|
+
"-c:a", "aac", "-b:a", "96k",
|
|
56
|
+
"-movflags", "+faststart",
|
|
57
|
+
out,
|
|
58
|
+
]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A still of one moment with the commented region boxed, for agents to look at.
|
|
62
|
+
export function makeMarkedFrame(file, out, t, x, y) {
|
|
63
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
64
|
+
const filters = ["scale='min(1600,iw)':-2"];
|
|
65
|
+
if (x != null && y != null) {
|
|
66
|
+
const bw = "iw*0.14";
|
|
67
|
+
const bh = "ih*0.14";
|
|
68
|
+
filters.push(`drawbox=x=iw*${x}-${bw}/2:y=ih*${y}-${bh}/2:w=${bw}:h=${bh}:color=0xff3b6b@0.95:t=6`);
|
|
69
|
+
}
|
|
70
|
+
run(["-ss", String(Math.max(0, t)), "-i", file, "-frames:v", "1", "-vf", filters.join(","), "-q:v", "3", out]);
|
|
71
|
+
}
|
package/src/remote.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { BRAND } from "./brand.js";
|
|
5
|
+
import { fail, readJsonSync, writeJsonSync, progress } from "./util.js";
|
|
6
|
+
|
|
7
|
+
export function configDir() {
|
|
8
|
+
if (process.platform === "win32" && process.env.APPDATA) return path.join(process.env.APPDATA, BRAND.configHome);
|
|
9
|
+
return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), BRAND.configHome);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const credsFile = () => path.join(configDir(), "credentials.json");
|
|
13
|
+
|
|
14
|
+
export function readCreds() {
|
|
15
|
+
return readJsonSync(credsFile(), { defaultRemote: null, remotes: {} });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function writeCreds(creds) {
|
|
19
|
+
writeJsonSync(credsFile(), creds);
|
|
20
|
+
try {
|
|
21
|
+
fs.chmodSync(credsFile(), 0o600);
|
|
22
|
+
} catch {
|
|
23
|
+
/* Windows: the file sits in the user's own profile */
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const normRemote = (u) => String(u).trim().replace(/\/+$/, "");
|
|
28
|
+
|
|
29
|
+
export function remoteFor(repo, override) {
|
|
30
|
+
if (override) return normRemote(override);
|
|
31
|
+
if (process.env[BRAND.remoteEnv]) return normRemote(process.env[BRAND.remoteEnv]);
|
|
32
|
+
if (repo?.config?.remote) return normRemote(repo.config.remote);
|
|
33
|
+
const creds = readCreds();
|
|
34
|
+
return normRemote(creds.defaultRemote || BRAND.defaultRemote);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function tokenFor(remote) {
|
|
38
|
+
if (process.env[BRAND.tokenEnv]) return process.env[BRAND.tokenEnv];
|
|
39
|
+
return readCreds().remotes?.[remote]?.token ?? null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function needToken(remote) {
|
|
43
|
+
const t = tokenFor(remote);
|
|
44
|
+
if (!t) fail(`Not logged in to ${remote}. Run \`${BRAND.bin} login\` (or set ${BRAND.tokenEnv}).`);
|
|
45
|
+
return t;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function api(remote, method, route, { token, json, body, headers = {}, raw = false } = {}) {
|
|
49
|
+
const h = { ...headers };
|
|
50
|
+
if (token) h.authorization = `Bearer ${token}`;
|
|
51
|
+
if (json !== undefined) {
|
|
52
|
+
h["content-type"] = "application/json";
|
|
53
|
+
body = JSON.stringify(json);
|
|
54
|
+
}
|
|
55
|
+
let res;
|
|
56
|
+
try {
|
|
57
|
+
res = await fetch(remote + route, { method, headers: h, body });
|
|
58
|
+
} catch (e) {
|
|
59
|
+
fail(`Can't reach ${remote} (${e.cause?.code || e.message}).`);
|
|
60
|
+
}
|
|
61
|
+
if (raw) {
|
|
62
|
+
if (!res.ok) fail(`${method} ${route} → ${res.status} ${await res.text().catch(() => "")}`.trim());
|
|
63
|
+
return res;
|
|
64
|
+
}
|
|
65
|
+
const text = await res.text();
|
|
66
|
+
let data = null;
|
|
67
|
+
try {
|
|
68
|
+
data = text ? JSON.parse(text) : null;
|
|
69
|
+
} catch {
|
|
70
|
+
/* not JSON */
|
|
71
|
+
}
|
|
72
|
+
if (!res.ok) {
|
|
73
|
+
const msg = data?.error || text.slice(0, 300) || res.statusText;
|
|
74
|
+
if (res.status === 401) fail(`${msg}\nRun \`${BRAND.bin} login\` again.`);
|
|
75
|
+
fail(`${msg} (${res.status})`);
|
|
76
|
+
}
|
|
77
|
+
return data;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const SINGLE_LIMIT = 90 * 1024 * 1024;
|
|
81
|
+
const PART_SIZE = 50 * 1024 * 1024;
|
|
82
|
+
|
|
83
|
+
// Upload one object by its hash. Large files go up in parts (Workers cap a request body near 100 MB).
|
|
84
|
+
export async function uploadBlob(remote, token, { hash, size, file, contentType = "application/octet-stream", label }) {
|
|
85
|
+
if (size <= SINGLE_LIMIT) {
|
|
86
|
+
const blob = await fs.openAsBlob(file, { type: contentType });
|
|
87
|
+
await api(remote, "PUT", `/api/blobs/${hash}`, { token, body: blob, headers: { "content-type": contentType, "x-size": String(size) } });
|
|
88
|
+
progress(label, size, size);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const { uploadId } = await api(remote, "POST", `/api/blobs/${hash}/uploads`, { token, json: { size, contentType } });
|
|
92
|
+
const parts = [];
|
|
93
|
+
const fd = fs.openSync(file, "r");
|
|
94
|
+
try {
|
|
95
|
+
let n = 1;
|
|
96
|
+
for (let off = 0; off < size; off += PART_SIZE, n++) {
|
|
97
|
+
const len = Math.min(PART_SIZE, size - off);
|
|
98
|
+
const buf = Buffer.alloc(len);
|
|
99
|
+
fs.readSync(fd, buf, 0, len, off);
|
|
100
|
+
const part = await api(remote, "PUT", `/api/blobs/${hash}/uploads/${encodeURIComponent(uploadId)}/${n}`, {
|
|
101
|
+
token,
|
|
102
|
+
body: buf,
|
|
103
|
+
headers: { "content-type": "application/octet-stream" },
|
|
104
|
+
});
|
|
105
|
+
parts.push(part);
|
|
106
|
+
progress(label, off + len, size);
|
|
107
|
+
}
|
|
108
|
+
} finally {
|
|
109
|
+
fs.closeSync(fd);
|
|
110
|
+
}
|
|
111
|
+
await api(remote, "POST", `/api/blobs/${hash}/uploads/${encodeURIComponent(uploadId)}/complete`, { token, json: { parts, size } });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function download(remote, token, route, dest) {
|
|
115
|
+
const res = await api(remote, "GET", route, { token, raw: true });
|
|
116
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
117
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
118
|
+
fs.writeFileSync(dest, buf);
|
|
119
|
+
return buf.length;
|
|
120
|
+
}
|
package/src/snapshot.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import fsp from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { BRAND } from "./brand.js";
|
|
5
|
+
import { compileIgnore } from "./ignore.js";
|
|
6
|
+
import { readJsonSync, writeJsonSync, sha256File } from "./util.js";
|
|
7
|
+
|
|
8
|
+
// Never versioned, whatever the engine: dependencies, VCS data, our own store, secrets.
|
|
9
|
+
export const BASE_IGNORE = [
|
|
10
|
+
"node_modules/",
|
|
11
|
+
".git/",
|
|
12
|
+
`${BRAND.dir}/`,
|
|
13
|
+
".wrangler/",
|
|
14
|
+
".DS_Store",
|
|
15
|
+
"Thumbs.db",
|
|
16
|
+
"desktop.ini",
|
|
17
|
+
"*.log",
|
|
18
|
+
"*.tmp",
|
|
19
|
+
".env",
|
|
20
|
+
".env.*",
|
|
21
|
+
".dev.vars",
|
|
22
|
+
"*.pem",
|
|
23
|
+
"*.key",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
export function readUserIgnore(root) {
|
|
27
|
+
try {
|
|
28
|
+
return fs.readFileSync(path.join(root, BRAND.ignoreFile), "utf8").split(/\r?\n/);
|
|
29
|
+
} catch {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function ignoreFor(root, adapter) {
|
|
35
|
+
return compileIgnore([...BASE_IGNORE, ...(adapter.ignore ?? []), ...readUserIgnore(root)]);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Hash every tracked file. Unchanged files (same mtime and size) reuse the cached hash.
|
|
39
|
+
export async function scan(repo, adapter) {
|
|
40
|
+
const isIgnored = ignoreFor(repo.root, adapter);
|
|
41
|
+
const cacheFile = repo.p("index.json");
|
|
42
|
+
const cache = readJsonSync(cacheFile, {});
|
|
43
|
+
const nextCache = {};
|
|
44
|
+
const files = {};
|
|
45
|
+
|
|
46
|
+
async function walk(abs, rel) {
|
|
47
|
+
let entries;
|
|
48
|
+
try {
|
|
49
|
+
entries = await fsp.readdir(abs, { withFileTypes: true });
|
|
50
|
+
} catch {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
for (const ent of entries) {
|
|
54
|
+
const r = rel ? `${rel}/${ent.name}` : ent.name;
|
|
55
|
+
const a = path.join(abs, ent.name);
|
|
56
|
+
if (ent.isSymbolicLink()) continue;
|
|
57
|
+
if (ent.isDirectory()) {
|
|
58
|
+
if (!isIgnored(r, true)) await walk(a, r);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (!ent.isFile() || isIgnored(r, false)) continue;
|
|
62
|
+
const st = await fsp.stat(a);
|
|
63
|
+
const hit = cache[r];
|
|
64
|
+
const h = hit && hit.m === st.mtimeMs && hit.s === st.size ? hit.h : await sha256File(a);
|
|
65
|
+
nextCache[r] = { m: st.mtimeMs, s: st.size, h };
|
|
66
|
+
files[r] = { h, s: st.size };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
await walk(repo.root, "");
|
|
71
|
+
writeJsonSync(cacheFile, nextCache);
|
|
72
|
+
return Object.fromEntries(Object.keys(files).sort().map((k) => [k, files[k]]));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function storeFiles(repo, files) {
|
|
76
|
+
for (const [rel, f] of Object.entries(files)) {
|
|
77
|
+
if (!repo.hasObj(f.h)) await repo.putFile(path.join(repo.root, ...rel.split("/")), f.h);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function diffManifests(a = {}, b = {}) {
|
|
82
|
+
const added = [];
|
|
83
|
+
const removed = [];
|
|
84
|
+
const changed = [];
|
|
85
|
+
for (const k of Object.keys(b)) {
|
|
86
|
+
if (!(k in a)) added.push(k);
|
|
87
|
+
else if (a[k].h !== b[k].h) changed.push(k);
|
|
88
|
+
}
|
|
89
|
+
for (const k of Object.keys(a)) if (!(k in b)) removed.push(k);
|
|
90
|
+
return { added, removed, changed, total: added.length + removed.length + changed.length };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function manifestBytes(files) {
|
|
94
|
+
return Object.values(files).reduce((n, f) => n + f.s, 0);
|
|
95
|
+
}
|
package/src/store.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import fsp from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { BRAND } from "./brand.js";
|
|
5
|
+
import { fail, readJsonSync, writeJsonSync, sha256Buffer } from "./util.js";
|
|
6
|
+
|
|
7
|
+
export function findRoot(from = process.cwd()) {
|
|
8
|
+
let d = path.resolve(from);
|
|
9
|
+
for (;;) {
|
|
10
|
+
if (fs.existsSync(path.join(d, BRAND.dir, "config.json"))) return d;
|
|
11
|
+
const up = path.dirname(d);
|
|
12
|
+
if (up === d) return null;
|
|
13
|
+
d = up;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function openRepo(from) {
|
|
18
|
+
const root = findRoot(from);
|
|
19
|
+
if (!root) fail(`Not a ${BRAND.name} project (no ${BRAND.dir}/ here or above). Run \`${BRAND.bin} init\` first.`);
|
|
20
|
+
return new Repo(root);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Local store layout:
|
|
24
|
+
// .retakes/config.json project settings, HEAD, link to the remote project
|
|
25
|
+
// .retakes/versions/<n>.json one file per saved version
|
|
26
|
+
// .retakes/objects/ab/cdef... content-addressed file copies (sha256)
|
|
27
|
+
// .retakes/index.json mtime/size → hash cache, so scans stay fast
|
|
28
|
+
// .retakes/derived/ posters and previews made from renders
|
|
29
|
+
export class Repo {
|
|
30
|
+
constructor(root) {
|
|
31
|
+
this.root = root;
|
|
32
|
+
this.dir = path.join(root, BRAND.dir);
|
|
33
|
+
this._config = null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
static create(root, config) {
|
|
37
|
+
const repo = new Repo(root);
|
|
38
|
+
fs.mkdirSync(path.join(repo.dir, "versions"), { recursive: true });
|
|
39
|
+
fs.mkdirSync(path.join(repo.dir, "objects"), { recursive: true });
|
|
40
|
+
repo._config = config;
|
|
41
|
+
repo.saveConfig();
|
|
42
|
+
return repo;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
p(...parts) {
|
|
46
|
+
return path.join(this.dir, ...parts);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
get config() {
|
|
50
|
+
if (!this._config) this._config = readJsonSync(this.p("config.json"), null) ?? fail(`${BRAND.dir}/config.json is unreadable.`);
|
|
51
|
+
return this._config;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
saveConfig() {
|
|
55
|
+
writeJsonSync(this.p("config.json"), this._config);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
versions() {
|
|
59
|
+
const dir = this.p("versions");
|
|
60
|
+
if (!fs.existsSync(dir)) return [];
|
|
61
|
+
return fs
|
|
62
|
+
.readdirSync(dir)
|
|
63
|
+
.filter((f) => /^\d+\.json$/.test(f))
|
|
64
|
+
.map((f) => readJsonSync(path.join(dir, f), null))
|
|
65
|
+
.filter(Boolean)
|
|
66
|
+
.sort((a, b) => a.n - b.n);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
version(n) {
|
|
70
|
+
const v = readJsonSync(this.p("versions", `${n}.json`), null);
|
|
71
|
+
if (!v) fail(`No version v${n}. Run \`${BRAND.bin} log\` to list them.`);
|
|
72
|
+
return v;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
resolveRef(ref) {
|
|
76
|
+
if (ref == null || ref === "HEAD" || ref === "head") {
|
|
77
|
+
const h = this.config.head;
|
|
78
|
+
if (h == null) fail("No versions saved yet.");
|
|
79
|
+
return this.version(h);
|
|
80
|
+
}
|
|
81
|
+
const n = Number(String(ref).replace(/^v/i, ""));
|
|
82
|
+
if (!Number.isInteger(n)) fail(`"${ref}" is not a version (use 3 or v3).`);
|
|
83
|
+
return this.version(n);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
nextNumber() {
|
|
87
|
+
const all = this.versions();
|
|
88
|
+
return all.length ? all[all.length - 1].n + 1 : 1;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
writeVersion(v) {
|
|
92
|
+
writeJsonSync(this.p("versions", `${v.n}.json`), v);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
objPath(h) {
|
|
96
|
+
return this.p("objects", h.slice(0, 2), h.slice(2));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
hasObj(h) {
|
|
100
|
+
return fs.existsSync(this.objPath(h));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async putFile(abs, h) {
|
|
104
|
+
const dest = this.objPath(h);
|
|
105
|
+
if (fs.existsSync(dest)) return;
|
|
106
|
+
await fsp.mkdir(path.dirname(dest), { recursive: true });
|
|
107
|
+
const tmp = `${dest}.${process.pid}.tmp`;
|
|
108
|
+
await fsp.copyFile(abs, tmp);
|
|
109
|
+
await fsp.rename(tmp, dest);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async putBuffer(buf) {
|
|
113
|
+
const h = sha256Buffer(buf);
|
|
114
|
+
const dest = this.objPath(h);
|
|
115
|
+
if (!fs.existsSync(dest)) {
|
|
116
|
+
await fsp.mkdir(path.dirname(dest), { recursive: true });
|
|
117
|
+
await fsp.writeFile(dest, buf);
|
|
118
|
+
}
|
|
119
|
+
return h;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
readObj(h) {
|
|
123
|
+
return fs.readFileSync(this.objPath(h));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Read a file as it was in a version, from the object store.
|
|
127
|
+
readVersionFile(v, rel) {
|
|
128
|
+
const f = v.files?.[rel];
|
|
129
|
+
if (!f || !this.hasObj(f.h)) return null;
|
|
130
|
+
return this.readObj(f.h).toString("utf8");
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/util.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
|
|
6
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
7
|
+
const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
8
|
+
export const c = {
|
|
9
|
+
dim: paint("2"),
|
|
10
|
+
bold: paint("1"),
|
|
11
|
+
green: paint("32"),
|
|
12
|
+
yellow: paint("33"),
|
|
13
|
+
red: paint("31"),
|
|
14
|
+
cyan: paint("36"),
|
|
15
|
+
magenta: paint("35"),
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export class CliError extends Error {}
|
|
19
|
+
export function fail(message) {
|
|
20
|
+
throw new CliError(message);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function sha256File(file) {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
const h = crypto.createHash("sha256");
|
|
26
|
+
fs.createReadStream(file)
|
|
27
|
+
.on("error", reject)
|
|
28
|
+
.on("data", (d) => h.update(d))
|
|
29
|
+
.on("end", () => resolve(h.digest("hex")));
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const sha256Buffer = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
|
|
34
|
+
|
|
35
|
+
export const toPosix = (p) => p.split(path.sep).join("/");
|
|
36
|
+
|
|
37
|
+
export function humanBytes(n) {
|
|
38
|
+
if (n == null) return "?";
|
|
39
|
+
const u = ["B", "KB", "MB", "GB", "TB"];
|
|
40
|
+
let i = 0;
|
|
41
|
+
let v = n;
|
|
42
|
+
while (v >= 1024 && i < u.length - 1) {
|
|
43
|
+
v /= 1024;
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
return `${v < 10 && i ? v.toFixed(1) : Math.round(v)} ${u[i]}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function ago(iso) {
|
|
50
|
+
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
|
|
51
|
+
if (s < 60) return "just now";
|
|
52
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
|
|
53
|
+
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
|
|
54
|
+
return `${Math.floor(s / 86400)}d ago`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function fmtTime(t) {
|
|
58
|
+
if (t == null || Number.isNaN(t)) return "-";
|
|
59
|
+
const m = Math.floor(t / 60);
|
|
60
|
+
const s = t - m * 60;
|
|
61
|
+
return `${m}:${s.toFixed(2).padStart(5, "0")}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function readJsonSync(file, fallback) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
67
|
+
} catch {
|
|
68
|
+
return fallback;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function writeJsonSync(file, value) {
|
|
73
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
74
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
75
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n");
|
|
76
|
+
fs.renameSync(tmp, file);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function openBrowser(url) {
|
|
80
|
+
try {
|
|
81
|
+
const opts = { stdio: "ignore", detached: true };
|
|
82
|
+
if (process.platform === "win32") spawn("rundll32", ["url.dll,FileProtocolHandler", url], opts).unref();
|
|
83
|
+
else if (process.platform === "darwin") spawn("open", [url], opts).unref();
|
|
84
|
+
else spawn("xdg-open", [url], opts).unref();
|
|
85
|
+
} catch {
|
|
86
|
+
/* the URL is printed anyway */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Which agent is running this command (recorded on each version).
|
|
91
|
+
export function detectAgent() {
|
|
92
|
+
const env = process.env;
|
|
93
|
+
if (env.RETAKES_AGENT) return env.RETAKES_AGENT;
|
|
94
|
+
if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return "claude-code";
|
|
95
|
+
if (Object.keys(env).some((k) => k.startsWith("CODEX_"))) return "codex";
|
|
96
|
+
if (env.CURSOR_TRACE_ID || env.CURSOR_AGENT) return "cursor";
|
|
97
|
+
return "human";
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// "handle/slug", "handle/slug@3" or a full URL like https://host/handle/slug/v/3
|
|
101
|
+
export function parseTarget(input) {
|
|
102
|
+
if (!input) fail("Name a project: handle/slug (optionally @version).");
|
|
103
|
+
let s = input.trim();
|
|
104
|
+
let host = null;
|
|
105
|
+
const url = /^https?:\/\/[^/]+/i.exec(s);
|
|
106
|
+
if (url) {
|
|
107
|
+
host = url[0];
|
|
108
|
+
s = s.slice(url[0].length).replace(/^\/+/, "");
|
|
109
|
+
const m = /^([^/]+)\/([^/?#]+)(?:\/v\/(\d+))?/.exec(s);
|
|
110
|
+
if (!m) fail(`Can't read a project from ${input}`);
|
|
111
|
+
return { host, handle: m[1], slug: m[2], number: m[3] ? Number(m[3]) : null };
|
|
112
|
+
}
|
|
113
|
+
const m = /^@?([^/\s]+)\/([^@\s/]+)(?:@v?(\d+))?$/.exec(s);
|
|
114
|
+
if (!m) fail(`Expected handle/slug or handle/slug@3, got "${input}"`);
|
|
115
|
+
return { host, handle: m[1], slug: m[2], number: m[3] ? Number(m[3]) : null };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function slugify(s) {
|
|
119
|
+
return (
|
|
120
|
+
String(s)
|
|
121
|
+
.toLowerCase()
|
|
122
|
+
.normalize("NFKD")
|
|
123
|
+
.replace(/[^\w\s-]/g, "")
|
|
124
|
+
.trim()
|
|
125
|
+
.replace(/[\s_]+/g, "-")
|
|
126
|
+
.replace(/-+/g, "-")
|
|
127
|
+
.slice(0, 60) || "video"
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function progress(label, done, total) {
|
|
132
|
+
if (!process.stdout.isTTY) return;
|
|
133
|
+
const pct = total ? Math.floor((done / total) * 100) : 100;
|
|
134
|
+
process.stdout.write(`\r ${label} ${pct}% (${humanBytes(done)} / ${humanBytes(total)}) `);
|
|
135
|
+
if (done >= total) process.stdout.write("\n");
|
|
136
|
+
}
|