Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea

## [Unreleased]

### Fixed
- A bare app target with an Objective-C `main.m` (the React Native templates before 0.77) builds, instead of stopping
in SwiftPM with "library product 'App' should not contain executable targets (it has 'App')": the file is compiled
as `AppMain.m` in its folder (any C-family `main.<ext>` as `AppMain.<ext>`), and the build says so in an `ℹ` line. A
`main.swift` is refused early, by `build` and `doctor --project`, with the remedy: mark the app delegate class
`@main` and remove `main.swift` from the app target.

## [0.1.0-alpha.6] - 2026-11-05

### Upgrading from 0.1.0-alpha.5
Expand Down
10 changes: 10 additions & 0 deletions docs/bare-react-native.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,16 @@ The target's Sources phase is copied to `ios-xtool/Sources/App` keeping its layo
type (`.xcdatamodeld`, `.intentdefinition`, `.s`, ...) stops the build with `unsupported source type in the app target`.
Sources outside `ios/` and two compiled files with the same name are errors.

SwiftPM takes a target with a compiled file named `main.<ext>` (in any case) for an executable target, and xtool links
the app's entry point from the App library, so a C-family `main` file is copied under another name in its folder:
`main.m`, the entry point of the React Native templates before 0.77, is compiled as `AppMain.m` (`main.mm` as
`AppMain.mm`, and so on), and the build prints `ℹ <Target>/main.m is compiled as AppMain.m: …`. The file still defines
`main` and keeps its imports, so `UIApplicationMain(…, NSStringFromClass([AppDelegate class]))` starts the app as in
Xcode. An app file already named `AppMain.<ext>` is an error, as two files with the same name are. A `main.swift` is
refused, by `build` and `doctor --project`, because Swift allows top-level code only in a file named `main.swift`: mark
the app delegate class `@main`, as the template's `AppDelegate.swift` does, move any other top-level code into it, and
remove `main.swift` from the app target.

## Mixed Swift + Objective-C/C++ app target

