fix(swiftpm): fix two ways array build settings were mishandled (#57744)

Summary:
Two bugs in `addArrayStringValues`, which adds members to an array build setting (`HEADER_SEARCH_PATHS`, `OTHER_LDFLAGS`, `FRAMEWORK_SEARCH_PATHS`, `LD_RUNPATH_SEARCH_PATHS`). Both hit real projects; neither was visible from the existing fixture.

**1. A promoted scalar was never restored.** A setting that already exists as a scalar gets promoted to a `( … )` array, but that was recorded as a plain member-append — so `deinit` stripped the members and left the array shell plus its injected `"$(inherited)"` behind. Stock Xcode projects hit this: the app template sets `LD_RUNPATH_SEARCH_PATHS = "$(inherited) executable_path/Frameworks";` as a target-level scalar.

Fixed by pinning the pre-injection value in `.spm-injected.json` and restoring it in place. It is stored raw (a bare scalar's token runs to the `;`, carrying whitespace that must come back), recorded only if the merge actually changed the field, and not restored if the field is gone.

**2. A one-line array was corrupted.** The append anchored on `lastIndexOf('\n', tokenEnd - 1)`, which assumes multi-line. With no newline in the value that lands on the *previous* line, so members were spliced above the field, outside the array:

```
{
		"/new",                             ← bare entry in the dict body: invalid pbxproj
	HEADER_SEARCH_PATHS = ("/vendor", );    ← member never added
}
```

The result is a project Xcode cannot open, and `deinit` could not remove the stray line. Xcode writes multi-line arrays, but hand-edited projects and other generators (XcodeGen, Tuist) emit compact ones. Fixed by splicing inline ahead of the `)`; removal gained matching delimiter-anchored patterns, so the span removed is the span inserted. The dedupe parse was also quote-blind — a member holding a quoted comma parsed as two tokens — and is now quote-aware.

**Tradeoff:** reversing a promotion rewrites the whole field, so members hand-added to a promoted array afterwards are lost.

**Rebase note:** `main` has since grown an overlapping guard (`buildSettingValueTokens`) that skips the append when every value is already present, avoiding the *no-op* promotion. It is kept and complements this change: main still promotes irreversibly when there *is* a fresh value to add to a scalar, which is what the restore here covers. The two records stay mutually exclusive per key, pinned by a test.

## Changelog:

[Internal] [Fixed] - SwiftPM: `spm deinit` restores a promoted scalar build setting, and `spm add` no longer corrupts a one-line array

Pull Request resolved: https://github.com/react/react-native/pull/57744

Test Plan:
`yarn jest packages/react-native/scripts` → **963 tests, 32 suites** green; eslint, prettier and flow clean.

Written red first: byte-identical `add` → `deinit` round-trips for each pre-existing shape (absent, multi-line, bare and quoted scalars, and the one-line forms), plus `add` → `update` → `deinit`. The multi-line path is unchanged byte-for-byte, verified by a differential harness over 48 add/remove cases against the previous implementation.

Re-verified after the rebase on the committed `HelloWorld.xcodeproj`, driving the real `injectSpmIntoExistingXcodeproj` / `removeSpmInjection`. On `main` a one-line `HEADER_SEARCH_PATHS` gains a bare `"…/autolinking/headers",` entry above the field and never receives the member; with this change it lands inside the array, and a pre-existing scalar comes back exactly.

Reviewed By: fabriziocucci

Differential Revision: D114317839

Pulled By: cipolleschi

fbshipit-source-id: 08bc81f80855721bf2123143063462109a99ac25
This commit is contained in:
Christian Falch authored and meta-codesync[bot] committed 2026-08-18 05:08:17 -07:00
1 parent 385fa84925
commit 8ac3e2fa58
6 files changed
+579 -29

No files matched your search

@@ -222,7 +222,7 @@ left alone.
| Path | Commit? | Why |
|------|---------|-----|
| `MyApp.xcodeproj/` | Yes | Your project, with SwiftPM injected in place. Holds your signing, capabilities, Build Phases — `add` only adds SwiftPM refs/settings, additively. |
| `MyApp.xcodeproj/.spm-injected.json` | Yes | Marker recording every edit `add` made, so `deinit` can surgically reverse it and re-runs stay idempotent. Also pins settings later runs and Xcode builds must reuse: the `--version` pin (`artifactsVersionOverride`) that keeps later runs on the same artifact slots, and the [autolinking config command](#the-autolinking-config-command-is-remembered). |
| `MyApp.xcodeproj/.spm-injected.json` | Yes | Marker recording every edit `add` made — plus the pre-injection value of any build setting it rewrote — so `deinit` can surgically reverse it and re-runs stay idempotent. Also pins settings later runs and Xcode builds must reuse: the `--version` pin (`artifactsVersionOverride`) that keeps later runs on the same artifact slots, and the [autolinking config command](#the-autolinking-config-command-is-remembered). |
| `build/generated/` | No | Codegen/autolinking output; regenerated |
| `build/xcframeworks/` | No | Symlinks to the machine-local artifact cache |
| `Package.resolved` | No | SwiftPM resolution file; machine-specific |
@@ -234,7 +234,22 @@ stays untouched, and a re-run is a no-op. The injected refs point at three
stable sub-package paths under `build/`; adding or removing community deps
changes the sub-package contents (gitignored) and never re-injects. `deinit`
removes exactly what was injected (using the marker), leaving the project
byte-identical to its pre-`add` state.
byte-identical to its pre-`add` state — with one exception, described next.
**Build settings that already exist** are edited in place. The four array
settings `add` merges into — `HEADER_SEARCH_PATHS`, `OTHER_LDFLAGS`,
`FRAMEWORK_SEARCH_PATHS`, `LD_RUNPATH_SEARCH_PATHS` — keep the shape they were
written in: Xcode's multi-line form as well as the compact one-line form hand
edits and other generators (XcodeGen, Tuist) emit. One that exists as a plain
*scalar* is promoted to a `( … )` array — the shape an Xcode-authored target can
carry, e.g. a
`LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";` written
as a scalar rather than a list. `add` records the pre-injection value in the
marker and
`deinit` restores it by rewriting the whole field — once folded together, the
injected members and your own are indistinguishable — so **members you add to
a promoted array by hand afterwards are lost**. That applies to `update` too,
which reverts to the recorded baseline before re-injecting.
Because everything under `build/` is gitignored, a clean checkout has no
resolvable Swift packages until they are regenerated — see the next section.
@@ -56,6 +56,15 @@ function buildSettingsOf(text, configUuid) {
);
return text.slice(open, text.indexOf('};', open));
}
// Derive a variant whose app-target configs already carry HEADER_SEARCH_PATHS,
// set to any valid pbxproj value: a plain scalar (which injection promotes to an
// array) or an array injection appends to.
function withHeaderSearchPaths(value) {
return PLAIN.replaceAll(
'PRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;',
`HEADER_SEARCH_PATHS = ${value};\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;`,
);
}
const RN_PATH = '../node_modules/react-native';
@@ -289,6 +298,50 @@ describe('injectSpmIntoPbxproj — Tier 2 (build settings + phase)', () => {
expect(syncIdx).toBeLessThan(sourcesIdx);
});
it.each([
[
'"$(inherited)"',
['"$(inherited)"', '"$(SRCROOT)/build/generated/autolinking/headers"'],
],
[
'"$(inherited) $(SRCROOT)/vendor/include"',
[
'"$(inherited)"',
'"$(inherited) $(SRCROOT)/vendor/include"',
'"$(SRCROOT)/build/generated/autolinking/headers"',
],
],
])(
'promotes a pre-existing HEADER_SEARCH_PATHS scalar (%s) to an array, keeping its value and one $(inherited)',
(scalar, expectedMembers) => {
const {text} = inject(withHeaderSearchPaths(scalar));
const arrays = [
...text.matchAll(/HEADER_SEARCH_PATHS = \(\n([\s\S]*?)\t+\);/g),
].map(m =>
m[1]
.split('\n')
.map(line => line.trim().replace(/,$/, ''))
.filter(member => member.length > 0),
);
// Both app-target configs (Debug + Release).
expect(arrays).toEqual([expectedMembers, expectedMembers]);
},
);
it('appends to a pre-existing ONE-LINE HEADER_SEARCH_PATHS array in place', () => {
const {text} = inject(withHeaderSearchPaths('("$(inherited)", )'));
expect(isBalanced(text)).toBe(true);
const arrays = [
...text.matchAll(/HEADER_SEARCH_PATHS = \(([^\n]*)\);/g),
].map(m => m[1]);
// Both app-target configs, each keeping the one-line shape it was written in.
expect(arrays).toEqual(
Array(2).fill(
'"$(inherited)", "$(SRCROOT)/build/generated/autolinking/headers", ',
),
);
});
it('adds one generated embed phase immediately after Frameworks', () => {
const {text} = inject(PLAIN);
expect(text).not.toContain('Fix SPM Embedded Flavor');
@@ -39,12 +39,41 @@ afterEach(() => {
// Build a throwaway app dir: <tmp>/MyApp.xcodeproj/project.pbxproj seeded with
// the plain (SPM-only) fixture, and a node_modules/react-native sibling so the
// relative reactNativePath resolves.
function scaffoldApp() {
// Pre-existing values for an injected array setting (HEADER_SEARCH_PATHS),
// seeded into both app-target configs. The plain fixture has none, so it only
// ever exercises the create-from-absent path; deinit must restore each of
// these forms — a plain scalar is ordinary, valid pbxproj.
const PRE_EXISTING_HEADER_SEARCH_PATHS = {
'a bare $(inherited) scalar': '"$(inherited)"',
'a scalar with real content': '"$(inherited) $(SRCROOT)/vendor/include"',
'an array': '(\n\t\t\t\t"$(inherited)",\n\t\t\t)',
// What hand edits and other generators (XcodeGen, Tuist) write.
'a one-line array': '("$(inherited)", )',
};
// Seed a whole `KEY = value;` field (comments and stray whitespace included)
// into both app-target configs.
function withSetting(field /*: string */) {
return PLAIN.replaceAll(
'PRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;',
`${field}\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;`,
);
}
function withHeaderSearchPaths(value /*: string */) {
return withSetting(`HEADER_SEARCH_PATHS = ${value};`);
}
function scaffoldApp(pbxproj /*: string */ = PLAIN) {
const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-deinit-'));
scaffoldedAppRoots.push(appRoot);
const xcodeprojPath = path.join(appRoot, 'MyApp.xcodeproj');
fs.mkdirSync(xcodeprojPath, {recursive: true});
fs.writeFileSync(path.join(xcodeprojPath, 'project.pbxproj'), PLAIN, 'utf8');
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
pbxproj,
'utf8',
);
const rnRoot = path.join(appRoot, 'node_modules', 'react-native');
fs.mkdirSync(rnRoot, {recursive: true});
const artifactRoot = path.join(appRoot, 'build', 'xcframeworks');
@@ -1179,3 +1208,172 @@ describe('readPinnedConfigCommand', () => {
expect(readPinnedConfigCommand(appRoot)).toBeNull();
});
});
describe.each(Object.entries(PRE_EXISTING_HEADER_SEARCH_PATHS))(
'removeSpmInjection with HEADER_SEARCH_PATHS already set to %s',
(_label, value) => {
it('restores the pre-existing value byte-for-byte', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withHeaderSearchPaths(value),
);
const before = pbxprojOf(xcodeprojPath);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(pbxprojOf(xcodeprojPath)).not.toBe(before);
expect(removeSpmInjection({appRoot, xcodeprojPath}).status).toBe(
'removed',
);
expect(pbxprojOf(xcodeprojPath)).toBe(before);
});
it('re-syncing is byte-for-byte identical', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withHeaderSearchPaths(value),
);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const first = pbxprojOf(xcodeprojPath);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(pbxprojOf(xcodeprojPath)).toBe(first);
});
},
);
// findField's token for a BARE scalar ends AT the `;`, so it includes any
// whitespace before it. Deinit must put those bytes back exactly, not a
// tidied-up version of them.
describe.each([
'HEADER_SEARCH_PATHS = $(inherited) ; /* note */',
'HEADER_SEARCH_PATHS = ;',
])('removeSpmInjection with the untrimmed scalar `%s`', field => {
it('restores it byte-for-byte', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(withSetting(field));
const before = pbxprojOf(xcodeprojPath);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(pbxprojOf(xcodeprojPath)).not.toBe(before);
expect(removeSpmInjection({appRoot, xcodeprojPath}).status).toBe('removed');
expect(pbxprojOf(xcodeprojPath)).toBe(before);
});
});
describe('a scalar array setting injection has nothing to add to', () => {
const SCALAR = 'FRAMEWORK_SEARCH_PATHS = "$(inherited)";';
const EDITED = 'FRAMEWORK_SEARCH_PATHS = "$(inherited) $(SRCROOT)/Vendor";';
// The fixture's flavored-frameworks manifest is empty, so
// FRAMEWORK_SEARCH_PATHS is injected with no values at all.
it('is left untouched, unrecorded, and survives a later user edit', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(withSetting(SCALAR));
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const injected = pbxprojOf(xcodeprojPath);
expect(injected).toContain(SCALAR);
expect(injected).not.toMatch(/FRAMEWORK_SEARCH_PATHS = \(/);
for (const change of readMarker(xcodeprojPath).buildSettingChanges) {
expect(change.promotedArrayScalars ?? {}).not.toHaveProperty(
'FRAMEWORK_SEARCH_PATHS',
);
}
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
injected.replaceAll(SCALAR, EDITED),
'utf8',
);
removeSpmInjection({appRoot, xcodeprojPath});
const after = pbxprojOf(xcodeprojPath);
expect(after).toContain(EDITED);
expect(after).not.toContain(SCALAR);
});
});
describe('a promoted array setting the user deleted after add', () => {
const SCALAR = '"$(inherited) $(SRCROOT)/vendor/include"';
it('is not resurrected by deinit', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withHeaderSearchPaths(SCALAR),
);
const before = pbxprojOf(xcodeprojPath);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const deleted = pbxprojOf(xcodeprojPath).replace(
/\n\t+HEADER_SEARCH_PATHS = \(\n[\s\S]*?\n\t+\);/g,
'',
);
expect(deleted).not.toContain('HEADER_SEARCH_PATHS');
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
deleted,
'utf8',
);
removeSpmInjection({appRoot, xcodeprojPath});
// Everything else is back to its pre-injection bytes; only the setting the
// user deleted stays gone.
expect(pbxprojOf(xcodeprojPath)).toBe(
before.replaceAll(`\n\t\t\t\tHEADER_SEARCH_PATHS = ${SCALAR};`, ''),
);
});
});
// `deinit` removes appendedArrayValues before it restores promotedArrayScalars,
// so recording a key under both happens to come out right today: the scalar
// restore rewrites the whole value last. That makes the exclusivity below
// invisible to a round-trip test, which is why it is asserted on the marker
// directly — reversing those two loops would otherwise silently start removing
// array members from an already-restored scalar.
describe('a promoted scalar is recorded once, not twice', () => {
it('records promotedArrayScalars and not appendedArrayValues for the key', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withHeaderSearchPaths('"$(inherited) $(SRCROOT)/vendor/include"'),
);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const changes = readMarker(xcodeprojPath).buildSettingChanges;
expect(changes.length).toBeGreaterThan(0);
for (const change of changes) {
expect(Object.keys(change.promotedArrayScalars ?? {})).toContain(
'HEADER_SEARCH_PATHS',
);
expect(Object.keys(change.appendedArrayValues ?? {})).not.toContain(
'HEADER_SEARCH_PATHS',
);
}
});
});
@@ -42,6 +42,19 @@ const PLAIN_PBXPROJ = fs.readFileSync(
'utf8',
);
// The app target's Debug buildSettings dict, as a body range.
function targetDebugDict(text) {
const cfg = findObjectByUuid(text, 'AA0000000000000000000901');
const bs = findField(text, cfg, 'buildSettings');
return {uuid: 'x', bodyOpen: bs.valueStart, bodyClose: bs.tokenEnd - 1};
}
// Delimiter balance, checked with the module's own quote-aware scanner: the
// outermost `{` must close on the file's last `}`.
function isBalanced(text) {
return scanToClose(text, text.indexOf('{')) === text.lastIndexOf('}');
}
// ---------------------------------------------------------------------------
// generateUUID
// ---------------------------------------------------------------------------
@@ -196,12 +209,6 @@ describe('addArrayMembers', () => {
});
describe('addArrayStringValues', () => {
function targetDebugDict(text) {
const cfg = findObjectByUuid(text, 'AA0000000000000000000901');
const bs = findField(text, cfg, 'buildSettings');
return {uuid: 'x', bodyOpen: bs.valueStart, bodyClose: bs.tokenEnd - 1};
}
it('creates an array seeded with $(inherited)', () => {
const out = addArrayStringValues(
PLAIN_PBXPROJ,
@@ -230,6 +237,50 @@ describe('addArrayStringValues', () => {
expect(out).toContain('"-ObjC"');
});
// Xcode writes the seed quoted, but the unquoted form is just as valid and
// appears in hand-edited projects. Both are the same value to the build
// system, so neither may be re-emitted alongside the seed.
it.each(['"$(inherited)"', '$(inherited)'])(
'promotes a bare %s scalar without emitting the seed twice',
priorValue => {
const scalar = PLAIN_PBXPROJ.replace(
'PRODUCT_NAME = "$(TARGET_NAME)";',
`OTHER_LDFLAGS = ${priorValue}; PRODUCT_NAME = "$(TARGET_NAME)";`,
);
const out = addArrayStringValues(
scalar,
targetDebugDict(scalar),
'OTHER_LDFLAGS',
['"-ObjC"'],
);
const members = /OTHER_LDFLAGS = \(\n([\s\S]*?)\t+\);/
.exec(out)[1]
.split('\n')
.map(line => line.trim().replace(/,$/, ''))
.filter(member => member.length > 0);
// The scalar's value IS the seed the array is created with.
expect(members).toEqual(['"$(inherited)"', '"-ObjC"']);
},
);
it('promotes an empty scalar without emitting a bare `,` member', () => {
const scalar = PLAIN_PBXPROJ.replace(
'PRODUCT_NAME = "$(TARGET_NAME)";',
'OTHER_LDFLAGS = ; PRODUCT_NAME = "$(TARGET_NAME)";',
);
const out = addArrayStringValues(
scalar,
targetDebugDict(scalar),
'OTHER_LDFLAGS',
['"-ObjC"'],
);
const block = /OTHER_LDFLAGS = \(\n([\s\S]*?)\t+\);/.exec(out)[1];
// Asserted on the raw block: a member list filtered for emptiness (as the
// test above does) would hide the malformed element this guards against.
expect(block.split('\n').filter(line => /^\s*,$/.test(line))).toEqual([]);
expect(block).toContain('"-ObjC"');
});
it('dedups by EXACT token, not substring (adds "-ObjC" even when "-ObjCFoo" is present)', () => {
const withArray = PLAIN_PBXPROJ.replace(
'PRODUCT_NAME = "$(TARGET_NAME)";',
@@ -261,6 +312,102 @@ describe('addArrayStringValues', () => {
});
});
// Xcode writes array build settings multi-line, but hand-edited projects and
// other generators (XcodeGen, Tuist) emit compact one-line ones. Members must
// land INSIDE the array whatever its shape, and `deinit` must be able to take
// them back out again — hence the byte-identical add→remove round trip.
describe('array build settings of every written shape', () => {
const NEW = '"/new"';
// Seed `OTHER_LDFLAGS = <value>;` into the app target's Debug config.
function withValue(value) {
return PLAIN_PBXPROJ.replace(
'\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";',
`\t\t\t\tOTHER_LDFLAGS = ${value};\n\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";`,
);
}
function add(text, values) {
return addArrayStringValues(
text,
targetDebugDict(text),
'OTHER_LDFLAGS',
values,
);
}
function remove(text, values) {
return removeArrayStringValues(
text,
targetDebugDict(text),
'OTHER_LDFLAGS',
values,
);
}
describe.each([
['an empty array', '()'],
['a lone member with no trailing comma', '("/a")'],
['a trailing comma and space', '("/a", )'],
['no space after the comma', '("/a","/b")'],
['a space after the comma', '("/a", "/b")'],
['a member whose quotes hold a comma and parens', '("$(FOO(x)),weird")'],
['the multi-line shape Xcode writes', '(\n\t\t\t\t\t"/a",\n\t\t\t\t)'],
])('%s', (_label, shape) => {
const input = withValue(shape);
it('adds the value inside the array, leaving the file balanced', () => {
const out = add(input, [NEW]);
const field = findField(out, targetDebugDict(out), 'OTHER_LDFLAGS');
expect(field.value.trimStart().startsWith('(')).toBe(true);
expect(field.value).toContain(NEW);
// Nothing was spliced ahead of the field — i.e. outside the array.
expect(out.slice(0, field.matchStart)).toBe(
input.slice(0, field.matchStart),
);
expect(isBalanced(out)).toBe(true);
});
it.each([[[NEW]], [[NEW, '"/new2"']]])(
'remove undoes add of %j byte-for-byte',
values => {
const added = add(input, values);
expect(added).not.toBe(input);
expect(remove(added, values)).toBe(input);
},
);
});
it.each([
['a value that is not there', '("/a", )', '"/zzz"'],
['a member stripped of its quotes', '("$(inherited)", )', '$(inherited)'],
])('removes nothing when asked for %s', (_label, shape, value) => {
const input = withValue(shape);
expect(remove(input, [value])).toBe(input);
});
it('is a no-op when a one-line array already holds the value', () => {
const input = withValue(`(${NEW})`);
expect(add(input, [NEW])).toBe(input);
});
it('dedupes a member whose quotes hold a comma', () => {
const weird = '"$(FOO(x)),weird"';
const input = withValue(`(${weird}, )`);
expect(add(input, [weird])).toBe(input);
});
it('splices a multi-line array on its own line, before the closing `)`', () => {
const input = withValue('(\n\t\t\t\t\t"/a",\n\t\t\t\t)');
expect(add(input, [NEW])).toBe(
input.replace(
'\t\t\t\t\t"/a",\n',
`\t\t\t\t\t"/a",\n\t\t\t\t\t${NEW},\n`,
),
);
});
});
describe('ensureScalarField', () => {
it('adds a scalar only when absent', () => {
const project = findProjectObject(PLAIN_PBXPROJ);
+48 -1
View File
@@ -156,6 +156,11 @@ type BuildSettingChange = {
// value), e.g. a ${PODS_ROOT}-anchored REACT_NATIVE_PATH that dangles once
// CocoaPods is deintegrated. Deinit restores the original.
replacedScalars?: {[string]: string},
// Array settings that existed as a SCALAR and were promoted to a `( … )`
// array (key → the pre-injection raw value text, quotes included). Deinit
// restores that value verbatim; removing the injected members would leave
// the promoted array and its `"$(inherited)"` seed behind.
promotedArrayScalars?: {[string]: string},
};
// An array field injection CREATED (rather than appended to a pre-existing
// one), so deinit removes the whole field and lands byte-identical.
@@ -1770,6 +1775,7 @@ function mergeReactBuildSettings(
};
const createdArrayKeys /*: Array<string> */ = [];
const appendedArrayValues /*: {[string]: Array<string>} */ = {};
const promotedArrayScalars /*: {[string]: string} */ = {};
const createdScalars /*: Array<string> */ = [];
const arraySettings = [
...INJECTED_ARRAY_SETTINGS,
@@ -1784,6 +1790,14 @@ function mergeReactBuildSettings(
continue;
}
const existing = findField(text, d, key);
// Non-null only for a scalar addArrayStringValues would promote to an array
// (same array-vs-scalar test it uses). Kept RAW: findField's token for a
// bare scalar ends at the `;`, so it carries any whitespace before it, and
// deinit has to write those bytes back verbatim.
const priorScalar =
existing != null && !existing.value.trimStart().startsWith('(')
? existing.value
: null;
if (existing == null) {
createdArrayKeys.push(key);
} else {
@@ -1797,9 +1811,20 @@ function mergeReactBuildSettings(
// has no record of and so could never reverse.
continue;
}
appendedArrayValues[key] = fresh;
if (priorScalar == null) {
appendedArrayValues[key] = fresh;
}
}
const beforeAdd = text;
text = addArrayStringValues(text, d, key, values);
// Record only a promotion that actually happened: addArrayStringValues
// no-ops when `values` is empty or every value is already a member, and a
// recorded-but-untouched field would have deinit clobber whatever the user
// has there by then. Restoring the scalar subsumes removing the injected
// members, so the two records stay mutually exclusive per key.
if (priorScalar != null && text !== beforeAdd) {
promotedArrayScalars[key] = priorScalar;
}
}
const replacedScalars /*: {[string]: string} */ = {};
for (const {key, value} of scalars) {
@@ -1858,6 +1883,9 @@ function mergeReactBuildSettings(
appendedArrayValues,
createdScalars,
replacedScalars,
...(Object.keys(promotedArrayScalars).length > 0
? {promotedArrayScalars}
: {}),
},
};
}
@@ -2604,6 +2632,25 @@ function removeRecordedBuildSettings(
);
}
}
const promotedArrayScalars /*: {[string]: string} */ =
change.promotedArrayScalars ?? {};
for (const key of Object.keys(promotedArrayScalars)) {
const current = dict();
const originalValue = promotedArrayScalars[key];
// A field that is gone was deleted by the user after injection; restoring
// it would resurrect it, at the top of the dict, matching neither state.
if (
current != null &&
typeof originalValue === 'string' &&
findField(text, current, key) != null
) {
// Rewriting the whole value is what makes the promotion reversible at
// all — its members and its `"$(inherited)"` seed are indistinguishable
// from the user's own once folded together. The tradeoff: members the
// user hand-added to the promoted array afterwards are discarded.
text = setScalarField(text, current, key, originalValue);
}
}
for (const key of change.createdArrayKeys ?? []) {
const current = dict();
if (current != null) {
+108 -18
View File
@@ -404,6 +404,38 @@ function addArrayMembers(
return text.slice(0, obj.bodyOpen + 1) + block + text.slice(obj.bodyOpen + 1);
}
/**
* Indices of the `,` separators at an array's top level — a comma inside a
* quoted member (`"$(FOO),weird"`) separates nothing.
*/
function topLevelCommas(inner /*: string */) /*: Array<number> */ {
const out = [];
for (let i = 0; i < inner.length; i++) {
if (inner[i] === '"') {
i = scanString(inner, i);
} else if (inner[i] === ',') {
out.push(i);
}
}
return out;
}
/**
* The members of an array's inner text (what sits between its parens), trimmed
* and with empty slots — e.g. the one a trailing comma leaves — dropped. A bare
* scalar value parses as its own single member.
*/
function arrayMembers(inner /*: string */) /*: Array<string> */ {
const members = [];
let start = 0;
for (const comma of topLevelCommas(inner)) {
members.push(inner.slice(start, comma));
start = comma + 1;
}
members.push(inner.slice(start));
return members.map(m => m.trim()).filter(m => m !== '');
}
/**
* Append raw string values to a `( … )` array build-setting (e.g.
* OTHER_LDFLAGS), deduping by exact token. Creates the setting seeded with
@@ -422,31 +454,57 @@ function addArrayStringValues(
const field = findField(text, obj, key);
if (field != null) {
const isArray = field.value.trimStart().startsWith('(');
const openParen = isArray
? field.valueStart + field.value.indexOf('(')
: -1;
const closeParen = isArray ? scanToClose(text, openParen) : -1;
const inner = isArray ? text.slice(openParen + 1, closeParen) : field.value;
// Dedup by EXACT existing member, not substring — a substring check would
// treat `"-ObjC"` as already present when only `"-ObjCFoo"` is there (and
// vice-versa). Parse the current members (array `( … )` or bare scalar).
const existingMembers = new Set(
field.value
.replace(/^\s*\(/, '')
.replace(/\)\s*$/, '')
.split(',')
.map(s => s.trim())
.filter(s => s.length > 0),
);
// vice-versa).
const existingMembers = new Set(arrayMembers(inner));
const fresh = values.filter(v => !existingMembers.has(v));
if (fresh.length === 0) {
return text;
}
if (field.value.trimStart().startsWith('(')) {
// Existing array — splice fresh members before the closing `)`.
const lineStart = text.lastIndexOf('\n', field.tokenEnd - 1) + 1;
const lines = fresh.map(v => `${memberIndent}${v},\n`).join('');
return text.slice(0, lineStart) + lines + text.slice(lineStart);
if (isArray) {
if (inner.includes('\n')) {
// Multi-line array — one member per line, before the closing `)`.
const lineStart = text.lastIndexOf('\n', closeParen) + 1;
const lines = fresh.map(v => `${memberIndent}${v},\n`).join('');
return text.slice(0, lineStart) + lines + text.slice(lineStart);
}
// One-line array (hand-edited projects, XcodeGen, Tuist) — splice the
// members in ahead of the `)`, in the separator style already there.
// Reformatting it multi-line instead would have to record the old shape
// to stay reversible on deinit.
const commas = topLevelCommas(inner);
const gapMatch =
commas.length > 0 ? /^[\t ]*/.exec(inner.slice(commas[0] + 1)) : null;
const gap = gapMatch != null ? gapMatch[0] : ' ';
const core = inner.replace(/[\t ]+$/, '');
const joined = fresh.join(`,${gap}`);
const insertion =
core === ''
? joined
: core.endsWith(',')
? `${gap}${joined},`
: `,${gap}${joined}`;
const at = openParen + 1 + core.length;
return text.slice(0, at) + insertion + text.slice(at);
}
// Existing scalar — promote to an array preserving the prior value.
// Existing scalar — promote to an array preserving the prior value. Skip it
// when it IS the `"$(inherited)"` the array is seeded with (emitted twice),
// or when it is empty (a bare `,` is not a valid plist element). The seed
// test unquotes first: pbxproj accepts `$(inherited)` bare, and Xcode's own
// quoted form is the same value to the build system.
const prior = field.value.trim();
const carriesPrior =
prior !== '' && prior.replace(/^"(.*)"$/s, '$1') !== '$(inherited)';
const replacement = arrayBlock([
'"$(inherited)"',
field.value.trim(),
...(carriesPrior ? [prior] : []),
...fresh,
]);
return (
@@ -501,7 +559,12 @@ function setScalarField(
// ---------------------------------------------------------------------------
// Surgical removal — the inverse of the additive helpers above. `deinit` uses
// these to undo exactly what injection added, leaving every other byte (incl.
// user edits made after injection) untouched. All are pure string transforms.
// user edits made after injection) untouched. The exception is a scalar that
// injection promoted to an array: reversing that rewrites the whole field (see
// removeRecordedBuildSettings), so members added to it afterwards are lost.
// That is not deinit-only — every re-sync reverts from the recorded baseline
// before re-injecting, so an `spm update` discards them just the same.
// All are pure string transforms.
// ---------------------------------------------------------------------------
/**
@@ -563,6 +626,33 @@ function removeField(
return text.slice(0, f.matchStart) + text.slice(f.tokenEnd + 1);
}
/**
* Drop one member from an array field's value text. The patterns mirror the
* forms addArrayStringValues inserts, tried in the order that makes the span
* removed exactly the span it added: a line of its own (multi-line array), then
* after a comma, before a comma, or alone ahead of the `)` (the one-line
* shapes). Each is anchored on a delimiter, so a value that is merely a prefix
* of a longer member is never mistaken for it.
*/
function removeArrayMember(
region /*: string */,
value /*: string */,
) /*: string */ {
const v = escapeRegExp(value);
for (const pattern of [
`\\n[\\t ]*${v},`,
`,[\\t ]*${v}(?=[\\t ]*[,)])`,
`[\\t ]*${v},[\\t ]*`,
`[\\t ]*${v}(?=[\\t ]*\\))`,
]) {
const shorter = region.replace(new RegExp(pattern), '');
if (shorter !== region) {
return shorter;
}
}
return region;
}
/**
* Remove specific raw string members from an existing `( … )` array field
* (inverse of addArrayStringValues' append branch). Leaves the field and any
@@ -580,7 +670,7 @@ function removeArrayStringValues(
}
let region = text.slice(f.valueStart, f.tokenEnd);
for (const val of values) {
region = region.replace(new RegExp(`\\n[\\t ]*${escapeRegExp(val)},`), '');
region = removeArrayMember(region, val);
}
return text.slice(0, f.valueStart) + region + text.slice(f.tokenEnd);
}