diff --git a/lib/common/helpers.ts b/lib/common/helpers.ts index 095743db5e..c73ca2eee2 100644 --- a/lib/common/helpers.ts +++ b/lib/common/helpers.ts @@ -125,6 +125,71 @@ function sanitizePluginName(pluginName: string): string { return pluginName.split("/").pop(); } +function getScopeQualifiedPluginName(pluginName: string): string | null { + const parts = pluginName.split("/"); + if (parts.length < 2 || !parts[0].startsWith("@")) { + return null; + } + + const scope = parts[0].slice(1).replace(/[^A-Za-z0-9_]/g, "_"); + return `${scope}_${getShortPluginName(pluginName)}`; +} + +// The aar name doubles as a Java package segment (the `org.nativescript.` +// namespace fallback), which cannot start with a digit. +function withoutLeadingDigit(name: string): string { + return /^[0-9]/.test(name) ? `_${name}` : name; +} + +/** + * Maps each plugin name to a file-system and Java-package safe name for its aar + * that is unique among `pluginNames`. A plugin whose short name is not shared + * keeps `getShortPluginName(name)`, so projects without clashes keep their names. + * Throws if two plugins still end up with the same name. + */ +export function getUniqueShortPluginNames( + pluginNames: string[], +): Map { + const sortedNames = _.sortBy(_.uniq(pluginNames)); + const namesByShortName = _.groupBy(sortedNames, getShortPluginName); + const result = new Map(); + const owners = new Map(); + + for (const pluginName of sortedNames) { + const shortName = getShortPluginName(pluginName); + const aarName = + namesByShortName[shortName].length === 1 + ? shortName + : withoutLeadingDigit( + getScopeQualifiedPluginName(pluginName) ?? shortName, + ); + + const owner = owners.get(aarName); + if (owner !== undefined) { + throw new Error( + `The plugins "${owner}" and "${pluginName}" both need the Android aar name "${aarName}". Remove one of them from the project.`, + ); + } + + owners.set(aarName, pluginName); + result.set(pluginName, aarName); + } + + return result; +} + +/** + * Every aar name `getUniqueShortPluginNames` can give this plugin, depending on + * which other plugins are installed. + */ +export function getCandidateAarNames(pluginName: string): string[] { + const shortName = getShortPluginName(pluginName); + return _.uniq([ + shortName, + withoutLeadingDigit(getScopeQualifiedPluginName(pluginName) ?? shortName), + ]); +} + export async function executeActionByChunks( initialData: T[] | IDictionary, chunkSize: number, diff --git a/lib/common/test/unit-tests/helpers.ts b/lib/common/test/unit-tests/helpers.ts index 39db1dbdf2..ee5aa542f3 100644 --- a/lib/common/test/unit-tests/helpers.ts +++ b/lib/common/test/unit-tests/helpers.ts @@ -1111,4 +1111,129 @@ const test = require("./test");`, assert.deepStrictEqual(seen.sink, ["kept"]); }); }); + + describe("getUniqueShortPluginNames", () => { + const toObject = (names: string[]) => + Object.fromEntries(helpers.getUniqueShortPluginNames(names)); + + it("keeps the short name of plugins without a clash", () => { + assert.deepStrictEqual( + toObject([ + "@nativescript/core", + "nativescript-plugin", + "@scope/my-plugin", + "9-lives", + ]), + { + "@nativescript/core": "core", + "nativescript-plugin": "nativescript_plugin", + "@scope/my-plugin": "my_plugin", + "9-lives": "9_lives", + }, + ); + }); + + it("qualifies clashing scoped plugins with their scope", () => { + assert.deepStrictEqual( + toObject(["@foo/plugin-x", "@bar/plugin-x", "@nativescript/core"]), + { + "@foo/plugin-x": "foo_plugin_x", + "@bar/plugin-x": "bar_plugin_x", + "@nativescript/core": "core", + }, + ); + }); + + it("lets an unscoped plugin keep its name when it clashes with a scoped one", () => { + assert.deepStrictEqual(toObject(["plugin-x", "@foo/plugin-x"]), { + "plugin-x": "plugin_x", + "@foo/plugin-x": "foo_plugin_x", + }); + }); + + it("replaces characters a scope may contain but a name may not", () => { + assert.deepStrictEqual(toObject(["@my.org~x/plugin", "@a/plugin"]), { + "@my.org~x/plugin": "my_org_x_plugin", + "@a/plugin": "a_plugin", + }); + }); + + it("prefixes clashing names that would start with a digit", () => { + assert.deepStrictEqual(toObject(["@1password/plugin", "@a/plugin"]), { + "@1password/plugin": "_1password_plugin", + "@a/plugin": "a_plugin", + }); + assert.deepStrictEqual(toObject(["9-lives", "@a/9-lives"]), { + "9-lives": "_9_lives", + "@a/9-lives": "a_9_lives", + }); + }); + + it("fails when two plugins still share a name", () => { + assert.throws( + () => + helpers.getUniqueShortPluginNames(["@foo/plugin-x", "@foo/plugin_x"]), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + assert.throws( + () => + helpers.getUniqueShortPluginNames([ + "foo-plugin-x", + "@foo/plugin-x", + "@bar/plugin-x", + ]), + /"@foo\/plugin-x" and "foo-plugin-x".*"foo_plugin_x"/, + ); + }); + + it("does not depend on the order of the plugins", () => { + const names = ["@foo/plugin-x", "plugin-x", "@bar/plugin-x", "other"]; + const expected = toObject(names); + assert.deepStrictEqual(toObject([...names].reverse()), expected); + assert.deepStrictEqual( + toObject([names[2], names[0], names[3], names[1]]), + expected, + ); + assert.throws( + () => + helpers.getUniqueShortPluginNames(["@foo/plugin_x", "@foo/plugin-x"]), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + }); + }); + + describe("getCandidateAarNames", () => { + it("lists the short and the scope-qualified name of a scoped plugin", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("@foo/plugin-x"), [ + "plugin_x", + "foo_plugin_x", + ]); + }); + + it("lists the short name of an unscoped plugin", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("plugin-x"), [ + "plugin_x", + ]); + assert.deepStrictEqual(helpers.getCandidateAarNames("9-lives"), [ + "9_lives", + "_9_lives", + ]); + }); + + it("covers every name getUniqueShortPluginNames gives", () => { + const projects = [ + ["@foo/plugin-x"], + ["@foo/plugin-x", "@bar/plugin-x"], + ["plugin-x", "@foo/plugin-x"], + ["@1a/plugin", "@b/plugin", "plugin", "9-lives", "@c/9-lives"], + ]; + for (const project of projects) { + for (const [name, aarName] of helpers.getUniqueShortPluginNames( + project, + )) { + assert.include(helpers.getCandidateAarNames(name), aarName); + } + } + }); + }); }); diff --git a/lib/definitions/android-plugin-migrator.d.ts b/lib/definitions/android-plugin-migrator.d.ts index f5ad873307..b787557e7e 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -3,6 +3,11 @@ import { IProjectDir } from "../common/declarations"; interface IPluginBuildOptions extends IAndroidBuildOptions { projectDir?: string; + /** + * File name (without extension) of the built aar and of its temp build dir. + * Defaults to the plugin's short name. + */ + aarName?: string; } interface IAndroidBuildOptions { @@ -17,6 +22,11 @@ interface IAndroidBuildOptions { interface IAndroidPluginBuildService { buildAar(options: IPluginBuildOptions): Promise; migrateIncludeGradle(options: IPluginBuildOptions): boolean; + /** + * Whether the plugin has sources to build but `aarOutputDir` lacks its aar + * or still holds one the CLI built under another of its candidate names. + */ + hasOutdatedAar(options: IPluginBuildOptions): boolean; } /** diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index 88098d55b0..901a06bcbb 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -8,7 +8,12 @@ import { PLUGIN_BUILD_DATA_FILENAME, SCOPED_ANDROID_RUNTIME_NAME, } from "../constants"; -import { getShortPluginName, hook, quoteString } from "../common/helpers"; +import { + getCandidateAarNames, + getShortPluginName, + hook, + quoteString, +} from "../common/helpers"; import { Builder, parseString } from "xml2js"; import { IRuntimeGradleVersions, @@ -39,6 +44,15 @@ import * as _ from "lodash"; import { resolvePackageJSONPath } from "@rigor789/resolve-package-path"; import { cwd } from "process"; +interface IStaleAar { + aarPath: string; + /** + * The CLI's earlier build output the aar must match to be deleted. Absent + * when the aar is deleted whatever its content. + */ + previousOutputPath?: string; +} + export class AndroidPluginBuildService implements IAndroidPluginBuildService { private get $platformsDataService(): IPlatformsDataService { return this.$injector.resolve("platformsDataService"); @@ -226,19 +240,26 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { const androidSourceDirectories = this.getAndroidSourceDirectories( options.platformsAndroidDirPath, ); - const shortPluginName = getShortPluginName(options.pluginName); - const pluginTempDir = path.join(options.tempPluginDirPath, shortPluginName); + const aarName = this.getAarName(options); + const pluginTempDir = path.join(options.tempPluginDirPath, aarName); + const staleAars = + options.aarName && (manifestFilePath || androidSourceDirectories.length) + ? this.getStaleAars(options, aarName) + : []; const pluginSourceFileHashesInfo = await this.getSourceFilesHashes( options.platformsAndroidDirPath, - shortPluginName, + [ + path.join(options.platformsAndroidDirPath, `${aarName}.aar`), + ...staleAars.map((staleAar) => staleAar.aarPath), + ], ); + this.removeStaleAars(options.pluginName, staleAars); const shouldBuildAar = await this.shouldBuildAar({ manifestFilePath, androidSourceDirectories, pluginTempDir, - pluginSourceDir: options.platformsAndroidDirPath, - shortPluginName, + aarPath: path.join(this.getAarOutputDir(options), `${aarName}.aar`), fileHashesInfo: pluginSourceFileHashesInfo, }); @@ -249,7 +270,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { await this.updateManifest( manifestFilePath, pluginTempMainSrcDir, - shortPluginName, + aarName, ); this.copySourceSetDirectories( androidSourceDirectories, @@ -260,6 +281,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { options.platformsAndroidDirPath, options.projectDir, options.pluginName, + aarName, ); await this.buildPlugin({ gradlePath: options.gradlePath, @@ -269,15 +291,134 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { projectDir: options.projectDir, }); this.$watchIgnoreListService.addFileToIgnoreList( - path.join(options.aarOutputDir, `${shortPluginName}.aar`), + path.join(options.aarOutputDir, `${aarName}.aar`), ); - this.copyAar(shortPluginName, pluginTempDir, options.aarOutputDir); + this.copyAar(aarName, pluginTempDir, options.aarOutputDir); this.writePluginHashInfo(pluginSourceFileHashesInfo, pluginTempDir); } return shouldBuildAar; } + public hasOutdatedAar(options: IPluginBuildOptions): boolean { + if ( + !this.$fs.exists(options.platformsAndroidDirPath) || + (!this.getManifest(options.platformsAndroidDirPath) && + !this.getAndroidSourceDirectories(options.platformsAndroidDirPath) + .length) + ) { + return false; + } + + const aarName = this.getAarName(options); + return ( + !this.$fs.exists( + path.join(this.getAarOutputDir(options), `${aarName}.aar`), + ) || this.getStaleAars(options, aarName).length > 0 + ); + } + + private getAarName(options: IPluginBuildOptions): string { + return options.aarName ?? getShortPluginName(options.pluginName); + } + + private getAarOutputDir(options: IPluginBuildOptions): string { + return options.aarOutputDir || options.platformsAndroidDirPath; + } + + /** + * Aars in `aarOutputDir` under another of the plugin's candidate names that + * the CLI built. Earlier CLIs copied every built plugin's aar to + * `.aar`, overwriting any file the package shipped under that + * name, so that file is always a leftover. A scope-qualified name is only + * ever built by this plugin, so that file is a leftover only if the temp + * project for the name was set up for this plugin and has a build output to + * compare it with; otherwise the package ships it. + */ + private getStaleAars( + options: IPluginBuildOptions, + aarName: string, + ): IStaleAar[] { + const aarOutputDir = this.getAarOutputDir(options); + const shortName = getShortPluginName(options.pluginName); + const staleAars: IStaleAar[] = []; + for (const candidate of getCandidateAarNames(options.pluginName)) { + const aarPath = path.join(aarOutputDir, `${candidate}.aar`); + if (candidate === aarName || !this.$fs.exists(aarPath)) { + continue; + } + + if (candidate === shortName) { + staleAars.push({ aarPath }); + continue; + } + + const tempProjectDir = path.join(options.tempPluginDirPath, candidate); + const previousOutputPath = path.join( + tempProjectDir, + "build", + "outputs", + "aar", + `${candidate}-release.aar`, + ); + if ( + this.$fs.exists(previousOutputPath) && + this.getTempProjectPluginName(tempProjectDir) === options.pluginName + ) { + staleAars.push({ aarPath, previousOutputPath }); + } + } + + return staleAars; + } + + /** + * The npm name setupGradle substituted into the temp project's build.gradle. + */ + private getTempProjectPluginName(tempProjectDir: string): string | null { + try { + const buildGradle = this.$fs.readText( + path.join(tempProjectDir, "build.gradle"), + ); + return ( + buildGradle.match(/project\.ext\.PLUGIN_NAME\s*=\s*"([^"]*)"/)?.[1] ?? + null + ); + } catch (err) { + return null; + } + } + + /** + * Gradle templates add every aar in a plugin's platforms/android to the app, + * so an aar the CLI built for this plugin under another candidate name would + * duplicate its classes. + */ + private removeStaleAars(pluginName: string, staleAars: IStaleAar[]): void { + for (const { aarPath, previousOutputPath } of staleAars) { + if ( + previousOutputPath && + !this.isSameFileContent(aarPath, previousOutputPath) + ) { + this.$errors.fail( + `${aarPath} has a name the CLI built ${pluginName}'s aar under before, but differs from that build's output at ${previousOutputPath}. If it is an old build it would add duplicate classes to the app. Delete it or run \`ns clean\`.`, + ); + } + } + + for (const { aarPath } of staleAars) { + this.$watchIgnoreListService.addFileToIgnoreList(aarPath); + this.$logger.trace(`Removing stale plugin aar ${aarPath}`); + this.$fs.deleteFile(aarPath); + } + } + + private isSameFileContent(first: string, second: string): boolean { + const firstContent = this.$fs.readFile(first) as Buffer; + const secondContent = this.$fs.readFile(second) as Buffer; + return firstContent.equals(secondContent); + } + private cleanPluginDir(pluginTempDir: string): void { // In case plugin was already built in the current process, we need to clean the old sources as they may break the new build. this.$fs.deleteDirectory(pluginTempDir); @@ -286,15 +427,12 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { private getSourceFilesHashes( pluginTempPlatformsAndroidDir: string, - shortPluginName: string, + excludedAarPaths: string[], ): Promise { - const pathToAar = path.join( - pluginTempPlatformsAndroidDir, - `${shortPluginName}.aar`, - ); + const excluded = new Set(excludedAarPaths); const pluginNativeDataFiles = this.$fs.enumerateFilesInDirectorySync( pluginTempPlatformsAndroidDir, - (file: string, stat: IFsStats) => file !== pathToAar, + (file: string, stat: IFsStats) => !excluded.has(file), ); return this.$filesHashService.generateHashes(pluginNativeDataFiles); } @@ -311,8 +449,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { manifestFilePath: string; androidSourceDirectories: string[]; pluginTempDir: string; - pluginSourceDir: string; - shortPluginName: string; + aarPath: string; fileHashesInfo: IStringDictionary; }): Promise { let shouldBuildAar = @@ -321,9 +458,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { if ( shouldBuildAar && this.$fs.exists(opts.pluginTempDir) && - this.$fs.exists( - path.join(opts.pluginSourceDir, `${opts.shortPluginName}.aar`), - ) + this.$fs.exists(opts.aarPath) ) { const buildDataFile = this.getPathToPluginBuildDataFile( opts.pluginTempDir, @@ -401,6 +536,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { platformsAndroidDirPath: string, projectDir: string, pluginName: string, + aarName: string, ): Promise { const gradleTemplatePath = path.resolve( path.join(__dirname, "../../vendor/gradle-plugin"), @@ -424,9 +560,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { this.replaceFileContent(buildGradlePath, "{{pluginName}}", pluginName); this.replaceFileContent(settingsGradlePath, "{{pluginName}}", pluginName); - // gets the package from the AndroidManifest to use as the namespace or fallback to the `org.nativescript.${shortPluginName}` - const shortPluginName = getShortPluginName(pluginName); - + // gets the package from the AndroidManifest to use as the namespace or fallback to the `org.nativescript.${aarName}` const manifestPath = path.join( pluginTempDir, "src", @@ -435,7 +569,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { ); const manifestContent = this.$fs.readText(manifestPath); - let packageName = `org.nativescript.${shortPluginName}`; + let packageName = `org.nativescript.${aarName}`; const xml = await this.getXml(manifestContent); if (xml["manifest"]) { if (xml["manifest"]["$"]["package"]) { diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index d4ba573a08..2484de9b8c 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -6,7 +6,7 @@ import * as semver from "semver"; import * as projectServiceBaseLib from "./platform-project-service-base"; import { DeviceAndroidDebugBridge } from "../common/mobile/android/device-android-debug-bridge"; import { Configurations, LiveSyncPaths } from "../common/constants"; -import { hook } from "../common/helpers"; +import { getUniqueShortPluginNames, hook } from "../common/helpers"; import { performanceLog } from ".././common/decorators"; import { IProjectData, @@ -16,6 +16,7 @@ import { import { IPlatformData, IBuildOutputOptions, + INodeModulesDependenciesBuilder, IPlatformEnvironmentRequirements, IValidBuildOutputData, } from "../definitions/platform"; @@ -159,6 +160,11 @@ export class AndroidProjectService super($fs, $projectDataService); } + private pluginAarNames: { + projectDir: string; + names: Map; + } = null; + private _platformData: IPlatformData = null; public getPlatformData(projectData: IProjectData): IPlatformData { if (!projectData && !this._platformData) { @@ -695,15 +701,11 @@ export class AndroidProjectService AndroidProjectService.ANDROID_PLATFORM_NAME, ); if (this.$fs.exists(pluginPlatformsFolderPath)) { - const options: IPluginBuildOptions = { - gradlePath: this.$options.gradlePath, - gradleArgs: this.$options.gradleArgs, - projectDir: projectData.projectDir, - pluginName: pluginData.name, - platformsAndroidDirPath: pluginPlatformsFolderPath, - aarOutputDir: pluginPlatformsFolderPath, - tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), - }; + const options = this.getPluginBuildOptions( + pluginData, + pluginPlatformsFolderPath, + projectData, + ); if (await this.$androidPluginBuildService.buildAar(options)) { this.$logger.info(`Built aar for ${options.pluginName}`); @@ -713,6 +715,90 @@ export class AndroidProjectService } } + public shouldRepreparePlugin( + pluginData: IPluginData, + projectData: IProjectData, + ): boolean { + if (!this.getPluginAarNames(projectData).has(pluginData.name)) { + return false; + } + + return this.$androidPluginBuildService.hasOutdatedAar( + this.getPluginBuildOptions( + pluginData, + this.getPluginPlatformsFolderPath( + pluginData, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ), + projectData, + ), + ); + } + + private getPluginBuildOptions( + pluginData: IPluginData, + pluginPlatformsFolderPath: string, + projectData: IProjectData, + ): IPluginBuildOptions { + const options: IPluginBuildOptions = { + gradlePath: this.$options.gradlePath, + gradleArgs: this.$options.gradleArgs, + projectDir: projectData.projectDir, + pluginName: pluginData.name, + platformsAndroidDirPath: pluginPlatformsFolderPath, + aarOutputDir: pluginPlatformsFolderPath, + tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), + }; + + const aarName = this.getPluginAarNames(projectData).get(pluginData.name); + if (aarName) { + options.aarName = aarName; + } + + return options; + } + + /** + * Normally computed by beforePrepareAllPlugins; computed here from the + * project's production dependencies when a plugin is prepared without it. + */ + private getPluginAarNames(projectData: IProjectData): Map { + if (this.pluginAarNames?.projectDir !== projectData.projectDir) { + const dependencies = this.$injector + .resolve( + "nodeModulesDependenciesBuilder", + ) + .getProductionDependencies( + projectData.projectDir, + projectData.ignoredDependencies, + ); + this.setPluginAarNames( + projectData, + this.filterUniqueDependencies(dependencies).filter( + AndroidProjectService.isNativeAndroidDependency, + ), + ); + } + + return this.pluginAarNames.names; + } + + private setPluginAarNames( + projectData: IProjectData, + nativeDependencyData: IDependencyData[], + ): void { + let names: Map; + try { + names = getUniqueShortPluginNames( + nativeDependencyData.map((dep) => dep.name), + ); + } catch (err) { + this.$errors.fail(err.message); + } + + this.pluginAarNames = { projectDir: projectData.projectDir, names }; + } + public async processConfigurationFilesFromAppResources(): Promise { return; } @@ -775,6 +861,7 @@ export class AndroidProjectService let nativeDependencyData = dependencies.filter( AndroidProjectService.isNativeAndroidDependency, ); + this.setPluginAarNames(projectData, nativeDependencyData); let nativeDependencies = nativeDependencyData.map( ({ name, directory, dependencies }) => { diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index c2107cf4c1..ee28d606e9 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -24,6 +24,8 @@ describe("androidPluginBuildService", () => { const pluginName = "my-plugin"; const shortPluginName = getShortPluginName(pluginName); let spawnFromEventCalled = false; + let ignoredFiles: string[] = []; + let hashedFiles: string[] = []; let fs: IFileSystem; let androidBuildPluginService: AndroidPluginBuildService; let tempFolder: string; @@ -75,15 +77,17 @@ describe("androidPluginBuildService", () => { const testInjector: IInjector = new stubs.InjectorStub(); testInjector.register("fs", FsLib.FileSystem); testInjector.register("childProcess", { - spawnFromEvent: async (command: string): Promise => { - const finalAarName = `${shortPluginName}-release.aar`; + spawnFromEvent: async ( + command: string, + args: string[], + ): Promise => { + const pluginDir = args[args.indexOf("-p") + 1]; const aar = path.join( - tempFolder, - shortPluginName, + pluginDir, "build", "outputs", "aar", - finalAarName, + `${path.basename(pluginDir)}-release.aar`, ); fs.writeFile(aar, ""); spawnFromEventCalled = command.indexOf("gradlew") !== -1; @@ -93,9 +97,10 @@ describe("androidPluginBuildService", () => { testInjector.register("packageManager", setupNpm(options)); testInjector.register("projectData", stubs.ProjectDataStub); testInjector.register("filesHashService", { - generateHashes: async ( - files: string[], - ): Promise => ({}), + generateHashes: async (files: string[]): Promise => { + hashedFiles = files; + return {}; + }, getChanges: async ( files: string[], oldHashes: IStringDictionary, @@ -106,8 +111,9 @@ describe("androidPluginBuildService", () => { ): boolean => !!options.hasChangesInShasums, }); + ignoredFiles = []; testInjector.register("watchIgnoreListService", { - addFileToIgnoreList: () => ({}), + addFileToIgnoreList: (file: string) => ignoredFiles.push(file), }); fs = testInjector.resolve("fs"); @@ -415,6 +421,294 @@ dependencies { }); }); + describe("aar names", () => { + const scopedPluginName = "@foo/my-plugin"; + const qualifiedName = "foo_my_plugin"; + + function setupScoped( + overrides?: Partial, + ): IPluginBuildOptions { + return { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + aarName: qualifiedName, + ...overrides, + }; + } + + function writePreviousOutput( + name: string, + content: string, + builtFor = scopedPluginName, + ) { + fs.writeFile( + path.join(tempFolder, name, "build.gradle"), + `android {\n project.ext.PLUGIN_NAME = "${builtFor}"\n}\n`, + ); + fs.writeFile( + path.join( + tempFolder, + name, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ), + content, + ); + } + + it("uses aarName for the temp project, the aar and the namespace fallback", async () => { + const config = setupScoped(); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + const buildGradle = fs.readText( + path.join(tempFolder, qualifiedName, "build.gradle"), + ); + assert.include( + buildGradle, + `namespace "org.nativescript.${qualifiedName}"`, + ); + assert.isTrue(fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`))); + assert.isFalse(fs.exists(path.join(tempFolder, shortPluginName))); + assert.isFalse( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.deepStrictEqual(ignoredFiles, [ + path.join(pluginFolder, `${qualifiedName}.aar`), + ]); + }); + + it("does not hash the aar it builds or one it built under its other name", async () => { + const config = setupScoped(); + for (const name of [shortPluginName, qualifiedName, "unrelated"]) { + fs.writeFile(path.join(pluginFolder, `${name}.aar`), name); + } + + await androidBuildPluginService.buildAar(config); + + assert.include(hashedFiles, path.join(pluginFolder, "unrelated.aar")); + assert.notInclude( + hashedFiles, + path.join(pluginFolder, `${shortPluginName}.aar`), + ); + assert.notInclude( + hashedFiles, + path.join(pluginFolder, `${qualifiedName}.aar`), + ); + }); + + it("deletes an aar under the plugin's short name whatever its content", async () => { + const config = setupScoped(); + const staleAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "not like any build output"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + assert.isTrue(fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`))); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("deletes the old short-name aars of clashing plugins built by an older CLI", async () => { + const foo = setupScoped({ + pluginName: "@foo/plugin-x", + aarName: "foo_plugin_x", + }); + const barFolder = mkdtempSync( + path.join(tmpdir(), "androidPluginBuildService-plugin-"), + ); + fs.copyFile( + path.join(pluginFolder, "AndroidManifest.xml"), + path.join(barFolder, "AndroidManifest.xml"), + ); + const bar: IPluginBuildOptions = { + ...foo, + pluginName: "@bar/plugin-x", + aarName: "bar_plugin_x", + platformsAndroidDirPath: barFolder, + aarOutputDir: barFolder, + }; + const fooOldAar = path.join(pluginFolder, "plugin_x.aar"); + const barOldAar = path.join(barFolder, "plugin_x.aar"); + fs.writeFile(fooOldAar, "foo build"); + fs.writeFile(barOldAar, "bar build"); + writePreviousOutput("plugin_x", "bar build", "@bar/plugin-x"); + + assert.isTrue(await androidBuildPluginService.buildAar(foo)); + assert.isTrue(await androidBuildPluginService.buildAar(bar)); + + assert.isFalse(fs.exists(fooOldAar)); + assert.isFalse(fs.exists(barOldAar)); + assert.isTrue(fs.exists(path.join(pluginFolder, "foo_plugin_x.aar"))); + assert.isTrue(fs.exists(path.join(barFolder, "bar_plugin_x.aar"))); + }); + + it("deletes a short-name aar that a plugin with sources ships when another plugin now owns that name", async () => { + const config = setupScoped({ + pluginName: "@foo/plugin-x", + aarName: "foo_plugin_x", + }); + const shippedAar = path.join(pluginFolder, "plugin_x.aar"); + fs.writeFile(shippedAar, "shipped"); + writePreviousOutput("plugin_x", "built for plugin-x", "plugin-x"); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + assert.isFalse(fs.exists(shippedAar)); + assert.isTrue(fs.exists(path.join(pluginFolder, "foo_plugin_x.aar"))); + assert.equal( + fs.readText( + path.join( + tempFolder, + "plugin_x", + "build", + "outputs", + "aar", + "plugin_x-release.aar", + ), + ), + "built for plugin-x", + ); + }); + + it("keeps the aars of a plugin without sources to build", async () => { + const config: IPluginBuildOptions = { + ...setup(), + pluginName: "@foo/plugin-x", + aarName: "foo_plugin_x", + }; + const shippedAar = path.join(pluginFolder, "plugin_x.aar"); + fs.writeFile(shippedAar, "shipped"); + + assert.isFalse(await androidBuildPluginService.buildAar(config)); + + assert.equal(fs.readText(shippedAar), "shipped"); + assert.notInclude(ignoredFiles, shippedAar); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("deletes a scope-qualified aar the CLI built for the plugin", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const staleAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(staleAar, "previous build"); + writePreviousOutput(qualifiedName, "previous build"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("fails on a scope-qualified aar that differs from the CLI's build of the plugin under that name", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const staleAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(staleAar, "shipped"); + writePreviousOutput(qualifiedName, "something else"); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + let error: Error = null; + try { + await androidBuildPluginService.buildAar(config); + } catch (err) { + error = err; + } + + assert.include(error?.message, staleAar); + assert.include( + error?.message, + path.join( + tempFolder, + qualifiedName, + "build", + "outputs", + "aar", + `${qualifiedName}-release.aar`, + ), + ); + assert.include(error?.message, "Delete it or run `ns clean`"); + assert.isTrue(fs.exists(staleAar)); + assert.isFalse(spawnFromEventCalled); + }); + + it("keeps a scope-qualified aar the CLI never built", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const shippedAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(shippedAar, "shipped"); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + assert.equal(fs.readText(shippedAar), "shipped"); + assert.notInclude(ignoredFiles, shippedAar); + assert.include(hashedFiles, shippedAar); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("keeps a scope-qualified aar whose temp project was not set up for the plugin", async () => { + const config = setupScoped({ aarName: shortPluginName }); + const shippedAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(shippedAar, "shipped"); + writePreviousOutput(qualifiedName, "something else", "@other/my-plugin"); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + assert.equal(fs.readText(shippedAar), "shipped"); + + assert.notInclude(ignoredFiles, shippedAar); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + + fs.deleteFile(path.join(tempFolder, qualifiedName, "build.gradle")); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + await androidBuildPluginService.buildAar(config); + assert.equal(fs.readText(shippedAar), "shipped"); + }); + + it("leaves other candidate aars alone when no aarName is given", async () => { + const config: IPluginBuildOptions = { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + }; + const otherAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(otherAar, "kept"); + writePreviousOutput(qualifiedName, "kept"); + + await androidBuildPluginService.buildAar(config); + + assert.isTrue(fs.exists(otherAar)); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + }); + + describe("hasOutdatedAar", () => { + it("is false for a plugin without sources to build", () => { + const config: IPluginBuildOptions = { + ...setup({ addIncludeGradle: true }), + aarName: shortPluginName, + }; + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("is true while the aar is missing", () => { + const config = setupScoped(); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + fs.writeFile(path.join(pluginFolder, `${qualifiedName}.aar`), ""); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + }); + }); + describe("migrateIncludeGradle", () => { it("if there is a legacy include.gradle file", async () => { const config: IPluginBuildOptions = setup({ diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index 1961548012..7f758ecad3 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -4,6 +4,9 @@ import * as stubs from "../stubs"; import { assert } from "chai"; import * as sinon from "sinon"; import * as path from "path"; +import { mkdtempSync, realpathSync } from "fs"; +import { tmpdir } from "os"; +import { FileSystem } from "../../lib/common/file-system"; import { GradleCommandService } from "../../lib/services/android/gradle-command-service"; import { GradleBuildService } from "../../lib/services/android/gradle-build-service"; import { GradleBuildArgsService } from "../../lib/services/android/gradle-build-args-service"; @@ -12,7 +15,10 @@ import { IAndroidToolsInfo, IAndroidToolsInfoData, IAndroidResourcesMigrationService, + IDependencyData, } from "../../lib/declarations"; +import { IPluginData } from "../../lib/definitions/plugins"; +import { IPluginBuildOptions } from "../../lib/definitions/android-plugin-migrator"; import { IInjector } from "../../lib/common/definitions/yok"; import { IDictionary, @@ -102,7 +108,7 @@ describe("androidProjectService", () => { childProcess = injector.resolve("childProcess"); const getPlatformDataStub: sinon.SinonStub = sandbox.stub( androidProjectService, - "getPlatformData" + "getPlatformData", ); getPlatformDataStub.callsFake(() => { return { @@ -120,7 +126,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -136,7 +142,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -152,7 +158,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -169,7 +175,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -182,30 +188,30 @@ describe("androidProjectService", () => { const pathToAppResourcesDir = path.join(projectDir, "app", "App_Resources"); const pathToAppResourcesAndroid = path.join( pathToAppResourcesDir, - "Android" + "Android", ); const pathToPlatformsAndroid = path.join( projectDir, "platforms", - "android" + "android", ); const pathToResDirInPlatforms = path.join( pathToPlatformsAndroid, "app", "src", "main", - "res" + "res", ); const valuesV27Path = path.join(pathToResDirInPlatforms, "values-v27"); const valuesV28Path = path.join(pathToResDirInPlatforms, "values-v28"); const libsPath = path.join(pathToResDirInPlatforms, "libs"); const drawableHdpiPath = path.join( pathToResDirInPlatforms, - "drawable-hdpi" + "drawable-hdpi", ); const drawableLdpiPath = path.join( pathToResDirInPlatforms, - "drawable-ldpi" + "drawable-ldpi", ); let deletedDirs: string[] = []; let copiedFiles: { @@ -232,7 +238,7 @@ describe("androidProjectService", () => { }; fs.copyFile = ( sourceFileName: string, - destinationFileName: string + destinationFileName: string, ): void => { copiedFiles.push({ sourceFileName, destinationFileName }); }; @@ -245,7 +251,7 @@ describe("androidProjectService", () => { const androidToolsInfo = injector.resolve("androidToolsInfo"); androidToolsInfo.getToolsInfo = ( - config?: IProjectDir + config?: IProjectDir, ): IAndroidToolsInfoData => { return { compileSdkVersion, @@ -256,12 +262,12 @@ describe("androidProjectService", () => { describe("when new Android App_Resources structure is detected (post {N} 4.0 structure)", () => { const pathToSrcDirInAppResources = path.join( pathToAppResourcesAndroid, - "src" + "src", ); beforeEach(() => { const androidResourcesMigrationService = injector.resolve( - "androidResourcesMigrationService" + "androidResourcesMigrationService", ); androidResourcesMigrationService.hasMigrated = () => true; }); @@ -277,7 +283,7 @@ describe("androidProjectService", () => { "platforms", "android", "app", - "src" + "src", ), }, ]); @@ -333,7 +339,7 @@ describe("androidProjectService", () => { beforeEach(() => { const androidResourcesMigrationService = injector.resolve( - "androidResourcesMigrationService" + "androidResourcesMigrationService", ); androidResourcesMigrationService.hasMigrated = () => false; }); @@ -404,3 +410,225 @@ describe("androidProjectService", () => { }); }); }); + +describe("androidProjectService plugin aar names", () => { + let fs: IFileSystem; + let service: AndroidProjectService; + let projectDir: string; + let platformDir: string; + let dependencies: IDependencyData[]; + let buildAarCalls: IPluginBuildOptions[]; + let outdatedAar: boolean; + + function createProjectData(): IProjectData { + return ({ + projectDir, + platformsDir: path.join(projectDir, "platforms"), + ignoredDependencies: [], + }); + } + + function addPlugin(plugin: { + name: string; + dependencies?: string[]; + native?: boolean; + }): void { + const directory = path.join(projectDir, "node_modules", plugin.name); + const nativescript = + plugin.native === false ? {} : { platforms: { android: "8.0.0" } }; + fs.writeFile( + path.join(directory, "platforms", "android", "AndroidManifest.xml"), + "", + ); + dependencies.push({ + name: plugin.name, + directory, + depth: 0, + version: "1.0.0", + nativescript, + dependencies: plugin.dependencies ?? [], + }); + } + + function pluginData(name: string): IPluginData { + const directory = path.join(projectDir, "node_modules", name); + return ({ + name, + fullPath: directory, + pluginPlatformsFolderPath: (platform: string) => + path.join(directory, "platforms", platform), + }); + } + + function addClashingPlugins(): void { + addPlugin({ name: "@nativescript/core" }); + addPlugin({ name: "@foo/plugin-x", dependencies: ["@nativescript/core"] }); + addPlugin({ name: "@bar/plugin-x" }); + } + + beforeEach(() => { + projectDir = realpathSync( + mkdtempSync(path.join(tmpdir(), "android-aar-names-")), + ); + platformDir = path.join(projectDir, "platforms", "android"); + dependencies = []; + buildAarCalls = []; + outdatedAar = false; + + const testInjector = new Yok(); + testInjector.register("injector", testInjector); + testInjector.register("fs", FileSystem); + testInjector.register("logger", stubs.LoggerStub); + testInjector.register("errors", stubs.ErrorsStub); + testInjector.register("options", {}); + testInjector.register("projectDataService", {}); + testInjector.register("nodeModulesDependenciesBuilder", { + getProductionDependencies: () => dependencies, + }); + testInjector.register("androidPluginBuildService", { + buildAar: async (options: IPluginBuildOptions) => { + buildAarCalls.push(options); + return false; + }, + migrateIncludeGradle: () => false, + hasOutdatedAar: () => outdatedAar, + }); + for (const unused of [ + "androidToolsInfo", + "devicePlatformsConstants", + "platformEnvironmentRequirements", + "androidResourcesMigrationService", + "filesHashService", + "gradleCommandService", + "gradleBuildService", + "analyticsService", + ]) { + testInjector.register(unused, {}); + } + testInjector.register("androidProjectService", AndroidProjectService); + + fs = testInjector.resolve("fs"); + service = testInjector.resolve("androidProjectService"); + }); + + it("writes the same dependencies.json when no short names clash", async () => { + addPlugin({ + name: "nativescript-plugin", + dependencies: ["@nativescript/core", "lodash"], + }); + addPlugin({ name: "@nativescript/core" }); + addPlugin({ name: "lodash", native: false }); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + const relative = (name: string) => + path.relative(platformDir, path.join(projectDir, "node_modules", name)); + assert.equal( + fs.readText(path.join(platformDir, "dependencies.json")), + JSON.stringify( + [ + { + name: "@nativescript/core", + directory: relative("@nativescript/core"), + dependencies: [], + }, + { + name: "nativescript-plugin", + directory: relative("nativescript-plugin"), + dependencies: ["@nativescript/core"], + }, + ], + null, + 4, + ), + ); + }); + + it("builds plugins without a clash under their short name", async () => { + addClashingPlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@nativescript/core"), + projectData, + ); + + const nativeDir = path.join( + projectDir, + "node_modules", + "@nativescript", + "core", + "platforms", + "android", + ); + assert.deepStrictEqual(buildAarCalls, [ + { + gradlePath: undefined, + gradleArgs: undefined, + projectDir, + pluginName: "@nativescript/core", + platformsAndroidDirPath: nativeDir, + aarOutputDir: nativeDir, + tempPluginDirPath: path.join(projectDir, "platforms", "tempPlugin"), + aarName: "core", + }, + ]); + }); + + it("builds clashing plugins under scope-qualified names", async () => { + addClashingPlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + await service.preparePluginNativeCode( + pluginData("@bar/plugin-x"), + projectData, + ); + + assert.deepStrictEqual( + buildAarCalls.map((options) => options.aarName), + ["foo_plugin_x", "bar_plugin_x"], + ); + }); + + it("works out the aar names when plugins are prepared on their own", async () => { + addClashingPlugins(); + + await service.preparePluginNativeCode( + pluginData("@bar/plugin-x"), + createProjectData(), + ); + + assert.equal(buildAarCalls[0].aarName, "bar_plugin_x"); + }); + + it("asks for a reprepare when the plugin's aar is outdated", async () => { + addClashingPlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + assert.isFalse( + service.shouldRepreparePlugin(pluginData("@foo/plugin-x"), projectData), + ); + outdatedAar = true; + assert.isTrue( + service.shouldRepreparePlugin(pluginData("@foo/plugin-x"), projectData), + ); + }); + + it("fails prepare when two plugins cannot get distinct aar names", async () => { + addPlugin({ name: "@foo/plugin-x" }); + addPlugin({ name: "@foo/plugin_x" }); + + await assert.isRejected( + service.beforePrepareAllPlugins(createProjectData(), dependencies), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + assert.isFalse(fs.exists(path.join(platformDir, "dependencies.json"))); + }); +}); diff --git a/test/stubs.ts b/test/stubs.ts index c21b07ce22..35baf6cc3a 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -750,6 +750,10 @@ export class AndroidPluginBuildServiceStub implements IAndroidPluginBuildService migrateIncludeGradle(options: IPluginBuildOptions): boolean { return true; } + + hasOutdatedAar(options: IPluginBuildOptions): boolean { + return false; + } } export class PlatformProjectServiceStub