Skip to content

Commit ee2d411

Browse files
authored
Fix SwiftPM: native library added after setup is not compiled until a clean build (#60462)
When you add a native library to a SwiftPM app, xcodebuild resolves the package graph first. Then the "Sync SPM Autolinking" scheme pre-action adds the library to the Autolinked Package.swift. Xcode keeps the old package graph for the new manifest, so incremental builds never compile the library and the app fails at runtime (for example "RNSVGCircle is not registered"). Only a clean build fixed it. The pre-action now syncs only when the Autolinked manifest is missing. Once it exists, the "Sync SPM Autolinking" build phase syncs it. When that sync changes the manifest, the build fails once with "native modules changed. Build again." The next build compiles the library. Test: yarn jest packages/react-native/scripts/spm --no-cache -i (1264 passed, 0 failed).
1 parent 1df562c commit ee2d411

3 files changed

Lines changed: 69 additions & 24 deletions

File tree

‎packages/react-native/scripts/spm/__tests__/generate-spm-xcodeproj-test.js‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,7 @@ describe('sync scripts', () => {
382382
let fakeNode;
383383
let rnDir;
384384
let syncLog;
385+
let output;
385386

386387
// Does to the generated dir what a real sync does: on a mismatch it prints
387388
// the errors, records them, refreshes the stamp, and exits 2.
@@ -392,6 +393,7 @@ if [ "$1" = "--print" ]; then
392393
fi
393394
echo sync >> "$FAKE_SYNC_LOG"
394395
DIR="$SRCROOT/build/generated/autolinking"
396+
[ -n "$FAKE_MANIFEST" ] && printf '%s' "$FAKE_MANIFEST" > "$DIR/Package.swift"
395397
date > "$DIR/.spm-sync-stamp"
396398
if [ -n "$FAKE_MISMATCH" ]; then
397399
echo "$FAKE_MISMATCH" >&2
@@ -438,9 +440,9 @@ rm -f "$DIR/.spm-plugin-mismatch"
438440
fs.rmSync(root, {recursive: true, force: true});
439441
});
440442

441-
function build({mismatch}) {
443+
function build({mismatch, manifest = '', phase = script}) {
442444
fs.writeFileSync(syncLog, '');
443-
const result = spawnSync('/bin/bash', ['-c', script], {
445+
const result = spawnSync('/bin/bash', ['-c', phase], {
444446
encoding: 'utf8',
445447
env: {
446448
PATH: process.env.PATH,
@@ -450,9 +452,10 @@ rm -f "$DIR/.spm-plugin-mismatch"
450452
FAKE_RN_DIR: rnDir,
451453
FAKE_SYNC_LOG: syncLog,
452454
FAKE_MISMATCH: mismatch ? MISMATCH : '',
455+
FAKE_MANIFEST: manifest,
453456
},
454457
});
455-
const output = result.stdout + result.stderr;
458+
output = result.stdout + result.stderr;
456459
return {
457460
status: result.status,
458461
errors: output.split(MISMATCH).length - 1,
@@ -544,11 +547,43 @@ rm -f "$DIR/.spm-plugin-mismatch"
544547
syncs: 0,
545548
});
546549
});
550+
551+
describe('the Autolinked manifest', () => {
552+
const manifestPath = () => path.join(generatedDir, 'Package.swift');
553+
554+
it('the build phase fails when its sync changes the manifest', () => {
555+
fs.writeFileSync(manifestPath(), 'RNScreens\n');
556+
const manifest = 'RNScreens\nRNSVG\n';
557+
expect(build({mismatch: false, manifest}).status).toBe(1);
558+
expect(output).toContain(
559+
'error: React Native SwiftPM: native modules changed. Build again.',
560+
);
561+
expect(build({mismatch: false, manifest}).status).toBe(0);
562+
});
563+
564+
it('the build phase passes when its sync leaves the manifest unchanged', () => {
565+
fs.writeFileSync(manifestPath(), 'RNScreens\n');
566+
expect(build({mismatch: false, manifest: 'RNScreens\n'})).toEqual({
567+
status: 0,
568+
errors: 0,
569+
syncs: 1,
570+
});
571+
});
572+
573+
it('the pre-action does not sync when the manifest exists', () => {
574+
fs.writeFileSync(manifestPath(), 'RNScreens\n');
575+
const preAction = buildSchemePreActionScript(baked);
576+
expect(build({mismatch: false, phase: preAction})).toEqual({
577+
status: 0,
578+
errors: 0,
579+
syncs: 0,
580+
});
581+
});
582+
});
547583
});
548584

