Skip to content

Commit becf804

Browse files
committed
Turn on Xcode compilation caching for SwiftPM package targets
Xcode applies its compilation cache to Swift package targets only through the per-user workspace setting CompilationCachingSetting. Project and xcconfig build settings do not reach them. The Sync SPM Autolinking build phase now writes CompilationCachingSetting=Enable to the user's WorkspaceSettings.xcsettings when the key is missing. It keeps other keys, leaves an explicit value or a malformed file alone, never fails the build, and is turned off with RCT_SPM_SKIP_COMPILATION_CACHE_SETTING=1.
1 parent 9d5467a commit becf804

4 files changed

Lines changed: 172 additions & 0 deletions

File tree

‎packages/react-native/scripts/spm/__docs__/spm-scripts.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,10 @@ those are not pins: every `add`/`update` sets them from the environment again.
318318
| `build/xcframeworks/` | `add`, `update`, `scaffold` | The `debug/` and `release/` flavor slots (symlinks into the cache), `ReactHeadersTarget/`, the headers-only xcframeworks, `Package.swift`, `flavored-frameworks.json`, `.artifact-stamp`. |
319319
| `.build/`, `Package.resolved` | Xcode / SwiftPM | SwiftPM's own build directory and resolution file. Machine-specific. |
320320

