Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ios): spm package support #176

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions .changeset/warm-emus-collect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@trapezedev/project': minor
'@trapezedev/configure': minor
---

Add support for iOS SPM (SwiftPackageManager) packages
6 changes: 5 additions & 1 deletion packages/configure/src/definitions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AndroidGradleInjectType } from '@trapezedev/project';
import { AndroidGradleInjectType, IosSPMPackageDefinition } from '@trapezedev/project';

export type OperationMeta = string[];
export interface Operation {
Expand Down Expand Up @@ -144,3 +144,7 @@ export type IosXCConfigOperationValue = {
file?: string;
set?: any;
}

export interface IosSpmPackagesOperation {
value: IosSPMPackageDefinition[];
}
2 changes: 2 additions & 0 deletions packages/configure/src/op.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ function createOpDisplayText(op: Partial<Operation>) {
return (Array.isArray(op.value) ? op.value : op.value.entries).map((v: any) => Object.keys(v)).join(', ');
case 'ios.frameworks':
return op.value.join(', ');
case 'ios.spmPackages':
return op.value.map((v: any) => `${v.name} (${v.libs.join(', ')})`).join(', ');
case 'ios.plist':
return `${op.value.entries.length} modifications`;
case 'ios.xml':
Expand Down
12 changes: 12 additions & 0 deletions packages/configure/src/operations/ios/spmPackages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Context } from '../../ctx';
import { Operation, OperationMeta } from '../../definitions';

export default async function execute(ctx: Context, op: Operation) {
for (let spmPackage of op.value) {
ctx.project.ios?.addSPMPackage(op.iosTarget, spmPackage);
}
}

export const OPS: OperationMeta = [
'ios.spmPackages'
]
48 changes: 48 additions & 0 deletions packages/configure/test/ops/ios.spmPackages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { copy } from '@ionic/utils-fs';
import { XCConfigFile } from '@trapezedev/project/src';
import { join } from 'path';
import tempy from 'tempy';

import { Context, loadContext } from '../../src/ctx';
import { IosSpmPackagesOperation, Operation } from '../../src/definitions';
import Op from '../../src/operations/ios/spmPackages';

describe('op: ios.spmPackages', () => {
let dir: string;
let ctx: Context;

beforeEach(async () => {
dir = tempy.directory();

await copy('../common/test/fixtures/ios-and-android', dir);

ctx = await loadContext(dir);
ctx.args.quiet = true;
});

it('should set ios.spmPackages', async () => {
const op: IosSpmPackagesOperation = {
value: [
{
name: 'swift-numerics',
libs: ['Numberics'],
repositoryURL: 'https://github.com/apple/swift-numerics.git',
version: '1.0.0'
},
{
name: 'local-swift-numerics',
libs: ['Numberics'],
path: '../path/to/local-swift-numerics'
},
],
};

await Op(ctx, op as Operation);

const pbxProject = ctx.project.ios?.getPbxProject()
const pbxProjectText = pbxProject?.writeSync()

expect(pbxProjectText).toContain('https://github.com/apple/swift-numerics.git')
expect(pbxProjectText).toContain('../path/to/local-swift-numerics')
});
});
17 changes: 17 additions & 0 deletions packages/project/src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export interface IosPbxProject {
[key: string]: any;
}

export type IosPbxArrayValue = { value: string; comment: string };

export interface IosEntitlements {
[key: string]: any;
}
Expand Down Expand Up @@ -48,6 +50,21 @@ export type IosBuildName = 'Debug' | 'Release' | string;
export type IosTargetName = string;
export type IosProjectName = string;

export interface IosRemoteSPMPackageDefinition {
name: string;
libs: string[];
repositoryURL: string;
version: string;
}

export interface IosLocalSPMPackageDefinition {
name: string;
libs: string[];
path: string;
}

export type IosSPMPackageDefinition = IosRemoteSPMPackageDefinition | IosLocalSPMPackageDefinition;

/**
* Android definitions
*/
Expand Down
15 changes: 14 additions & 1 deletion packages/project/src/ios/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { copy, pathExists, readdir, writeFile } from '@ionic/utils-fs';

import { parsePbxProject, pbxReadString, pbxSerializeString } from "../util/pbx";
import { MobileProject } from "../project";
import { IosPbxProject, IosEntitlements, IosFramework, IosBuildName, IosTarget, IosTargetName, IosTargetBuildConfiguration, IosFrameworkOpts } from '../definitions';
import { IosPbxProject, IosEntitlements, IosFramework, IosBuildName, IosTarget, IosTargetName, IosTargetBuildConfiguration, IosFrameworkOpts, IosSPMPackageDefinition } from '../definitions';
import { VFSRef, VFSFile } from '../vfs';
import { XmlFile } from '../xml';
import { PlistFile } from '../plist';
import { PlatformProject } from '../platform-project';
import { Logger } from '../logger';
import { assertParentDirs } from '../util/fs';
import { addSPMPackageToProject } from './spm';

const defaultEntitlementsPlist = `
<?xml version="1.0" encoding="UTF-8"?>
Expand Down Expand Up @@ -362,6 +363,18 @@ export class IosProject extends PlatformProject {
return this.pbxProject?.pbxFrameworksBuildPhaseObj(target.id)?.files?.map((f: any) => f.comment.split(' ')[0]);
}

/**
* Add a SPM framework for the given target.
* If the `targetName` is null the main app target is used.
*/
addSPMPackage(targetName: IosTargetName | null, packageDef: IosSPMPackageDefinition, opts: IosFrameworkOpts = {}) {
targetName = this.assertTargetName(targetName || null);
const target = this.getTarget(targetName);
if (this.pbxProject) {
addSPMPackageToProject(this.pbxProject, target!.id, packageDef, this.project.projectRoot);
}
}

/**
* Get the path to the entitlements file for the given target and build.
* If the `targetName` is null the main app target is used. If the `buildName` is null the first
Expand Down
158 changes: 158 additions & 0 deletions packages/project/src/ios/spm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import {
IosPbxArrayValue,
IosPbxProject,
IosSPMPackageDefinition,
} from '../definitions';
import path from 'path';

export function addSPMPackageToProject(
project: IosPbxProject,
targetId: string,
pkg: IosSPMPackageDefinition,
projectRoot: string,
) {
const helper = new SPMHelper(project);
const target = project.pbxNativeTargetSection()[targetId];
const firstProject = project.getFirstProject().firstProject;
const packageReferences: IosPbxArrayValue[] = (firstProject[
'packageReferences'
] ??= []);
const packageProductReferences: IosPbxArrayValue[] = (target[
'packageProductDependencies'
] ??= []);
const frameworkBuildPhaseObj = project.pbxFrameworksBuildPhaseObj(targetId);
const frameworkBuildPhaseFiles: IosPbxArrayValue[] = (frameworkBuildPhaseObj[
'files'
] ??= []);

let packageReferenceComment: string;
let packageReferenceSection: string;
let packageReferenceSectionContent: Record<string, any>;

if ('path' in pkg) {
// local package
const relativePath = path.relative(projectRoot, path.resolve(projectRoot, pkg.path));
packageReferenceComment = `XCLocalSwiftPackageReference "${relativePath}"`;
packageReferenceSection = 'XCLocalSwiftPackageReference';
packageReferenceSectionContent = {
isa: packageReferenceSection,
relativePath: JSON.stringify(relativePath),
};
} else {
// remote package
packageReferenceComment = `XCRemoteSwiftPackageReference "${pkg.name}"`;
packageReferenceSection = 'XCRemoteSwiftPackageReference';
packageReferenceSectionContent = {
isa: packageReferenceSection,
repositoryURL: JSON.stringify(pkg.repositoryURL),
requirement: {
// todo: support different ranges?
kind: 'upToNextMajorVersion',
minimumVersion: pkg.version,
},
};
}

const { uuid: spmPackageReferenceUUID, comment: spmPackageReferenceComment } =
helper.addOrUpdateEntry(
packageReferenceSection,
packageReferenceComment,
packageReferenceSectionContent,
);

helper.addOrUpdateArrayEntry(packageReferences, spmPackageReferenceUUID, {
value: spmPackageReferenceUUID,
comment: packageReferenceComment,
});

for (const lib of pkg.libs) {
const { uuid: spmProductDependencyUUID } = helper.addOrUpdateEntry(
'XCSwiftPackageProductDependency',
lib,
{
isa: 'XCSwiftPackageProductDependency',
package: spmPackageReferenceUUID,
package_comment: spmPackageReferenceComment,
productName: lib,
},
);

const libComment = `${lib} in Frameworks`;

const { uuid: spmBuildFileUuid } = helper.addOrUpdateEntry(
'PBXBuildFile',
libComment,
{
isa: 'PBXBuildFile',
productRef: spmProductDependencyUUID,
productRef_comment: lib,
},
);

helper.addOrUpdateArrayEntry(
packageProductReferences,
spmProductDependencyUUID,
{
value: spmProductDependencyUUID,
comment: lib,
},
);

helper.addOrUpdateArrayEntry(frameworkBuildPhaseFiles, spmBuildFileUuid, {
value: spmBuildFileUuid,
comment: libComment,
});
}
}

class SPMHelper {
constructor(private pbxProject: IosPbxProject) {}

addOrUpdateArrayEntry(
array: IosPbxArrayValue[],
lookupValue: string,
value: IosPbxArrayValue,
) {
const existing = array.find(entry => entry.value === lookupValue);

if (existing) {
Object.assign(existing, value);
return;
}

array.push(value);
}

addOrUpdateEntry(section: string, entryComment: string, entry: any) {
const pbxSection = this.getOrCreateSection(section);
const entryUuid = this.getExistingOrGenerateUUID(section, entryComment);

const entryCommentKey = `${entryUuid}_comment`;
pbxSection[entryCommentKey] = entryComment;
pbxSection[entryUuid] = entry;

return {
uuid: entryUuid,
comment: entryComment,
};
}

getExistingOrGenerateUUID(section: string, comment: string) {
const existingUUID = Object.keys(
this.pbxProject.hash.project.objects[section],
)
.find(key => {
if (key.endsWith('_comment')) {
return this.pbxProject.hash.project.objects[section][key] === comment;
}
return false;
})
?.replace('_comment', '');

return existingUUID ?? this.pbxProject.generateUuid();
}

getOrCreateSection(section: string) {
return (this.pbxProject.hash.project.objects[section] ??= new Object());
}
}
Loading