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
95 changes: 89 additions & 6 deletions cli/src/util/capacitor-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ import { fatal } from '../errors';
import { convertToUnixPath } from './fs';
import { resolveNode } from './node';

const SOURCE_PACKAGE_URL = 'https://github.com/ionic-team/capacitor';
export const SOURCE_PACKAGE_IDENTITY = 'capacitor';
const SOURCE_PACKAGE_NAME = new RegExp(`name:\\s*"${SOURCE_PACKAGE_IDENTITY}"`);
export const SOURCE_PACKAGE_IDENTITY = 'capacitor-ios';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to this PR specifically: we should tweak the docs entry with this new identity https://github.com/ionic-team/capacitor-docs/blob/f5de151948208d132c1a76f5eee3f2cd44d45a27/docs/main/updating/9-0.md#capacitor-builds-from-node_modules

I suppose this can be done in ionic-team/capacitor-docs#639

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'll do it in ionic-team/capacitor-docs#639, but good catch.


/** Matches the source package's git URL, with or without `.git`, but not repos sharing its prefix. */
const SOURCE_PACKAGE_URL = /url:\s*"https:\/\/github\.com\/ionic-team\/capacitor(?:\.git)?\/?"/i;

/**
* Names a path dependency on Capacitor may carry: the current identity, and the one syncs before
* the `capacitor-ios` rename pinned. A plugin rewritten by such a sync keeps the old name until
* it is synced again.
*/
const PINNED_PACKAGE_NAMES = [SOURCE_PACKAGE_IDENTITY, 'capacitor'];

/** Product providing the Cordova compatibility layer. */
export const CORDOVA_PRODUCT = 'CapacitorCordova';
Expand All @@ -20,6 +28,12 @@ const PLATFORM_PACKAGE = '@capacitor/ios';
/** Plugins published before Capacitor 9 depend on the platform as a prebuilt xcframework. */
const BINARY_PACKAGE_IDENTITY = 'capacitor-swift-pm';

/**
* Cordova plugins that ship their own `Package.swift` depend on `apache/cordova-ios` for the
* `Cordova` product, which the Capacitor source package also vends.
*/
const CORDOVA_PACKAGE_URL = /url:\s*"https:\/\/github\.com\/apache\/cordova-ios(?:\.git)?\/?"/i;

/**
* Resolves the Capacitor Swift package generated `Package.swift` files should depend on: the
* `@capacitor/ios` npm already installed in the app, which ships the package alongside the sources.
Expand Down Expand Up @@ -97,9 +111,73 @@ export function renderCapacitorPackage(absolutePath: string, fromDir: string): s
* copy of the framework. Rewriting keeps the whole graph on one identity.
*/
export function rewriteCapacitorDependency(content: string, absolutePath: string, fromDir: string): string {
const rewritten = replacePackageCalls(content, renderCapacitorPackage(absolutePath, fromDir));
const capacitorCalls = findPackageCalls(content).filter((call) => referencesCapacitor(call.text));
if (capacitorCalls.length === 0) {
return content;
}

// Collected before the calls are replaced: once they are, every one reads `capacitor-ios` and
// the name each target's `.product(package:)` was written against is gone. The pinned names are
// included because a sync that renamed only the `.package(...)` entry left products on the old
// name behind.
const previousNames = new Set(
[...capacitorCalls.flatMap((call) => packageReferenceNames(call.text)), ...PINNED_PACKAGE_NAMES].filter(
(name) => name !== SOURCE_PACKAGE_IDENTITY,
Comment thread
markemer marked this conversation as resolved.
Resolved
),
);

let rewritten = replacePackageCalls(content, renderCapacitorPackage(absolutePath, fromDir));

// A name some other dependency still answers to belongs to that dependency, not Capacitor. SPM
// resolves `.product(package:)` against a dependency's pinned name and its derived identity alike,
// so both are reserved.
const remainingNames = new Set(
findPackageCalls(rewritten)
.filter((call) => !referencesCapacitor(call.text))
.flatMap((call) => packageReferenceNames(call.text)),
);

for (const name of previousNames) {
if (remainingNames.has(name)) {
continue;
Comment thread
markemer marked this conversation as resolved.
Resolved
}
rewritten = rewritten.replace(
new RegExp(`(package:\\s*)"${escapeRegExp(name)}"`, 'gi'),
`$1"${SOURCE_PACKAGE_IDENTITY}"`,
);
}
Comment on lines +140 to +148

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could edit text inside comments and strings, not sure if that's intended or not.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. I think it's unlikely that these will be in comments? So we're probably ok?


return rewritten.split(`package: "${BINARY_PACKAGE_IDENTITY}"`).join(`package: "${SOURCE_PACKAGE_IDENTITY}"`);
return rewritten;
}

/**
* The names a `.product(package:)` may use to refer to the dependency a `.package(...)` call
* declares, lowercased: its explicit `name:` when it pins one, and the identity SPM derives from
* the last component of its URL or path. SPM accepts either, so a pinned name does not retire the
* derived identity.
*/
function packageReferenceNames(call: string): string[] {
const names = new Set<string>();

const explicit = call.match(/name:\s*"([^"]+)"/);
if (explicit) {
names.add(explicit[1].toLowerCase());
}

