toolcrib 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 +21 -0
- package/README.md +203 -0
- package/package.json +34 -0
- package/src/commands/apply.js +91 -0
- package/src/commands/doctor.js +178 -0
- package/src/commands/init.js +140 -0
- package/src/commands/merge.js +251 -0
- package/src/commands/versions.js +18 -0
- package/src/index.js +87 -0
- package/src/lib/bundler.js +87 -0
- package/src/lib/deps.js +74 -0
- package/src/lib/fences.js +129 -0
- package/src/lib/git.js +79 -0
- package/src/lib/github.js +102 -0
- package/src/lib/managedDocs.js +51 -0
- package/src/lib/patchFallback.js +30 -0
- package/src/lib/patches.js +120 -0
- package/src/lib/project.js +80 -0
- package/src/lib/release.js +42 -0
- package/src/lib/zip.js +65 -0
package/src/lib/git.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { spawn, execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
|
|
4
|
+
const execFileAsync = promisify(execFile);
|
|
5
|
+
const isWindows = process.platform === 'win32';
|
|
6
|
+
|
|
7
|
+
/** Base options applied to every spawned git process. */
|
|
8
|
+
const baseOpts = (cwd) => ({
|
|
9
|
+
cwd,
|
|
10
|
+
windowsHide: true, // belt-and-suspenders against any console flash on Windows
|
|
11
|
+
shell: isWindows, // needed so Windows resolves the git.cmd shim correctly
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
/** Quick, buffered checks — output isn't meant for the user, just a yes/no/value. */
|
|
15
|
+
async function quietGit(args, cwd) {
|
|
16
|
+
try {
|
|
17
|
+
const { stdout } = await execFileAsync('git', args, baseOpts(cwd));
|
|
18
|
+
return { ok: true, stdout: stdout.trim() };
|
|
19
|
+
} catch (err) {
|
|
20
|
+
return { ok: false, error: err };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function isGitInstalled() {
|
|
25
|
+
return (await quietGit(['--version'])).ok;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function isInsideGitRepo(cwd) {
|
|
29
|
+
return (await quietGit(['rev-parse', '--is-inside-work-tree'], cwd)).ok;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function gitInit(cwd) {
|
|
33
|
+
return quietGit(['init'], cwd);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Streaming apply — the user should see git's own output live, especially
|
|
38
|
+
* on failure (git apply's "patch does not apply" messages point at the
|
|
39
|
+
* exact failing hunk, which is genuinely useful diagnostic info worth
|
|
40
|
+
* surfacing rather than swallowing and reformatting).
|
|
41
|
+
*/
|
|
42
|
+
export function gitApplyStreaming(patchPath, cwd) {
|
|
43
|
+
return new Promise((resolve) => {
|
|
44
|
+
const proc = spawn('git', ['apply', patchPath], {
|
|
45
|
+
...baseOpts(cwd),
|
|
46
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
let stderr = '';
|
|
50
|
+
proc.stdout.on('data', (chunk) => process.stdout.write(chunk));
|
|
51
|
+
proc.stderr.on('data', (chunk) => {
|
|
52
|
+
stderr += chunk;
|
|
53
|
+
process.stderr.write(chunk);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
proc.on('close', (code) => {
|
|
57
|
+
resolve(code === 0 ? { success: true } : { success: false, error: stderr.trim() });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
proc.on('error', (err) => resolve({ success: false, error: err.message }));
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Ensures a git repo is present before attempting `git apply`, offering to
|
|
66
|
+
* initialize one on the spot rather than failing outright — this is the
|
|
67
|
+
* common real-world gap (git installed, but the project itself was never
|
|
68
|
+
* `git init`'d yet), not a platform limitation.
|
|
69
|
+
*/
|
|
70
|
+
export async function ensureGitRepo(cwd, { confirmFn }) {
|
|
71
|
+
if (await isInsideGitRepo(cwd)) return true;
|
|
72
|
+
if (!(await isGitInstalled())) return false;
|
|
73
|
+
|
|
74
|
+
const shouldInit = await confirmFn('No git repository found here. Initialize one now?');
|
|
75
|
+
if (!shouldInit) return false;
|
|
76
|
+
|
|
77
|
+
const result = await gitInit(cwd);
|
|
78
|
+
return result.ok;
|
|
79
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const REPO = 'escape-llc/toolcrib';
|
|
4
|
+
const ASSET_NAME = 'toolcrib.zip';
|
|
5
|
+
const CHECKSUM_ASSET_NAME = 'toolcrib.zip.sha256';
|
|
6
|
+
|
|
7
|
+
// Optional overrides for tests/mirrors — unset in normal use, everything
|
|
8
|
+
// targets real GitHub. Integration tests point these at a local server
|
|
9
|
+
// so the full download/verify/extract pipeline runs for real without
|
|
10
|
+
// depending on network access or a published release existing.
|
|
11
|
+
const API_BASE = process.env.TOOLCRIB_API_BASE || 'https://api.github.com';
|
|
12
|
+
const RELEASES_BASE = process.env.TOOLCRIB_RELEASES_BASE || `https://github.com/${REPO}/releases`;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* List published (non-draft) releases from the GitHub API, newest first.
|
|
16
|
+
* No auth needed for public repos; subject to the standard 60/hr
|
|
17
|
+
* unauthenticated rate limit, which is fine for occasional CLI use.
|
|
18
|
+
*/
|
|
19
|
+
export async function listVersions() {
|
|
20
|
+
const res = await fetch(`${API_BASE}/repos/${REPO}/releases`, {
|
|
21
|
+
headers: { Accept: 'application/vnd.github+json' },
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
if (!res.ok) {
|
|
25
|
+
throw new Error(`Failed to fetch release list: ${res.status} ${res.statusText}`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const releases = await res.json();
|
|
29
|
+
|
|
30
|
+
return releases
|
|
31
|
+
.filter((r) => !r.draft)
|
|
32
|
+
.map((r) => ({
|
|
33
|
+
version: r.tag_name.replace(/^v/, ''),
|
|
34
|
+
publishedAt: r.published_at,
|
|
35
|
+
prerelease: r.prerelease,
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function assetUrl(version, assetName) {
|
|
40
|
+
return version === 'latest'
|
|
41
|
+
? `${RELEASES_BASE}/latest/download/${assetName}`
|
|
42
|
+
: `${RELEASES_BASE}/download/v${version}/${assetName}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolve "latest" to a concrete version string, so callers (and CLI
|
|
47
|
+
* output) always know exactly what was fetched rather than the moving
|
|
48
|
+
* target name. Always print this — see index.js — so re-running
|
|
49
|
+
* `init latest` after a new release appears is never a silent surprise.
|
|
50
|
+
*/
|
|
51
|
+
export async function resolveVersion(version) {
|
|
52
|
+
if (version !== 'latest') return version;
|
|
53
|
+
const versions = await listVersions();
|
|
54
|
+
const newest = versions.find((v) => !v.prerelease);
|
|
55
|
+
if (!newest) throw new Error('No published releases found.');
|
|
56
|
+
return newest.version;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function fetchText(url) {
|
|
60
|
+
const res = await fetch(url, { redirect: 'follow' });
|
|
61
|
+
if (!res.ok) throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`);
|
|
62
|
+
return res.text();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function fetchBuffer(url) {
|
|
66
|
+
const res = await fetch(url, { redirect: 'follow' });
|
|
67
|
+
if (!res.ok) throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`);
|
|
68
|
+
return Buffer.from(await res.arrayBuffer());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function sha256(buffer) {
|
|
72
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Download a release zip + its checksum sibling, verify integrity,
|
|
77
|
+
* and return the raw buffer. Throws on mismatch (corrupted/truncated
|
|
78
|
+
* download, or a tampered file at rest — see design notes on what a
|
|
79
|
+
* checksum does and doesn't guarantee against a compromised source).
|
|
80
|
+
*/
|
|
81
|
+
export async function downloadReleaseZip(version) {
|
|
82
|
+
const zipUrl = assetUrl(version, ASSET_NAME);
|
|
83
|
+
const checksumUrl = assetUrl(version, CHECKSUM_ASSET_NAME);
|
|
84
|
+
|
|
85
|
+
const [zipBuffer, checksumText] = await Promise.all([
|
|
86
|
+
fetchBuffer(zipUrl),
|
|
87
|
+
fetchText(checksumUrl).catch(() => null), // tolerate older releases with no checksum asset
|
|
88
|
+
]);
|
|
89
|
+
|
|
90
|
+
if (checksumText) {
|
|
91
|
+
const expected = checksumText.trim().split(/\s+/)[0];
|
|
92
|
+
const actual = sha256(zipBuffer);
|
|
93
|
+
if (actual !== expected) {
|
|
94
|
+
throw new Error(
|
|
95
|
+
`Checksum mismatch for ${ASSET_NAME} (expected ${expected}, got ${actual}). ` +
|
|
96
|
+
`The download may be corrupted or incomplete — try again.`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return zipBuffer;
|
|
102
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown-specific application of lib/fences.js: managed blocks for ai-docs
|
|
3
|
+
* content (CORE.md, NEW_APP.md, REFACTOR_APP.md) merged into the user's own
|
|
4
|
+
* AGENTS.md / CLAUDE.md, so that content can still be round-trip detected
|
|
5
|
+
* and updated on `toolcrib merge`, the same way vendored files under
|
|
6
|
+
* ./toolcrib/ already are.
|
|
7
|
+
*/
|
|
8
|
+
import { FENCE_STYLES, buildFence, extractFence, upsertFence } from './fences.js';
|
|
9
|
+
|
|
10
|
+
// doc-id -> source filename under ai-docs/, in the order they should read
|
|
11
|
+
// when more than one is present in the same target file.
|
|
12
|
+
export const MANAGED_DOCS = {
|
|
13
|
+
core: 'CORE.md',
|
|
14
|
+
'new-app': 'NEW_APP.md',
|
|
15
|
+
'refactor-app': 'REFACTOR_APP.md',
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// Files the CLI knows to scan for managed blocks. AGENTS.md is preferred
|
|
19
|
+
// when proposing a new block and neither file exists yet.
|
|
20
|
+
export const KNOWN_TARGET_FILES = ['AGENTS.md', 'CLAUDE.md'];
|
|
21
|
+
export const DEFAULT_TARGET_FILE = 'AGENTS.md';
|
|
22
|
+
|
|
23
|
+
/** Build a complete fenced block (start marker, content, end marker) for a doc. */
|
|
24
|
+
export function buildManagedBlock(docId, version, content) {
|
|
25
|
+
return buildFence(FENCE_STYLES.markdown, docId, version, content);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Find an existing managed block for `docId` in `fileContent`. Returns null if absent. */
|
|
29
|
+
export function extractManagedBlock(fileContent, docId) {
|
|
30
|
+
return extractFence(FENCE_STYLES.markdown, fileContent, docId);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Insert or replace the managed block for `docId` in `fileContent`.
|
|
35
|
+
* If a block for this docId already exists, only that span is replaced —
|
|
36
|
+
* everything else in the file (the user's own instructions, other docIds'
|
|
37
|
+
* blocks) is left untouched. Otherwise the block is appended.
|
|
38
|
+
*/
|
|
39
|
+
export function upsertManagedBlock(fileContent, docId, version, content) {
|
|
40
|
+
return upsertFence(FENCE_STYLES.markdown, fileContent, docId, version, content);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** List every managed docId present in `fileContent`, with its recorded version and content. */
|
|
44
|
+
export function listManagedBlocks(fileContent) {
|
|
45
|
+
return Object.keys(MANAGED_DOCS)
|
|
46
|
+
.map((docId) => {
|
|
47
|
+
const block = extractManagedBlock(fileContent, docId);
|
|
48
|
+
return block ? { docId, ...block } : null;
|
|
49
|
+
})
|
|
50
|
+
.filter(Boolean);
|
|
51
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parsePatch, applyPatch } from 'diff';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Last-resort patch application when git is unavailable and the user
|
|
7
|
+
* declined to `git init`. Uses the same `diff` library already depended
|
|
8
|
+
* on for patch generation, so no new dependency is introduced for this
|
|
9
|
+
* fallback path. Less battle-tested than `git apply` against messy
|
|
10
|
+
* real-world drift, which is why it's the fallback, not the default.
|
|
11
|
+
*/
|
|
12
|
+
export function applyPatchFallback(patchPath, projectRoot) {
|
|
13
|
+
const patchText = fs.readFileSync(patchPath, 'utf-8');
|
|
14
|
+
const [parsed] = parsePatch(patchText);
|
|
15
|
+
|
|
16
|
+
const targetRelPath = parsed.newFileName.replace(/^b\//, '');
|
|
17
|
+
const targetPath = path.join(projectRoot, targetRelPath);
|
|
18
|
+
|
|
19
|
+
const isNewFile = parsed.oldFileName === '/dev/null';
|
|
20
|
+
const currentContent = isNewFile ? '' : fs.readFileSync(targetPath, 'utf-8');
|
|
21
|
+
|
|
22
|
+
const result = applyPatch(currentContent, parsed);
|
|
23
|
+
if (result === false) {
|
|
24
|
+
return { success: false, error: 'Patch did not apply cleanly against current file content.' };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
28
|
+
fs.writeFileSync(targetPath, result);
|
|
29
|
+
return { success: true };
|
|
30
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import fsp from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createTwoFilesPatch } from 'diff';
|
|
5
|
+
|
|
6
|
+
export const PATCH_DIR = './toolcrib-patches';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Join path segments with '/' explicitly — never Node's path.join(), and
|
|
10
|
+
* never the platform separator. Every relPath handed to
|
|
11
|
+
* PendingChanges.propose() ends up in a git patch header, and git apply
|
|
12
|
+
* rejects backslash-separated paths outright.
|
|
13
|
+
*
|
|
14
|
+
* path.join() is NOT safe here even when its inputs already look like they
|
|
15
|
+
* use '/': it normalizes its result to the platform separator regardless
|
|
16
|
+
* of what separators were already present in the inputs. Confirmed via a
|
|
17
|
+
* real end-to-end `init` -> `apply` run on Windows — every nested vendored
|
|
18
|
+
* file failed with "invalid path" until every relPath construction in this
|
|
19
|
+
* CLI (commands/init.js, commands/merge.js, lib/zip.js) went through
|
|
20
|
+
* explicit forward-slash joining instead of path.join().
|
|
21
|
+
*/
|
|
22
|
+
export function joinPatchPath(...segments) {
|
|
23
|
+
return segments
|
|
24
|
+
.map((segment) => segment.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+|\/+$/g, ''))
|
|
25
|
+
.filter(Boolean)
|
|
26
|
+
.join('/');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Normalize line endings before any content comparison, so a checkout-time
|
|
31
|
+
* CRLF/LF conversion (Git's core.autocrlf, an editor's save behavior, etc.)
|
|
32
|
+
* never registers as a "real" difference. Applied consistently everywhere
|
|
33
|
+
* content is compared, never persisted — see design notes on why cached
|
|
34
|
+
* hashes proved fragile and were dropped in favor of on-demand comparison.
|
|
35
|
+
*/
|
|
36
|
+
export function normalize(content) {
|
|
37
|
+
return content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Collects proposed file changes as unified diff patches. Nothing is ever
|
|
42
|
+
* written directly to a pre-existing or ambiguous target — every mutation
|
|
43
|
+
* this CLI makes (new vendored files, package.json, .gitignore, the version
|
|
44
|
+
* lockfile) flows through here uniformly, then the human/AI applies what
|
|
45
|
+
* they want via `toolcrib apply` or `git apply` directly.
|
|
46
|
+
*
|
|
47
|
+
* Notably absent: the user's own AGENTS.md / CLAUDE.md. The CLI vendors
|
|
48
|
+
* ai-docs/ into ./toolcrib/ai-docs/ and tells the user to merge relevant
|
|
49
|
+
* content in themselves (init.js's outro) — it never reads or proposes
|
|
50
|
+
* changes to those files, so there's currently no tracked record of what
|
|
51
|
+
* content in them originated from toolcrib vs. the user's own writing.
|
|
52
|
+
*/
|
|
53
|
+
export class PendingChanges {
|
|
54
|
+
constructor() {
|
|
55
|
+
this.entries = [];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {string} relPath - path relative to the project root. Normalized
|
|
60
|
+
* to forward slashes unconditionally (see joinPatchPath's docstring) —
|
|
61
|
+
* this is the last-mile enforcement point before a patch header is
|
|
62
|
+
* built, regardless of whether the caller already went through
|
|
63
|
+
* joinPatchPath() or constructed relPath some other way.
|
|
64
|
+
* @param {string} currentContent - '' if the file doesn't exist yet
|
|
65
|
+
* @param {string} proposedContent - the desired final content
|
|
66
|
+
* @param {string} [label] - display label for the patch header
|
|
67
|
+
*/
|
|
68
|
+
propose(relPath, currentContent, proposedContent, label) {
|
|
69
|
+
relPath = relPath.replace(/\\/g, '/');
|
|
70
|
+
// label defaults to the *normalized* relPath — a default parameter
|
|
71
|
+
// expression (`label = relPath`) would capture the pre-normalization
|
|
72
|
+
// value instead, since defaults evaluate before the function body runs.
|
|
73
|
+
if (label === undefined) label = relPath;
|
|
74
|
+
if (normalize(currentContent) === normalize(proposedContent)) return; // no-op, nothing to propose
|
|
75
|
+
|
|
76
|
+
const isNewFile = currentContent === '';
|
|
77
|
+
const patch = createTwoFilesPatch(
|
|
78
|
+
isNewFile ? '/dev/null' : `a/${relPath}`,
|
|
79
|
+
`b/${relPath}`,
|
|
80
|
+
currentContent,
|
|
81
|
+
proposedContent,
|
|
82
|
+
isNewFile ? undefined : `${label} (current)`,
|
|
83
|
+
isNewFile ? `${label} (new file)` : `${label} (proposed)`
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
this.entries.push({ relPath, patch, isNewFile });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
isEmpty() {
|
|
90
|
+
return this.entries.length === 0;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
count() {
|
|
94
|
+
return this.entries.length;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
summarize() {
|
|
98
|
+
return this.entries
|
|
99
|
+
.map((e) => ` ${e.isNewFile ? '+ (new) ' : '~ '}${e.relPath}`)
|
|
100
|
+
.join('\n');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Write every staged patch to PATCH_DIR, numbered for stable apply order. */
|
|
104
|
+
async writeAll(projectRoot) {
|
|
105
|
+
const dir = path.join(projectRoot, PATCH_DIR);
|
|
106
|
+
await fsp.rm(dir, { recursive: true, force: true }); // clear stale patches from a prior run
|
|
107
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
108
|
+
|
|
109
|
+
const written = [];
|
|
110
|
+
this.entries.forEach((entry, i) => {
|
|
111
|
+
const seq = String(i + 1).padStart(4, '0');
|
|
112
|
+
const safeName = entry.relPath.replace(/[/\\]/g, '-');
|
|
113
|
+
const filePath = path.join(dir, `${seq}-${safeName}.patch`);
|
|
114
|
+
fs.writeFileSync(filePath, entry.patch);
|
|
115
|
+
written.push(filePath);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
return written;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { FENCE_STYLES, upsertFence, extractFence } from './fences.js';
|
|
4
|
+
|
|
5
|
+
// No leading "./" — git apply rejects paths with one as invalid, and
|
|
6
|
+
// every other relPath used in PendingChanges (component files, package.json)
|
|
7
|
+
// is already written without it. Consistency here matters, not just style.
|
|
8
|
+
const LOCK_PATH = 'toolcrib/.toolcrib-lock.json';
|
|
9
|
+
const GITIGNORE_ENTRIES = ['/toolcrib-patches/'];
|
|
10
|
+
const GITIGNORE_FENCE_ID = 'gitignore';
|
|
11
|
+
|
|
12
|
+
// Node's fs never strips a UTF-8 BOM from a 'utf-8' read — it stays as a
|
|
13
|
+
// literal at the start of the string. Left in place, it breaks
|
|
14
|
+
// JSON.parse() outright ("Unexpected token" — a real, well-known Node
|
|
15
|
+
// gotcha, not hypothetical: package.json/tsconfig.json saved by some
|
|
16
|
+
// Windows editors carry one), and would otherwise sit in front of whatever
|
|
17
|
+
// content starts the file (e.g. a managed fence written into a brand new
|
|
18
|
+
// AGENTS.md) without necessarily breaking regex matching, but silently
|
|
19
|
+
// corrupting any byte-for-byte comparison against BOM-less content. Strip
|
|
20
|
+
// it at the read chokepoint, once, rather than defending against it at
|
|
21
|
+
// every call site.
|
|
22
|
+
function stripBOM(text) {
|
|
23
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function readJsonIfExists(filePath) {
|
|
27
|
+
if (!fs.existsSync(filePath)) return null;
|
|
28
|
+
return JSON.parse(stripBOM(fs.readFileSync(filePath, 'utf-8')));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function readTextIfExists(filePath) {
|
|
32
|
+
return fs.existsSync(filePath) ? stripBOM(fs.readFileSync(filePath, 'utf-8')) : '';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The ONLY thing persisted locally between CLI runs is the installed
|
|
37
|
+
* version string — no cached hashes, no file-by-file state. Everything
|
|
38
|
+
* else is recomputed on demand against the immutable release artifacts,
|
|
39
|
+
* which is what keeps merge/doctor correct regardless of local
|
|
40
|
+
* environment quirks (line-ending drift, etc.) — see design notes.
|
|
41
|
+
*/
|
|
42
|
+
export function readLock(projectRoot) {
|
|
43
|
+
return readJsonIfExists(path.join(projectRoot, LOCK_PATH));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function proposeLockUpdate(projectRoot, version) {
|
|
47
|
+
const lockPath = path.join(projectRoot, LOCK_PATH);
|
|
48
|
+
const current = readTextIfExists(lockPath);
|
|
49
|
+
const proposed = JSON.stringify({ version }, null, 2) + '\n';
|
|
50
|
+
return { relPath: LOCK_PATH, current, proposed };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Propose adding toolcrib's required entries to .gitignore, idempotently.
|
|
55
|
+
* Wrapped in a `#`-comment fence (see lib/fences.js) so a future version
|
|
56
|
+
* can update or remove exactly these lines without disturbing anything the
|
|
57
|
+
* user added to .gitignore themselves — the same round-trip guarantee
|
|
58
|
+
* vendored files under ./toolcrib/ already have.
|
|
59
|
+
*
|
|
60
|
+
* Note: a pre-fence install (from before this existed) may still have a
|
|
61
|
+
* bare, unfenced `/toolcrib-patches/` line from an earlier `init`. This
|
|
62
|
+
* proposes the fenced block alongside it rather than trying to detect and
|
|
63
|
+
* remove the old line — a harmless duplicate .gitignore entry, not a
|
|
64
|
+
* correctness issue, and not worth the extra migration logic to avoid.
|
|
65
|
+
*/
|
|
66
|
+
export function proposeGitignore(projectRoot, version) {
|
|
67
|
+
const gitignorePath = path.join(projectRoot, '.gitignore');
|
|
68
|
+
const current = readTextIfExists(gitignorePath);
|
|
69
|
+
|
|
70
|
+
const proposed = upsertFence(FENCE_STYLES.hash, current, GITIGNORE_FENCE_ID, version, GITIGNORE_ENTRIES.join('\n'));
|
|
71
|
+
if (proposed === current) return null; // already present with identical content — nothing to propose
|
|
72
|
+
|
|
73
|
+
return { relPath: '.gitignore', current, proposed };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Read back what version's worth of gitignore entries is currently fenced in, if any. */
|
|
77
|
+
export function readGitignoreFenceVersion(projectRoot) {
|
|
78
|
+
const current = readTextIfExists(path.join(projectRoot, '.gitignore'));
|
|
79
|
+
return extractFence(FENCE_STYLES.hash, current, GITIGNORE_FENCE_ID)?.version ?? null;
|
|
80
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import fsp from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { downloadReleaseZip, resolveVersion } from './github.js';
|
|
6
|
+
import { extractZip, listFilesRecursive } from './zip.js';
|
|
7
|
+
|
|
8
|
+
// See the matching stripBOM in lib/project.js for why this exists — Node's
|
|
9
|
+
// fs never strips a UTF-8 BOM from a 'utf-8' read, and it breaks
|
|
10
|
+
// JSON.parse() outright. Duplicated rather than imported: it's a one-line
|
|
11
|
+
// helper and this module has no other reason to depend on project.js.
|
|
12
|
+
function stripBOM(text) {
|
|
13
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Download + extract + resolve a release into a working temp directory,
|
|
18
|
+
* returning the resolved config plus a reader for actual file contents.
|
|
19
|
+
* Nothing here is cached or persisted between runs — every operation
|
|
20
|
+
* re-fetches and re-derives from the immutable release artifact, which
|
|
21
|
+
* is what makes `init`/`merge`/`doctor` idempotent and drift-proof (see
|
|
22
|
+
* design notes on why a persistent hash lockfile was dropped).
|
|
23
|
+
*/
|
|
24
|
+
export async function fetchRelease(version) {
|
|
25
|
+
const resolvedVersion = await resolveVersion(version);
|
|
26
|
+
const zipBuffer = await downloadReleaseZip(resolvedVersion);
|
|
27
|
+
|
|
28
|
+
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-release-'));
|
|
29
|
+
await extractZip(zipBuffer, tempDir);
|
|
30
|
+
|
|
31
|
+
const configPath = path.join(tempDir, 'toolcrib.config.json');
|
|
32
|
+
const config = JSON.parse(stripBOM(fs.readFileSync(configPath, 'utf-8')));
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
version: resolvedVersion,
|
|
36
|
+
config,
|
|
37
|
+
tempDir,
|
|
38
|
+
readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
|
|
39
|
+
allFiles: () => listFilesRecursive(tempDir).filter((f) => f !== 'toolcrib.config.json'),
|
|
40
|
+
cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
|
|
41
|
+
};
|
|
42
|
+
}
|
package/src/lib/zip.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import fsp from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Extract a zip buffer into a target directory.
|
|
12
|
+
*
|
|
13
|
+
* Node has no built-in zip reader, and adding a full unzip *library*
|
|
14
|
+
* pulls in native bindings or a nontrivial pure-JS implementation for
|
|
15
|
+
* something the OS/toolchain almost always already provides. Since this
|
|
16
|
+
* is CLI-only code (never vendored to the consumer's project — see the
|
|
17
|
+
* CLI-vs-vendored dependency boundary discussed in design), shelling out
|
|
18
|
+
* to a platform unzip tool is a reasonable, low-dependency choice here.
|
|
19
|
+
* If you'd rather have zero external-binary reliance, swap this for the
|
|
20
|
+
* `unzipper` or `yauzl` npm package — either is fine for CLI-only code.
|
|
21
|
+
*/
|
|
22
|
+
export async function extractZip(zipBuffer, targetDir) {
|
|
23
|
+
await fsp.mkdir(targetDir, { recursive: true });
|
|
24
|
+
|
|
25
|
+
const tmpZipPath = path.join(os.tmpdir(), `toolcrib-${Date.now()}.zip`);
|
|
26
|
+
await fsp.writeFile(tmpZipPath, zipBuffer);
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
if (process.platform === 'win32') {
|
|
30
|
+
// PowerShell's Expand-Archive ships on all modern Windows installs.
|
|
31
|
+
await execFileAsync('powershell', [
|
|
32
|
+
'-NoProfile',
|
|
33
|
+
'-Command',
|
|
34
|
+
`Expand-Archive -Path '${tmpZipPath}' -DestinationPath '${targetDir}' -Force`,
|
|
35
|
+
]);
|
|
36
|
+
} else {
|
|
37
|
+
await execFileAsync('unzip', ['-o', '-q', tmpZipPath, '-d', targetDir]);
|
|
38
|
+
}
|
|
39
|
+
} finally {
|
|
40
|
+
await fsp.unlink(tmpZipPath).catch(() => {});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Recursively list files under a directory, returning paths relative to it.
|
|
46
|
+
* Always forward-slash, regardless of host OS: these relPaths become git
|
|
47
|
+
* patch header paths downstream (see commands/init.js, merge.js), and git
|
|
48
|
+
* apply rejects backslash-separated paths outright. path.relative() returns
|
|
49
|
+
* backslash-separated paths on win32 — confirmed via a real end-to-end run
|
|
50
|
+
* on Windows that every nested vendored file failed to apply until this
|
|
51
|
+
* was normalized here, at the source, rather than at each call site.
|
|
52
|
+
*/
|
|
53
|
+
export function listFilesRecursive(dir, base = dir) {
|
|
54
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
55
|
+
let results = [];
|
|
56
|
+
for (const entry of entries) {
|
|
57
|
+
const full = path.join(dir, entry.name);
|
|
58
|
+
if (entry.isDirectory()) {
|
|
59
|
+
results = results.concat(listFilesRecursive(full, base));
|
|
60
|
+
} else {
|
|
61
|
+
results.push(path.relative(base, full).split(path.sep).join('/'));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return results;
|
|
65
|
+
}
|