diff --git a/lib/base-package-manager.ts b/lib/base-package-manager.ts index 5ee9a96abd..daa7141578 100644 --- a/lib/base-package-manager.ts +++ b/lib/base-package-manager.ts @@ -13,6 +13,14 @@ import { IHostInfo, } from "./common/declarations"; +// Options for the CLI itself. npm 12 fails on flags it doesn't know. +const CLI_ONLY_OPTIONS = [ + "path", + "frameworkPath", + "disableNpmInstall", + "ignoreScripts", +]; + export abstract class BasePackageManager implements INodePackageManager { public abstract install( packageName: string, @@ -136,6 +144,10 @@ export abstract class BasePackageManager implements INodePackageManager { protected getFlagsString(config: any, asArray: boolean): any { const array: Array = []; for (const flag in config) { + if (CLI_ONLY_OPTIONS.includes(flag)) { + continue; + } + if ( flag === "global" && this.packageManager !== "yarn" && diff --git a/lib/pnpm-package-manager.ts b/lib/pnpm-package-manager.ts index 5970d50c2e..4beb797e05 100644 --- a/lib/pnpm-package-manager.ts +++ b/lib/pnpm-package-manager.ts @@ -44,11 +44,6 @@ export class PnpmPackageManager extends BasePackageManager { if (config.ignoreScripts) { config["ignore-scripts"] = true; } - // CLI-internal options must never reach the command line: pnpm, unlike - // npm, hard-fails on unknown options. - delete config.ignoreScripts; - delete config.path; - delete config.frameworkPath; const packageJsonPath = path.join(pathToSave, "package.json"); const jsonContentBefore = this.$fs.readJson(packageJsonPath); diff --git a/lib/services/ios-project-service.ts b/lib/services/ios-project-service.ts index 7ac6f30c0e..bfe62dcee5 100644 --- a/lib/services/ios-project-service.ts +++ b/lib/services/ios-project-service.ts @@ -1532,7 +1532,11 @@ export class IOSProjectService projectData: IProjectData, ): Promise { const project = this.createPbxProj(projectData); - const group = await this.getRootGroup(groupName, sourceFolderPath); + const group = await this.getRootGroup( + groupName, + sourceFolderPath, + projectData.projectDir, + ); // pin the sources to the main app target: without an explicit target the // underlying xcode lib picks whichever "Sources" build phase it finds // first, which can be an extension target (e.g. a widget) once one @@ -1543,17 +1547,38 @@ export class IOSProjectService filesRelativeToProject: true, target: project.getFirstTarget()?.uuid, }); - project.addToHeaderSearchPaths(group.path); - const headerFiles = this.$fs.exists(sourceFolderPath) - ? this.$fs.enumerateFilesInDirectorySync( - sourceFolderPath, - (file, stat) => stat.isDirectory() || path.extname(file) === ".h", - ) - : []; - if ( - headerFiles.length > 0 && - !this.$fs.exists(path.join(sourceFolderPath, "module.modulemap")) - ) { + let headerFiles: string[]; + let headerSearchPaths: string[]; + if (fastGlob.isDynamicPattern(sourceFolderPath)) { + // A glob is no use as a search path, the folders of its headers and + // module maps are. + headerFiles = group.files.filter((file) => path.extname(file) === ".h"); + const moduleMaps = group.files.filter( + (file) => path.basename(file) === "module.modulemap", + ); + headerSearchPaths = _.uniq( + headerFiles.concat(moduleMaps).map((file) => path.dirname(file)), + ); + } else { + const sourceFolder = path.resolve( + projectData.projectDir, + sourceFolderPath, + ); + headerFiles = this.$fs.exists(sourceFolder) + ? this.$fs.enumerateFilesInDirectorySync( + sourceFolder, + (file, stat) => stat.isDirectory() || path.extname(file) === ".h", + ) + : []; + headerSearchPaths = [sourceFolder]; + } + headerSearchPaths.forEach((searchPath) => + project.addToHeaderSearchPaths(searchPath), + ); + const hasModuleMap = headerSearchPaths.some((searchPath) => + this.$fs.exists(path.join(searchPath, "module.modulemap")), + ); + if (headerFiles.length > 0 && !hasModuleMap) { this.$logger.warn( `warning: Directory ${sourceFolderPath} with native iOS source code doesn't contain a modulemap file. Metadata for it will not be generated and it will not be accessible from JavaScript. To learn more see https://docs.nativescript.org/guides/ios-source-code`, ); @@ -1597,27 +1622,33 @@ export class IOSProjectService } } - private async getRootGroup(name: string, rootPath: string) { + private async getRootGroup( + name: string, + rootPath: string, + projectRoot: string, + ) { const filePathsArr: string[] = []; const rootGroup: INativeSourceCodeGroup = { name: name, files: filePathsArr, + // nativescript-dev-xcode looks the group up by this exact string. Keep it + // as configured: resolving it duplicates the group in prepared projects. path: rootPath, }; if (fastGlob.isDynamicPattern(rootPath)) { - const projectRoot = this.$projectDataService.getProjectData().projectDir; - const filePaths = await fastGlob(rootPath); + // Relative to the project: --path can run the CLI from anywhere. + const filePaths = await fastGlob(rootPath, { cwd: projectRoot }); for (const filePath of filePaths) { - const sourceFilePath = path.normalize(path.join(projectRoot, filePath)); - filePathsArr.push(sourceFilePath); + filePathsArr.push(path.resolve(projectRoot, filePath)); } } else { - if (this.$fs.exists(rootPath)) { - const stats = this.$fs.getFsStats(rootPath); - if (stats.isDirectory() && !this.$fs.isEmptyDir(rootPath)) { - this.$fs.readDirectory(rootPath).forEach((fileName) => { - const filePath = path.join(rootGroup.path, fileName); + const folderPath = path.resolve(projectRoot, rootPath); + if (this.$fs.exists(folderPath)) { + const stats = this.$fs.getFsStats(folderPath); + if (stats.isDirectory() && !this.$fs.isEmptyDir(folderPath)) { + this.$fs.readDirectory(folderPath).forEach((fileName) => { + const filePath = path.join(folderPath, fileName); filePathsArr.push(filePath); }); } @@ -1684,6 +1715,7 @@ export class IOSProjectService const group = await this.getRootGroup( pluginData.name, pluginPlatformsFolderPath, + projectData.projectDir, ); project.removePbxGroup(group.name, group.path); project.removeFromHeaderSearchPaths(group.path); diff --git a/test/base-package-manager.ts b/test/base-package-manager.ts new file mode 100644 index 0000000000..5ca9242f5b --- /dev/null +++ b/test/base-package-manager.ts @@ -0,0 +1,74 @@ +import { assert } from "chai"; +import { BasePackageManager } from "../lib/base-package-manager"; +import { BunPackageManager } from "../lib/bun-package-manager"; +import { IInjector } from "../lib/common/definitions/yok"; +import { Yok } from "../lib/common/yok"; +import { NodePackageManager } from "../lib/node-package-manager"; +import { YarnPackageManager } from "../lib/yarn-package-manager"; +import * as stubs from "./stubs"; + +class TestPackageManager extends (BasePackageManager) { + constructor() { + super({}, {}, {}, {}, "npm"); + } +} + +describe("BasePackageManager", () => { + const flags = (config: object): string[] => + (new TestPackageManager()).getFlagsString(config, true); + + it("doesn't pass the CLI's own options to the package manager", () => { + assert.deepEqual( + flags({ + path: "apps/app", + frameworkPath: "runtime.tgz", + disableNpmInstall: true, + ignoreScripts: true, + }), + [], + ); + }); + + it("passes the package manager's options on", () => { + assert.deepEqual(flags({ "ignore-scripts": true, "save-dev": true }), [ + "--ignore-scripts", + "--save-dev", + ]); + }); + + [ + { name: "npm", packageManager: NodePackageManager }, + { name: "yarn", packageManager: YarnPackageManager }, + { name: "bun", packageManager: BunPackageManager }, + ].forEach(({ name, packageManager }) => { + it(`maps ignoreScripts to --ignore-scripts when installing with ${name}`, async () => { + const injector: IInjector = new Yok(); + injector.register("hostInfo", { isWindows: false }); + injector.register("errors", stubs.ErrorsStub); + injector.register("logger", stubs.LoggerStub); + injector.register("childProcess", stubs.ChildProcessStub); + injector.register("httpClient", {}); + injector.register("fs", stubs.FileSystemStub); + injector.register("pacoteService", {}); + injector.register(name, packageManager); + const projectDir = "/some-project"; + + await injector + .resolve(name) + .install(projectDir, projectDir, { + ignoreScripts: true, + path: "apps/app", + frameworkPath: "runtime.tgz", + }); + + const args = + injector.resolve( + "childProcess", + ).lastCommandArgs; + assert.include(args, "--ignore-scripts"); + assert.notInclude(args, "--ignoreScripts"); + assert.notInclude(args, "--path"); + assert.notInclude(args, "--frameworkPath"); + }); + }); +}); diff --git a/test/ios-project-service-native-source.ts b/test/ios-project-service-native-source.ts new file mode 100644 index 0000000000..c41da8c06e --- /dev/null +++ b/test/ios-project-service-native-source.ts @@ -0,0 +1,173 @@ +import { assert } from "chai"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { FileSystem } from "../lib/common/file-system"; +import { IOSProjectService } from "../lib/services/ios-project-service"; + +describe("iOSProjectService getRootGroup", () => { + let root: string; + let projectDir: string; + let sourcesDir: string; + let cwd: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "native-source-")); + projectDir = path.join(root, "apps", "app"); + sourcesDir = path.join(root, "libs", "native"); + fs.mkdirSync(projectDir, { recursive: true }); + fs.mkdirSync(sourcesDir, { recursive: true }); + fs.writeFileSync(path.join(sourcesDir, "Source.swift"), ""); + cwd = process.cwd(); + process.chdir(root); + }); + + afterEach(() => { + process.chdir(cwd); + fs.rmSync(root, { recursive: true, force: true }); + }); + + const getFiles = async (rootPath: string): Promise => { + const proto = IOSProjectService.prototype; + const { files } = await proto.getRootGroup.call( + { $fs: new FileSystem({}) }, + "Native", + rootPath, + projectDir, + ); + return files.map((file: string) => fs.realpathSync(file)); + }; + + const expectedSource = () => + fs.realpathSync(path.join(sourcesDir, "Source.swift")); + + it("resolves a glob against the project, not the working directory", async () => { + assert.deepEqual(await getFiles("../../libs/native/*.swift"), [ + expectedSource(), + ]); + }); + + it("keeps an absolute glob as it is", async () => { + assert.deepEqual(await getFiles(path.join(sourcesDir, "*.swift")), [ + expectedSource(), + ]); + }); + + it("resolves a folder against the project, not the working directory", async () => { + assert.deepEqual(await getFiles("../../libs/native"), [expectedSource()]); + }); + + const prepare = async (rootPath: string) => { + const groupPaths: string[] = []; + const groupFiles: string[] = []; + const searchPaths: string[] = []; + const warnings: string[] = []; + const proto = IOSProjectService.prototype; + await proto.prepareNativeSourceCode.call( + { + $fs: new FileSystem({}), + $logger: { warn: (message: string) => warnings.push(message) }, + getRootGroup: proto.getRootGroup, + savePbxProj: () => {}, + createPbxProj: () => ({ + addPbxGroup: (files: string[], name: string, groupPath: string) => { + groupPaths.push(groupPath); + groupFiles.push(...files); + }, + getFirstTarget: () => ({ uuid: "target" }), + addToHeaderSearchPaths: (searchPath: string) => + searchPaths.push(searchPath), + }), + }, + "Native", + rootPath, + { projectDir }, + ); + return { + groupPaths, + groupFiles: groupFiles.map((file) => fs.realpathSync(file)), + searchPaths: searchPaths.map((searchPath) => fs.realpathSync(searchPath)), + warnings, + }; + }; + + describe("pbxgroup", () => { + [".", path.join("apps", "app")].forEach((workingDir) => { + it(`keeps the configured folder as its key, run from ${workingDir}`, async () => { + process.chdir(path.join(root, workingDir)); + + const { groupPaths, groupFiles } = await prepare("../../libs/native"); + + assert.deepEqual(groupPaths, ["../../libs/native"]); + assert.deepEqual(groupFiles, [expectedSource()]); + }); + }); + }); + + describe("header search paths", () => { + const searchPathsFor = async (rootPath: string) => + (await prepare(rootPath)).searchPaths; + + it("uses the folders of the headers a glob matches", async () => { + const nested = path.join(sourcesDir, "nested"); + fs.mkdirSync(nested); + fs.writeFileSync(path.join(nested, "One.h"), ""); + fs.writeFileSync(path.join(nested, "Two.h"), ""); + + assert.deepEqual( + await searchPathsFor("../../libs/native/**/*.{h,swift}"), + [fs.realpathSync(nested)], + ); + }); + + it("adds nothing for a glob without headers", async () => { + assert.deepEqual(await searchPathsFor("../../libs/native/*.swift"), []); + }); + + it("uses the folder itself, against the project", async () => { + assert.deepEqual(await searchPathsFor("../../libs/native"), [ + fs.realpathSync(sourcesDir), + ]); + }); + }); + + describe("module map", () => { + let headers: string; + + beforeEach(() => { + headers = path.join(sourcesDir, "headers"); + fs.mkdirSync(headers); + fs.writeFileSync(path.join(headers, "Header.h"), ""); + }); + + it("warns when the headers a glob matches have no module map", async () => { + const { warnings } = await prepare("../../libs/native/**/*.h"); + + assert.lengthOf(warnings, 1); + }); + + it("finds a module map next to the headers a glob matches", async () => { + fs.writeFileSync(path.join(headers, "module.modulemap"), ""); + + const { warnings } = await prepare("../../libs/native/**/*.h"); + + assert.deepEqual(warnings, []); + }); + + it("adds the folder of a module map a glob matches to the search paths", async () => { + const modules = path.join(sourcesDir, "modules"); + fs.mkdirSync(modules); + fs.writeFileSync(path.join(modules, "module.modulemap"), ""); + + const { searchPaths, warnings } = await prepare( + "../../libs/native/**/*.{h,modulemap}", + ); + + assert.deepEqual(searchPaths, [ + fs.realpathSync(headers), + fs.realpathSync(modules), + ]); + assert.deepEqual(warnings, []); + }); + }); +});