const location = call.match(/(?:url|path):\s*"([^"]+)"/);
if (location) {
const lastComponent = location[1].replace(/\/+$/, '').split('/').pop() ?? '';
const identity = lastComponent.replace(/\.git$/i, '').toLowerCase();
if (identity) {
names.add(identity);
}
}

return [...names];
}

function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

/** Reads the version an existing `Package.swift` pins Capacitor to, if it pins one. */
Expand Down Expand Up @@ -163,7 +241,12 @@ export function patchPackageSwiftDeploymentTarget(
* the app, or the package it points at, has moved.
*/
function referencesCapacitor(call: string): boolean {
return call.includes(BINARY_PACKAGE_IDENTITY) || call.includes(SOURCE_PACKAGE_URL) || SOURCE_PACKAGE_NAME.test(call);
if (call.includes(BINARY_PACKAGE_IDENTITY) || SOURCE_PACKAGE_URL.test(call) || CORDOVA_PACKAGE_URL.test(call)) {
return true;
}

const pinned = call.match(/name:\s*"([^"]+)"/);
return pinned !== null && PINNED_PACKAGE_NAMES.includes(pinned[1].toLowerCase());
}

interface PackageCall {
Expand Down
1 change: 0 additions & 1 deletion cli/src/util/cordova-ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,6 @@ export async function generateCordovaPackageFile(p: Plugin, config: Config): Pro
if (platformTag.$?.package) {
const packageSwiftPath = join(p.rootPath, 'Package.swift');
let content = await readFile(packageSwiftPath, { encoding: 'utf-8' });
content = content.replace(`apache`, `ionic-team`).replaceAll(`cordova-ios`, SOURCE_PACKAGE_IDENTITY);
content = rewriteCapacitorDependency(content, capacitorPackagePath, p.rootPath);
content = patchPackageSwiftDeploymentTarget(content, config.ios.minVersion).content;

Expand Down
178 changes: 173 additions & 5 deletions cli/test/capacitor-package.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ describe('capacitor package resolution', () => {

expect(path).toBe(installed);
expect(renderCapacitorPackage(path, join(appRoot, 'ios', 'App', 'CapApp-SPM'))).toBe(
'.package(name: "capacitor", path: "../../../node_modules/@capacitor/ios")',
'.package(name: "capacitor-ios", path: "../../../node_modules/@capacitor/ios")',
);
});

it('renders relative to a plugin being rewritten, not just the app package', async () => {
const path = await resolveCapacitorPackagePath(makeConfig(appRoot));

expect(renderCapacitorPackage(path, join(appRoot, 'node_modules', '@capacitor', 'haptics'))).toBe(
'.package(name: "capacitor", path: "../ios")',
'.package(name: "capacitor-ios", path: "../ios")',
);
});

Expand Down Expand Up @@ -79,7 +79,7 @@ describe('capacitor package resolution', () => {
describe('rewriting an existing Package.swift', () => {
const installed = '/app/node_modules/@capacitor/ios';
const pluginDir = '/app/node_modules/@capacitor/haptics';
const rendered = '.package(name: "capacitor", path: "../ios")';
const rendered = '.package(name: "capacitor-ios", path: "../ios")';

const rewrite = (content: string) => rewriteCapacitorDependency(content, installed, pluginDir);

Expand All @@ -94,7 +94,7 @@ describe('rewriting an existing Package.swift', () => {
const after = rewrite(before);

expect(after).toContain(rendered);
expect(after).toContain('.product(name: "Capacitor", package: "capacitor")');
expect(after).toContain('.product(name: "Capacitor", package: "capacitor-ios")');
expect(after).not.toContain('capacitor-swift-pm');
});

Expand All @@ -109,13 +109,181 @@ describe('rewriting an existing Package.swift', () => {
const after = rewrite(before);

expect(after).toContain(rendered);
expect(after).toContain('.product(name: "Capacitor", package: "capacitor")');
expect(after).toContain('.product(name: "Capacitor", package: "capacitor-ios")');
});

it('repoints a path left behind by an earlier sync', () => {
expect(rewrite('.package(name: "capacitor", path: "../../../somewhere/else")')).toBe(rendered);
});

it('renames every product of a plugin on the source package, including Cordova', () => {
const before = `dependencies: [
.package(url: "https://github.com/ionic-team/capacitor.git", from: "9.0.0-beta.0")
],
targets: [
.target(
name: "Plugin",
dependencies: [
.product(name: "Capacitor", package: "capacitor"),
.product(name: "Cordova", package: "capacitor")
])
]`;

const after = rewrite(before);

expect(after).toContain(rendered);
expect(occurrences(after, 'package: "capacitor-ios"')).toBe(2);
expect(after).not.toContain('package: "capacitor"');
});

it('renames the products of a plugin rewritten by a sync from before the capacitor-ios rename', () => {
const before = `dependencies: [
.package(name: "capacitor", path: "../ios")
],
targets: [
.target(name: "Plugin", dependencies: [.product(name: "Capacitor", package: "capacitor")])
]`;

const after = rewrite(before);

expect(after).toContain(rendered);
expect(after).toContain('.product(name: "Capacitor", package: "capacitor-ios")');
});

it('heals a plugin whose dependency was renamed but whose products were not', () => {
const before = `dependencies: [
.package(name: "capacitor-ios", path: "../ios")
],
targets: [
.target(name: "Plugin", dependencies: [.product(name: "Capacitor", package: "capacitor")])
]`;

expect(rewrite(before)).toContain('.product(name: "Capacitor", package: "capacitor-ios")');
});

it('does not heal products that belong to another dependency identified as "capacitor"', () => {
const before = `dependencies: [
.package(name: "capacitor-ios", path: "../ios"),
.package(path: "../../@sentry/capacitor")
],
targets: [
.target(name: "Plugin", dependencies: [.product(name: "SentryCapacitor", package: "capacitor")])
]`;

expect(rewrite(before)).toContain('.product(name: "SentryCapacitor", package: "capacitor")');
});

it('does not heal products that reach another dependency through its derived identity', () => {
const before = `dependencies: [
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0"),
.package(name: "SentryCapacitor", path: "../../@sentry/capacitor")
],
targets: [
.target(name: "Plugin", dependencies: [
.product(name: "Capacitor", package: "capacitor-swift-pm"),
.product(name: "Sentry", package: "capacitor")
])
]`;

const after = rewrite(before);

expect(after).toContain('.product(name: "Capacitor", package: "capacitor-ios")');
expect(after).toContain('.product(name: "Sentry", package: "capacitor")');
});

it('renames products that reach a pinned Capacitor dependency through either of its names', () => {
const before = `dependencies: [
.package(name: "CapacitorSwiftPM", url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
],
targets: [
.target(name: "Plugin", dependencies: [
.product(name: "Capacitor", package: "CapacitorSwiftPM"),
.product(name: "Cordova", package: "capacitor-swift-pm")
])
]`;

const after = rewrite(before);

expect(occurrences(after, 'package: "capacitor-ios"')).toBe(2);
expect(after).not.toMatch(/package: "capacitor-?swift-?pm"/i);
});

it('leaves products of a similarly named dependency alone', () => {
const before = `dependencies: [
.package(url: "https://github.com/ionic-team/capacitor", from: "9.0.0"),
.package(name: "capacitor-plugin-foo", path: "../foo")
],
targets: [
.target(name: "Plugin", dependencies: [
.product(name: "Capacitor", package: "capacitor"),
.product(name: "Foo", package: "capacitor-plugin-foo")
])
]`;

const after = rewrite(before);

expect(after).toContain('.package(name: "capacitor-plugin-foo", path: "../foo")');
expect(after).toContain('.product(name: "Foo", package: "capacitor-plugin-foo")');
expect(after).toContain('.product(name: "Capacitor", package: "capacitor-ios")');
});

it('leaves repositories that only share the source package URL prefix alone', () => {
const before = '.package(url: "https://github.com/ionic-team/capacitor-plugins.git", from: "1.0.0")';

expect(rewrite(before)).toBe(before);
});

it('leaves path dependencies inside node_modules/@capacitor alone', () => {
const before = '.package(name: "CapacitorHaptics", path: "../../node_modules/@capacitor/haptics")';

expect(rewrite(before)).toBe(before);
});

it('repoints a Cordova plugin that ships its own Package.swift on cordova-ios', () => {
const before = `dependencies: [
.package(url: "https://github.com/apache/cordova-ios.git", branch: "master")
],
targets: [
.target(name: "CDVFoo", dependencies: [.product(name: "Cordova", package: "cordova-ios")])
]`;

const after = rewrite(before);

expect(after).toContain(rendered);
expect(after).toContain('.product(name: "Cordova", package: "capacitor-ios")');
expect(after).not.toContain('cordova-ios');
expect(after).not.toContain('github.com');
});

it('matches cordova-ios without the .git suffix and regardless of case', () => {
const before = `.package(url: "https://github.com/Apache/Cordova-iOS", from: "7.0.0")
.product(name: "Cordova", package: "Cordova-iOS")`;

const after = rewrite(before);

expect(after).toContain(rendered);
expect(after).toContain('.product(name: "Cordova", package: "capacitor-ios")');
});

it('leaves a Cordova plugin rewritten once unchanged on the next sync', () => {
const before = `dependencies: [
.package(url: "https://github.com/apache/cordova-ios.git", from: "7.0.0")
],
targets: [
.target(name: "CDVFoo", dependencies: [.product(name: "Cordova", package: "cordova-ios")])
]`;

const once = rewrite(before);

expect(rewrite(once)).toBe(once);
});

it('leaves repositories that only share the cordova-ios URL prefix alone', () => {
const before = '.package(url: "https://github.com/apache/cordova-ios-plugin-thing.git", from: "1.0.0")';

expect(rewrite(before)).toBe(before);
});

it('leaves a similarly named plugin package alone', () => {
const before = '.package(name: "capacitor-plugin-foo", path: "../foo")';

Expand Down
Loading