Skip to content

Commit c5278fd

Browse files
kraenhansenclaude
andcommitted
Add a ferric init command (#484)
* Add a `ferric init` command Scaffolds a package building a Rust Node-API module: the package.json, Cargo.toml, build.rs, src/lib.rs and .gitignore it needs, plus an entry in the workspace of the mono-repo it is initialized into. Run against a package that already exists, it updates rather than overwrites: every value already declared is kept, so a package only gains what it lacks, and an existing Cargo.toml is left untouched with notices about anything missing from it. `--dry-run` prints the plan without applying it. Ferric now runs its tests as part of the workspace test script, one of which asserts that initializing the checked-in ferric-example changes nothing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019peL1QhG54ysW6r3GKqkbo * Address review of the `ferric init` command Parse Cargo manifests with smol-toml and match workspace patterns with picomatch (what pnpm's own tooling matches with) instead of hand-rolled scanners, print a diff of every file being updated, and skip ancestors which can't be read or parsed while looking for the workspace. A test now asserts the init template declares the same dependency versions as the ferric-example, which CI builds and runs on devices — bumping the pins there fails until the template follows. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019peL1QhG54ysW6r3GKqkbo * Refine `ferric init` for existing packages and tie it to the example Bump outdated dependencies and napi crates in place, skip differing entrypoints and source files with a diff unless `--force` is passed, and make the Node-API version, crate versions and release profile configurable. Regenerate ferric-example with the new `init-ferric-example` script, which CI runs to fail on any difference from what `ferric init` generates. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * ci: trigger label-gated jobs Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Fix the release profile placeholder on CRLF checkouts Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Allow CRLF in the release profile test Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Split `ferric init` planning into steps Each step returns its changes, skips and notices without touching shared state, and package.json edits are pure functions compared against the original rather than tracked with a flag. Planning fails if two steps change the same file. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Run init steps through an async wrapper Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2daaa39 commit c5278fd

21 files changed

Lines changed: 2258 additions & 16 deletions

‎.changeset/ferric-init-command.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"ferric-cli": minor
3+
---
4+
5+
Add a `ferric init [path]` command, scaffolding a package building a Rust Node-API module.
6+
7+
It writes the `package.json`, `Cargo.toml`, `build.rs`, `src/lib.rs` and `.gitignore` a package needs, and adds it to the workspace of the mono-repo it is initialized into. Run against a package that already exists, it bumps outdated dependencies and crates in place, and prints a diff for every update. A differing entrypoint or source file is skipped with a diff to merge by hand, unless `--force` is passed. `--dry-run` prints all of this without writing anything.
8+
9+
A new `Cargo.toml` can be configured with `--node-api-version`, `--napi-crate-version`, `--napi-derive-crate-version`, `--napi-build-crate-version` and `--release-profile`.

‎.github/workflows/check.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ jobs:
7575
# weak-node-api's codegen it can't be reproduced here without reintroducing a
7676
# native build into the fastest-feedback job. See #414.
7777
- run: pnpm --filter weak-node-api run prebuild:prepare
78+
- run: pnpm run init-ferric-example
79+
- name: Verify ferric-example matches what ferric init generates
80+
run: |
81+
git status --porcelain packages/ferric-example
82+
git diff --exit-code packages/ferric-example
83+
test -z "$(git status --porcelain packages/ferric-example)"
7884
- run: pnpm run lint
7985
env:
8086
DEBUG: eslint:eslint

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
"changeset": "changeset",
2020
"release": "node --run prerelease && changeset publish",
2121
"prerelease": "node --run build && pnpm --recursive run prerelease && node --run publint",
22-
"init-macos-test-app": "node scripts/init-macos-test-app.ts"
22+
"init-macos-test-app": "node scripts/init-macos-test-app.ts",
23+
"init-ferric-example": "node scripts/init-ferric-example.ts"
2324
},
2425
"author": {
2526
"name": "Callstack",

‎packages/ferric-example/Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/ferric-example/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "ferric-example"
3-
version = "1.0.0"
3+
version = "0.1.0"
44
edition = "2021"
55
license = "MIT"
66

‎packages/ferric-example/package.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
"name": "@react-native-node-api/ferric-example",
33
"version": "0.1.3",
44
"private": true,
5-
"type": "commonjs",
65
"homepage": "https://github.com/callstackincubator/react-native-node-api",
76
"repository": {
87
"type": "git",
98
"url": "git+https://github.com/callstackincubator/react-native-node-api.git",
109
"directory": "packages/ferric-example"
1110
},
11+
"type": "commonjs",
1212
"main": "ferric_example.js",
1313
"types": "ferric_example.d.ts",
1414
"files": [
@@ -19,8 +19,8 @@
1919
],
2020
"scripts": {
2121
"build": "ferric build",
22-
"bootstrap": "node --run build",
23-
"build:types": "ferric build --dts-only"
22+
"build:types": "ferric build --dts-only",
23+
"bootstrap": "node --run build"
2424
},
2525
"dependencies": {
2626
"react-native-node-api": "workspace:*"

‎packages/ferric/README.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,42 @@ features = ["napi3"]
1919
```
2020

2121
Pass `--skip-feature-check` to bypass the check.
22+
23+
## `ferric init [path]`
24+
25+
Scaffold a package building a Rust Node-API module, or bring an existing package
26+
up to what `ferric build` expects of it:
27+
28+
```
29+
npx ferric init packages/my-addon
30+
```
31+
32+
The command creates whatever is missing — `package.json`, `Cargo.toml`,
33+
`build.rs`, `src/lib.rs` and `.gitignore` — and adds the package to the
34+
`pnpm-workspace.yaml` or `"workspaces"` of the mono-repo it is initialized into.
35+
36+
Running it against a package which already exists updates rather than overwrites:
37+
38+
- `package.json` gains the scripts, dependencies and prebuilt artifacts it lacks, and outdated dependencies are bumped.
39+
- An existing `Cargo.toml` keeps its comments and formatting. Outdated `napi`, `napi-derive` and `napi-build` versions are bumped in place, and the command points out anything else `ferric build` needs.
40+
- A `main`, `types`, `src/lib.rs` or `build.rs` that differs is skipped, printing a diff to merge by hand. Pass `--force` to overwrite them instead.
41+
42+
A newly created `Cargo.toml` can be configured with:
43+
44+
- `--node-api-version <version>`: the `napiN` feature to enable, defaulting to 3.
45+
- `--napi-crate-version`, `--napi-derive-crate-version` and `--napi-build-crate-version`: the crate versions, defaulting to those tested with `ferric-example`. These also set what an existing `Cargo.toml` is bumped to.
46+
- `--release-profile <speed|size|none>`: `speed` (the default) enables `lto` and a single codegen unit, `size` also optimizes for size and strips symbols, and `none` leaves `[profile.release]` out.
47+
48+
The name of the crate defaults to the package name without its npm scope
49+
(`@my-org/my-addon` becomes `my-addon`) and can be set with `--name`. Cargo
50+
normalizes it to `my_addon` for the artifacts it produces, which is the basename
51+
`ferric build` writes its outputs and entrypoint with.
52+
53+
Every file it updates is printed as a diff, and `--dry-run` prints the whole
54+
plan without writing anything:
55+
56+
```
57+
npx ferric init packages/my-addon --dry-run
58+
```
59+
60+
The [`ferric-example`](../ferric-example) package is generated by this command: run `pnpm run init-ferric-example` from the root of the repository after changing the templates, which CI asserts leaves no diff.

‎packages/ferric/package.json‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@
1111
"type": "module",
1212
"files": [
1313
"bin",
14-
"dist"
14+
"dist",
15+
"!dist/**/*.test.d.ts",
16+
"!dist/**/*.test.d.ts.map",
17+
"templates"
1518
],
1619
"bin": {
1720
"ferric": "./bin/ferric.js"
@@ -23,8 +26,16 @@
2326
"dependencies": {
2427
"@napi-rs/cli": "~3.10.8",
2528
"@react-native-node-api/cli-utils": "workspace:*",
29+
"diff": "^9.0.0",
30+
"picomatch": "^4.0.5",
2631
"react-native-node-api": "workspace:*",
32+
"semver": "^7.8.5",
33+
"smol-toml": "^1.8.0",
2734
"weak-node-api": "workspace:*",
2835
"zod": "^4.1.11"
36+
},
37+
"devDependencies": {
38+
"@types/picomatch": "^4.0.3",
39+
"@types/semver": "^7.8.0"
2940
}
3041
}
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
import { chalk } from "@react-native-node-api/cli-utils";
2+
import semver from "semver";
3+
import { parse as parseToml } from "smol-toml";
4+
5+
import { MAX_NODE_API_VERSION, getNodeApiVersion } from "./features.js";
6+
import { isRecord } from "./json.js";
7+
8+
export type CrateVersions = {
9+
napi: string;
10+
"napi-derive": string;
11+
"napi-build": string;
12+
};
13+
14+
const CRATES = [
15+
{ crate: "napi", table: "dependencies" },
16+
{ crate: "napi-derive", table: "dependencies" },
17+
{ crate: "napi-build", table: "build-dependencies" },
18+
] satisfies { crate: keyof CrateVersions; table: string }[];
19+
20+
/**
21+
* Cargo separates comparators with commas, which semver expects as spaces.
22+
*/
23+
function toSemverRange(requirement: string) {
24+
return semver.validRange(requirement.replaceAll(",", " "));
25+
}
26+
27+
export function isCrateVersion(requirement: string) {
28+
return toSemverRange(requirement) !== null;
29+
}
30+
31+
/**
32+
* Whether a declared version requirement allows only versions below the wanted
33+
* one. Requirements which aren't versions at all are never considered outdated.
34+
*/
35+
export function isOutdated(declared: string, wanted: string) {
36+
const declaredRange = toSemverRange(declared);
37+
const wantedRange = toSemverRange(wanted);
38+
if (!declaredRange || !wantedRange || declaredRange === "*") {
39+
return false;
40+
}
41+
return semver.gt(
42+
semver.minVersion(wantedRange) ?? "0.0.0",
43+
semver.minVersion(declaredRange) ?? "0.0.0",
44+
);
45+
}
46+
47+
/**
48+
* Replace a version in the text of a manifest, as serializing a parsed manifest
49+
* would lose its comments and formatting.
50+
*/
51+
function replaceCrateVersion({
52+
contents,
53+
table,
54+
crate,
55+
version,
56+
}: {
57+
contents: string;
58+
table: string;
59+
crate: string;
60+
version: string;
61+
}) {
62+
let section = "";
63+
const lines = contents.split("\n").map((line) => {
64+
const header = line.match(/^\s*\[([^[\]]+)\]/);
65+
if (header) {
66+
section = header[1].trim();
67+
return line;
68+
}
69+
const inTable = section === table && line.match(`^\\s*"?${crate}"?\\s*=`);
70+
const inCrateTable =
71+
section === `${table}.${crate}` && line.match(/^\s*version\s*=/);
72+
if (!inTable && !inCrateTable) {
73+
return line;
74+
}
75+
const pattern = inTable
76+
? /(=\s*(?:\{[^}]*?\bversion\s*=\s*)?)(["'])[^"']*\2/
77+
: /(=\s*)(["'])[^"']*\2/;
78+
return line.replace(pattern, `$1$2${version}$2`);
79+
});
80+
return lines.join("\n");
81+
}
82+
83+
function getCrateDeclaration(
84+
manifest: Record<string, unknown>,
85+
table: string,
86+
crate: string,
87+
) {
88+
const dependencies = manifest[table];
89+
return isRecord(dependencies) ? dependencies[crate] : undefined;
90+
}
91+
92+
function getStringArray(value: unknown) {
93+
return Array.isArray(value)
94+
? value.filter((item) => typeof item === "string")
95+
: [];
96+
}
97+
98+
function inspectFeatures(dependencies: Record<string, unknown>) {
99+
const result: string[] = [];
100+
const napi = dependencies["napi"];
101+
if (isRecord(napi) || typeof napi === "string") {
102+
if (!isRecord(napi) || napi["default-features"] !== false) {
103+
result.push(
104+
`Cargo.toml doesn't declare ${chalk.blue("default-features = false")} on ${chalk.blue("napi")}, which ferric build rejects`,
105+
);
106+
}
107+
const features = isRecord(napi) ? getStringArray(napi["features"]) : [];
108+
if (getNodeApiVersion(features) > MAX_NODE_API_VERSION) {
109+
result.push(
110+
`Cargo.toml enables a ${chalk.blue("napi")} feature above the Node-API version ${MAX_NODE_API_VERSION} supported by the host`,
111+
);
112+
}
113+
}
114+
const napiSys = dependencies["napi-sys"];
115+
if (isRecord(napiSys) || typeof napiSys === "string") {
116+
const version = isRecord(napiSys) ? napiSys["version"] : napiSys;
117+
if (typeof version === "string" && version.startsWith("=")) {
118+
result.push(
119+
`Cargo.toml pins ${chalk.blue(`napi-sys ${version}`)}, which is likely to conflict with newer ${chalk.blue("napi")} versions: remove the pin`,
120+
);
121+
}
122+
const features = isRecord(napiSys)
123+
? getStringArray(napiSys["features"])
124+
: [];
125+
if (features.includes("dyn-symbols")) {
126+
result.push(
127+
`Cargo.toml enables the ${chalk.blue("dyn-symbols")} feature of ${chalk.blue("napi-sys")}, which ferric build rejects`,
128+
);
129+
}
130+
}
131+
return result;
132+
}
133+
134+
/**
135+
* Bump outdated crates of an existing manifest in place and report anything else
136+
* it needs to build into a Node-API module. Everything but those versions is
137+
* left to the developer.
138+
*/
139+
export function updateCargoManifest(
140+
contents: string,
141+
crateVersions: CrateVersions,
142+
) {
143+
let manifest: unknown;
144+
try {
145+
manifest = parseToml(contents);
146+
} catch (error) {
147+
return {
148+
contents,
149+
notices: [
150+
`Cargo.toml could not be parsed: ${error instanceof Error ? error.message : String(error)}`,
151+
],
152+
};
153+
}
154+
if (!isRecord(manifest)) {
155+
return { contents, notices: ["Cargo.toml doesn't declare a package"] };
156+
}
157+
const parsed = manifest;
158+
const notices: string[] = [];
159+
const lib = parsed["lib"];
160+
const crateType = isRecord(lib) ? lib["crate-type"] : undefined;
161+
if (!Array.isArray(crateType) || !crateType.includes("cdylib")) {
162+
notices.push(
163+
`Cargo.toml doesn't declare ${chalk.blue('crate-type = ["cdylib"]')} in its ${chalk.blue("[lib]")} section, which Node-API modules are built as`,
164+
);
165+
}
166+
167+
let updated = contents;
168+
for (const { crate, table } of CRATES) {
169+
const wanted = crateVersions[crate];
170+
const declaration = getCrateDeclaration(parsed, table, crate);
171+
if (declaration === undefined) {
172+
notices.push(
173+
`Cargo.toml is missing ${chalk.blue(crate)} from its ${chalk.blue(`[${table}]`)}`,
174+
);
175+
continue;
176+
}
177+
const declared = isRecord(declaration)
178+
? declaration["version"]
179+
: declaration;
180+
if (typeof declared !== "string") {
181+
notices.push(
182+
`Cargo.toml doesn't declare ${chalk.blue(crate)} with a version: make sure it resolves to ${chalk.blue(wanted)} or newer`,
183+
);
184+
} else if (isOutdated(declared, wanted)) {
185+
const replaced = replaceCrateVersion({
186+
contents: updated,
187+
table,
188+
crate,
189+
version: wanted,
190+
});
191+
const result: unknown = parseToml(replaced);
192+
const resolved = isRecord(result)
193+
? getCrateDeclaration(result, table, crate)
194+
: undefined;
195+
const version = isRecord(resolved) ? resolved["version"] : resolved;
196+
if (version === wanted) {
197+
updated = replaced;
198+
} else {
199+
notices.push(
200+
`Couldn't update ${chalk.blue(crate)} in Cargo.toml: change ${chalk.blue(declared)} to ${chalk.blue(wanted)}`,
201+
);
202+
}
203+
}
204+
}
205+
206+
const dependencies = parsed["dependencies"];
207+
if (isRecord(dependencies)) {
208+
notices.push(...inspectFeatures(dependencies));
209+
}
210+
return { contents: updated, notices };
211+
}

0 commit comments

Comments
 (0)