Skip to content

Commit 30501c4

Browse files
chrfalchgabrieldonadel
authored andcommitted
SwiftPM autolinking: judge mixed languages by podspec sources (#59577)
The missing-manifest check scanned every file in a library on disk. A Swift file the podspec never compiles (for example an Expo adapter) marked an Objective-C library as mixed-language, so the build said to opt the library out instead of running `spm scaffold`. The check now reads the same podspec as the scaffolder, expands its source_files from the same root and applies exclude_files. It falls back to the disk scan when there is no podspec or it cannot be read. spm.modules keep the disk scan. (cherry picked from commit 20a44de)
1 parent 57b6fa1 commit 30501c4

4 files changed

Lines changed: 279 additions & 48 deletions

File tree

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

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const {
2222
generateSynthPackageSwift,
2323
hasMixedLanguageSources,
2424
hasPodspec,
25+
isMixedLanguageSourceList,
2526
linkHeaderTree,
2627
main,
2728
reactDescriptor,
@@ -1151,6 +1152,31 @@ describe('MissingManifestError + reportMissingManifests', () => {
11511152
});
11521153
});
11531154

1155+
describe('isMixedLanguageSourceList', () => {
1156+
it.each(['m', 'mm', 'c', 'cc', 'cpp', 'cxx'])(
1157+
'recognizes Swift mixed with .%s sources, ignoring case',
1158+
extension => {
1159+
expect(
1160+
isMixedLanguageSourceList([
1161+
'ios/Foo.SWIFT',
1162+
`ios/Bar.${extension.toUpperCase()}`,
1163+
]),
1164+
).toBe(true);
1165+
},
1166+
);
1167+
1168+
it.each([
1169+
['empty', []],
1170+
['Swift only', ['Foo.swift']],
1171+
['C-family only', ['Foo.m', 'Bar.cpp']],
1172+
['headers with Swift', ['Foo.h', 'Bar.hpp', 'Foo.swift']],
1173+
['non-source suffixes', ['Foo.swift.bak', 'Bar.m']],
1174+
['non-C-family suffixes', ['Foo.swift', 'Bar.cpp.bak']],
1175+
])('rejects %s source lists', (_name, files) => {
1176+
expect(isMixedLanguageSourceList(files)).toBe(false);
1177+
});
1178+
});
1179+
11541180
describe('hasMixedLanguageSources', () => {
11551181
let root;
11561182

@@ -1207,6 +1233,158 @@ function useTempApps() {
12071233
return {created, spies};
12081234
}
12091235

1236+
describe('main() — missing-manifest podspec sources', () => {
1237+
const {created} = useTempApps();
1238+
let isolated;
1239+
1240+
beforeEach(() => {
1241+
jest.isolateModules(() => {
1242+
jest.doMock('../read-podspec', () => {
1243+
const actual = jest.requireActual('../read-podspec');
1244+
return {
1245+
...actual,
1246+
// Exercise the real podspec parser without spawning CocoaPods.
1247+
readPodspecCached: podspecPath =>
1248+
actual.flattenSubspecs(actual.regexPodspec(podspecPath)),
1249+
};
1250+
});
1251+
isolated = require('../generate-spm-autolinking');
1252+
});
1253+
});
1254+
1255+
afterEach(() => {
1256+
jest.dontMock('../read-podspec');
1257+
});
1258+
1259+
function missingManifest({
1260+
sourceFiles,
1261+
excludeFiles = '',
1262+
swift = false,
1263+
podspecDir = '',
1264+
decoyPodspec = false,
1265+
iosConfig = (_depRoot, _podspecPath) => ({}),
1266+
}) {
1267+
const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-pod-sources-'));
1268+
created.push(appRoot);
1269+
const rnRoot = path.join(appRoot, 'rn');
1270+
fs.mkdirSync(rnRoot);
1271+
fs.writeFileSync(
1272+
path.join(appRoot, 'package.json'),
1273+
JSON.stringify({name: 'app'}),
1274+
);
1275+
const depRoot = path.join(appRoot, 'node_modules', 'react-native-foo');
1276+
fs.mkdirSync(path.join(depRoot, 'ios'), {recursive: true});
1277+
fs.mkdirSync(path.join(depRoot, 'expo', 'ios'), {recursive: true});
1278+
for (const file of ['ios/Foo.h', 'ios/Foo.m', 'expo/ios/X.swift']) {
1279+
fs.writeFileSync(path.join(depRoot, file), '');
1280+
}
1281+
if (swift) fs.writeFileSync(path.join(depRoot, 'ios/Bar.swift'), '');
1282+
const podspecPath = path.join(depRoot, podspecDir, 'Foo.podspec');
1283+
fs.writeFileSync(
1284+
podspecPath,
1285+
'Pod::Spec.new do |s|\n' +
1286+
' s.name = "Foo"\n' +
1287+
` s.source_files = "${sourceFiles}"\n` +
1288+
` s.exclude_files = "${excludeFiles}"\n` +
1289+
'end\n',
1290+
);
1291+
if (decoyPodspec) {
1292+
fs.writeFileSync(
1293+
path.join(depRoot, 'A.podspec'),
1294+
'Pod::Spec.new do |s|\n' +
1295+
' s.name = "A"\n' +
1296+
' s.source_files = "ios/**/*.{h,m}"\n' +
1297+
'end\n',
1298+
);
1299+
}
1300+
const autolinkDir = path.join(appRoot, 'build/generated/autolinking');
1301+
fs.mkdirSync(autolinkDir, {recursive: true});
1302+
fs.writeFileSync(
1303+
path.join(autolinkDir, 'autolinking.json'),
1304+
JSON.stringify({
1305+
dependencies: {
1306+
'react-native-foo': {
1307+
root: depRoot,
1308+
platforms: {ios: iosConfig(depRoot, podspecPath)},
1309+
},
1310+
},
1311+
}),
1312+
);
1313+
let error;
1314+
try {
1315+
isolated.main(['--app-root', appRoot, '--react-native-root', rnRoot]);
1316+
} catch (e) {
1317+
error = e;
1318+
}
1319+
expect(error).toBeInstanceOf(isolated.MissingManifestError);
1320+
expect(error.missingManifests).toHaveLength(1);
1321+
return error.missingManifests[0];
1322+
}
1323+
1324+
it('ignores stray Swift outside podspec sources and recommends scaffolding', () => {
1325+
const entry = missingManifest({sourceFiles: 'ios/**/*.{h,m,mm}'});
1326+
expect(entry.mixed).toBe(false);
1327+
expect(console.error).toHaveBeenCalledWith(
1328+
expect.stringContaining('npx react-native spm scaffold'),
1329+
);
1330+
expect(console.error).not.toHaveBeenCalledWith(
1331+
expect.stringContaining('mixed Swift'),
1332+
);
1333+
});
1334+
1335+
it('reports mixed languages when the podspec includes Swift and Objective-C', () => {
1336+
const entry = missingManifest({
1337+
sourceFiles: 'ios/**/*.{h,m,swift}',
1338+
swift: true,
1339+
});
1340+
expect(entry.mixed).toBe(true);
1341+
expect(console.error).toHaveBeenCalledWith(
1342+
expect.stringContaining('mixed Swift'),
1343+
);
1344+
expect(console.error).not.toHaveBeenCalledWith(
1345+
expect.stringContaining('npx react-native spm scaffold'),
1346+
);
1347+
});
1348+
1349+
it('judges the configured podspecPath, not the first podspec found', () => {
1350+
const entry = missingManifest({
1351+
sourceFiles: 'ios/**/*.{h,m,swift}',
1352+
swift: true,
1353+
decoyPodspec: true,
1354+
iosConfig: (_depRoot, podspecPath) => ({podspecPath}),
1355+
});
1356+
expect(entry.mixed).toBe(true);
1357+
});
1358+
1359+
it('expands podspec globs from the package root when sourceDir is nested', () => {
1360+
const entry = missingManifest({
1361+
sourceFiles: 'ios/**/*.{h,m,swift}',
1362+
swift: true,
1363+
podspecDir: 'ios',
1364+
iosConfig: (depRoot, podspecPath) => ({
1365+
podspecPath,
1366+
sourceDir: path.join(depRoot, 'ios'),
1367+
}),
1368+
});
1369+
expect(entry.mixed).toBe(true);
1370+
});
1371+
1372+
it('recommends scaffolding when exclude_files removes the only included Swift file', () => {
1373+
const entry = missingManifest({
1374+
sourceFiles: 'ios/**/*.{h,m,swift}',
1375+
excludeFiles: 'ios/Bar.swift',
1376+
swift: true,
1377+
});
1378+
expect(entry.mixed).toBe(false);
1379+
expect(console.error).toHaveBeenCalledWith(
1380+
expect.stringContaining('npx react-native spm scaffold'),
1381+
);
1382+
expect(console.error).not.toHaveBeenCalledWith(
1383+
expect.stringContaining('mixed Swift'),
1384+
);
1385+
});
1386+
});
1387+
12101388
// ---------------------------------------------------------------------------
12111389
// main() — autolinking plugin host exemption
12121390
//

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

Lines changed: 89 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import type {
2121
PluginPackageDep,
2222
PluginProductDep,
2323
PluginScriptPhase,
24+
PodspecModel,
2425
ReactDescriptor,
2526
RawAutolinkingJson,
2627
SpmModuleConfig,
@@ -71,7 +72,7 @@ const {
7172
MIN_IOS_VERSION_SUPPORTED,
7273
sanitizeIosDeploymentTarget,
7374
} = require('./ios-deployment-target');
74-
const {findPodspecs} = require('./read-podspec');
75+
const {findPodspecs, readPodspecCached} = require('./read-podspec');
7576
const {
7677
AUTOLINKED_PACKAGE_NAME,
7778
CXX_API_DEFINES,
@@ -500,14 +501,24 @@ function hasPodspec(absSource /*: string */) /*: boolean */ {
500501
}
501502

502503
/**
503-
* True when a dep has BOTH Swift and C-family (.m/.mm/.c/.cpp) sources. SPM
504-
* cannot compile mixed-language sources in a single target, and RN libs that
505-
* mix them are typically bidirectionally coupled (ObjC↔Swift) — which can't be
506-
* split into two targets either (it would be a circular dependency). So such a
507-
* dep is unsupportable by the scaffolder; we surface a clear, distinct error
508-
* instead of emitting a manifest that fails with a cryptic SPM resolve error.
509-
* Heuristic filesystem scan (bounded depth; skips examples/tests/build noise).
504+
* True when a source list has BOTH Swift and C-family (.m/.mm/.c/.cpp) files.
505+
* SPM cannot compile mixed-language sources in a single target, and RN libs
506+
* that mix them are typically bidirectionally coupled (ObjC↔Swift) — which
507+
* can't be split into two targets either (it would be a circular dependency).
508+
* So such a dep is unsupportable by the scaffolder; we surface a clear,
509+
* distinct error instead of emitting a manifest that fails with a cryptic SPM
510+
* resolve error.
510511
*/
512+
function isMixedLanguageSourceList(
513+
files /*: ReadonlyArray<string> */,
514+
) /*: boolean */ {
515+
return (
516+
files.some(f => /\.swift$/i.test(f)) &&
517+
files.some(f => /\.(mm?|c|cc|cpp|cxx)$/i.test(f))
518+
);
519+
}
520+
521+
// Heuristic filesystem scan (bounded depth; skips examples/tests/build noise).
511522
function hasMixedLanguageSources(absSource /*: string */) /*: boolean */ {
512523
const SKIP /*: Set<string> */ = new Set([
513524
'node_modules',
@@ -519,10 +530,9 @@ function hasMixedLanguageSources(absSource /*: string */) /*: boolean */ {
519530
'Example',
520531
'examples',
521532
]);
522-
let hasSwift = false;
523-
let hasClang = false;
533+
const files /*: Array<string> */ = [];
524534
const walk = (dir /*: string */, depth /*: number */) => {
525-
if (depth > 6 || (hasSwift && hasClang)) return;
535+
if (depth > 6) return;
526536
let entries /*: Array<{name: string, isDirectory(): boolean}> */ = [];
527537
try {
528538
// $FlowFixMe[incompatible-type] Dirent typing
@@ -537,16 +547,70 @@ function hasMixedLanguageSources(absSource /*: string */) /*: boolean */ {
537547
if (!name.startsWith('.') && !SKIP.has(name)) {
538548
walk(path.join(dir, name), depth + 1);
539549
}
540-
} else if (/\.swift$/i.test(name)) {
541-
hasSwift = true;
542-
} else if (/\.(mm?|c|cc|cpp|cxx)$/i.test(name)) {
543-
hasClang = true;
550+
} else {
551+
files.push(name);
544552
}
545-
if (hasSwift && hasClang) return;
546553
}
547554
};
548555
walk(absSource, 0);
549-
return hasSwift && hasClang;
556+
return isMixedLanguageSourceList(files);
557+
}
558+
559+
// Judges the sources the podspec compiles, like the scaffolder does, so a stray
560+
// Swift file the pod never builds can't flip the verdict. Only for the
561+
// missing-manifest error path: reading a podspec may spawn `pod ipc spec`.
562+
// Podspec choice and glob root match scaffoldPackageSwiftForDep. Where the
563+
// scaffolder would give up (podspec missing or unreadable), the filesystem
564+
// heuristic still yields a verdict for the error message.
565+
function isMixedLanguageDep(
566+
absSource /*: string */,
567+
root /*: string */,
568+
configuredPodspecPath /*: ?string */,
569+
) /*: boolean */ {
570+
const podspecPath = configuredPodspecPath ?? findPodspecs(root)[0];
571+
if (podspecPath != null) {
572+
try {
573+
const model = readPodspecCached(podspecPath);
574+
const {files} = podspecSourceFiles(root, model);
575+
return isMixedLanguageSourceList(files);
576+
} catch {
577+
// An unreadable podspec leaves only the filesystem heuristic available.
578+
}
579+
}
580+
return hasMixedLanguageSources(absSource);
581+
}
582+
583+
function podspecSourceFiles(
584+
root /*: string */,
585+
model /*: PodspecModel */,
586+
) /*: {files: Array<string>, warnings: Array<string>} */ {
587+
const warnings /*: Array<string> */ = [];
588+
// SPM's `sources:` field does NOT accept CocoaPods-style globs — it wants
589+
// a list of explicit file paths (relative to the target's `path:`).
590+
// Expand the podspec globs against the actual filesystem so the emitted
591+
// Package.swift parses cleanly.
592+
let expandedSources /*: Array<string> */ = [];
593+
try {
594+
expandedSources = expandSpmSourceGlobs(root, model.sourceFiles);
595+
} catch (e) {
596+
warnings.push(
597+
`Source glob expansion failed (${e.message}); emitting raw globs — SPM will likely reject them.`,
598+
);
599+
expandedSources = model.sourceFiles;
600+
}
601+
if (model.excludeFiles.length > 0) {
602+
try {
603+
// $FlowFixMe[untyped-import] micromatch has no types
604+
const micromatch = require('micromatch');
605+
const isExcluded = micromatch.matcher(model.excludeFiles);
606+
expandedSources = expandedSources.filter(f => !isExcluded(f));
607+
} catch (e) {
608+
warnings.push(
609+
`exclude_files filtering failed (${e.message}); keeping all sources.`,
610+
);
611+
}
612+
}
613+
return {files: expandedSources, warnings};
550614
}
551615

552616
/**
@@ -1377,6 +1441,7 @@ function main(argv /*:: ?: Array<string> */) /*: void */ {
13771441
origin: 'npm',
13781442
npmName: dep.name,
13791443
root: dep.root,
1444+
podspecPath: dep.platforms.ios.podspecPath,
13801445
});
13811446
log(`Found npm native module: ${target.name} → ${target.path}`);
13821447
}
@@ -1533,7 +1598,11 @@ function main(argv /*:: ?: Array<string> */) /*: void */ {
15331598
name: target.name,
15341599
npmName: entry.npmName ?? target.name,
15351600
hasPodspec: hasPodspec(absSource),
1536-
mixed: hasMixedLanguageSources(absSource),
1601+
mixed: isMixedLanguageDep(
1602+
absSource,
1603+
entry.root ?? absSource,
1604+
entry.podspecPath,
1605+
),
15371606
});
15381607
// Drop any stale wrapper from a previous synth-mode run so SPM doesn't
15391608
// resolve against it.
@@ -1995,6 +2064,8 @@ module.exports = {
19952064
findSelfManagedPackageDir,
19962065
hasPodspec,
19972066
hasMixedLanguageSources,
2067+
isMixedLanguageSourceList,
2068+
podspecSourceFiles,
19982069
readDenyPluginsFromConfig,
19992070
MissingManifestError,
20002071
reportMissingManifests,

0 commit comments

Comments
 (0)