549-
it('is deterministic, shared with the pre-action, and valid POSIX shell', () => {
585+
it('is deterministic and valid POSIX shell', () => {
550586
expect(buildSyncAutolinkingScript(baked)).toBe(script);
551-
expect(buildSchemePreActionScript(baked)).toBe(script);
552587
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-sync-script-'));
553588
const file = path.join(dir, 'sync.sh');
554589
fs.writeFileSync(file, script);

‎packages/react-native/scripts/spm/__tests__/spm-lifecycle-test.js‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ const {
7171
createSpmFixtureApp,
7272
} = require('./spm-fixture-app');
7373
const {checkSpmInvariants} = require('./spm-invariants');
74-
const {DOMParser} = require('@xmldom/xmldom');
7574
const fs = require('node:fs');
7675
const path = require('node:path');
7776

@@ -198,19 +197,13 @@ function assertHermesCompilerResolves() {
198197
}
199198
}
200199

200+
// The pre-action exits early once the manifest exists; from then on the build
201+
// phase script runs the same stale check.
201202
function syncPreActionScript() {
202-
const scheme = new DOMParser().parseFromString(
203-
fs.readFileSync(app.schemePath, 'utf8'),
204-
'text/xml',
203+
return fs.readFileSync(
204+
path.join(app.appRoot, 'ReactNativeSPM/Scripts/sync-autolinking.sh'),
205+
'utf8',
205206
);
206-
const actions = Array.from(scheme.getElementsByTagName('ActionContent'));
207-
const preAction = actions.find(
208-
action => action.getAttribute('title') === 'Sync SPM Autolinking',
209-
);
210-
if (preAction == null) {
211-
throw new Error('The scheme has no "Sync SPM Autolinking" pre-action');
212-
}
213-
return preAction.getAttribute('scriptText');
214207
}
215208

216209
// Runs the scheme pre-action as Xcode would and reports whether its stale

‎packages/react-native/scripts/spm/generate-spm-xcodeproj.js‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -940,25 +940,42 @@ fi
940940
`;
941941
}
942942

943-
// Scheme pre-action: re-run codegen + autolinking before package resolution.
943+
// Scheme pre-action: syncs only while the Autolinked manifest is missing.
944944
function buildSchemePreActionScript(
945945
reactNativePath /*: string */,
946946
) /*: string */ {
947-
return `${nodeAndRnDirPreamble(reactNativePath)}
947+
return `# Runs after package resolution: rewriting the manifest here goes stale.
948+
if [ -f "$SRCROOT/build/generated/autolinking/Package.swift" ]; then
949+
exit 0
950+
fi
951+
952+
${nodeAndRnDirPreamble(reactNativePath)}
948953
949954
${syncStaleCheckAndDispatch()}
950955
`;
951956
}
952957

953-
// The in-target phase is only an autolinking safety net. Runtime framework
958+
// The in-target phase keeps autolinking current. Runtime framework
954959
// selection is expressed entirely through build settings and the independent
955960
// Embed React Native Flavored Frameworks phase.
956961
function buildSyncAutolinkingScript(
957962
reactNativePath /*: string */,
958963
) /*: string */ {
959964
return `${nodeAndRnDirPreamble(reactNativePath)}
960965
966+
AUTOLINKED_MANIFEST="$SRCROOT/build/generated/autolinking/Package.swift"
967+
OLD_SUM=""
968+
if [ -f "$AUTOLINKED_MANIFEST" ]; then
969+
OLD_SUM="$(cksum < "$AUTOLINKED_MANIFEST")"
970+
fi
971+
961972
${syncStaleCheckAndDispatch()}
973+
974+
# Xcode planned this build with the old package graph; the next uses the new.
975+
if [ -n "$OLD_SUM" ] && [ "$(cksum < "$AUTOLINKED_MANIFEST")" != "$OLD_SUM" ]; then
976+
echo "error: React Native SwiftPM: native modules changed. Build again."
977+
exit 1
978+
fi
962979
`;
963980
}
964981
// XML-attribute escape. The sync script uses `>` and `&` for redirection and
@@ -1768,8 +1785,8 @@ function injectSpmIntoPbxproj(
17681785
),
17691786
};
17701787

1771-
// 6. The Sync SPM Autolinking build phase (safety net; the scheme pre-action
1772-
// is what fires before SPM resolution). Prepended so it runs before
1788+
// 6. The Sync SPM Autolinking build phase (keeps the Autolinked manifest
1789+
// current). Prepended so it runs before
17731790
// Sources. We do NOT add a JS-bundle phase — an existing app already
17741791
// bundles JS via its own phase.
17751792
const syncPhaseUuid = mkUuid('PBXShellScriptBuildPhase', 'SyncAutolinking');
@@ -2217,8 +2234,8 @@ function addPreActionToScheme(
22172234
}
22182235

22192236
/**
2220-
* Ensure the app target's shared scheme runs the sync pre-action before SPM
2221-
* resolution. Updates the scheme that builds the target if one exists,
2237+
* Ensure the app target's shared scheme runs the sync pre-action before each
2238+
* build. Updates the scheme that builds the target if one exists,
22222239
* otherwise creates a fresh shared scheme. Returns 'updated' | 'created' |
22232240
* 'unchanged'.
22242241
*/

0 commit comments

Comments
 (0)