If the target compiles any `.m`, `.mm`, `.c` or `.cpp` file, it is built as one mixed-language target, the same
Expand Down
10 changes: 10 additions & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,16 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin
- **"Missing SceneDelegate.swift: <path> (Info.plist's UIApplicationSceneManifest names ...)":** `SceneDelegate.swift`
is optional (SDK 57's template has none), but Info.plist names a scene delegate class and the file is missing, so
`ios/` is incomplete. `rn-xtool build --clean` regenerates it with `expo prebuild --clean`.
- **"library product 'App' should not contain executable targets (it has 'App')"** (bare React Native, from SwiftPM in
the `xtool` step): the app target compiles a file named `main`, usually the `main.m` of a React Native template from
before 0.77 (`AppDelegate.h`/`AppDelegate.mm` plus `main.m`). SwiftPM takes a target with a file named `main.<ext>`
for an executable target, while xtool links the app's entry point from the App library, so rn-xtool 0.1.0-alpha.6
and earlier stop here. Later releases copy a C-family `main` file as `AppMain.<ext>` in the same folder and print
"ℹ <Target>/main.m is compiled as AppMain.m: SwiftPM takes a target with a file named main for an executable, and
xtool links the app's entry point from the App library"; the app starts as before. A `main.swift` stops the build
before the patches with "The app target compiles <Target>/main.swift: …", which gives the remedy: mark the app
delegate class `@main`, move any other top-level code into it, and remove `main.swift` from the app target. See
[Sources](bare-react-native.md#sources).
- **"rn-xtool could not patch <package>":** your project has a different version of a package than the one this release
of rn-xtool patches, and the patch does not apply to it (on SDK 57 or 58, a newer patch of the SDK that changed a
patched file; on bare React Native, a newer patch of its line). The message names the versions. On SDK 58 (Expo
Expand Down
17 changes: 14 additions & 3 deletions src/generate/bareSources.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { cp, mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import type { BareTargetContent, TargetFile } from "../project/index.js";
import { compiledName, type BareTargetContent, type TargetFile } from "../project/index.js";

/** What the copy of a bare app target gives the manifest (absolute paths). */
export interface CopiedBareTarget {
Expand Down Expand Up @@ -38,7 +38,8 @@ async function copyListed(file: TargetFile, dest: string): Promise<void> {
* target folder (`ios/<Target>/Native/X.m` → `Native/X.m`; files elsewhere in ios/ keep their
* path from ios/), with one forwarding header per header in `include/` so `#import "X.h"` resolves
* from any folder as Xcode's header maps allow, plus `<ProductModuleName>-Swift.h` forwarding to `App-Swift.h`
* in a mixed target. Resources are staged flat in `resourcesDir`, laid
* in a mixed target. A C-family `main.m` (any `main.<ext>`) is copied as `AppMain.<ext>` in its folder, so SwiftPM keeps
* App a library target. Resources are staged flat in `resourcesDir`, laid
* out as Xcode copies them to the bundle root (xtool.yml lists each top-level entry).
*/
export async function copyBareTarget(
Expand Down Expand Up @@ -72,9 +73,19 @@ export async function copyBareTarget(
};

const code = [...bare.swiftSources, ...bare.cSources, ...bare.headers, ...(bare.bridgingHeader ? [bare.bridgingHeader] : [])];
const cSources = new Set(bare.cSources);
const codeDest = new Map<TargetFile, string>();
for (const file of code) {
const dest = place(file);
let dest = place(file);
const base = path.posix.basename(dest);
const name = cSources.has(file) ? compiledName(dest) : base;
if (name !== base) {
dest = path.posix.join(path.posix.dirname(dest), name);
log(
`ℹ ${file.relPath} is compiled as ${name}: SwiftPM takes a target with a file named main for an executable, ` +
"and xtool links the app's entry point from the App library",
);
}
if (dest.split("/")[0] === INCLUDE_DIR) {
throw new Error(`${file.relPath} would land in Sources/App/${INCLUDE_DIR}/, which holds the generated header forwards; rename its folder`);
}
Expand Down
2 changes: 1 addition & 1 deletion src/project/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ProjectInfo, ReadProjectOptions } from "./types.js";

export type { ExpoProject, ProjectInfo, ProjectKind, ReadProjectOptions } from "./types.js";
export type { BareTargetContent, TargetFile } from "./pbxproj.js";
export { readTargetContent } from "./pbxproj.js";
export { compiledName, readTargetContent } from "./pbxproj.js";
export { DetectError, detectProjectKind } from "./detect.js";
export { RN_CLI_MISSING } from "./bare.js";
export { buildVars, defaultBundleIdentifier, isInstalled, MissingBundleIdentifierError, readExpoProject } from "./expo.js";
Expand Down
36 changes: 32 additions & 4 deletions src/project/pbxproj.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,20 @@ const IGNORABLE_FLAGS = ["OTHER_CFLAGS", "OTHER_LDFLAGS", "OTHER_SWIFT_FLAGS"];
/** Flags the template sets that the generated project already provides. */
const BENIGN_FLAGS = new Set(["$(inherited)", "-ObjC", "-lc++"]);

/**
* SwiftPM's rule (PackageBuilder.swift, `Sources.computeModuleKind`): a target with a compiled source whose lowercased
* name is `main.<ext>`, one dot, is an executable target. The App target must stay a library: xtool links the app's
* entry point from the App library product.
*/
const SWIFTPM_MAIN = /^main\.[^.]+$/i;
const MAIN_COPY = "AppMain";

/** The name a compiled C-family source of the app target is copied and compiled under: `main.m` → `AppMain.m`. */
export function compiledName(relPath: string): string {
const base = path.posix.basename(relPath);
return SWIFTPM_MAIN.test(base) ? `${MAIN_COPY}${path.posix.extname(base)}` : base;
}

/** Splits a build setting like Xcode: whitespace separates words, `"…"` groups, `\\x` is a literal x. */
function shellWords(value: string): string[] {
const out: string[] = [];
Expand Down Expand Up @@ -355,6 +369,17 @@ export function readTargetContent(p: Pbxproj, iosDir: string): BareTargetContent
if (unsupported.length > 0) {
throw new DetectError(`unsupported source type in the app target: ${unsupported.join(", ")}`);
}
// A renamed main.swift would lose its top-level code: Swift allows that only in a file named main.swift.
const swiftMain = swiftSources.find((f) => SWIFTPM_MAIN.test(path.posix.basename(f.relPath)));
if (swiftMain) {
const base = path.posix.basename(swiftMain.relPath);
throw new DetectError(
`The app target compiles ${swiftMain.relPath}: SwiftPM takes a target with a file named main for an executable, ` +
"and xtool links the app's entry point from the App library. Mark the app delegate class @main " +
`(as the React Native template's AppDelegate.swift does), move any other top-level code of ${base} into it, ` +
`and remove ${base} from the app target`,
);
}
for (const uuid of phaseFiles(objs, target, "PBXResourcesBuildPhase", variants)) {
if (!objs.PBXFileReference[uuid]) continue;
const file = fileOf(uuid);
Expand All @@ -375,14 +400,17 @@ export function readTargetContent(p: Pbxproj, iosDir: string): BareTargetContent
}
}

const seen = new Map<string, string>();
const seen = new Map<string, TargetFile>();
for (const f of [...swiftSources, ...cSources]) {
const base = path.posix.basename(f.relPath);
const base = compiledName(f.relPath);
const first = seen.get(base);
if (first !== undefined) {
throw new DetectError(`Two compiled sources share the name ${base} (${first} and ${f.relPath}); the generated target needs unique file names`);
const renamed = (x: TargetFile): boolean => path.posix.basename(x.relPath) !== base;
const [a, b] = renamed(f) ? [f, first] : [first, f];
const lead = renamed(a) ? `${a.relPath}, which is compiled as ${base},` : a.relPath;
throw new DetectError(`Two compiled sources share the name ${base} (${lead} and ${b.relPath}); the generated target needs unique file names`);
}
seen.set(base, f.relPath);
seen.set(base, f);
}

const bridging = resolveSetting(p, "SWIFT_OBJC_BRIDGING_HEADER")?.trim();
Expand Down
44 changes: 44 additions & 0 deletions tests/generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,50 @@ describe("writeIosXtool", () => {
expect(await readFile(join(paths.iosXtool, "xtool.yml"), "utf8")).toContain(" - Resources/Inter.ttf\n");
});

/** The with-objc pbxproj with `file` (relative to HelloWorld/) in the app group and the Sources phase. */
const withAppSource = (src: string, file: string): string =>
src
.replace(
"/* End PBXFileReference section */",
`\t\tD10000000000000000000001 = {isa = PBXFileReference; path = "${file}"; sourceTree = "<group>"; };\n/* End PBXFileReference section */`,
)
.replace(
"/* End PBXBuildFile section */",
"\t\tD10000000000000000000002 = {isa = PBXBuildFile; fileRef = D10000000000000000000001; };\n/* End PBXBuildFile section */",
)
.replace(/(13B07FAE1A68108700A75B9A \/\* HelloWorld \*\/ = \{\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = \(\n)/, "$1\t\t\t\tD10000000000000000000001,\n")
.replace(/(isa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = \(\n)/, "$1\t\t\t\tD10000000000000000000002,\n");

it.each([
["main.m", "AppMain.m"],
["main.mm", "AppMain.mm"],
["Main.c", "AppMain.c"],
["Supporting/main.m", "Supporting/AppMain.m"],
])("compiles a bare %s as %s, so SwiftPM keeps App a library", async (file, copied) => {
const { app, paths, ctx, logs } = await bareProject({ pbxproj: (src) => withAppSource(src, file) });
expect(ctx.project.bare!.cSources.map((f) => f.relPath)).toContain(`HelloWorld/${file}`);
const text = '#import "AppDelegate.h"\nint main(int argc, char *argv[]) { return 0; }\n';
await mkdir(join(app, file, ".."), { recursive: true });
await writeFile(join(app, file), text);
await writeIosXtool(ctx);
expect(await readFile(join(paths.sources, copied), "utf8")).toBe(text);
expect(await readdir(join(paths.sources, copied, ".."))).not.toContain(file.split("/").pop());
expect(logs).toContain(
`ℹ HelloWorld/${file} is compiled as ${copied.split("/").pop()}: SwiftPM takes a target with a file named main ` +
"for an executable, and xtool links the app's entry point from the App library",
);
});

it("refuses an app file named like the copy of main.m", async () => {
const { app, ctx } = await bareProject({ pbxproj: (src) => withAppSource(src, "main.m") });
await writeFile(join(app, "main.m"), "int main(void) { return 0; }\n");
await writeFile(join(app, "AppMain.m"), "// mine\n");
ctx.project.bare!.cSources.push({ absPath: join(app, "AppMain.m"), relPath: "HelloWorld/AppMain.m" });
await expect(writeIosXtool(ctx)).rejects.toThrow(
"HelloWorld/main.m and HelloWorld/AppMain.m would both be copied to Sources/App/AppMain.m",
);
});

it("refuses a header that would land among the include/ forwards", async () => {
const { app, ctx } = await bareProject();
await mkdir(join(app, "include"), { recursive: true });
Expand Down
41 changes: 41 additions & 0 deletions tests/project/pbxproj.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,4 +319,45 @@ describe("readTargetContent", () => {
const { content } = await read(src);
expect(rel(content().headers)).toEqual(["HelloWorld/Bridge.hpp", "HelloWorld/Native/NativeModule.h"]);
});

it("keeps an Objective-C main.m among the C sources", async () => {
const src = addFile(await withObjc(), { path: "main.m", group: HELLO, phase: "Sources" });
const { content } = await read(src);
expect(rel(content().cSources)).toEqual(["HelloWorld/Native/NativeModule.m", "HelloWorld/main.m"]);
});

it("rejects a compiled source named like the copy of main.m, in any folder", async () => {
for (const other of ["AppMain.m", "Other/AppMain.m"]) {
let src = await withObjc();
src = addFile(src, { path: "main.m", group: HELLO, phase: "Sources" });
src = addFile(src, { path: other, group: HELLO, phase: "Sources" });
const { content } = await read(src);
expect(content).toThrow(
`Two compiled sources share the name AppMain.m (HelloWorld/main.m, which is compiled as AppMain.m, and HelloWorld/${other}); ` +
"the generated target needs unique file names",
);
}
});

it("refuses main.swift, in any case, with the remedy", async () => {
for (const name of ["main.swift", "Main.swift"]) {
const src = addFile(await withObjc(), { path: name, group: HELLO, phase: "Sources" });
const { content } = await read(src);
expect(content).toThrow(
`The app target compiles HelloWorld/${name}: SwiftPM takes a target with a file named main for an executable, ` +
"and xtool links the app's entry point from the App library. Mark the app delegate class @main " +
`(as the React Native template's AppDelegate.swift does), move any other top-level code of ${name} into it, ` +
`and remove ${name} from the app target`,
);
}
});

it("leaves names that only start with main alone", async () => {
let src = await withObjc();
src = addFile(src, { path: "main.test.m", group: HELLO, phase: "Sources" });
src = addFile(src, { path: "MainView.swift", group: HELLO, phase: "Sources" });
const { content } = await read(src);
expect(rel(content().cSources)).toContain("HelloWorld/main.test.m");
expect(rel(content().swiftSources)).toContain("HelloWorld/MainView.swift");
});
});
Loading