321+
The Sync build phase also writes your per-user Xcode workspace settings in
322+
`MyApp.xcodeproj/project.xcworkspace/xcuserdata/`, to turn on
323+
[compilation caching](#auto-sync).
324+
321325
`deinit` leaves all of the above in place. It is regenerable, and removing it is
322326
`rm -rf build/ .build/` (see [Removing / resetting](#removing--resetting)).
323327

@@ -377,6 +381,7 @@ value, so **members you added to it by hand are lost**.
377381
| `RN_SPM_REMOTE_URL`, `RN_SPM_REMOTE_VERSION` | Reserved for the planned remote-package mode. Not supported. See [Remote-package mode (planned)](./spm-header-paths-contract.md#remote-package-mode-planned). |
378382
| `RN_DEP_VERSION` | Version of the `ReactNativeDependencies` artifact, or `nightly`. Defaults to the React Native version. |
379383
| `HERMES_VERSION` | Version of the Hermes artifact, `nightly`, or `latest-v1`. Defaults to the locally pinned `hermes-compiler` version, else `latest-v1`. |
384+
| `RCT_SPM_SKIP_COMPILATION_CACHE_SETTING` | `1` stops the Sync build phase from turning on [compilation caching](#auto-sync) in your per-user workspace settings. Set it in the environment of the build. |
380385

381386
A tarball path that does not exist fails the download. Each tarball override
382387
applies to both flavors, so the Debug and Release slots get the same file.
@@ -717,6 +722,10 @@ rm -rf build/xcframeworks build/generated .build
717722
react-native spm update
718723
```
719724

725+
`deinit` leaves the `CompilationCachingSetting` in your per-user workspace
726+
settings. To turn compilation caching off, delete `WorkspaceSettings.xcsettings`
727+
or set the key to `Disable`.
728+
720729
Xcode's "Clean Build Folder" (Cmd+Shift+K) only removes DerivedData. It does not
721730
touch SwiftPM-generated directories. The cached xcframework slot is shared
722731
across apps; refresh it with `react-native spm update --download force`.
@@ -855,6 +864,24 @@ create the first one: see [Fresh clones & CI](#fresh-clones--ci).
855864
`build/xcframeworks/`.
856865
4. If all inputs are fresh: exits immediately (~1ms).
857866

867+
**Compilation caching.** On every build, before the staleness check, the build
868+
phase turns on Xcode's compilation cache for the user who builds. Xcode applies
869+
the cache to Swift package targets only through the per-user workspace setting
870+
`CompilationCachingSetting`; project and xcconfig build settings do not reach
871+
them. The file is
872+
`MyApp.xcodeproj/project.xcworkspace/xcuserdata/<user>.xcuserdatad/WorkspaceSettings.xcsettings`:
873+
874+
- File missing: the phase creates it with `CompilationCachingSetting` =
875+
`Enable`.
876+
- Key missing: the phase adds it with `plutil`. Other keys stay.
877+
- Key present, with any value: the phase leaves it.
878+
- File not a valid plist: the phase leaves it.
879+
880+
Xcode reads the setting from the next build on, so the build after the one that
881+
writes it fills the cache. This step never fails the build. To keep the cache
882+
off, set the key to `Disable`, or set `RCT_SPM_SKIP_COMPILATION_CACHE_SETTING=1`
883+
in the environment of the build.
884+
858885
**Ordering.** As observed in an `xcodebuild -scheme … build` log on Xcode 26.6:
859886

860887
| Step | Owner |

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

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {execFileSync, spawnSync} = require('node:child_process');
2727
const fs = require('node:fs');
2828
const os = require('node:os');
2929
const path = require('node:path');
30+
const plist = require('plist');
3031

3132
const FRAMEWORK = {
3233
id: 'react',
@@ -582,6 +583,116 @@ rm -f "$DIR/.spm-plugin-mismatch"
582583
});
583584
});
584585

586+
describe('the compilation cache workspace setting', () => {
587+
const step =
588+
/^[^\n]*RCT_SPM_SKIP_COMPILATION_CACHE_SETTING[\s\S]*?^fi$/m.exec(
589+
script,
590+
)?.[0];
591+
const itWithPlutil = process.platform === 'darwin' ? it : it.skip;
592+
593+
let root;
594+
let xcodeprojPath;
595+
let settingsPath;
596+
597+
const runStep = (env = {}) =>
598+
spawnSync('/bin/bash', ['-c', `set -euo pipefail\n${String(step)}\n`], {
599+
encoding: 'utf8',
600+
env: {
601+
PATH: process.env.PATH,
602+
PROJECT_FILE_PATH: xcodeprojPath,
603+
USER: 'builder',
604+
...env,
605+
},
606+
});
607+
const readSettings = () =>
608+
plist.parse(fs.readFileSync(settingsPath, 'utf8'));
609+
const writeSettings = settings => {
610+
fs.mkdirSync(path.dirname(settingsPath), {recursive: true});
611+
fs.writeFileSync(settingsPath, plist.build(settings));
612+
};
613+
614+
beforeEach(() => {
615+
root = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-compile-cache-'));
616+
xcodeprojPath = path.join(root, 'MyApp.xcodeproj');
617+
fs.mkdirSync(xcodeprojPath);
618+
settingsPath = path.join(
619+
xcodeprojPath,
620+
'project.xcworkspace/xcuserdata/builder.xcuserdatad/WorkspaceSettings.xcsettings',
621+
);
622+
});
623+
624+
afterEach(() => {
625+
fs.rmSync(root, {recursive: true, force: true});
626+
});
627+
628+
it('is in the build phase only, before the stale check', () => {
629+
expect(step).toBeDefined();
630+
expect(script.indexOf(String(step))).toBeLessThan(
631+
script.indexOf('STAMP='),
632+
);
633+
expect(buildSchemePreActionScript(baked)).not.toContain(
634+
'CompilationCachingSetting',
635+
);
636+
});
637+
638+
it('creates the settings file with only the setting when it is missing', () => {
639+
expect(runStep().status).toBe(0);
640+
expect(readSettings()).toEqual({CompilationCachingSetting: 'Enable'});
641+
});
642+
643+
itWithPlutil('adds the setting and keeps the other keys', () => {
644+
writeSettings({BuildLocationStyle: 'UseAppPreferences'});
645+
expect(runStep().status).toBe(0);
646+
expect(readSettings()).toEqual({
647+
BuildLocationStyle: 'UseAppPreferences',
648+
CompilationCachingSetting: 'Enable',
649+
});
650+
});
651+
652+
it('leaves a setting the user chose', () => {
653+
writeSettings({CompilationCachingSetting: 'Disable'});
654+
const before = fs.readFileSync(settingsPath);
655+
expect(runStep().status).toBe(0);
656+
expect(fs.readFileSync(settingsPath)).toEqual(before);
657+
});
658+
659+
itWithPlutil('changes nothing on a second run', () => {
660+
writeSettings({BuildLocationStyle: 'UseAppPreferences'});
661+
runStep();
662+
const afterFirstRun = fs.readFileSync(settingsPath);
663+
expect(runStep().status).toBe(0);
664+
expect(fs.readFileSync(settingsPath)).toEqual(afterFirstRun);
665+
666+
fs.rmSync(settingsPath);
667+
runStep();
668+
const created = fs.readFileSync(settingsPath);
669+
expect(runStep().status).toBe(0);
670+
expect(fs.readFileSync(settingsPath)).toEqual(created);
671+
});
672+
673+
it('leaves a malformed file untouched', () => {
674+
fs.mkdirSync(path.dirname(settingsPath), {recursive: true});
675+
fs.writeFileSync(settingsPath, '<plist><dict><key>');
676+
expect(runStep().status).toBe(0);
677+
expect(fs.readFileSync(settingsPath, 'utf8')).toBe('<plist><dict><key>');
678+
});
679+
680+
it('writes nothing when RCT_SPM_SKIP_COMPILATION_CACHE_SETTING=1', () => {
681+
expect(
682+
runStep({RCT_SPM_SKIP_COMPILATION_CACHE_SETTING: '1'}).status,
683+
).toBe(0);
684+
expect(
685+
fs.existsSync(path.join(xcodeprojPath, 'project.xcworkspace')),
686+
).toBe(false);
687+
});
688+
689+
it('does not fail the build when the file cannot be written', () => {
690+
fs.rmSync(xcodeprojPath, {recursive: true});
691+
fs.writeFileSync(xcodeprojPath, '');
692+
expect(runStep()).toMatchObject({status: 0, stderr: ''});
693+
});
694+
});
695+
585696
it('is deterministic and valid POSIX shell', () => {
586697
expect(buildSyncAutolinkingScript(baked)).toBe(script);
587698
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-sync-script-'));

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ const {
7373
const {checkSpmInvariants} = require('./spm-invariants');
7474
const fs = require('node:fs');
7575
const path = require('node:path');
76+
const plist = require('plist');
7677

7778
const {spawnSync} = jest.requireActual('node:child_process');
7879

@@ -90,6 +91,7 @@ const SPM_ENVIRONMENT = [
9091
// Rewritten with the time of every sync, by design.
9192
const SYNC_STAMP = 'build/generated/autolinking/.spm-sync-stamp';
9293
const LIBS_DIR = 'build/generated/autolinking/libs';
94+
const BUILD_USER = 'spm-lifecycle';
9395
const [CURRENT_VERSION, NEXT_VERSION] = ARTIFACT_VERSIONS;
9496

9597
let app;
@@ -226,6 +228,7 @@ function preActionDispatchesSync() {
226228
SRCROOT: app.appRoot,
227229
PROJECT_DIR: app.appRoot,
228230
PROJECT_FILE_PATH: app.xcodeprojPath,
231+
USER: BUILD_USER,
229232
},
230233
},
231234
);
@@ -410,6 +413,17 @@ describe('spm lifecycle on a fixture app', () => {
410413
});
411414
});
412415

416+
it('turns on Xcode compilation caching for the user who builds', () => {
417+
preActionDispatchesSync();
418+
const settings = path.join(
419+
app.xcodeprojPath,
420+
`project.xcworkspace/xcuserdata/${BUILD_USER}.xcuserdatad/WorkspaceSettings.xcsettings`,
421+
);
422+
expect(plist.parse(fs.readFileSync(settings, 'utf8'))).toEqual({
423+
CompilationCachingSetting: 'Enable',
424+
});
425+
});
426+
413427
it('fails sync with exit 2 when a plugin adds a framework the project does not link', async () => {
414428
app.setPluginFrameworks(PLUGIN_FRAMEWORKS);
415429
try {

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -963,6 +963,26 @@ function buildSyncAutolinkingScript(
963963
) /*: string */ {
964964
return `${nodeAndRnDirPreamble(reactNativePath)}
965965
966+
# Xcode applies compilation caching to Swift package targets only through this
967+
# per-user setting; project and xcconfig build settings do not reach them.
968+
if [ "\${RCT_SPM_SKIP_COMPILATION_CACHE_SETTING:-}" != "1" ] && [ -n "\${PROJECT_FILE_PATH:-}" ]; then
969+
WORKSPACE_SETTINGS="$PROJECT_FILE_PATH/project.xcworkspace/xcuserdata/\${USER:-$(id -un 2>/dev/null || true)}.xcuserdatad/WorkspaceSettings.xcsettings"
970+
if [ ! -e "$WORKSPACE_SETTINGS" ]; then
971+
{ mkdir -p "$(dirname "$WORKSPACE_SETTINGS")" && printf '%s\\n' \\
972+
'<?xml version="1.0" encoding="UTF-8"?>' \\
973+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' \\
974+
'<plist version="1.0">' \\
975+
'<dict>' \\
976+
'<key>CompilationCachingSetting</key>' \\
977+
'<string>Enable</string>' \\
978+
'</dict>' \\
979+
'</plist>' > "$WORKSPACE_SETTINGS"; } 2>/dev/null || true
980+
elif ! plutil -extract CompilationCachingSetting xml1 -o - "$WORKSPACE_SETTINGS" >/dev/null 2>&1 &&
981+
plutil -lint -s "$WORKSPACE_SETTINGS" >/dev/null 2>&1; then
982+
plutil -insert CompilationCachingSetting -string Enable "$WORKSPACE_SETTINGS" >/dev/null 2>&1 || true
983+
fi
984+
fi
985+
966986
AUTOLINKED_MANIFEST="$SRCROOT/build/generated/autolinking/Package.swift"
967987
OLD_SUM=""
968988
if [ -f "$AUTOLINKED_MANIFEST" ]; then

0 commit comments

Comments
 (0)