From 103c36fd1a8a2272c1ce3b970e66e9bf8587388f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 10:17:49 -0300 Subject: [PATCH 1/9] feat(gradle-api): org.nativescript:gradle-api, a versioned Gradle API for plugins A Java Gradle library (plugin id `org.nativescript.api`, extension `nativescript`) that plugins load from their buildscript.gradle and call from include.gradle instead of building paths into node_modules or the CLI's output folders: apiLevel, has(capability), pluginBuild, self, isBuildingPlugin(name), projectRoot, appDir, appResourcesDir, plugin(name) / findPlugin(name) and resolvePackage(name) / findPackage(name). It reads the facts file NativeScript CLI 9.2+ writes (platforms/android/nativescript-gradle.json, schema in gradle-api/schema). A missing facts file, or one that no longer matches dependencies.json, fails with a message that asks to prepare the project with CLI 9.2 or newer. Compiled for Java 11 against the Gradle 7.5 API; functional tests cover Gradle 7.5.1, 8.14.3 and 9.8.1, and run the CLI's plugin-build template and a frozen copy of the 9.1 one with AGP. The plugin-build template applies the library whenever a buildscript.gradle put it on the classpath, so the dependencies {} and repositories {} blocks the CLI copies from a plugin's include.gradle can use it in the plugin's own aar build. --- .gitignore | 6 + gradle-api/.gitattributes | 2 + gradle-api/README.md | 441 ++++++++++++++++++ gradle-api/build.gradle.kts | 126 +++++ gradle-api/gradle.properties | 27 ++ gradle-api/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43764 bytes .../gradle/wrapper/gradle-wrapper.properties | 8 + gradle-api/gradlew | 251 ++++++++++ gradle-api/gradlew.bat | 94 ++++ gradle-api/samples/sample-plugin/package.json | 12 + .../platforms/android/buildscript.gradle | 10 + .../platforms/android/include.gradle | 11 + .../schema/nativescript-gradle.schema.json | 109 +++++ gradle-api/settings.gradle.kts | 14 + .../org/nativescript/gradle/AppBuildTest.java | 190 ++++++++ .../gradle/ExtractedIncludeGradleTest.java | 58 +++ .../org/nativescript/gradle/Fixtures.java | 263 +++++++++++ .../nativescript/gradle/PluginBuildTest.java | 215 +++++++++ .../packages/fixture-plugin-b/package.json | 1 + .../platforms/android/buildscript.gradle | 3 + .../platforms/android/include.gradle | 22 + .../app-fixture/packages/js-only/package.json | 1 + .../platforms/android/app/build.gradle | 75 +++ .../platforms/android/build.gradle | 13 + .../platforms/android/settings.gradle | 2 + .../cli-9.1-plugin-template/build.gradle | 249 ++++++++++ .../cli-9.1-plugin-template/gradle.properties | 22 + .../cli-9.1-plugin-template/settings.gradle | 33 ++ .../extracted/sample-plugin-include.gradle | 8 + .../org/nativescript/gradle/NativeScript.java | 43 ++ .../gradle/NativeScriptExtension.java | 192 ++++++++ .../gradle/NativeScriptPlugin.java | 26 ++ .../org/nativescript/gradle/PluginInfo.java | 68 +++ .../gradle/internal/BuildInputs.java | 65 +++ .../DefaultNativeScriptExtension.java | 146 ++++++ .../gradle/internal/DefaultPluginInfo.java | 49 ++ .../nativescript/gradle/internal/Facts.java | 309 ++++++++++++ .../nativescript/gradle/internal/Json.java | 366 +++++++++++++++ .../gradle/internal/NodePackages.java | 41 ++ .../gradle/internal/PluginData.java | 53 +++ .../gradle/internal/Resolution.java | 145 ++++++ .../org/nativescript/gradle/package-info.java | 28 ++ .../gradle/internal/BuildInputsTest.java | 30 ++ .../DefaultNativeScriptExtensionTest.java | 131 ++++++ .../gradle/internal/FactsTest.java | 256 ++++++++++ .../gradle/internal/FakeInputs.java | 60 +++ .../gradle/internal/JsonTest.java | 158 +++++++ .../gradle/internal/ResolutionTest.java | 220 +++++++++ .../gradle/internal/TestFiles.java | 49 ++ .../resources/facts/v2-unknown-fields.json | 25 + vendor/gradle-plugin/build.gradle | 9 + 51 files changed, 4735 insertions(+) create mode 100644 gradle-api/.gitattributes create mode 100644 gradle-api/README.md create mode 100644 gradle-api/build.gradle.kts create mode 100644 gradle-api/gradle.properties create mode 100644 gradle-api/gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle-api/gradle/wrapper/gradle-wrapper.properties create mode 100755 gradle-api/gradlew create mode 100644 gradle-api/gradlew.bat create mode 100644 gradle-api/samples/sample-plugin/package.json create mode 100644 gradle-api/samples/sample-plugin/platforms/android/buildscript.gradle create mode 100644 gradle-api/samples/sample-plugin/platforms/android/include.gradle create mode 100644 gradle-api/schema/nativescript-gradle.schema.json create mode 100644 gradle-api/settings.gradle.kts create mode 100644 gradle-api/src/functionalTest/java/org/nativescript/gradle/AppBuildTest.java create mode 100644 gradle-api/src/functionalTest/java/org/nativescript/gradle/ExtractedIncludeGradleTest.java create mode 100644 gradle-api/src/functionalTest/java/org/nativescript/gradle/Fixtures.java create mode 100644 gradle-api/src/functionalTest/java/org/nativescript/gradle/PluginBuildTest.java create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/package.json create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/buildscript.gradle create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/include.gradle create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/packages/js-only/package.json create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/platforms/android/app/build.gradle create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/platforms/android/build.gradle create mode 100644 gradle-api/src/functionalTest/resources/app-fixture/platforms/android/settings.gradle create mode 100644 gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/build.gradle create mode 100644 gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/gradle.properties create mode 100644 gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/settings.gradle create mode 100644 gradle-api/src/functionalTest/resources/extracted/sample-plugin-include.gradle create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/NativeScript.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/NativeScriptExtension.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/NativeScriptPlugin.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/PluginInfo.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/BuildInputs.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultNativeScriptExtension.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultPluginInfo.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/Facts.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/Json.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/NodePackages.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/PluginData.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/internal/Resolution.java create mode 100644 gradle-api/src/main/java/org/nativescript/gradle/package-info.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/BuildInputsTest.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/DefaultNativeScriptExtensionTest.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/FactsTest.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/FakeInputs.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/JsonTest.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/ResolutionTest.java create mode 100644 gradle-api/src/test/java/org/nativescript/gradle/internal/TestFiles.java create mode 100644 gradle-api/src/test/resources/facts/v2-unknown-fields.json diff --git a/.gitignore b/.gitignore index 2c4b2d2127..4d874c6797 100644 --- a/.gitignore +++ b/.gitignore @@ -131,3 +131,9 @@ CLAUDE.local.md .env.* !.env.example .envrc + +# org.nativescript:gradle-api +gradle-api/build/ +gradle-api/**/.gradle/ +gradle-api/.kotlin/ +gradle-api/samples/**/build/ diff --git a/gradle-api/.gitattributes b/gradle-api/.gitattributes new file mode 100644 index 0000000000..4e03091347 --- /dev/null +++ b/gradle-api/.gitattributes @@ -0,0 +1,2 @@ +gradlew.bat text eol=crlf +*.jar binary diff --git a/gradle-api/README.md b/gradle-api/README.md new file mode 100644 index 0000000000..a8f7c17ebb --- /dev/null +++ b/gradle-api/README.md @@ -0,0 +1,441 @@ +# org.nativescript:gradle-api + +A small, versioned Gradle library that NativeScript plugins call from their Android Gradle files +instead of guessing where things are on disk. It needs **NativeScript CLI 9.2 or newer**. + +```groovy +// platforms/android/include.gradle +apply plugin: "org.nativescript.api" + +logger.info("App_Resources: ${nativescript.appResourcesDir}") +``` + +- **For plugin authors:** [Why](#why), [Adopting it](#adopting-it), + [Your plugin's own `.aar` build](#your-plugins-own-aar-build), + [Depending on other plugins](#depending-on-other-plugins), [API](#api), [Errors](#errors), + [Recipes](#recipes), [Compatibility](#compatibility), [Rules](#rules-for-plugin-authors). +- **For CLI/runtime maintainers:** [How it works](#how-it-works), [The facts file](#the-facts-file), + [Versioning rules](#versioning-rules), [Releasing](#releasing). + +## Why + +Plugin Gradle files today find things by building paths themselves: + +```groovy +// a real-world include.gradle +def widgetsDir = "$USER_PROJECT_ROOT/node_modules/@nativescript/core/platforms/android" +// another one +maven { url = project.file('../../../node_modules/detox/Detox-android') } +// and the most common one +if (!project.hasProperty("tempBuild")) { apply plugin: 'com.google.gms.google-services' } +``` + +Every one of these bakes in a detail the CLI should be free to change: where `node_modules` is, +where the CLI writes a plugin's built `.aar`, how many `../` lead to the project root, or what the +`tempBuild` property means. This library answers those questions for you, from a file in which the +CLI writes the answers down. + +## Adopting it + +Requirements: + +- **NativeScript CLI 9.2 or newer** in the apps that use your plugin. The CLI is installed per + project (`npm i -D nativescript@latest`), and 9.2 builds projects made with older CLIs, so this + asks nothing of an app beyond updating that dev dependency. With an older CLI, the build stops + with a message that says so (see [Errors](#errors)). +- **Android runtime 8.4 or newer** (Gradle 7.5, JDK 11), the oldest toolchain the library is built + for. If your plugin still supports older runtimes, keep your current Gradle code for them: adding + the library to `buildscript.gradle` breaks their builds. + +**1. Put the library on the build classpath** in `platforms/android/buildscript.gradle`: + +```groovy +repositories { + mavenCentral() +} +dependencies { + classpath "org.nativescript:gradle-api:" +} +``` + +(No version is published yet; this README is part of the proposal.) + +Pin the **lowest** version that has what you need, never a range or `+`. Every plugin in an app adds +the library to the same classpath and Gradle keeps the highest version, which is always backwards +compatible. + +Add it **only** in `platforms/android/buildscript.gradle`, never on a root classpath: not in a +plugin's `rootbuildscript.gradle`, not in the app's `App_Resources/Android/rootbuildscript.gradle`, +and not in the root `build.gradle` of `platforms/android`. Gradle looks up classes in the root +project's class loader before the app's, so a version on the root classpath wins over every +plugin's `buildscript.gradle`, even one that asks for a newer version, and every plugin in the app +gets that older version. + +**2. If you use `nativescript` in the app build**, apply the library at the top of +`platforms/android/include.gradle`. The whole file runs in the app build, including its +`repositories {}` and `dependencies {}` blocks; only code inside the `tempBuild` check of +[the next section](#your-plugins-own-aar-build) is skipped there. + +```groovy +apply plugin: "org.nativescript.api" +``` + +Applying it again from several plugins is fine. + +**3. Use `nativescript`** (see [API](#api) and [Recipes](#recipes)). + +Mention the CLI 9.2+ requirement in your plugin's README and changelog, and release it as a major +version: apps on older CLIs find out at build time, from the check in the next section. + +Never refer to the library's classes from `include.gradle` (`import org.nativescript.gradle...`, +`NativeScript.of(project)`): Gradle compiles applied scripts with a class loader that can't see +them, even when the plugin itself is applied. Always go through the `nativescript` extension. +`NativeScript.of(project)` is for Gradle code written in Java or Kotlin. + +## Your plugin's own `.aar` build + +The CLI builds a plugin's own Android sources into an `.aar` in a separate, temporary Gradle build. +In that build, **only the `repositories {}` and `dependencies {}` blocks of your `include.gradle` +run**: the CLI copies them out of the file. Nothing else in the file runs there, including the +`apply plugin:` line. CLI 9.2+ runs your `buildscript.gradle` in that build and applies the library +itself, so `nativescript` is available in those two blocks. + +CLIs before 9.2 don't load the library there, and Gradle would stop with "Could not get unknown +property 'nativescript'", which doesn't tell the app developer what to do. Check for the extension +first and give them a clear message instead: + +```groovy +dependencies { + if (project.hasProperty("tempBuild")) { + if (project.extensions.findByName("nativescript") == null) { + throw new GradleException("@nativescript/gradle-api-sample needs NativeScript CLI 9.2 or newer: npm i -D nativescript@latest") + } + compileOnly nativescript.plugin("@nativescript/core").artifacts + } +} +``` + +- `tempBuild` is set in every plugin `.aar` build by every CLI since 8.4: your own build, and the + builds of plugins that depend on yours, where your full `include.gradle` runs. The check keeps + the block out of the app build, which runs it too but already links every plugin. +- Each copied block runs on its own, without the rest of the file, and the CLI copies + `repositories {}` before `dependencies {}`. If both use `nativescript`, start both with the check. +- With CLI 9.2+ the check always passes in your own build; it exists only for older CLIs. + +The CLI finds those blocks by searching for the first occurrence of the words `dependencies` and +`repositories` in the file, so keep those words out of comments and code above the real blocks, and +never put a `buildscript {}` block in `include.gradle`. + +## Depending on other plugins + +| What your plugin needs | What it writes | +|---|---| +| Another plugin it lists in its `package.json` `dependencies` | Nothing: in its own `.aar` build the CLI adds that plugin's `.aar`/`.jar` files as `implementation`, and in the app build every plugin is linked. | +| A plugin it doesn't list (typically `@nativescript/core`, usually a peer) | `compileOnly nativescript.plugin("...").artifacts` inside the `tempBuild` check, as in [the block above](#your-plugins-own-aar-build), for the `.aar`/`.jar` files that plugin **ships prebuilt** in its package. Not `implementation`: Android's library plugin rejects a local `.aar` as `implementation` when it packages yours ("Direct local .aar file dependencies are not supported when building an AAR"), and the app links that plugin anyway. | +| Its own prebuilt `.jar`/`.aar` | Nothing, if they're in `platforms/android` or `platforms/android/libs`: the app build links them. | +| A Maven library | The usual `implementation "group:artifact:version"`. | + +The CLI builds plugins' `.aar`s one after the other: `@nativescript/core` first, then every plugin +after the plugins it lists in its `dependencies`. The order between unrelated plugins is not +defined, and `artifacts` only includes an `.aar` once it exists, so on a clean build +`compileOnly nativescript.plugin(X).artifacts` can miss an `.aar` the CLI builds from X's sources. +If you need such an `.aar`, list X in your `dependencies`. `@nativescript/core` is always fine. + +Never write `implementation files(...)` or `flatDir` pointing into another package or into +`node_modules`: the CLI decides where plugins' files are (see +[`pluginBuildLocation`](#for-app-developers-building-plugins-in-platformsandroid-opt-in)), and the +app build already links them. + +Known limits of the CLI's and runtime's templates today: + +- A plugin's `.aar` files are found by name in `platforms/android` and `platforms/android/libs` + only. An `.aar` in any other subfolder fails to resolve ("Could not resolve :name.") in the app + build and in the `.aar` builds of plugins that depend on it. +- In the `.aar` build of a plugin that depends on a plugin with `.jar` files, the CLI's template + fails with "Could not get unknown property 'pluginsJarLibraries'". +- In your own `.aar` build, your own prebuilt `.jar`/`.aar` files are not on the compile classpath: + your Java/Kotlin sources can't use classes from them. + +## API + +`apiLevel` is `1` for everything below. New methods raise it; nothing is ever removed or changed. + +| Member | Needs facts | Returns | +|---|---|---| +| `nativescript.apiLevel` | No | The API level of the library on the classpath. | +| `nativescript.pluginBuild` | No | `true` in the CLI's temporary build of some plugin's `.aar`. | +| `nativescript.isBuildingPlugin(String)` | No | Whether the plugin build is building that npm package. | +| `nativescript.self` | In a plugin build | In a plugin build, the plugin being built (see below). `null` in the app build, without reading the facts file. | +| `nativescript.has(String)` | Yes | Whether the CLI guarantees a capability (see [Capabilities](#capabilities)). | +| `nativescript.projectRoot` | Yes | The NativeScript project root (the folder with the app's `package.json`; `project.root` in the facts file). | +| `nativescript.appDir` | Yes | The app source folder (`appPath` in `nativescript.config`). | +| `nativescript.appResourcesDir` | Yes | `App_Resources`. | +| `nativescript.plugin(String)` | Yes | A plugin the CLI lists, by npm name. Throws if the app doesn't have it. | +| `nativescript.findPlugin(String)` | Yes | Same, or `null`. | +| `nativescript.resolvePackage(String)` | Yes | Any installed npm package's folder. Throws if not found. | +| `nativescript.findPackage(String)` | Yes | Same, or `null`. | + +"Needs facts" members read the facts file CLI 9.2+ writes, and throw one of the [errors](#errors) +below when it is missing or out of date. Without it, only the first three work, and `self` in the +app build. + +A plugin (`PluginInfo`): + +| Member | Returns | +|---|---| +| `name` | The npm package name. | +| `packageDir` | The installed package. Treat it as read-only. | +| `nativeDir` | Where Gradle reads the plugin's Android files from. | +| `artifacts` | Every `.aar` and `.jar` under `nativeDir`, as a lazy `FileCollection`. It includes the `.aar` the CLI builds from the plugin's sources once that exists (see [Depending on other plugins](#depending-on-other-plugins)). | +| `options` | Per-plugin options. Reserved; empty for now. | + +`plugin` / `findPlugin` only know the plugins the CLI lists: packages that declare Android support +in their `package.json` (`"nativescript": { "platforms": { "android": ... } }`), such as +`@nativescript/core`. A package with a `platforms/android` folder but no such declaration is not a +plugin. For any other npm package, use `resolvePackage` / `findPackage`. + +**`pluginBuild` and `self` in practice.** Your full `include.gradle` runs in the app build and in +the `.aar` builds of plugins that *depend on you*. So a full `include.gradle` that sees +`pluginBuild == true` is always running inside another plugin's build, and `self` is that other +plugin. This is what the common `tempBuild` check was really testing: + +```groovy +// apply the Google Services plugin only to the app, not to dependents' aar builds +if (!nativescript.pluginBuild) { + apply plugin: "com.google.gms.google-services" +} +``` + +`resolvePackage` returns the folder the CLI recorded for a plugin, and otherwise looks for +`node_modules/` from the project root upwards, like Node. It's best effort: package managers +that don't hoist (pnpm's default layout) may not resolve packages your app doesn't depend on +directly. + +### Capabilities + +`has(String)` answers from the facts file's `capabilities` list, which is empty today. Capability +names are dotted lowercase `area.feature` (for example `build.abis`). Once a CLI version lists a +capability, every later CLI lists it with the same meaning: names are only ever added. + +## Errors + +The library reads the facts file on the first use of a member that needs it, and stops the build +with one of these messages when it can't: + +- **No facts file**, because a CLI before 9.2 prepared the project: + + > A plugin of this app uses org.nativescript:gradle-api, which needs the project to be prepared + > by NativeScript CLI 9.2 or newer, but there is no facts file at + > `/platforms/android/nativescript-gradle.json`. Update the project's CLI with + > `npm i -D nativescript@latest`, then run `ns prepare android`. + +- **Out-of-date facts file**, because a different CLI (such as an older global one) prepared the + project after the one that wrote it: + + > The NativeScript facts file `<…>/nativescript-gradle.json` does not match + > `<…>/dependencies.json`: a different NativeScript CLI rewrote dependencies.json after the facts + > file was written. Run `ns prepare android` again with the NativeScript CLI the project uses. + + (Or, if `dependencies.json` is gone: "There is no `<…>/dependencies.json` next to the + NativeScript facts file `<…>`." followed by the same advice.) + +- **Library too old for the facts file**, because the file's `minReaderSchemaVersion` is above the + schema version this library supports: + + > The NativeScript facts file `<…>` needs org.nativescript:gradle-api supporting facts schema N, + > but this version of the library supports up to M. Update the plugins of this app that use + > org.nativescript:gradle-api: any one that pins a newer version of the library is enough. + +- **Invalid facts file** ("Invalid NativeScript facts file `<…>`: …"), when a required field such as + `minReaderSchemaVersion` or `dependenciesJson.sha256` is missing or has the wrong type, or + `minReaderSchemaVersion` is greater than `schemaVersion`. The CLI + never writes such a file; prepare again. + +## Recipes + +**Compile against another plugin's Android library (e.g. core's widgets) in your own `.aar` build:** +the block in [Your plugin's own `.aar` build](#your-plugins-own-aar-build). + +**Read a file from App_Resources:** + +```groovy +def config = new File(nativescript.appResourcesDir, "Android/my-plugin.json") +``` + +**Point at another npm package's Maven repository** (detox, react-native style): + +```groovy +apply plugin: "org.nativescript.api" // the block also runs in the app build + +repositories { + if (project.extensions.findByName("nativescript") == null) { + throw new GradleException("my-plugin needs NativeScript CLI 9.2 or newer: npm i -D nativescript@latest") + } + maven { url = new File(nativescript.resolvePackage("detox"), "Detox-android") } +} +``` + +**Only in the app build:** `if (!nativescript.pluginBuild) { ... }`. + +## Compatibility + +| | CLI 9.1 and older | CLI 9.2+ | +|---|---|---| +| Plugin not using the library | Unchanged | Its own `buildscript.gradle` also runs in its own `.aar` build | +| Plugin using the library, app build | `apiLevel`, `pluginBuild`, `isBuildingPlugin` and `self` (null) work; anything else stops the build with the [no facts file](#errors) error | Facts from the CLI | +| Plugin using the library, its own `.aar` build | Library not loaded, so the [check](#your-plugins-own-aar-build) stops the build with the plugin's message (or, if a plugin it depends on applied the library, the [no facts file](#errors) error) | Library loaded and applied, facts from the CLI | +| Project prepared again by an older CLI after 9.2 | The [out-of-date facts file](#errors) error | | + +With [`pluginBuildLocation: "platforms"`](#for-app-developers-building-plugins-in-platformsandroid-opt-in) +(CLI 9.2+), Gradle also reads every plugin's files from a copy in `platforms/android/.ns-plugins/`. + +Building `platforms/android` from Android Studio works too: CLI 9.2+ leaves the facts file there +after `ns prepare android`, so the library has the same answers without the CLI's command-line +flags. + +### For app developers: building plugins in `platforms/android` (opt-in) + +```ts +// nativescript.config.ts +export default { + android: { pluginBuildLocation: "platforms" }, +} satisfies NativeScriptConfig; +``` + +`android.pluginBuildLocation` sets where the CLI builds plugins' native Android code. The default, +`"node_modules"`, builds each plugin's `.aar` inside its package, as CLIs up to 9.1 do. With +`"platforms"`, the CLI never writes into `node_modules`. It copies each native plugin's +`platforms/android` and `package.json` into `platforms/android/.ns-plugins//`, builds plugin +`.aar`s there, and points the Android build at the copies. No runtime change is needed (checked +against the runtime's Gradle templates from 6.5.3 to current), and Android Studio builds use the +copies too. Earlier builds may have left `.aar` files inside `node_modules`; +reinstall `node_modules` once after turning this on to get rid of them. + +`"platforms"` is opt-in while plugins adopt this library, and is expected to become the default in a +future major version of the CLI. + +## Rules for plugin authors + +- Require NativeScript CLI 9.2+: say so in your README and changelog, and start each copied block + that uses `nativescript` with the [check](#your-plugins-own-aar-build). +- Pin the lowest library version you need; no ranges. +- Everything in the version you pin is always there: an app may end up with a newer library, never + an older one. To use something newer only when it's available, check `apiLevel` (or `has(...)`) + first. +- Never build paths into `node_modules` or into the CLI's output folders; ask the library. + +## How it works + +``` +nativescript.config.ts ─┐ +package.json files ─────┼─> ns prepare android ─> platforms/android/nativescript-gradle.json +App_Resources ──────────┘ (and dependencies.json, as before) + │ + -Pnativescript.factsFile │ or found next to the app build + ▼ + plugin buildscript.gradle ─> org.nativescript:gradle-api ─> `nativescript` extension + │ + no facts file, or it doesn't match │ + dependencies.json ▼ + error: prepare with CLI 9.2+ +``` + +The CLI decides everything (where plugins are, what they're called, project layout) and writes the +answers down. Gradle only reads them. The library never guesses: without a facts file that matches +the project, it stops the build and says what to run. + +## The facts file + +`platforms/android/nativescript-gradle.json`, written by `ns prepare android` before any plugin is +built. The schema is [`schema/nativescript-gradle.schema.json`](schema/nativescript-gradle.schema.json). + +```json +{ + "schemaVersion": 1, + "minReaderSchemaVersion": 1, + "cli": { "version": "9.2.0" }, + "runtime": { "name": "@nativescript/android", "version": "9.0.0" }, + "capabilities": [], + "dependenciesJson": { "sha256": "…" }, + "project": { "root": "../..", "appDir": "../../src", "appResourcesDir": "../../App_Resources" }, + "plugins": [ + { + "name": "@nativescript/core", + "packageDir": "../../node_modules/@nativescript/core", + "nativeDir": "../../node_modules/@nativescript/core/platforms/android", + "aarName": "core", + "aar": "../../node_modules/@nativescript/core/platforms/android/core.aar", + "dependencies": [], + "options": {} + } + ] +} +``` + +- Paths are relative to the file, with forward slashes, so the folder can move. +- `minReaderSchemaVersion` is the lowest `schemaVersion` a reader must understand to use the file, + never above the file's own `schemaVersion`. + A library that supports only older schema versions refuses it (see [Errors](#errors)) instead of + reading part of it. CLI 9.2 writes `1`. +- `dependenciesJson.sha256` is the hash of the `dependencies.json` the CLI wrote next to it. A CLI + that doesn't know about this file (9.1 and older, e.g. a global one used by mistake) still + rewrites `dependencies.json` but leaves this file behind; the library notices the mismatch and + stops with the [out-of-date facts file](#errors) error rather than give outdated answers. +- `capabilities` lists behaviours the CLI guarantees, so the library can tell "not set" apart from + "this CLI doesn't know about it". Empty in version 1. +- `options` is reserved for per-plugin settings from `nativescript.config`. + +## Versioning rules + +These are what keep old plugins working on new CLIs, and new plugins working on CLIs from 9.2 on. + +**Facts file:** fields are only added. A field never changes meaning and is never removed. +`schemaVersion` goes up when fields are added; readers accept any version and read what they know, +as long as it isn't below the file's `minReaderSchemaVersion`. A CLI raises `minReaderSchemaVersion` +only for a change that old readers would get wrong if they ignored it, which should be never: it is +the one way to tell libraries already published "you can't read this". Paths are relative. Anything a newer CLI does differently is expressed as data in the file, not as a +rule readers must know. A facts file that doesn't match the `dependencies.json` next to it is an +error, never used. + +**Library:** the public API only grows. Old methods keep working forever; behaviour that depends on +the CLI checks the facts file or a capability before relying on it. The library compiles for Java +11 and the Gradle 7.5 API, the oldest toolchain supported NativeScript runtimes use. + +## Releasing + +Builds and tests run in `.github/workflows/gradle_api.yml`, on Linux (unit and functional tests) +and Windows (unit tests). Pushing a tag `gradle-api-v` on a commit of `main` that matches +`VERSION_NAME` in `gradle.properties` (not a `-SNAPSHOT`) publishes to Maven Central and releases +it at once, from the protected `maven-central` GitHub environment; the workflow refuses a tag on +any other commit. Give that environment required reviewers, since a Maven Central release can't be +undone. It needs these environment secrets: + +- `MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD`: a Central Portal user token with publishing + rights on the `org.nativescript` namespace. +- `MAVEN_CENTRAL_SIGNING_KEY`, `MAVEN_CENTRAL_SIGNING_KEY_PASSWORD`: the release signing key + (ASCII-armored) and its passphrase. The public key must be on keys.openpgp.org and + keyserver.ubuntu.com. + +Publishing uses `com.vanniktech.maven.publish` 0.35.0, the newest release that runs on the Gradle +8.14 wrapper; moving to Gradle 9 allows newer ones. + +Local development needs JDK 17 installed (the functional tests run Gradle 7.5.1, which doesn't +start on newer JDKs): + +```bash +cd gradle-api +./gradlew check # unit + functional tests (AGP tests need ANDROID_HOME) +./gradlew publishToMavenLocal # try it from a local app +``` + +### CLI release notes + +CLI changes from this work that affect plugins that don't use the library, for the CLI 9.2 release +notes: + +- **A plugin's own `platforms/android/buildscript.gradle` now also runs in that plugin's own `.aar` + build.** Before 9.2 it ran only in the app build and in the `.aar` builds of plugins that depend + on it. A plugin whose `buildscript.gradle` adds classpath dependencies or repositories now gets + them in its own build too. Check that it doesn't assume the app build (for example by reading + properties only the app's Gradle project sets); `project.hasProperty("tempBuild")` tells the two + apart. diff --git a/gradle-api/build.gradle.kts b/gradle-api/build.gradle.kts new file mode 100644 index 0000000000..e2dad201f6 --- /dev/null +++ b/gradle-api/build.gradle.kts @@ -0,0 +1,126 @@ +plugins { + `java-gradle-plugin` + id("com.vanniktech.maven.publish") version "0.35.0" +} + +// Plugins on NativeScript Android runtimes back to 8.4 build with Gradle 7.5 on JDK 11. +val oldestSupportedGradle = "7.5.1" +val oldestSupportedJava = 11 + +tasks.withType().configureEach { + options.release = oldestSupportedJava + options.encoding = "UTF-8" + options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror")) +} + +tasks.javadoc { + (options as StandardJavadocDocletOptions).apply { + encoding = "UTF-8" + addStringOption("-release", oldestSupportedJava.toString()) + addBooleanOption("Xdoclint:all,-missing", true) + } + exclude("org/nativescript/gradle/internal/**") +} + +// java-gradle-plugin adds the running Gradle's API to `api`; compile against the oldest supported +// one instead so that using anything newer fails here rather than in a user's build. +configurations.named("api") { + withDependencies { removeIf { it is FileCollectionDependency } } +} + +val functionalTest: SourceSet by sourceSets.creating + +dependencies { + compileOnly("dev.gradleplugins:gradle-api:$oldestSupportedGradle") + + testImplementation(gradleApi()) + testImplementation(platform("org.junit:junit-bom:5.13.4")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + + "functionalTestImplementation"(gradleTestKit()) + "functionalTestImplementation"(platform("org.junit:junit-bom:5.13.4")) + "functionalTestImplementation"("org.junit.jupiter:junit-jupiter") + "functionalTestRuntimeOnly"("org.junit.platform:junit-platform-launcher") +} + +gradlePlugin { + plugins { + create("nativescript") { + id = "org.nativescript.api" + implementationClass = "org.nativescript.gradle.NativeScriptPlugin" + displayName = "NativeScript Gradle API" + description = providers.gradleProperty("POM_DESCRIPTION").get() + } + } +} + +// Functional tests consume the library the way plugins do, from a Maven repository, so they see +// the published metadata and the real buildscript class loader scoping. +val testRepo = layout.buildDirectory.dir("test-repo") + +publishing { + repositories { + maven { + name = "testRepo" + url = uri(testRepo) + } + } +} + +val cleanTestRepo by tasks.registering(Delete::class) { + delete(testRepo) +} + +tasks.withType().configureEach { + if (name.endsWith("ToTestRepoRepository")) { + dependsOn(cleanTestRepo) + } +} + +// A release version is signed with keys only the publish job has; the test repository needs none. +tasks.withType().configureEach { + val signingKey = providers.gradleProperty("signingInMemoryKey") + onlyIf("a signing key is configured") { signingKey.isPresent } +} + +tasks.withType().configureEach { + useJUnitPlatform() + testLogging { + events("failed", "skipped") + exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL + } +} + +val functionalTestTask = tasks.register("functionalTest") { + description = "Runs the TestKit tests against the library published to the test repository." + group = LifecycleBasePlugin.VERIFICATION_GROUP + testClassesDirs = functionalTest.output.classesDirs + classpath = functionalTest.runtimeClasspath + shouldRunAfter(tasks.test) + + dependsOn("publishAllPublicationsToTestRepoRepository") + // The repository itself differs on every publish: snapshot file names carry a timestamp. + inputs.files(tasks.jar).withNormalizer(ClasspathNormalizer::class) + inputs.dir("samples").withPathSensitivity(PathSensitivity.RELATIVE) + inputs.dir("../vendor/gradle-plugin").withPathSensitivity(PathSensitivity.RELATIVE) + + // Gradle 7.5 cannot run on JDK 21+, and TestKit starts its builds on the test JVM. + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(17) } + + val androidHome = providers.environmentVariable("ANDROID_HOME") + inputs.property("androidHomeSet", androidHome.map { true }.orElse(false)) + + systemProperty("nativescript.testRepo", testRepo.get().asFile.absolutePath) + systemProperty("nativescript.libraryVersion", providers.gradleProperty("VERSION_NAME").get()) + systemProperty("nativescript.libraryJar", tasks.jar.get().archiveFile.get().asFile.absolutePath) + systemProperty("nativescript.samplesDir", file("samples").absolutePath) + systemProperty("nativescript.vendorGradlePluginDir", file("../vendor/gradle-plugin").absolutePath) + val gradleVersions = providers.gradleProperty("functionalTestGradleVersions").orElse("7.5.1,8.14.3,9.8.1") + inputs.property("gradleVersions", gradleVersions) + systemProperty("nativescript.gradleVersions", gradleVersions.get()) +} + +tasks.check { + dependsOn(functionalTestTask) +} diff --git a/gradle-api/gradle.properties b/gradle-api/gradle.properties new file mode 100644 index 0000000000..517e8ab316 --- /dev/null +++ b/gradle-api/gradle.properties @@ -0,0 +1,27 @@ +org.gradle.caching=true +org.gradle.configuration-cache=true + +GROUP=org.nativescript +POM_ARTIFACT_ID=gradle-api +VERSION_NAME=0.1.0-SNAPSHOT + +POM_NAME=NativeScript Gradle API +POM_DESCRIPTION=Gradle API for NativeScript plugins: project paths, installed plugins and CLI capabilities, from the facts NativeScript CLI 9.2 and newer write. +POM_INCEPTION_YEAR=2026 +POM_URL=https://github.com/NativeScript/nativescript-cli + +POM_LICENSE_NAME=The Apache Software License, Version 2.0 +POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt +POM_LICENSE_DIST=repo + +POM_SCM_URL=https://github.com/NativeScript/nativescript-cli +POM_SCM_CONNECTION=scm:git:git://github.com/NativeScript/nativescript-cli.git +POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/NativeScript/nativescript-cli.git + +POM_DEVELOPER_ID=nativescript +POM_DEVELOPER_NAME=NativeScript team +POM_DEVELOPER_URL=https://github.com/NativeScript + +mavenCentralPublishing=true +mavenCentralAutomaticPublishing=true +signAllPublications=true diff --git a/gradle-api/gradle/wrapper/gradle-wrapper.jar b/gradle-api/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..1b33c55baabb587c669f562ae36f953de2481846 GIT binary patch literal 43764 zcma&OWmKeVvL#I6?i3D%6z=Zs?ofE*?rw#G$eqJB ziT4y8-Y@s9rkH0Tz>ll(^xkcTl)CY?rS&9VNd66Yc)g^6)JcWaY(5$5gt z8gr3SBXUTN;~cBgz&})qX%#!Fxom2Yau_`&8)+6aSN7YY+pS410rRUU*>J}qL0TnJ zRxt*7QeUqTh8j)Q&iavh<}L+$Jqz))<`IfKussVk%%Ah-Ti?Eo0hQH!rK%K=#EAw0 zwq@@~XNUXRnv8$;zv<6rCRJ6fPD^hfrh;0K?n z=p!u^3xOgWZ%f3+?+>H)9+w^$Tn1e;?UpVMJb!!;f)`6f&4|8mr+g)^@x>_rvnL0< zvD0Hu_N>$(Li7|Jgu0mRh&MV+<}`~Wi*+avM01E)Jtg=)-vViQKax!GeDc!xv$^mL z{#OVBA$U{(Zr8~Xm|cP@odkHC*1R8z6hcLY#N@3E-A8XEvpt066+3t9L_6Zg6j@9Q zj$$%~yO-OS6PUVrM2s)(T4#6=JpI_@Uz+!6=GdyVU?`!F=d;8#ZB@(5g7$A0(`eqY z8_i@3w$0*es5mrSjhW*qzrl!_LQWs4?VfLmo1Sd@Ztt53+etwzAT^8ow_*7Jp`Y|l z*UgSEwvxq+FYO!O*aLf-PinZYne7Ib6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5Qc978+QUd>J%`fyn{*TsiG-dWMiJXNgwBaT zJ=wgYFt+1ACW)XwtNx)Q9tA2LPoB&DkL16P)ERWQlY4%Y`-5aM9mZ{eKPUgI!~J3Z zkMd5A_p&v?V-o-6TUa8BndiX?ooviev(DKw=*bBVOW|=zps9=Yl|-R5@yJe*BPzN}a0mUsLn{4LfjB_oxpv(mwq# zSY*%E{iB)sNvWfzg-B!R!|+x(Q|b@>{-~cFvdDHA{F2sFGA5QGiIWy#3?P2JIpPKg6ncI^)dvqe`_|N=8 '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradle-api/gradlew.bat b/gradle-api/gradlew.bat new file mode 100644 index 0000000000..db3a6ac207 --- /dev/null +++ b/gradle-api/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/gradle-api/samples/sample-plugin/package.json b/gradle-api/samples/sample-plugin/package.json new file mode 100644 index 0000000000..6724fd6bc2 --- /dev/null +++ b/gradle-api/samples/sample-plugin/package.json @@ -0,0 +1,12 @@ +{ + "name": "@nativescript/gradle-api-sample", + "version": "1.0.0", + "private": true, + "description": "Example NativeScript plugin using org.nativescript:gradle-api from its Android Gradle files.", + "license": "Apache-2.0", + "nativescript": { + "platforms": { + "android": "8.4.0" + } + } +} diff --git a/gradle-api/samples/sample-plugin/platforms/android/buildscript.gradle b/gradle-api/samples/sample-plugin/platforms/android/buildscript.gradle new file mode 100644 index 0000000000..d8e999b7f5 --- /dev/null +++ b/gradle-api/samples/sample-plugin/platforms/android/buildscript.gradle @@ -0,0 +1,10 @@ +// Applied to the app's buildscript and, with CLI 9.2+, to this plugin's own aar build, so the +// library is on the classpath before include.gradle runs. When several plugins declare it, Gradle +// uses the highest version. +repositories { + mavenCentral() +} + +dependencies { + classpath "org.nativescript:gradle-api:0.1.0" +} diff --git a/gradle-api/samples/sample-plugin/platforms/android/include.gradle b/gradle-api/samples/sample-plugin/platforms/android/include.gradle new file mode 100644 index 0000000000..2b25d9f4cd --- /dev/null +++ b/gradle-api/samples/sample-plugin/platforms/android/include.gradle @@ -0,0 +1,11 @@ +// The CLI builds this plugin's aar in a separate project that runs only the next block, not the +// rest of this file. CLI 9.2+ loads org.nativescript:gradle-api there and applies it; older CLIs +// don't, so the block stops with a clear message instead of failing on an unknown `nativescript`. +dependencies { + if (project.hasProperty("tempBuild")) { + if (project.extensions.findByName("nativescript") == null) { + throw new GradleException("@nativescript/gradle-api-sample needs NativeScript CLI 9.2 or newer: npm i -D nativescript@latest") + } + compileOnly nativescript.plugin("@nativescript/core").artifacts + } +} diff --git a/gradle-api/schema/nativescript-gradle.schema.json b/gradle-api/schema/nativescript-gradle.schema.json new file mode 100644 index 0000000000..8696acbf0e --- /dev/null +++ b/gradle-api/schema/nativescript-gradle.schema.json @@ -0,0 +1,109 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://nativescript.org/schemas/nativescript-gradle.schema.json", + "title": "NativeScript Gradle facts", + "description": "Written by the NativeScript CLI at prepare time to platforms/android/nativescript-gradle.json and read by org.nativescript:gradle-api. Fields are only ever added: readers must ignore unknown fields, and a field never changes meaning. Every path is relative to the directory containing this file and uses forward slashes.", + "type": "object", + "required": ["schemaVersion", "minReaderSchemaVersion", "dependenciesJson", "project", "plugins"], + "properties": { + "schemaVersion": { + "description": "Bumped only when a field is added. Readers accept any version that minReaderSchemaVersion allows them to, and read the fields they know.", + "type": "integer", + "minimum": 1 + }, + "minReaderSchemaVersion": { + "description": "The lowest schemaVersion a reader must support to read this file; never greater than schemaVersion. A reader that supports only a lower schema version must refuse the file, rather than read it partially.", + "type": "integer", + "minimum": 1 + }, + "cli": { + "type": "object", + "properties": { + "version": { "type": "string" } + } + }, + "runtime": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "version": { "type": "string" } + } + }, + "dependenciesJson": { + "description": "The dependencies.json the CLI wrote next to this file, before this file. A CLI that does not write this file still rewrites dependencies.json but leaves this file behind, so readers report an error, rather than use this file, when dependencies.json is missing or no longer has this hash.", + "type": "object", + "required": ["sha256"], + "properties": { + "sha256": { + "description": "Lowercase hex SHA-256 of the exact bytes of dependencies.json.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + } + }, + "capabilities": { + "description": "Behaviours the CLI that wrote this file guarantees. Lets readers tell 'not set' apart from 'this CLI does not know about it'.", + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true + }, + "project": { + "type": "object", + "required": ["root", "appDir", "appResourcesDir"], + "properties": { + "root": { + "description": "The NativeScript project root (the folder with the app's package.json).", + "$ref": "#/$defs/path" + }, + "appDir": { "$ref": "#/$defs/path" }, + "appResourcesDir": { "$ref": "#/$defs/path" } + } + }, + "plugins": { + "description": "Every npm package with Android native code, in dependency order (a plugin comes after the plugins it depends on).", + "type": "array", + "items": { "$ref": "#/$defs/plugin" } + } + }, + "$defs": { + "path": { + "type": "string", + "pattern": "^[^\\\\]*$" + }, + "plugin": { + "type": "object", + "required": ["name", "packageDir", "nativeDir", "aarName", "aar", "dependencies"], + "properties": { + "name": { + "description": "The npm package name.", + "type": "string" + }, + "packageDir": { + "description": "The installed npm package. Read-only.", + "$ref": "#/$defs/path" + }, + "nativeDir": { + "description": "The directory Gradle reads the plugin's Android files from: the package's platforms/android, or the CLI's copy of it in platforms/android/.ns-plugins when the app sets android.pluginBuildLocation to \"platforms\".", + "$ref": "#/$defs/path" + }, + "aarName": { + "description": "File name, without extension, of the aar the CLI builds from the plugin's sources. Unique among the plugins with sources to build; for a plugin without any, its short name.", + "type": "string" + }, + "aar": { + "description": "Where the CLI puts that aar. The file only exists if the plugin has sources to build.", + "$ref": "#/$defs/path" + }, + "dependencies": { + "description": "Names of the other entries in plugins that this plugin depends on.", + "type": "array", + "items": { "type": "string" } + }, + "options": { + "description": "Per-plugin options for the plugin's own Gradle code. Reserved; always empty for now.", + "type": "object" + } + } + } + } +} diff --git a/gradle-api/settings.gradle.kts b/gradle-api/settings.gradle.kts new file mode 100644 index 0000000000..54c0e01236 --- /dev/null +++ b/gradle-api/settings.gradle.kts @@ -0,0 +1,14 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +dependencyResolutionManagement { + repositories { + mavenCentral() + } +} + +rootProject.name = "gradle-api" diff --git a/gradle-api/src/functionalTest/java/org/nativescript/gradle/AppBuildTest.java b/gradle-api/src/functionalTest/java/org/nativescript/gradle/AppBuildTest.java new file mode 100644 index 0000000000..e72febb1f4 --- /dev/null +++ b/gradle-api/src/functionalTest/java/org/nativescript/gradle/AppBuildTest.java @@ -0,0 +1,190 @@ +package org.nativescript.gradle; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.stream.Stream; +import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * The app build: plugins' buildscript.gradle and include.gradle applied to {@code :app} the way the + * Android runtime's template does, without the Android Gradle Plugin. + */ +class AppBuildTest { + enum Cli { + /** A CLI before 9.2, which writes no facts file. */ + NO_FACTS, + /** CLI 9.2+, which passes the facts file's path. */ + FACTS_PROPERTY, + /** platforms/android opened without the CLI, e.g. in Android Studio. */ + FACTS_FOUND, + /** A CLI before 9.2 prepared the project after a 9.2+ one: facts left behind. */ + STALE_FACTS; + + boolean usesFacts() { + return this == FACTS_PROPERTY || this == FACTS_FOUND; + } + } + + @TempDir + Path tempDir; + + static Stream cases() { + List cases = new ArrayList<>(); + for (String gradleVersion : Fixtures.gradleVersions()) { + for (Cli cli : Cli.values()) { + cases.add(Arguments.of(gradleVersion, cli)); + } + } + return cases.stream(); + } + + @ParameterizedTest(name = "Gradle {0}, {1}") + @MethodSource("cases") + void answersFromTheAppBuild(String gradleVersion, Cli cli) throws Exception { + Path project = tempDir.toRealPath().resolve("project"); + Path platformsAndroid = project.resolve("platforms/android"); + Fixtures.copyTree(fixture().resolve("platforms/android"), platformsAndroid); + Fixtures.copyTree(fixture().resolve("packages"), project.resolve("node_modules")); + // In one mode fixture-plugin-b pins a higher version than the sample, which Gradle must pick + // for the whole classpath. The other modes keep resolving the library as published. + String pluginBLibraryVersion = cli == Cli.FACTS_FOUND ? Fixtures.HIGH_LIBRARY_VERSION : Fixtures.libraryVersion(); + Path pluginB = project.resolve("node_modules/fixture-plugin-b/platforms/android/buildscript.gradle"); + Fixtures.write(pluginB, Fixtures.read(pluginB).replace("@LIBRARY_VERSION@", pluginBLibraryVersion)); + Path core = Fixtures.installCore(project); + Fixtures.installSample(project); + Fixtures.write(project.resolve("package.json"), "{ \"name\": \"fixture-app\" }\n"); + Path dependenciesJson = Fixtures.write(platformsAndroid.resolve("dependencies.json"), String.join("\n", + "[", + " { \"name\": \"@nativescript/core\", \"directory\": \"../../node_modules/@nativescript/core\", \"dependencies\": [] },", + " { \"name\": \"" + Fixtures.SAMPLE_NAME + "\", \"directory\": \"../../node_modules/" + Fixtures.SAMPLE_NAME + "\", \"dependencies\": [\"@nativescript/core\"] },", + " { \"name\": \"fixture-plugin-b\", \"directory\": \"../../node_modules/fixture-plugin-b\", \"dependencies\": [] }", + "]", + "")); + + List arguments = new ArrayList<>(List.of( + "help", "--offline", "--stacktrace", "--warning-mode=fail", + "--init-script", + Fixtures.path(Fixtures.writeInitScript(tempDir, Fixtures.writeHighVersionRepo(tempDir.resolve("high-repo")))))); + Path factsFile = platformsAndroid.resolve("nativescript-gradle.json"); + if (cli != Cli.NO_FACTS) { + // fixture-plugin-b is left out: an installed package with platforms/android that the CLI + // does not list is not a plugin. + Fixtures.write(factsFile, String.join("\n", + "{", + " \"schemaVersion\": 1,", + " \"minReaderSchemaVersion\": 1,", + " \"dependenciesJson\": { \"sha256\": \"" + Fixtures.sha256(dependenciesJson) + "\" },", + " \"capabilities\": [\"fixture.capability\"],", + " \"project\": { \"root\": \"../..\", \"appDir\": \"../../src\", \"appResourcesDir\": \"../../src/App_Resources\" },", + " \"plugins\": [", + " { \"name\": \"@nativescript/core\", \"packageDir\": \"../../node_modules/@nativescript/core\",", + " \"nativeDir\": \"../../node_modules/@nativescript/core/platforms/android\", \"aarName\": \"core\",", + " \"aar\": \"../../node_modules/@nativescript/core/platforms/android/core.aar\", \"dependencies\": [],", + " \"options\": { \"flag\": true } },", + " { \"name\": \"" + Fixtures.SAMPLE_NAME + "\", \"packageDir\": \"../../node_modules/" + Fixtures.SAMPLE_NAME + "\",", + " \"nativeDir\": \".ns-plugins/sample/platforms/android\", \"aarName\": \"sample\",", + " \"aar\": \".ns-plugins/sample/platforms/android/sample.aar\", \"dependencies\": [\"@nativescript/core\"] }", + " ]", + "}", + "")); + if (cli == Cli.FACTS_PROPERTY) { + arguments.add("-Pnativescript.factsFile=" + Fixtures.path(factsFile)); + } + if (cli == Cli.STALE_FACTS) { + Fixtures.write(dependenciesJson, Fixtures.read(dependenciesJson) + "\n"); + } + } + + GradleRunner runner = GradleRunner.create() + .withGradleVersion(gradleVersion) + .withProjectDir(platformsAndroid.toFile()) + .withArguments(arguments) + .forwardOutput(); + + if (!cli.usesFacts()) { + BuildResult result = runner.buildAndFail(); + String error = cli == Cli.NO_FACTS + ? "A plugin of this app uses org.nativescript:gradle-api, which needs the project to be prepared by" + + " NativeScript CLI 9.2 or newer, but there is no facts file at " + Fixtures.path(factsFile) + + ". Update the project's CLI with `npm i -D nativescript@latest`, then run `ns prepare android`." + : "The NativeScript facts file " + Fixtures.path(factsFile) + " does not match " + + Fixtures.path(dependenciesJson) + ": a different NativeScript CLI rewrote dependencies.json" + + " after the facts file was written. Run `ns prepare android` again with the NativeScript CLI" + + " the project uses."; + assertTrue(result.getOutput().lines().anyMatch(line -> line.equals("> " + error)), result.getOutput()); + Map probes = Fixtures.probes(result); + assertEquals("false", probes.get("b.pluginBuild"), "pluginBuild needs no facts"); + assertEquals("null", probes.get("b.self"), "self needs no facts outside a plugin build"); + assertHighestLibraryVersionWins(probes, pluginBLibraryVersion); + return; + } + + BuildResult result = runner.build(); + Map probes = Fixtures.probes(result); + assertHighestLibraryVersionWins(probes, pluginBLibraryVersion); + + Path appDir = project.resolve("src"); + assertEquals("true", probes.get("typed"), "NativeScript.of returns the extension"); + assertEquals("true", probes.get("b.sameExtension"), "include.gradle reaches the extension by its name"); + assertEquals("false", probes.get("b.libraryClassVisible"), "include.gradle cannot see the library's classes"); + assertEquals("false", probes.get("b.pluginBuild")); + assertEquals("null", probes.get("b.self")); + assertEquals(Fixtures.path(project), probes.get("b.projectRoot")); + assertEquals("1", probes.get("apiLevel")); + assertEquals("false", probes.get("pluginBuild")); + assertEquals("null", probes.get("self")); + assertEquals("false", probes.get("buildingSample")); + assertEquals(Fixtures.path(project), probes.get("projectRoot")); + assertEquals(Fixtures.path(appDir), probes.get("appDir")); + assertEquals(Fixtures.path(appDir.resolve("App_Resources")), probes.get("appResourcesDir")); + assertEquals("true", probes.get("has")); + assertEquals(Fixtures.path(core), probes.get("core.packageDir")); + assertEquals(Fixtures.path(core.resolve("platforms/android")), probes.get("core.nativeDir")); + assertEquals("inner.aar,widgets-release.aar", probes.get("core.artifacts")); + assertEquals("[flag:true]", probes.get("core.options")); + assertEquals( + Fixtures.path(platformsAndroid.resolve(".ns-plugins/sample/platforms/android")), + probes.get("sample.nativeDir")); + assertEquals(Fixtures.path(project.resolve("node_modules/js-only")), probes.get("jsOnly")); + assertEquals("null", probes.get("jsOnlyPlugin"), "a package without native code is not a plugin"); + assertEquals("null", probes.get("unlistedPlugin"), "a package the CLI does not list is not a plugin"); + assertEquals("null", probes.get("missingPlugin")); + assertEquals("null", probes.get("missingPackage")); + String error = probes.get("pluginError"); + assertTrue(error.contains("'not-installed'") && error.contains("@nativescript/core, " + Fixtures.SAMPLE_NAME), + "error names the plugin and lists the known ones: " + error); + } + + /** The sample pins the version under test; Gradle keeps the higher of it and fixture-plugin-b's. */ + private static void assertHighestLibraryVersionWins(Map probes, String pluginBLibraryVersion) { + assertEquals( + String.join(",", new TreeSet<>(List.of(Fixtures.libraryVersion(), pluginBLibraryVersion))), + probes.get("libraryRequested")); + if (pluginBLibraryVersion.equals(Fixtures.HIGH_LIBRARY_VERSION)) { + assertEquals(Fixtures.HIGH_LIBRARY_VERSION, probes.get("librarySelected")); + assertEquals( + "gradle-api-" + Fixtures.HIGH_LIBRARY_VERSION + ".jar", + probes.get("b.libraryJar"), + "the extension's class comes from the higher version's jar"); + } else { + assertEquals(Fixtures.libraryVersion(), probes.get("librarySelected")); + } + } + + private static Path fixture() throws URISyntaxException { + return new File(AppBuildTest.class.getResource("/app-fixture").toURI()).toPath(); + } +} diff --git a/gradle-api/src/functionalTest/java/org/nativescript/gradle/ExtractedIncludeGradleTest.java b/gradle-api/src/functionalTest/java/org/nativescript/gradle/ExtractedIncludeGradleTest.java new file mode 100644 index 0000000000..62a882dfeb --- /dev/null +++ b/gradle-api/src/functionalTest/java/org/nativescript/gradle/ExtractedIncludeGradleTest.java @@ -0,0 +1,58 @@ +package org.nativescript.gradle; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * The golden file the plugin build test appends must be what the CLI extracts from the sample's + * include.gradle; the CLI's own tests check it produces the same file. + */ +class ExtractedIncludeGradleTest { + @Test + void goldenFileMatchesTheSample() throws Exception { + String includeGradle = Fixtures.read(Fixtures.samplesDir().resolve("sample-plugin/platforms/android/include.gradle")); + String golden = Fixtures.read(PluginBuildTest.extractedIncludeGradle()); + + assertEquals(golden, String.join("\n", extract(includeGradle))); + } + + // A port of getIncludeGradleCompileDependenciesScope and getScope in + // lib/services/android-plugin-build-service.ts. + private static List extract(String content) { + List result = new ArrayList<>(); + if (content.indexOf("dependencies") == -1) { + return result; + } + if (content.indexOf("repositories") >= 0) { + result.add(scope("repositories", content)); + } + result.add(scope("dependencies", content)); + return result; + } + + private static String scope(String name, String content) { + StringBuilder result = new StringBuilder(); + boolean foundFirstBracket = false; + int openBrackets = 0; + for (int i = content.indexOf(name); i != -1 && i < content.length(); i++) { + char c = content.charAt(i); + if (c == '{') { + if (openBrackets == 0) { + foundFirstBracket = true; + } + openBrackets++; + } + if (c == '}') { + openBrackets--; + } + result.append(c); + if (openBrackets == 0 && foundFirstBracket) { + break; + } + } + return result.toString(); + } +} diff --git a/gradle-api/src/functionalTest/java/org/nativescript/gradle/Fixtures.java b/gradle-api/src/functionalTest/java/org/nativescript/gradle/Fixtures.java new file mode 100644 index 0000000000..f1d55b69f8 --- /dev/null +++ b/gradle-api/src/functionalTest/java/org/nativescript/gradle/Fixtures.java @@ -0,0 +1,263 @@ +package org.nativescript.gradle; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; +import org.gradle.testkit.runner.BuildResult; + +final class Fixtures { + static final String SAMPLE_NAME = "@nativescript/gradle-api-sample"; + + private Fixtures() {} + + static String requiredProperty(String name) { + String value = System.getProperty(name); + if (value == null || value.isEmpty()) { + throw new IllegalStateException("System property " + name + " is not set; run through the functionalTest task."); + } + return value; + } + + static Path testRepo() { + return Path.of(requiredProperty("nativescript.testRepo")); + } + + static String libraryVersion() { + return requiredProperty("nativescript.libraryVersion"); + } + + static Path samplesDir() { + return Path.of(requiredProperty("nativescript.samplesDir")); + } + + static Path vendorGradlePluginDir() { + return Path.of(requiredProperty("nativescript.vendorGradlePluginDir")); + } + + static List gradleVersions() { + return Arrays.asList(requiredProperty("nativescript.gradleVersions").split(",")); + } + + static Path libraryJar() { + return Path.of(requiredProperty("nativescript.libraryJar")); + } + + /** A version of the library above any real one, published by {@link #writeHighVersionRepo(Path)}. */ + static final String HIGH_LIBRARY_VERSION = "99.0.0"; + + /** Writes a Maven repository holding the library under test as {@link #HIGH_LIBRARY_VERSION}. */ + static Path writeHighVersionRepo(Path dir) { + Path versionDir = dir.resolve("org/nativescript/gradle-api").resolve(HIGH_LIBRARY_VERSION); + String baseName = "gradle-api-" + HIGH_LIBRARY_VERSION; + try { + Files.createDirectories(versionDir); + Files.copy(libraryJar(), versionDir.resolve(baseName + ".jar"), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + write(versionDir.resolve(baseName + ".pom"), String.join("\n", + "", + " 4.0.0", + " org.nativescript", + " gradle-api", + " " + HIGH_LIBRARY_VERSION + "", + "", + "")); + return dir; + } + + /** Makes every buildscript resolve the library from the test repository, then {@code moreRepos}, first. */ + static Path writeInitScript(Path dir, Path... moreRepos) { + StringBuilder repos = new StringBuilder(); + for (Path repo : Stream.concat(Stream.of(testRepo()), Stream.of(moreRepos)).collect(Collectors.toList())) { + repos.append(" maven { url = '").append(repo.toUri()).append("' }\n"); + } + return write(dir.resolve("test-repo.init.gradle"), String.join("\n", + "allprojects {", + " buildscript {", + " repositories {", + repos + " }", + " }", + "}", + "")); + } + + /** Copies the sample plugin into node_modules, pointing its buildscript at the version under test. */ + static Path installSample(Path projectDir) { + Path target = projectDir.resolve("node_modules").resolve(SAMPLE_NAME); + copyTree(samplesDir().resolve("sample-plugin"), target); + Path buildscript = target.resolve("platforms/android/buildscript.gradle"); + String text = read(buildscript); + String replaced = text.replaceAll("org\\.nativescript:gradle-api:[^\"']+", "org.nativescript:gradle-api:" + libraryVersion()); + if (replaced.equals(text) && !text.contains(libraryVersion())) { + throw new IllegalStateException("No org.nativescript:gradle-api classpath dependency in " + buildscript); + } + write(buildscript, replaced); + return target; + } + + /** + * A stand-in for @nativescript/core: a package whose native directory holds Android libraries, + * one of them below the top level. {@code widgets-release.aar} contains {@link #CORE_CLASS}. + */ + static Path installCore(Path projectDir) { + Path core = projectDir.resolve("node_modules/@nativescript/core"); + write(core.resolve("package.json"), "{ \"name\": \"@nativescript/core\", \"version\": \"9.0.0\" }\n"); + Path classes = projectDir.resolve("core-classes"); + writeAar(core.resolve("platforms/android/widgets-release.aar"), compile(classes, CORE_CLASS)); + writeAar(core.resolve("platforms/android/nested/inner.aar"), compile(classes, "org.nativescript.widgets.nested.Inner")); + return core; + } + + static final String CORE_CLASS = "org.nativescript.widgets.Probe"; + + private static Map compile(Path workDir, String className) { + JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); + if (javac == null) { + throw new IllegalStateException("The functional tests need a JDK, not a JRE"); + } + int dot = className.lastIndexOf('.'); + String packageName = className.substring(0, dot); + String simpleName = className.substring(dot + 1); + Path out = workDir.resolve(simpleName + "-classes"); + Path source = write(workDir.resolve(simpleName + "-src").resolve(className.replace('.', '/') + ".java"), + "package " + packageName + ";\npublic final class " + simpleName + " {}\n"); + try { + Files.createDirectories(out); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + int exit = javac.run(null, null, null, "--release", "11", "-d", path(out), path(source)); + if (exit != 0) { + throw new IllegalStateException("javac failed for " + source); + } + String entry = className.replace('.', '/') + ".class"; + return Map.of(entry, readBytes(out.resolve(entry))); + } + + private static void writeAar(Path aar, Map classes) { + ByteArrayOutputStream classesJar = new ByteArrayOutputStream(); + try (ZipOutputStream jar = new ZipOutputStream(classesJar)) { + for (Map.Entry entry : classes.entrySet()) { + putEntry(jar, entry.getKey(), entry.getValue()); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + String packageName = classes.keySet().iterator().next().replaceFirst("/[^/]+$", "").replace('/', '.'); + try { + Files.createDirectories(aar.getParent()); + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(aar))) { + putEntry(zip, "AndroidManifest.xml", ("\n").getBytes(StandardCharsets.UTF_8)); + putEntry(zip, "classes.jar", classesJar.toByteArray()); + putEntry(zip, "R.txt", new byte[0]); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void putEntry(ZipOutputStream zip, String name, byte[] content) throws IOException { + zip.putNextEntry(new ZipEntry(name)); + zip.write(content); + zip.closeEntry(); + } + + private static byte[] readBytes(Path file) { + try { + return Files.readAllBytes(file); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + static Path write(Path file, String content) { + try { + Files.createDirectories(file.getParent()); + Files.write(file, content.getBytes(StandardCharsets.UTF_8)); + return file; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + static String read(Path file) { + try { + return new String(Files.readAllBytes(file), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + static void copyTree(Path source, Path target) { + try (Stream paths = Files.walk(source)) { + for (Path path : paths.collect(Collectors.toList())) { + Path destination = target.resolve(source.relativize(path).toString()); + if (Files.isDirectory(path)) { + Files.createDirectories(destination); + } else { + Files.createDirectories(destination.getParent()); + Files.copy(path, destination, StandardCopyOption.REPLACE_EXISTING); + } + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** Lines printed as {@code NS|key|value}, by key. A key printed twice must print the same value. */ + static Map probes(BuildResult result) { + Map values = new LinkedHashMap<>(); + for (String line : result.getOutput().split("\\R")) { + if (!line.startsWith("NS|")) { + continue; + } + String[] parts = line.split("\\|", 3); + String previous = values.put(parts[1], parts.length > 2 ? parts[2] : ""); + if (previous != null && !previous.equals(values.get(parts[1]))) { + throw new AssertionError("Probe " + parts[1] + " printed both '" + previous + "' and '" + values.get(parts[1]) + "'"); + } + } + return values; + } + + static String sha256(Path file) { + try { + StringBuilder hex = new StringBuilder(); + for (byte b : MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file))) { + hex.append(String.format("%02x", b)); + } + return hex.toString(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + static String path(Path path) { + return path.toAbsolutePath().normalize().toFile().getPath(); + } + + static String path(File file) { + return path(file.toPath()); + } +} diff --git a/gradle-api/src/functionalTest/java/org/nativescript/gradle/PluginBuildTest.java b/gradle-api/src/functionalTest/java/org/nativescript/gradle/PluginBuildTest.java new file mode 100644 index 0000000000..27de9a1111 --- /dev/null +++ b/gradle-api/src/functionalTest/java/org/nativescript/gradle/PluginBuildTest.java @@ -0,0 +1,215 @@ +package org.nativescript.gradle; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.GradleRunner; +import org.gradle.testkit.runner.TaskOutcome; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * The CLI's build of a plugin's aar: a CLI's template with the extracted block of the sample's + * include.gradle appended, as the CLI does, compiling a class that uses one from core's aar. + */ +class PluginBuildTest { + // The Android Gradle Plugin version decides which Gradle versions can run this build. + private static final String ANDROID_GRADLE_PLUGIN = "8.12.1"; + private static final String GRADLE = "8.14.3"; + private static final String COMPILE_TASK = ":compileReleaseJavaWithJavac"; + private static final String SAMPLE_AAR_NAME = "gradle_api_sample"; + + enum Template { + /** + * CLI 9.1 and older: a copy of the template they ship, in cli-9.1-plugin-template. It must + * never change, so that the sample keeps being checked against what those CLIs run. + */ + CLI_9_1, + /** The current CLI's template, from vendor/gradle-plugin. */ + CURRENT; + + Path dir() throws URISyntaxException { + return this == CURRENT + ? Fixtures.vendorGradlePluginDir() + : new File(PluginBuildTest.class.getResource("/cli-9.1-plugin-template").toURI()).toPath(); + } + } + + /** {@code android.pluginBuildLocation}: where the build reads plugins' native files from. */ + enum Layout { + NODE_MODULES, + /** The CLI's copies in platforms/android/.ns-plugins, which dependencies.json points at. */ + PLATFORMS + } + + // Evaluated inside a dependencies block, as the extracted block is. + private static final String PROBE = String.join("\n", + "", + "dependencies {", + " println \"NS|pluginBuild|${nativescript.pluginBuild}\"", + " println \"NS|self|${nativescript.self?.name}\"", + " println \"NS|buildingSample|${nativescript.isBuildingPlugin('" + Fixtures.SAMPLE_NAME + "')}\"", + " println \"NS|projectRoot|${nativescript.projectRoot}\"", + " println \"NS|appDir|${nativescript.appDir}\"", + " println \"NS|appResourcesDir|${nativescript.appResourcesDir}\"", + " println \"NS|corePackage|${nativescript.findPackage('@nativescript/core')}\"", + "}", + "println \"NS|compileOnly|\" + configurations.compileOnly.dependencies.withType(FileCollectionDependency)" + + ".collectMany { it.files.files }.collect { it.path }.sort().join(',')", + ""); + + @TempDir + Path tempDir; + + @BeforeAll + static void requireAndroidSdk() { + String androidHome = System.getenv("ANDROID_HOME"); + assumeTrue(androidHome != null && new File(androidHome).isDirectory(), "ANDROID_HOME is not set"); + } + + static Stream cases() { + return Stream.of( + Arguments.of(Template.CLI_9_1, Layout.NODE_MODULES), + Arguments.of(Template.CURRENT, Layout.NODE_MODULES), + Arguments.of(Template.CURRENT, Layout.PLATFORMS)); + } + + @ParameterizedTest(name = "{0} template, plugins in {1}") + @MethodSource("cases") + void compilesThePluginAgainstCore(Template template, Layout layout) throws Exception { + Path project = tempDir.toRealPath().resolve("project"); + Path platformsAndroid = project.resolve("platforms/android"); + Path core = Fixtures.installCore(project); + Path sample = Fixtures.installSample(project); + Fixtures.write(project.resolve("package.json"), "{ \"name\": \"fixture-app\" }\n"); + + // dependencies.json directories, relative to platforms/android. + String coreDir = "../../node_modules/@nativescript/core"; + String sampleDir = "../../node_modules/" + Fixtures.SAMPLE_NAME; + if (layout == Layout.PLATFORMS) { + // Moved rather than copied, so that the build only finds core's libraries through the facts. + coreDir = ".ns-plugins/core"; + sampleDir = ".ns-plugins/" + SAMPLE_AAR_NAME; + mirror(core, platformsAndroid.resolve(coreDir)); + mirror(sample, platformsAndroid.resolve(sampleDir)); + } + Path coreNativeDir = platformsAndroid.resolve(coreDir).resolve("platforms/android").normalize(); + // Core is a peer of the sample, as of most plugins: the template adds no dependency on it, + // so the compile relies on the include.gradle block. + Path dependenciesJson = Fixtures.write(platformsAndroid.resolve("dependencies.json"), String.join("\n", + "[", + " { \"name\": \"@nativescript/core\", \"directory\": \"" + coreDir + "\", \"dependencies\": [] },", + " { \"name\": \"" + Fixtures.SAMPLE_NAME + "\", \"directory\": \"" + sampleDir + "\", \"dependencies\": [] }", + "]", + "")); + + Path pluginDir = project.resolve("platforms/tempPlugin/" + SAMPLE_AAR_NAME); + for (String name : List.of("build.gradle", "settings.gradle", "gradle.properties")) { + String text = Fixtures.read(template.dir().resolve(name)) + .replace("{{pluginName}}", Fixtures.SAMPLE_NAME) + .replace("{{pluginNamespace}}", "org.nativescript.gradle_api_sample") + .replace("{{runtimeAndroidPluginVersion}}", ANDROID_GRADLE_PLUGIN); + assertFalse(text.contains("{{"), "unknown placeholder left in " + name); + Fixtures.write(pluginDir.resolve(name), text); + } + Path buildGradle = pluginDir.resolve("build.gradle"); + Fixtures.write(buildGradle, Fixtures.read(buildGradle) + "\n" + Fixtures.read(extractedIncludeGradle()) + "\n" + PROBE); + Fixtures.write(pluginDir.resolve("src/main/AndroidManifest.xml"), + "\n"); + Fixtures.write(pluginDir.resolve("src/main/java/org/nativescript/gradle_api_sample/UsesCore.java"), String.join("\n", + "package org.nativescript.gradle_api_sample;", + "", + "public final class UsesCore {", + " public static Class coreClass() { return " + Fixtures.CORE_CLASS + ".class; }", + "}", + "")); + + List arguments = new ArrayList<>(List.of( + COMPILE_TASK, "--stacktrace", + "--init-script", Fixtures.path(Fixtures.writeInitScript(tempDir)), + "-PtempBuild=true", + "-PappPath=" + Fixtures.path(project.resolve("app")), + "-PappResourcesPath=" + Fixtures.path(project.resolve("app/App_Resources")))); + if (template == Template.CURRENT) { + Path factsFile = Fixtures.write(platformsAndroid.resolve("nativescript-gradle.json"), String.join("\n", + "{", + " \"schemaVersion\": 1,", + " \"minReaderSchemaVersion\": 1,", + " \"dependenciesJson\": { \"sha256\": \"" + Fixtures.sha256(dependenciesJson) + "\" },", + " \"capabilities\": [],", + " \"project\": { \"root\": \"../..\", \"appDir\": \"../../src\", \"appResourcesDir\": \"../../src/App_Resources\" },", + " \"plugins\": [", + " { \"name\": \"@nativescript/core\", \"packageDir\": \"../../node_modules/@nativescript/core\",", + " \"nativeDir\": \"" + coreDir + "/platforms/android\", \"aarName\": \"core\",", + " \"aar\": \"" + coreDir + "/platforms/android/core.aar\", \"dependencies\": [] },", + " { \"name\": \"" + Fixtures.SAMPLE_NAME + "\", \"packageDir\": \"../../node_modules/" + Fixtures.SAMPLE_NAME + "\",", + " \"nativeDir\": \"" + sampleDir + "/platforms/android\", \"aarName\": \"" + SAMPLE_AAR_NAME + "\",", + " \"aar\": \"" + sampleDir + "/platforms/android/" + SAMPLE_AAR_NAME + ".aar\", \"dependencies\": [] }", + " ]", + "}", + "")); + arguments.add("-Pnativescript.factsFile=" + Fixtures.path(factsFile)); + } + + // Outside host-project embedding the CLI sets neither variable, so the template's defaults apply. + Map environment = new HashMap<>(System.getenv()); + environment.remove("USER_PROJECT_ROOT"); + environment.remove("USER_PROJECT_PLATFORMS_ANDROID"); + GradleRunner runner = GradleRunner.create() + .withGradleVersion(GRADLE) + .withProjectDir(pluginDir.toFile()) + .withArguments(arguments) + .withEnvironment(environment) + .forwardOutput(); + + if (template == Template.CLI_9_1) { + BuildResult result = runner.buildAndFail(); + String error = "> " + Fixtures.SAMPLE_NAME + " needs NativeScript CLI 9.2 or newer: npm i -D nativescript@latest"; + assertTrue(result.getOutput().lines().anyMatch(error::equals), result.getOutput()); + return; + } + + BuildResult result = runner.build(); + Map probes = Fixtures.probes(result); + + assertEquals(TaskOutcome.SUCCESS, result.task(COMPILE_TASK).getOutcome()); + assertEquals( + Fixtures.path(coreNativeDir.resolve("nested/inner.aar")) + "," + + Fixtures.path(coreNativeDir.resolve("widgets-release.aar")), + probes.get("compileOnly")); + assertEquals("true", probes.get("pluginBuild")); + assertEquals(Fixtures.SAMPLE_NAME, probes.get("self")); + assertEquals("true", probes.get("buildingSample")); + assertEquals(Fixtures.path(project), probes.get("projectRoot")); + assertEquals(Fixtures.path(project.resolve("src")), probes.get("appDir")); + assertEquals(Fixtures.path(project.resolve("src/App_Resources")), probes.get("appResourcesDir")); + assertEquals(Fixtures.path(core), probes.get("corePackage")); + } + + /** What the CLI puts in a plugin's copy in .ns-plugins: its package.json and platforms/android. */ + private static void mirror(Path packageDir, Path mirrorDir) throws IOException { + Files.createDirectories(mirrorDir.resolve("platforms")); + Files.move(packageDir.resolve("platforms/android"), mirrorDir.resolve("platforms/android")); + Files.copy(packageDir.resolve("package.json"), mirrorDir.resolve("package.json")); + } + + static Path extractedIncludeGradle() throws URISyntaxException { + return new File(PluginBuildTest.class.getResource("/extracted/sample-plugin-include.gradle").toURI()).toPath(); + } +} diff --git a/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/package.json b/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/package.json new file mode 100644 index 0000000000..66669d27af --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/package.json @@ -0,0 +1 @@ +{ "name": "fixture-plugin-b", "version": "1.0.0" } diff --git a/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/buildscript.gradle b/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/buildscript.gradle new file mode 100644 index 0000000000..a7a528e6f5 --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/buildscript.gradle @@ -0,0 +1,3 @@ +dependencies { + classpath "org.nativescript:gradle-api:@LIBRARY_VERSION@" +} diff --git a/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/include.gradle b/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/include.gradle new file mode 100644 index 0000000000..a5f732c5d5 --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/packages/fixture-plugin-b/platforms/android/include.gradle @@ -0,0 +1,22 @@ +// A plugin that uses the library in the app build, so it applies it; the sample plugin uses it +// only in its own aar build. +apply plugin: "org.nativescript.api" + +def nsFromB = project.extensions.getByName("nativescript") +println "NS|b.sameExtension|${nativescript.is(nsFromB)}" +// Printed before anything that needs the facts file, so that builds without one show it too. +println "NS|b.pluginBuild|${nsFromB.pluginBuild}" +println "NS|b.self|${nsFromB.self}" +println "NS|b.libraryJar|${new File(nsFromB.getClass().protectionDomain.codeSource.location.toURI()).name}" +println "NS|b.projectRoot|${nsFromB.projectRoot}" + +// Scripts applied with `apply from` get their own class loader, which does not see the +// classes buildscript.gradle put on the project's classpath, even though the plugin id resolves. +def libraryClassVisible +try { + Class.forName("org.nativescript.gradle.NativeScript") + libraryClassVisible = true +} catch (ClassNotFoundException ignored) { + libraryClassVisible = false +} +println "NS|b.libraryClassVisible|$libraryClassVisible" diff --git a/gradle-api/src/functionalTest/resources/app-fixture/packages/js-only/package.json b/gradle-api/src/functionalTest/resources/app-fixture/packages/js-only/package.json new file mode 100644 index 0000000000..49e0840168 --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/packages/js-only/package.json @@ -0,0 +1 @@ +{ "name": "js-only", "version": "1.0.0" } diff --git a/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/app/build.gradle b/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/app/build.gradle new file mode 100644 index 0000000000..658b661162 --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/app/build.gradle @@ -0,0 +1,75 @@ +// Mirrors how the @nativescript/android app template's app/build.gradle applies plugins' Gradle +// files: buildscript.gradle to this project's buildscript, include.gradle from inside `android {}`. +// The template reads the root project's properties implicitly, which Gradle 9 deprecates; reading +// them through rootProject keeps the build free of deprecations so the tests can fail on any. +buildscript { + def applyBuildScriptConfigurations = { -> + rootProject.nativescriptDependencies.each { dep -> + def pathToPluginBuildScriptGradle = "$rootDir/${dep.directory}/${rootProject.PLATFORMS_ANDROID}/buildscript.gradle" + def pluginBuildScriptGradle = file(pathToPluginBuildScriptGradle) + if (pluginBuildScriptGradle.exists()) { + apply from: pathToPluginBuildScriptGradle, to: buildscript + } + } + } + applyBuildScriptConfigurations() +} + +def isLibrary = { it.group == "org.nativescript" && it.module == "gradle-api" } +def classpathResult = buildscript.configurations.classpath.incoming.resolutionResult +println "NS|libraryRequested|" + classpathResult.allDependencies.collect { it.requested } + .findAll { it instanceof org.gradle.api.artifacts.component.ModuleComponentSelector && isLibrary(it) } + .collect { it.version }.unique().sort().join(',') +println "NS|librarySelected|" + classpathResult.allComponents.collect { it.id } + .findAll { it instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier && isLibrary(it) } + .collect { it.version }.join(',') + +// Stands in for the Android Gradle Plugin's extension, so include.gradle runs with the same +// closure delegation as in a real app build. +class FakeAndroidExtension { + String namespace +} + +extensions.create("android", FakeAndroidExtension) + +def applyPluginGradleConfigurations = { -> + rootProject.nativescriptDependencies.each { dep -> + def includeGradlePath = "$rootDir/${dep.directory}/${rootProject.PLATFORMS_ANDROID}/include.gradle" + if (file(includeGradlePath).exists()) { + apply from: includeGradlePath + } + } +} + +android { + namespace = "org.nativescript.fixture" + applyPluginGradleConfigurations() +} + +def ns = extensions.getByName("nativescript") +println "NS|typed|${org.nativescript.gradle.NativeScript.of(project).is(ns)}" +println "NS|apiLevel|${ns.apiLevel}" +println "NS|pluginBuild|${ns.pluginBuild}" +println "NS|self|${ns.self}" +println "NS|buildingSample|${ns.isBuildingPlugin('@nativescript/gradle-api-sample')}" +println "NS|projectRoot|${ns.projectRoot}" +println "NS|appDir|${ns.appDir}" +println "NS|appResourcesDir|${ns.appResourcesDir}" +println "NS|has|${ns.has('fixture.capability')}" +def core = ns.plugin("@nativescript/core") +println "NS|core.packageDir|${core.packageDir}" +println "NS|core.nativeDir|${core.nativeDir}" +println "NS|core.artifacts|${core.artifacts.files.collect { it.name }.sort().join(',')}" +println "NS|core.options|${core.options}" +println "NS|sample.nativeDir|${ns.plugin('@nativescript/gradle-api-sample').nativeDir}" +println "NS|jsOnly|${ns.findPackage('js-only')}" +println "NS|jsOnlyPlugin|${ns.findPlugin('js-only')}" +println "NS|unlistedPlugin|${ns.findPlugin('fixture-plugin-b')}" +println "NS|missingPlugin|${ns.findPlugin('not-installed')}" +println "NS|missingPackage|${ns.findPackage('not-installed')}" +try { + ns.plugin("not-installed") + println "NS|pluginError|none" +} catch (GradleException e) { + println "NS|pluginError|${e.message}" +} diff --git a/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/build.gradle b/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/build.gradle new file mode 100644 index 0000000000..45257cc3ea --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/build.gradle @@ -0,0 +1,13 @@ +// Mirrors the parts of the @nativescript/android app template's root build.gradle that its +// app/build.gradle uses to apply plugins' Gradle files. +import groovy.json.JsonSlurper + +buildscript { + def initialize = { -> + def dependenciesJson = file("$rootDir/dependencies.json") + project.ext.nativescriptDependencies = new JsonSlurper().parseText(dependenciesJson.text) + project.ext.PLATFORMS_ANDROID = "platforms/android" + } + + initialize() +} diff --git a/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/settings.gradle b/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/settings.gradle new file mode 100644 index 0000000000..0c6d0a2de5 --- /dev/null +++ b/gradle-api/src/functionalTest/resources/app-fixture/platforms/android/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = "fixture-app" +include ":app" diff --git a/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/build.gradle b/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/build.gradle new file mode 100644 index 0000000000..ee6de65efd --- /dev/null +++ b/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/build.gradle @@ -0,0 +1,249 @@ +import groovy.json.JsonSlurper +import org.gradle.internal.logging.text.StyledTextOutputFactory +import static org.gradle.internal.logging.text.StyledTextOutput.Style +import java.nio.file.Paths + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-parcelize' + +buildscript { + // project.ext.USER_PROJECT_ROOT = "$rootDir/../../.." + project.ext.PLATFORMS_ANDROID = "platforms/android" + project.ext.PLUGIN_NAME = "{{pluginName}}" + + def USER_PROJECT_ROOT_FROM_ENV = System.getenv('USER_PROJECT_ROOT'); + if (USER_PROJECT_ROOT_FROM_ENV != null && !USER_PROJECT_ROOT_FROM_ENV.equals("")) { + project.ext.USER_PROJECT_ROOT = USER_PROJECT_ROOT_FROM_ENV; + } else { + project.ext.USER_PROJECT_ROOT = "$rootDir/../../../" + } + + def USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV = System.getenv('USER_PROJECT_PLATFORMS_ANDROID'); + if (USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV != null && !USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV.equals("")) { + project.ext.USER_PROJECT_PLATFORMS_ANDROID = USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV; + } else { + project.ext.USER_PROJECT_PLATFORMS_ANDROID = project.ext.USER_PROJECT_ROOT + PLATFORMS_ANDROID + } + + + def getDepPlatformDir = { dep -> + file("${project.ext.USER_PROJECT_PLATFORMS_ANDROID}/${dep.directory}/$PLATFORMS_ANDROID") + } + def computeKotlinVersion = { -> project.hasProperty("kotlinVersion") ? kotlinVersion : "2.2.20" } + def kotlinVersion = computeKotlinVersion() + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:{{runtimeAndroidPluginVersion}}' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } + + // Set up styled logger + project.ext.getDepPlatformDir = getDepPlatformDir + project.ext.outLogger = services.get(StyledTextOutputFactory).create("colouredOutputLogger") + + // the build script will not work with previous versions of the CLI (3.1 or earlier) + def dependenciesJson = file("${project.ext.USER_PROJECT_PLATFORMS_ANDROID}/dependencies.json") + def appDependencies = new JsonSlurper().parseText(dependenciesJson.text) + def pluginData = appDependencies.find { it.name == project.ext.PLUGIN_NAME } + project.ext.nativescriptDependencies = appDependencies.findAll{pluginData.dependencies.contains(it.name)} + project.ext.getAppPath = { -> + def relativePathToApp = "app" + def nsConfigFile = file("$USER_PROJECT_ROOT/nsconfig.json") + def nsConfig + + if (nsConfigFile.exists()) { + nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8")) + } + + if (project.hasProperty("appPath")) { + // when appPath is passed through -PappPath=/path/to/app + // the path could be relative or absolute - either case will work + relativePathToApp = appPath + } else if (nsConfig != null && nsConfig.appPath != null) { + relativePathToApp = nsConfig.appPath + } + + project.ext.appPath = Paths.get(USER_PROJECT_ROOT).resolve(relativePathToApp).toAbsolutePath() + + return project.ext.appPath + } + + project.ext.getAppResourcesPath = { -> + def relativePathToAppResources + def absolutePathToAppResources + def nsConfigFile = file("$USER_PROJECT_ROOT/nsconfig.json") + def nsConfig + + if (nsConfigFile.exists()) { + nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8")) + } + + if (project.hasProperty("appResourcesPath")) { + // when appResourcesPath is passed through -PappResourcesPath=/path/to/App_Resources + // the path could be relative or absolute - either case will work + relativePathToAppResources = appResourcesPath + absolutePathToAppResources = Paths.get(USER_PROJECT_ROOT).resolve(relativePathToAppResources).toAbsolutePath() + } else if (nsConfig != null && nsConfig.appResourcesPath != null) { + relativePathToAppResources = nsConfig.appResourcesPath + absolutePathToAppResources = Paths.get(USER_PROJECT_ROOT).resolve(relativePathToAppResources).toAbsolutePath() + } else { + absolutePathToAppResources = "${getAppPath()}/App_Resources" + } + + project.ext.appResourcesPath = absolutePathToAppResources + + return absolutePathToAppResources + } + + def applyBuildScriptConfigurations = { -> + def absolutePathToAppResources = getAppResourcesPath() + def pathToBuildScriptGradle = "$absolutePathToAppResources/Android/buildscript.gradle" + def buildScriptGradle = file(pathToBuildScriptGradle) + if (buildScriptGradle.exists()) { + outLogger.withStyle(Style.SuccessHeader).println "\t ~ applying user-defined buildscript from ${buildScriptGradle}" + apply from: pathToBuildScriptGradle, to: buildscript + } + + nativescriptDependencies.each { dep -> + def pathToPluginBuildScriptGradle = "${getDepPlatformDir(dep)}/buildscript.gradle" + def pluginBuildScriptGradle = file(pathToPluginBuildScriptGradle) + if (pluginBuildScriptGradle.exists()) { + outLogger.withStyle(Style.SuccessHeader).println "\t + applying user-defined buildscript from dependency ${pluginBuildScriptGradle}" + apply from: pathToPluginBuildScriptGradle, to: buildscript + } + } + + def pathToPluginBuildScriptGradle = "$rootDir/buildscript.gradle" + def pluginBuildScriptGradle = file(pathToPluginBuildScriptGradle) + if (pluginBuildScriptGradle.exists()) { + outLogger.withStyle(Style.SuccessHeader).println "\t ~ applying user-defined buildscript from dependency ${pluginBuildScriptGradle}" + apply from: pathToPluginBuildScriptGradle, to: buildscript + } + } + applyBuildScriptConfigurations() + +} + +def pluginDependencies + +allprojects { + repositories { + // used for local *.AAR files + pluginDependencies = nativescriptDependencies.collect { + getDepPlatformDir(it) + } + + // some plugins may have their android dependencies in a /libs subdirectory + pluginDependencies.addAll(nativescriptDependencies.collect { + "${getDepPlatformDir(it)}/libs" + }) + mavenLocal() + mavenCentral() + maven { + url 'https://maven.google.com/' + name 'Google' + } + if (pluginDependencies.size() > 0) { + flatDir { + dirs pluginDependencies + } + } + } +} + + +def computeCompileSdkVersion = { -> project.hasProperty("compileSdk") ? compileSdk : 35 } +def computeTargetSdkVersion = { -> project.hasProperty("targetSdk") ? targetSdk : 35 as int } +def computeBuildToolsVersion = { -> + project.hasProperty("buildToolsVersion") ? buildToolsVersion : "35.0.1" +} + +android { + namespace "{{pluginNamespace}}" + + kotlinOptions { + jvmTarget = '17' + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + + if (project.hasProperty("ndkVersion")) { + ndkVersion project.ndkVersion + } + + def applyPluginGradleConfigurations = { -> + nativescriptDependencies.each { dep -> + def includeGradlePath = "${getDepPlatformDir(dep)}/include.gradle" + if (file(includeGradlePath).exists()) { + apply from: includeGradlePath + } + } + } + applyBeforePluginGradleConfiguration() + applyPluginGradleConfigurations() + + compileSdkVersion computeCompileSdkVersion() + buildToolsVersion computeBuildToolsVersion() + + defaultConfig { + targetSdkVersion computeTargetSdkVersion() + versionCode 1 + versionName "1.0" + } +} + + +def applyBeforePluginGradleConfiguration() { + def appResourcesPath = getAppResourcesPath() + def pathToBeforePluginGradle = "$appResourcesPath/Android/before-plugins.gradle" + def beforePluginGradle = file(pathToBeforePluginGradle) + if (beforePluginGradle.exists()) { + outLogger.withStyle(Style.SuccessHeader).println "\t ~ applying user-defined configuration from ${beforePluginGradle}" + apply from: pathToBeforePluginGradle + } +} + +task addDependenciesFromNativeScriptPlugins { + nativescriptDependencies.each { dep -> + def aarFiles = fileTree(dir: getDepPlatformDir(dep), include: ["**/*.aar"]) + aarFiles.each { aarFile -> + def length = aarFile.name.length() - 4 + def fileName = aarFile.name[0.. + def jarFileAbsolutePath = jarFile.getAbsolutePath() + outLogger.withStyle(Style.SuccessHeader).println "\t + adding jar plugin dependency: $jarFileAbsolutePath" + pluginsJarLibraries.add(jarFile.getAbsolutePath()) + } + + project.dependencies.add("implementation", jarFiles) + } +} + +tasks.whenTaskAdded({ DefaultTask currentTask -> + if (currentTask.name == 'bundleRelease' || currentTask.name == 'bundleDebug') { + def generateBuildConfig = project.hasProperty("generateBuildConfig") ? project.generateBuildConfig : false + def generateR = project.hasProperty("generateR") ? project.generateR : false + if (!generateBuildConfig) { + currentTask.exclude '**/BuildConfig.class' + } + if (!generateR) { + currentTask.exclude '**/R.class', '**/R$*.class' + } + } +}) diff --git a/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/gradle.properties b/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/gradle.properties new file mode 100644 index 0000000000..84a8b08c9c --- /dev/null +++ b/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +#org.gradle.parallel=true + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx16384M + +android.enableJetifier=true +android.useAndroidX=true +android.nonTransitiveRClass=true +android.enableSeparateRClassCompilation=true \ No newline at end of file diff --git a/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/settings.gradle b/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/settings.gradle new file mode 100644 index 0000000000..d8e66382d3 --- /dev/null +++ b/gradle-api/src/functionalTest/resources/cli-9.1-plugin-template/settings.gradle @@ -0,0 +1,33 @@ +import groovy.json.JsonSlurper + +// def USER_PROJECT_ROOT = "$rootDir/../../../" +def PLATFORMS_ANDROID = "platforms/android" +def PLUGIN_NAME = "{{pluginName}}" + +def USER_PROJECT_PLATFORMS_ANDROID +def USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV = System.getenv('USER_PROJECT_PLATFORMS_ANDROID'); +if (USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV != null && !USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV.equals("")) { + USER_PROJECT_PLATFORMS_ANDROID = USER_PROJECT_PLATFORMS_ANDROID_FROM_ENV; +} else { + USER_PROJECT_PLATFORMS_ANDROID = "$rootDir/../../../platforms/android" +} + +def dependenciesJson = file("${USER_PROJECT_PLATFORMS_ANDROID}/dependencies.json") +def appDependencies = new JsonSlurper().parseText(dependenciesJson.text) +def pluginData = appDependencies.find { it.name == PLUGIN_NAME } +def nativescriptDependencies = appDependencies.findAll{pluginData.name == it.name} + +def getDepPlatformDir = { dep -> + file("$USER_PROJECT_PLATFORMS_ANDROID/${dep.directory}/$PLATFORMS_ANDROID") +} + +def applyIncludeSettingsGradlePlugin = { + nativescriptDependencies.each { dep -> + def includeSettingsGradlePath = "${getDepPlatformDir(dep)}/include-settings.gradle" + if (file(includeSettingsGradlePath).exists()) { + apply from: includeSettingsGradlePath + } + } +} + +applyIncludeSettingsGradlePlugin() \ No newline at end of file diff --git a/gradle-api/src/functionalTest/resources/extracted/sample-plugin-include.gradle b/gradle-api/src/functionalTest/resources/extracted/sample-plugin-include.gradle new file mode 100644 index 0000000000..e8cac7ec7b --- /dev/null +++ b/gradle-api/src/functionalTest/resources/extracted/sample-plugin-include.gradle @@ -0,0 +1,8 @@ +dependencies { + if (project.hasProperty("tempBuild")) { + if (project.extensions.findByName("nativescript") == null) { + throw new GradleException("@nativescript/gradle-api-sample needs NativeScript CLI 9.2 or newer: npm i -D nativescript@latest") + } + compileOnly nativescript.plugin("@nativescript/core").artifacts + } +} \ No newline at end of file diff --git a/gradle-api/src/main/java/org/nativescript/gradle/NativeScript.java b/gradle-api/src/main/java/org/nativescript/gradle/NativeScript.java new file mode 100644 index 0000000000..25b8998e74 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/NativeScript.java @@ -0,0 +1,43 @@ +package org.nativescript.gradle; + +import org.gradle.api.GradleException; +import org.gradle.api.Project; + +/** + * Entry point for Java and Kotlin code, such as another Gradle plugin built on this library. + * + *

Scripts applied with {@code apply from}, which include every plugin's {@code include.gradle}, + * get their own class loader and cannot see this class even when {@code buildscript.gradle} put the + * library on the project's classpath. They apply the plugin by id and use the extension + * dynamically, through {@code project.extensions.getByName("nativescript")}. + */ +public final class NativeScript { + private NativeScript() {} + + /** + * The {@value NativeScriptExtension#NAME} extension of {@code project}, applying {@link + * NativeScriptPlugin} first if needed. + * + * @param project the project, normally {@code :app} in the app build + * @return the extension + * @throws GradleException if the project's extension comes from another copy of this library, + * loaded by a different class loader + */ + public static NativeScriptExtension of(Project project) { + Object extension = project.getExtensions().findByName(NativeScriptExtension.NAME); + if (extension == null) { + project.getPluginManager().apply(NativeScriptPlugin.class); + extension = project.getExtensions().getByName(NativeScriptExtension.NAME); + } + if (extension instanceof NativeScriptExtension) { + return (NativeScriptExtension) extension; + } + throw new GradleException("The '" + NativeScriptExtension.NAME + "' extension of " + project + + " is a " + extension.getClass().getName() + " (class loader " + extension.getClass().getClassLoader() + + "), not this copy of org.nativescript:gradle-api's " + NativeScriptExtension.class.getName() + + ". Either something else registered an extension of that name, or another copy of the library" + + " in a different class loader did; then put the library on the classpath of the buildscript that" + + " applies it, or use the extension dynamically through project.extensions.getByName(\"" + + NativeScriptExtension.NAME + "\")."); + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/NativeScriptExtension.java b/gradle-api/src/main/java/org/nativescript/gradle/NativeScriptExtension.java new file mode 100644 index 0000000000..d37cf21876 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/NativeScriptExtension.java @@ -0,0 +1,192 @@ +package org.nativescript.gradle; + +import java.io.File; + +/** + * What a NativeScript plugin's Gradle code can ask about the project being built, registered as + * the {@value #NAME} extension by {@link NativeScriptPlugin}. + * + *

Answers come from the facts file ({@code platforms/android/nativescript-gradle.json}) that + * NativeScript CLI 9.2 and newer write when preparing the project. {@link #getApiLevel()}, {@link + * #isPluginBuild()}, {@link #isBuildingPlugin(String)}, and {@link #getSelf()} outside a plugin + * build, work without it. Every other member needs it and throws a {@link + * org.gradle.api.GradleException} when it is used: + * + *

    + *
  • if there is no facts file, because a CLI before 9.2 prepared the project. The message says + * to update the project's CLI and prepare it again; + *
  • if the facts file no longer matches the {@code dependencies.json} next to it, because a + * different CLI prepared the project after the one that wrote it. The message says to + * prepare it again with the project's CLI; + *
  • if the facts file needs a newer version of this library than the one on the classpath. + * The message says to update the plugin that adds the library. + *
+ * + *

Everything is worked out on first use, during configuration, and does not change afterwards. + * Read what a task needs while configuring it rather than calling this from a task action. + * + *

Two builds can use this API: + * + *

    + *
  • the app build ({@code platforms/android}), where every plugin's {@code include.gradle} is + * applied to the {@code :app} project; + *
  • a plugin build, the throwaway project in which the CLI compiles one plugin's sources into + * an aar. Only the {@code repositories} and {@code dependencies} blocks of that plugin's own + * {@code include.gradle} run there, but the {@code include.gradle} files of the plugins it + * depends on run in full. + *
+ * + *

Not intended to be implemented outside this library; methods may be added in later versions. + * Check {@link #getApiLevel()} before calling a method newer than the version a plugin declares, + * because another plugin may have put a newer version of this library on the classpath, never an + * older one. + * + *

{@code
+ * dependencies {
+ *     if (project.hasProperty("tempBuild")) {
+ *         if (project.extensions.findByName("nativescript") == null) {
+ *             throw new GradleException("my-plugin needs NativeScript CLI 9.2 or newer: npm i -D nativescript@latest")
+ *         }
+ *         compileOnly nativescript.plugin("@nativescript/core").artifacts
+ *     }
+ * }
+ * }
+ */ +public interface NativeScriptExtension { + /** The name the extension is registered under. */ + String NAME = "nativescript"; + + /** + * The API level this copy of the library implements: 1 for the methods documented as such, and + * one more for each later version that adds methods. + * + * @return the API level, at least 1 + * @since API level 1 + */ + int getApiLevel(); + + /** + * Whether the CLI that prepared the project guarantees a behaviour. Capability names are listed + * in the facts file's schema documentation. + * + *

Names are dotted and lowercase, {@code area.feature}, such as {@code build.abis}. A CLI only + * ever adds capabilities: once a CLI version declares one, every later version does too. + * + * @param capability the capability name + * @return true if the CLI declared it + * @throws org.gradle.api.GradleException if the project has no facts file or it is out of date + * @since API level 1 + */ + boolean has(String capability); + + /** + * Whether this Gradle build is the CLI's build of one plugin's aar rather than the app build. + * + * @return true in a plugin build + * @since API level 1 + */ + boolean isPluginBuild(); + + /** + * In a plugin build, the plugin whose aar is being built. A dependency's {@code include.gradle} + * applied there sees the plugin that depends on it, not itself. In the app build it is null + * and needs no facts file. + * + * @return that plugin, or null in the app build or if the CLI did not name the plugin + * @throws org.gradle.api.GradleException in a plugin build, if the project has no facts file or + * it is out of date + * @since API level 1 + */ + PluginInfo getSelf(); + + /** + * Whether this is the plugin build of the given plugin. + * + * @param npmName the plugin's npm package name, such as {@code @nativescript/core} + * @return true only in that plugin's own aar build + * @since API level 1 + */ + boolean isBuildingPlugin(String npmName); + + /** + * The NativeScript project root: the directory with the app's {@code package.json}. Not to be + * confused with Gradle's {@code project.projectDir}. + * + * @return an absolute, normalized directory + * @throws org.gradle.api.GradleException if the project has no facts file or it is out of date + * @since API level 1 + */ + File getProjectRoot(); + + /** + * The app's source directory ({@code appPath} in the NativeScript config). + * + * @return an absolute, normalized directory + * @throws org.gradle.api.GradleException if the project has no facts file or it is out of date + * @since API level 1 + */ + File getAppDir(); + + /** + * The app's {@code App_Resources} directory ({@code appResourcesPath} in the NativeScript config). + * + * @return an absolute, normalized directory + * @throws org.gradle.api.GradleException if the project has no facts file or it is out of date + * @since API level 1 + */ + File getAppResourcesDir(); + + /** + * A plugin of the project: a package the CLI lists in the facts file because its {@code + * package.json} declares Android support. Any other package, even one with a {@code + * platforms/android} directory, is not a plugin; find it with {@link #findPackage(String)}. + * + * @param npmName the npm package name, such as {@code @nativescript/core} + * @return the plugin + * @throws org.gradle.api.GradleException if there is no such plugin, in which case the message + * lists the plugins that are known, or if the project has no facts file or it is out of date + * @throws IllegalArgumentException if {@code npmName} is not an npm package name + * @since API level 1 + */ + PluginInfo plugin(String npmName); + + /** + * Like {@link #plugin(String)}, but returns null when there is no such plugin. + * + * @param npmName the npm package name, such as {@code @nativescript/core} + * @return the plugin, or null + * @throws IllegalArgumentException if {@code npmName} is not an npm package name + * @throws org.gradle.api.GradleException if the project has no facts file or it is out of date + * @since API level 1 + */ + PluginInfo findPlugin(String npmName); + + /** + * The directory of any installed npm package, native plugin or not. + * + *

Packages the CLI lists as plugins resolve to the directory it recorded. Others are looked + * up the way Node does: {@code node_modules/} in the project root, then in each parent + * directory. This is best effort: layouts that keep packages out of the project's {@code + * node_modules}, such as pnpm's isolated mode for packages the app does not depend on directly, + * may not resolve. + * + * @param npmName the npm package name + * @return the package directory + * @throws org.gradle.api.GradleException if the package is not found, or if the project has no + * facts file or it is out of date + * @throws IllegalArgumentException if {@code npmName} is not an npm package name + * @since API level 1 + */ + File resolvePackage(String npmName); + + /** + * Like {@link #resolvePackage(String)}, but returns null when the package is not found. + * + * @param npmName the npm package name + * @return the package directory, or null + * @throws IllegalArgumentException if {@code npmName} is not an npm package name + * @throws org.gradle.api.GradleException if the project has no facts file or it is out of date + * @since API level 1 + */ + File findPackage(String npmName); +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/NativeScriptPlugin.java b/gradle-api/src/main/java/org/nativescript/gradle/NativeScriptPlugin.java new file mode 100644 index 0000000000..d04366103a --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/NativeScriptPlugin.java @@ -0,0 +1,26 @@ +package org.nativescript.gradle; + +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.nativescript.gradle.internal.DefaultNativeScriptExtension; + +/** + * Registers the {@value NativeScriptExtension#NAME} extension, plugin id {@code + * org.nativescript.api}. + * + *

Every plugin of an app applies this to the same {@code :app} project; applying it again, or + * when the extension already exists, does nothing. + */ +public class NativeScriptPlugin implements Plugin { + /** Creates the plugin; Gradle does this when it is applied. */ + public NativeScriptPlugin() {} + + @Override + public void apply(Project project) { + if (project.getExtensions().findByName(NativeScriptExtension.NAME) != null) { + return; + } + project.getExtensions() + .add(NativeScriptExtension.class, NativeScriptExtension.NAME, new DefaultNativeScriptExtension(project)); + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/PluginInfo.java b/gradle-api/src/main/java/org/nativescript/gradle/PluginInfo.java new file mode 100644 index 0000000000..6bf64d866d --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/PluginInfo.java @@ -0,0 +1,68 @@ +package org.nativescript.gradle; + +import java.io.File; +import java.util.Map; +import org.gradle.api.file.FileCollection; + +/** + * A plugin of the NativeScript project: an npm package with Android native code, as listed in the + * facts file the CLI wrote. + * + *

Not intended to be implemented outside this library; methods may be added in later versions. + * + * @see NativeScriptExtension#plugin(String) + */ +public interface PluginInfo { + /** + * The npm package name. + * + * @return the name, such as {@code @nativescript/core} + * @since API level 1 + */ + String getName(); + + /** + * The installed npm package. Treat it as read-only: with {@code android.pluginBuildLocation} + * set to {@code "platforms"}, the CLI leaves {@code node_modules} untouched and works on a copy + * of the native files instead. + * + * @return an absolute, normalized directory + * @since API level 1 + */ + File getPackageDir(); + + /** + * The directory the build reads the plugin's Android files from: the package's {@code + * platforms/android}, or the CLI's copy of it. + * + * @return an absolute, normalized directory + * @since API level 1 + */ + File getNativeDir(); + + /** + * Every {@code .aar} and {@code .jar} under the {@linkplain #getNativeDir() native directory}, + * including the aar the CLI builds from the plugin's sources once it exists. Evaluated lazily. + * + *

Meant for {@code compileOnly} in a plugin's own aar build: the app build already packages + * these files. There, {@code compileOnly nativescript.plugin("...").artifacts} is reliable for + * the artifacts a package ships prebuilt, and for the plugins yours lists as dependencies in its + * {@code package.json}, whose aars the CLI builds first. The CLI also builds + * {@code @nativescript/core} first, so core is always fine. For any other plugin, an aar the CLI + * builds from its sources may not exist yet on a clean build. + * + * @return a live view of those files + * @since API level 1 + */ + FileCollection getArtifacts(); + + /** + * Options the project sets for this plugin. Values are JSON values: {@code String}, {@code + * Boolean}, {@code Integer}, {@code Long}, {@code java.math.BigInteger}, {@code + * java.math.BigDecimal}, {@code null}, and unmodifiable {@code List}s and {@code Map}s of them. + * + * @return an unmodifiable map + * @since API level 1 + */ + Map getOptions(); +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/BuildInputs.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/BuildInputs.java new file mode 100644 index 0000000000..48b3a1a553 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/BuildInputs.java @@ -0,0 +1,65 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import org.gradle.api.Project; +import org.gradle.api.file.ProjectLayout; +import org.gradle.api.plugins.ExtraPropertiesExtension; +import org.gradle.api.provider.ProviderFactory; + +/** What {@link Resolution} reads from the build. */ +public interface BuildInputs { + /** + * An extra property of the project or, failing that, of its nearest ancestor that has one; else + * a Gradle property ({@code -P}, gradle.properties). Null when absent. + */ + Object property(String name); + + /** An environment variable, null when absent or empty. */ + String environmentVariable(String name); + + /** The root project's directory. */ + File rootDir(); + + /** The bytes of {@code file}, null if it is not a regular file. */ + byte[] fileContents(File file); + + static BuildInputs of(Project project) { + ProviderFactory providers = project.getProviders(); + ProjectLayout layout = project.getLayout(); + File rootDir = project.getRootDir(); + return new BuildInputs() { + // Not Project.findProperty: its implicit lookup in parent projects is deprecated since + // Gradle 9.x, and the templates set their extra properties on the root project. + @Override + public Object property(String name) { + for (Project p = project; p != null; p = p.getParent()) { + ExtraPropertiesExtension extra = p.getExtensions().getExtraProperties(); + if (extra.has(name)) { + return extra.get(name); + } + } + return providers.gradleProperty(name).getOrNull(); + } + + @Override + public String environmentVariable(String name) { + String value = providers.environmentVariable(name).getOrNull(); + return value == null || value.isEmpty() ? null : value; + } + + @Override + public File rootDir() { + return rootDir; + } + + // Through providers so that the configuration cache tracks the file, including its absence. + @Override + public byte[] fileContents(File file) { + return providers + .fileContents(layout.file(providers.provider(() -> file))) + .getAsBytes() + .getOrNull(); + } + }; + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultNativeScriptExtension.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultNativeScriptExtension.java new file mode 100644 index 0000000000..d7aef2adf0 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultNativeScriptExtension.java @@ -0,0 +1,146 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.gradle.api.GradleException; +import org.gradle.api.Project; +import org.gradle.api.model.ObjectFactory; +import org.nativescript.gradle.NativeScriptExtension; +import org.nativescript.gradle.PluginInfo; + +public final class DefaultNativeScriptExtension implements NativeScriptExtension { + public static final int API_LEVEL = 1; + + private static final String PLUGIN_NAME_PROPERTY = "PLUGIN_NAME"; + + private final BuildInputs inputs; + private final ObjectFactory objects; + private final Map pluginInfos = new ConcurrentHashMap<>(); + private volatile Resolution resolution; + + public DefaultNativeScriptExtension(Project project) { + this(BuildInputs.of(project), project.getObjects()); + } + + public DefaultNativeScriptExtension(BuildInputs inputs, ObjectFactory objects) { + this.inputs = inputs; + this.objects = objects; + } + + // Read on first use rather than when applied: in the plugin build the library is applied + // reflectively, and plugins may apply it before the template has set its extra properties. + // Members that need no facts must not call this, and a failure is not kept. + private Resolution resolution() { + Resolution result = resolution; + if (result == null) { + synchronized (this) { + result = resolution; + if (result == null) { + result = Resolution.resolve(inputs); + resolution = result; + } + } + } + return result; + } + + @Override + public int getApiLevel() { + return API_LEVEL; + } + + @Override + public boolean has(String capability) { + return resolution().getCapabilities().contains(capability); + } + + // Every CLI since 8.4 passes -PtempBuild=true only to the throwaway project that builds a + // plugin's aar, whose template also sets PLUGIN_NAME. + @Override + public boolean isPluginBuild() { + return inputs.property(Resolution.TEMP_BUILD_PROPERTY) != null; + } + + private String pluginName() { + return isPluginBuild() ? Resolution.asString(inputs.property(PLUGIN_NAME_PROPERTY)) : null; + } + + @Override + public PluginInfo getSelf() { + if (!isPluginBuild()) { + return null; + } + resolution(); + String name = pluginName(); + return name != null ? findPlugin(name) : null; + } + + @Override + public boolean isBuildingPlugin(String npmName) { + return npmName != null && npmName.equals(pluginName()); + } + + @Override + public File getProjectRoot() { + return resolution().getProjectRoot(); + } + + @Override + public File getAppDir() { + return resolution().getAppDir(); + } + + @Override + public File getAppResourcesDir() { + return resolution().getAppResourcesDir(); + } + + @Override + public PluginInfo plugin(String npmName) { + PluginInfo plugin = findPlugin(npmName); + if (plugin == null) { + Resolution r = resolution(); + throw new GradleException("NativeScript plugin '" + npmName + "' is not listed in " + r.getFacts().getFile() + + ". Known plugins: " + + (r.getPlugins().isEmpty() ? "none" : String.join(", ", r.getPlugins().keySet())) + + ". Only packages that declare Android support in their package.json are plugins;" + + " find any other package with resolvePackage."); + } + return plugin; + } + + @Override + public PluginInfo findPlugin(String npmName) { + NodePackages.validate(npmName); + PluginInfo cached = pluginInfos.get(npmName); + if (cached != null) { + return cached; + } + PluginData data = resolution().findPlugin(npmName); + if (data == null) { + return null; + } + return pluginInfos.computeIfAbsent(npmName, name -> new DefaultPluginInfo(data, objects)); + } + + @Override + public File resolvePackage(String npmName) { + File dir = findPackage(npmName); + if (dir == null) { + throw new GradleException("npm package '" + npmName + "' is not installed in " + + new File(getProjectRoot(), "node_modules") + " or a parent directory."); + } + return dir; + } + + @Override + public File findPackage(String npmName) { + return resolution().findPackage(npmName); + } + + @Override + public String toString() { + return "extension '" + NAME + "'"; + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultPluginInfo.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultPluginInfo.java new file mode 100644 index 0000000000..02a06a6b75 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/DefaultPluginInfo.java @@ -0,0 +1,49 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import java.util.Map; +import org.gradle.api.file.FileCollection; +import org.gradle.api.model.ObjectFactory; +import org.nativescript.gradle.PluginInfo; + +final class DefaultPluginInfo implements PluginInfo { + private final PluginData data; + private final FileCollection artifacts; + + DefaultPluginInfo(PluginData data, ObjectFactory objects) { + this.data = data; + this.artifacts = objects.fileTree() + .from(data.getNativeDir()) + .matching(patterns -> patterns.include("**/*.aar", "**/*.jar")); + } + + @Override + public String getName() { + return data.getName(); + } + + @Override + public File getPackageDir() { + return data.getPackageDir(); + } + + @Override + public File getNativeDir() { + return data.getNativeDir(); + } + + @Override + public FileCollection getArtifacts() { + return artifacts; + } + + @Override + public Map getOptions() { + return data.getOptions(); + } + + @Override + public String toString() { + return "NativeScript plugin " + data; + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/Facts.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/Facts.java new file mode 100644 index 0000000000..4461f69798 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/Facts.java @@ -0,0 +1,309 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import org.gradle.api.GradleException; +import org.gradle.api.logging.Logger; +import org.gradle.api.logging.Logging; + +/** + * The CLI's {@code nativescript-gradle.json}, described by {@code schema/nativescript-gradle.schema.json}. + * + *

Fields are only ever added to the format, so unknown fields are ignored and a newer {@code + * schemaVersion} is read like this one, unless its {@code minReaderSchemaVersion} is newer than + * {@link #SUPPORTED_SCHEMA_VERSION}. + */ +public final class Facts { + /** + * The facts schema version this library supports: it knows every field up to this {@code + * schemaVersion}, and refuses files whose {@code minReaderSchemaVersion} is higher. + */ + public static final int SUPPORTED_SCHEMA_VERSION = 1; + + private static final Logger LOGGER = Logging.getLogger(Facts.class); + + // Checked against the file's whole content, not its mtime: the class loader holding this cache + // outlives builds in the daemon, and a rewrite can keep the size and land in the same mtime tick. + private static final Map CACHE = new ConcurrentHashMap<>(); + + private final File file; + private final String dependenciesJsonSha256; + private final Set capabilities; + private final File projectRoot; + private final File appDir; + private final File appResourcesDir; + private final Map plugins; + + private Facts( + File file, + String dependenciesJsonSha256, + Set capabilities, + File projectRoot, + File appDir, + File appResourcesDir, + Map plugins) { + this.file = file; + this.dependenciesJsonSha256 = dependenciesJsonSha256; + this.capabilities = Collections.unmodifiableSet(capabilities); + this.projectRoot = projectRoot; + this.appDir = appDir; + this.appResourcesDir = appResourcesDir; + this.plugins = Collections.unmodifiableMap(plugins); + } + + /** + * Parses {@code content}, read from {@code file}, reusing the previous result for that file while + * its content is unchanged. + * + * @throws GradleException if {@code content} is not valid facts + */ + public static Facts read(File file, byte[] content) { + File absolute = file.getAbsoluteFile(); + String key = absolute.getPath(); + CachedFacts cached = CACHE.get(key); + if (cached != null && Arrays.equals(cached.content, content)) { + return cached.facts; + } + Facts facts = parse(absolute, new String(content, StandardCharsets.UTF_8)); + CACHE.put(key, new CachedFacts(content, facts)); + return facts; + } + + /** + * Parses facts whose relative paths are relative to {@code file}'s directory. Does not touch the + * file system. + * + * @throws GradleException if {@code text} is not valid facts + */ + public static Facts parse(File file, String text) { + Object root; + try { + root = Json.parse(text); + } catch (Json.ParseException e) { + throw invalid(file, e.getMessage()); + } + Path base = file.getAbsoluteFile().toPath().getParent(); + Reader reader = new Reader(file, base); + Map top = reader.object(root, "the top level"); + + // The two versions are checked before any other field, so that a file this library cannot + // read asks for a newer library rather than being reported as invalid. + int minReaderSchemaVersion = reader.integer(top, "minReaderSchemaVersion", ""); + if (minReaderSchemaVersion < 1) { + throw invalid(file, "minReaderSchemaVersion must be at least 1"); + } + int schemaVersion = reader.integer(top, "schemaVersion", ""); + if (schemaVersion < 1) { + throw invalid(file, "schemaVersion must be at least 1"); + } + if (minReaderSchemaVersion > schemaVersion) { + throw invalid(file, "minReaderSchemaVersion must not be greater than schemaVersion"); + } + if (minReaderSchemaVersion > SUPPORTED_SCHEMA_VERSION) { + throw new GradleException("The NativeScript facts file " + file + " needs org.nativescript:gradle-api" + + " supporting facts schema " + minReaderSchemaVersion + ", but this version of the library" + + " supports up to " + SUPPORTED_SCHEMA_VERSION + ". Update the plugins of this app that" + + " use org.nativescript:gradle-api: any one that pins a newer version of the library is enough."); + } + + if (schemaVersion > SUPPORTED_SCHEMA_VERSION) { + LOGGER.info( + "{} has schemaVersion {}; this version of org.nativescript:gradle-api knows up to {}" + + " and ignores the fields it does not know.", + file, + schemaVersion, + SUPPORTED_SCHEMA_VERSION); + } + + Map dependenciesJson = reader.object(top.get("dependenciesJson"), "dependenciesJson"); + String dependenciesJsonSha256 = reader.requiredString(dependenciesJson, "sha256", "dependenciesJson."); + if (!dependenciesJsonSha256.matches("[0-9a-f]{64}")) { + throw invalid(file, "dependenciesJson.sha256 must be 64 lowercase hex digits"); + } + + Set capabilities = new LinkedHashSet<>(); + if (top.containsKey("capabilities")) { + List list = reader.array(top.get("capabilities"), "capabilities"); + for (int i = 0; i < list.size(); i++) { + capabilities.add(reader.string(list.get(i), "capabilities[" + i + "]")); + } + } + + Map project = reader.object(top.get("project"), "project"); + File projectRoot = reader.path(project, "root", "project."); + File appDir = reader.path(project, "appDir", "project."); + File appResourcesDir = reader.path(project, "appResourcesDir", "project."); + + Map plugins = new LinkedHashMap<>(); + List pluginList = reader.array(top.get("plugins"), "plugins"); + for (int i = 0; i < pluginList.size(); i++) { + String at = "plugins[" + i + "]"; + Map entry = reader.object(pluginList.get(i), at); + String prefix = at + "."; + String name = reader.requiredString(entry, "name", prefix); + List deps = reader.array(entry.get("dependencies"), prefix + "dependencies"); + List dependencies = new ArrayList<>(); + for (int d = 0; d < deps.size(); d++) { + dependencies.add(reader.string(deps.get(d), prefix + "dependencies[" + d + "]")); + } + Map options = + entry.containsKey("options") ? reader.object(entry.get("options"), prefix + "options") : Collections.emptyMap(); + File packageDir = reader.path(entry, "packageDir", prefix); + File nativeDir = reader.path(entry, "nativeDir", prefix); + // Required by the schema but not exposed: where aars live is the CLI's business. + reader.requiredString(entry, "aarName", prefix); + reader.path(entry, "aar", prefix); + PluginData plugin = new PluginData(name, packageDir, nativeDir, dependencies, options); + if (plugins.put(name, plugin) != null) { + throw invalid(file, "plugin '" + name + "' is listed more than once"); + } + } + + return new Facts( + file, dependenciesJsonSha256, capabilities, projectRoot, appDir, appResourcesDir, plugins); + } + + private static GradleException invalid(File file, String problem) { + return new GradleException("Invalid NativeScript facts file " + file + ": " + problem); + } + + /** The dependencies.json these facts must match, next to the facts file. */ + public File getDependenciesJsonFile() { + return new File(file.getAbsoluteFile().getParentFile(), "dependencies.json"); + } + + /** + * Fails if these facts no longer describe the project: a CLI that does not write facts rewrites + * the dependencies.json next to them but leaves them behind. + * + * @param content the current bytes of {@link #getDependenciesJsonFile()}, null if it is missing + * @throws GradleException if dependencies.json is missing or does not have the recorded hash + */ + public void checkDependenciesJson(byte[] content) { + File dependenciesJson = getDependenciesJsonFile(); + String rerun = " Run `ns prepare android` again with the NativeScript CLI the project uses."; + if (content == null) { + throw new GradleException( + "There is no " + dependenciesJson + " next to the NativeScript facts file " + file + "." + rerun); + } + if (!sha256(content).equals(dependenciesJsonSha256)) { + throw new GradleException("The NativeScript facts file " + file + " does not match " + dependenciesJson + + ": a different NativeScript CLI rewrote " + dependenciesJson.getName() + + " after the facts file was written." + rerun); + } + } + + static String sha256(byte[] content) { + MessageDigest digest; + try { + digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Every Java platform provides SHA-256", e); + } + StringBuilder hex = new StringBuilder(64); + for (byte b : digest.digest(content)) { + hex.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16)); + } + return hex.toString(); + } + + public File getFile() { + return file; + } + + public Set getCapabilities() { + return capabilities; + } + + public File getProjectRoot() { + return projectRoot; + } + + public File getAppDir() { + return appDir; + } + + public File getAppResourcesDir() { + return appResourcesDir; + } + + /** By npm name, in the order the CLI listed them. */ + public Map getPlugins() { + return plugins; + } + + private static final class CachedFacts { + final byte[] content; + final Facts facts; + + CachedFacts(byte[] content, Facts facts) { + this.content = content; + this.facts = facts; + } + } + + private static final class Reader { + private final File file; + private final Path base; + + Reader(File file, Path base) { + this.file = file; + this.base = base; + } + + @SuppressWarnings("unchecked") + Map object(Object value, String what) { + if (!(value instanceof Map)) { + throw invalid(file, what + " must be an object"); + } + return (Map) value; + } + + @SuppressWarnings("unchecked") + List array(Object value, String what) { + if (!(value instanceof List)) { + throw invalid(file, what + " must be an array"); + } + return (List) value; + } + + String string(Object value, String what) { + if (!(value instanceof String)) { + throw invalid(file, what + " must be a string"); + } + return (String) value; + } + + String requiredString(Map object, String key, String prefix) { + String value = string(object.get(key), prefix + key); + if (value.isEmpty()) { + throw invalid(file, prefix + key + " must not be empty"); + } + return value; + } + + int integer(Map object, String key, String prefix) { + Object value = object.get(key); + if (!(value instanceof Integer)) { + throw invalid(file, prefix + key + " must be an integer"); + } + return (Integer) value; + } + + File path(Map object, String key, String prefix) { + return base.resolve(requiredString(object, key, prefix)).normalize().toFile(); + } + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/Json.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/Json.java new file mode 100644 index 0000000000..8aa6eef53d --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/Json.java @@ -0,0 +1,366 @@ +package org.nativescript.gradle.internal; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Strict RFC 8259 JSON parser. + * + *

Not {@code groovy.json}: the library does not compile against Groovy, and the facts reader + * relies on the number types below. + * + *

Objects become unmodifiable {@link LinkedHashMap}s (a repeated key keeps the last value, as + * {@code JSON.parse} does), arrays unmodifiable lists, integers {@link Integer}, {@link Long} or + * {@link BigInteger} (the smallest that fits), other numbers {@link BigDecimal}, and {@code null} + * stays {@code null}. A leading byte order mark is skipped. + */ +public final class Json { + private static final int MAX_DEPTH = 512; + + private final String text; + private int pos; + private int depth; + + private Json(String text) { + this.text = text; + } + + /** + * Parses one JSON value, which must be the whole of {@code text} apart from whitespace. + * + * @throws ParseException if {@code text} is not valid JSON + */ + public static Object parse(String text) { + Json parser = new Json(text); + if (!text.isEmpty() && text.charAt(0) == 0xFEFF) { + parser.pos = 1; + } + parser.skipWhitespace(); + Object value = parser.readValue(); + parser.skipWhitespace(); + if (parser.pos < text.length()) { + throw parser.error("Unexpected " + parser.describeCurrent() + " after the JSON value"); + } + return value; + } + + private Object readValue() { + if (pos >= text.length()) { + throw error("Unexpected end of input, expected a value"); + } + char c = text.charAt(pos); + switch (c) { + case '{': + return readObject(); + case '[': + return readArray(); + case '"': + return readString(); + case 't': + expectLiteral("true"); + return Boolean.TRUE; + case 'f': + expectLiteral("false"); + return Boolean.FALSE; + case 'n': + expectLiteral("null"); + return null; + default: + if (c == '-' || (c >= '0' && c <= '9')) { + return readNumber(); + } + throw error("Unexpected " + describeCurrent() + ", expected a value"); + } + } + + private Map readObject() { + enter(); + pos++; + Map result = new LinkedHashMap<>(); + skipWhitespace(); + if (peek() == '}') { + pos++; + depth--; + return Collections.unmodifiableMap(result); + } + while (true) { + skipWhitespace(); + if (peek() != '"') { + throw error("Unexpected " + describeCurrent() + ", expected a string key"); + } + String key = readString(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + result.put(key, readValue()); + skipWhitespace(); + if (peek() == ',') { + pos++; + } else if (peek() == '}') { + pos++; + depth--; + return Collections.unmodifiableMap(result); + } else { + throw error("Unexpected " + describeCurrent() + ", expected ',' or '}'"); + } + } + } + + private List readArray() { + enter(); + pos++; + List result = new ArrayList<>(); + skipWhitespace(); + if (peek() == ']') { + pos++; + depth--; + return Collections.unmodifiableList(result); + } + while (true) { + skipWhitespace(); + result.add(readValue()); + skipWhitespace(); + if (peek() == ',') { + pos++; + } else if (peek() == ']') { + pos++; + depth--; + return Collections.unmodifiableList(result); + } else { + throw error("Unexpected " + describeCurrent() + ", expected ',' or ']'"); + } + } + } + + private String readString() { + pos++; + StringBuilder sb = new StringBuilder(); + while (true) { + if (pos >= text.length()) { + throw error("Unterminated string"); + } + char c = text.charAt(pos); + if (c == '"') { + pos++; + return sb.toString(); + } + if (c < 0x20) { + throw error("Unescaped control character U+" + String.format("%04X", (int) c) + " in string"); + } + if (c != '\\') { + sb.append(c); + pos++; + continue; + } + pos++; + if (pos >= text.length()) { + throw error("Unterminated string"); + } + char escaped = text.charAt(pos); + switch (escaped) { + case '"': + case '\\': + case '/': + sb.append(escaped); + break; + case 'b': + sb.append('\b'); + break; + case 'f': + sb.append('\f'); + break; + case 'n': + sb.append('\n'); + break; + case 'r': + sb.append('\r'); + break; + case 't': + sb.append('\t'); + break; + case 'u': + sb.append(readUnicodeEscape()); + continue; + default: + throw error("Invalid escape sequence '\\" + escaped + "'"); + } + pos++; + } + } + + private char readUnicodeEscape() { + int start = pos + 1; + if (start + 4 > text.length()) { + throw error("Incomplete \\u escape"); + } + int value = 0; + for (int i = start; i < start + 4; i++) { + char c = text.charAt(i); + int digit = c < 0x80 ? Character.digit(c, 16) : -1; + if (digit < 0) { + pos = i; + throw error("Invalid hex digit " + describeCurrent() + " in \\u escape"); + } + value = value * 16 + digit; + } + pos = start + 4; + return (char) value; + } + + private Number readNumber() { + int start = pos; + boolean integral = true; + if (peek() == '-') { + pos++; + } + if (peek() == '0') { + pos++; + if (isDigit(peek())) { + throw error("Leading zeros are not allowed"); + } + } else if (isDigit(peek())) { + skipDigits(); + } else { + throw error("Unexpected " + describeCurrent() + ", expected a digit"); + } + if (peek() == '.') { + integral = false; + pos++; + if (!isDigit(peek())) { + throw error("Unexpected " + describeCurrent() + ", expected a digit after '.'"); + } + skipDigits(); + } + if (peek() == 'e' || peek() == 'E') { + integral = false; + pos++; + if (peek() == '+' || peek() == '-') { + pos++; + } + if (!isDigit(peek())) { + throw error("Unexpected " + describeCurrent() + ", expected a digit in the exponent"); + } + skipDigits(); + } + String literal = text.substring(start, pos); + if (!integral) { + return new BigDecimal(literal); + } + BigInteger value = new BigInteger(literal); + if (value.bitLength() < 32) { + return value.intValue(); + } + if (value.bitLength() < 64) { + return value.longValue(); + } + return value; + } + + private void skipDigits() { + while (isDigit(peek())) { + pos++; + } + } + + private static boolean isDigit(int c) { + return c >= '0' && c <= '9'; + } + + private void expectLiteral(String literal) { + for (int i = 0; i < literal.length(); i++) { + if (peek() != literal.charAt(i)) { + throw error("Unexpected " + describeCurrent() + ", expected '" + literal + "'"); + } + pos++; + } + } + + private void expect(char c) { + if (peek() != c) { + throw error("Unexpected " + describeCurrent() + ", expected '" + c + "'"); + } + pos++; + } + + private void enter() { + if (++depth > MAX_DEPTH) { + throw error("Nesting deeper than " + MAX_DEPTH + " levels"); + } + } + + /** The current character, or -1 at the end of the input. */ + private int peek() { + return pos < text.length() ? text.charAt(pos) : -1; + } + + private void skipWhitespace() { + while (pos < text.length()) { + char c = text.charAt(pos); + if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { + return; + } + pos++; + } + } + + private String describeCurrent() { + if (pos >= text.length()) { + return "end of input"; + } + char c = text.charAt(pos); + if (c < 0x20 || c == 0x7F) { + return "character U+" + String.format("%04X", (int) c); + } + return "character '" + c + "'"; + } + + private ParseException error(String message) { + int line = 1; + int column = 1; + for (int i = 0; i < pos && i < text.length(); i++) { + if (text.charAt(i) == '\n') { + line++; + column = 1; + } else { + column++; + } + } + return new ParseException(message, pos, line, column); + } + + /** Invalid JSON, with the position of the first offending character. */ + public static final class ParseException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final int offset; + private final int line; + private final int column; + + ParseException(String message, int offset, int line, int column) { + super(message + " at line " + line + ", column " + column); + this.offset = offset; + this.line = line; + this.column = column; + } + + /** Zero-based character offset into the parsed text. */ + public int getOffset() { + return offset; + } + + /** One-based line number. */ + public int getLine() { + return line; + } + + /** One-based column number, counted in UTF-16 characters. */ + public int getColumn() { + return column; + } + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/NodePackages.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/NodePackages.java new file mode 100644 index 0000000000..714c1dd23c --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/NodePackages.java @@ -0,0 +1,41 @@ +package org.nativescript.gradle.internal; + +import java.io.File; + +/** Node's lookup of installed packages: {@code node_modules/} in a directory or any ancestor. */ +public final class NodePackages { + private NodePackages() {} + + /** + * The directory of the installed package {@code name} as seen from {@code fromDir}, or null. + * + * @throws IllegalArgumentException if {@code name} is not an npm package name + */ + public static File find(File fromDir, String name) { + validate(name); + for (File dir = fromDir.getAbsoluteFile(); dir != null; dir = dir.getParentFile()) { + File candidate = new File(new File(dir, "node_modules"), name); + if (new File(candidate, "package.json").isFile()) { + return candidate.toPath().normalize().toFile(); + } + } + return null; + } + + static void validate(String name) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("An npm package name must not be empty"); + } + String[] parts = name.split("/", -1); + boolean scoped = name.startsWith("@"); + boolean valid = scoped ? parts.length == 2 && parts[0].length() > 1 : parts.length == 1; + for (String part : parts) { + if (part.isEmpty() || part.equals(".") || part.equals("..") || part.indexOf('\\') >= 0 || part.indexOf(':') >= 0) { + valid = false; + } + } + if (!valid) { + throw new IllegalArgumentException("'" + name + "' is not an npm package name"); + } + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/PluginData.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/PluginData.java new file mode 100644 index 0000000000..f99c45cb05 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/PluginData.java @@ -0,0 +1,53 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** What is known about one npm package with Android native code. Immutable. */ +public final class PluginData { + private final String name; + private final File packageDir; + private final File nativeDir; + private final List dependencies; + private final Map options; + + public PluginData( + String name, + File packageDir, + File nativeDir, + List dependencies, + Map options) { + this.name = name; + this.packageDir = packageDir; + this.nativeDir = nativeDir; + this.dependencies = Collections.unmodifiableList(dependencies); + this.options = Collections.unmodifiableMap(options); + } + + public String getName() { + return name; + } + + public File getPackageDir() { + return packageDir; + } + + public File getNativeDir() { + return nativeDir; + } + + public List getDependencies() { + return dependencies; + } + + public Map getOptions() { + return options; + } + + @Override + public String toString() { + return name + " (" + nativeDir + ")"; + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/internal/Resolution.java b/gradle-api/src/main/java/org/nativescript/gradle/internal/Resolution.java new file mode 100644 index 0000000000..5ccc0041f5 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/internal/Resolution.java @@ -0,0 +1,145 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.gradle.api.GradleException; + +/** Everything the extension answers about the project, from the facts file the CLI wrote. */ +public final class Resolution { + public static final String FACTS_FILE_NAME = "nativescript-gradle.json"; + public static final String FACTS_FILE_PROPERTY = "nativescript.factsFile"; + public static final String TEMP_BUILD_PROPERTY = "tempBuild"; + + private static final String PLATFORMS_ANDROID_VARIABLE = "USER_PROJECT_PLATFORMS_ANDROID"; + + private final Facts facts; + + private Resolution(Facts facts) { + this.facts = facts; + } + + /** + * Reads the project's facts file. + * + * @throws GradleException if there is none, if it no longer matches the dependencies.json next + * to it, if it needs a newer version of this library, or if it is invalid + */ + public static Resolution resolve(BuildInputs inputs) { + List searched = new ArrayList<>(); + Located located = locateFacts(inputs, searched); + if (located == null) { + throw new GradleException("A plugin of this app uses org.nativescript:gradle-api, which needs the project" + + " to be prepared by NativeScript CLI 9.2 or newer, but there is no facts file at " + + searched.stream().map(File::toString).collect(Collectors.joining(" or ")) + + ". Update the project's CLI with `npm i -D nativescript@latest`, then run `ns prepare android`."); + } + Facts facts = Facts.read(located.file, located.content); + facts.checkDependenciesJson(inputs.fileContents(facts.getDependenciesJsonFile())); + return new Resolution(facts); + } + + private static Located locateFacts(BuildInputs inputs, List searched) { + String explicit = asString(inputs.property(FACTS_FILE_PROPERTY)); + if (explicit != null) { + File file = absolute(inputs.rootDir(), explicit); + Located located = Located.of(inputs, file); + if (located == null) { + throw new GradleException("-P" + FACTS_FILE_PROPERTY + " points to " + file + ", which does not exist."); + } + return located; + } + // Lets the app build find the facts without -P, as when Android Studio opens platforms/android. + File inRoot = absolute(inputs.rootDir(), FACTS_FILE_NAME); + searched.add(inRoot); + Located located = Located.of(inputs, inRoot); + if (located != null) { + return located; + } + // Only the plugin build template defines this; the CLI sets the variable when embedding the + // app in a host project. + String platformsAndroid = asString(inputs.property(PLATFORMS_ANDROID_VARIABLE)); + if (platformsAndroid == null && inputs.property(TEMP_BUILD_PROPERTY) != null) { + platformsAndroid = inputs.environmentVariable(PLATFORMS_ANDROID_VARIABLE); + } + if (platformsAndroid != null) { + File file = new File(absolute(inputs.rootDir(), platformsAndroid), FACTS_FILE_NAME); + if (!searched.contains(file)) { + searched.add(file); + return Located.of(inputs, file); + } + } + return null; + } + + public Facts getFacts() { + return facts; + } + + public File getProjectRoot() { + return facts.getProjectRoot(); + } + + public File getAppDir() { + return facts.getAppDir(); + } + + public File getAppResourcesDir() { + return facts.getAppResourcesDir(); + } + + public Set getCapabilities() { + return facts.getCapabilities(); + } + + /** The plugins the CLI listed, by npm name. */ + public Map getPlugins() { + return facts.getPlugins(); + } + + /** A plugin the CLI listed, or null. */ + public PluginData findPlugin(String name) { + NodePackages.validate(name); + return facts.getPlugins().get(name); + } + + /** The installed package's directory, null if not found. */ + public File findPackage(String name) { + NodePackages.validate(name); + PluginData listed = facts.getPlugins().get(name); + if (listed != null) { + return listed.getPackageDir(); + } + return NodePackages.find(facts.getProjectRoot(), name); + } + + static String asString(Object value) { + if (value == null) { + return null; + } + String string = value.toString(); + return string.isEmpty() ? null : string; + } + + private static File absolute(File base, String path) { + return base.toPath().resolve(path).toAbsolutePath().normalize().toFile(); + } + + private static final class Located { + final File file; + final byte[] content; + + private Located(File file, byte[] content) { + this.file = file; + this.content = content; + } + + static Located of(BuildInputs inputs, File file) { + byte[] content = inputs.fileContents(file); + return content != null ? new Located(file, content) : null; + } + } +} diff --git a/gradle-api/src/main/java/org/nativescript/gradle/package-info.java b/gradle-api/src/main/java/org/nativescript/gradle/package-info.java new file mode 100644 index 0000000000..33bc4d6298 --- /dev/null +++ b/gradle-api/src/main/java/org/nativescript/gradle/package-info.java @@ -0,0 +1,28 @@ +/** + * Gradle API for NativeScript plugins. + * + *

A plugin puts the library on the build's classpath from its {@code + * platforms/android/buildscript.gradle}: + * + *

{@code
+ * repositories { mavenCentral() }
+ * dependencies { classpath "org.nativescript:gradle-api:" }
+ * }
+ * + *

It needs the project to be prepared by NativeScript CLI 9.2 or newer, which also loads it in + * the plugin's own aar build and applies it there. A plugin that uses the {@link + * org.nativescript.gradle.NativeScriptExtension nativescript} extension in the app build applies it + * at the top of its {@code platforms/android/include.gradle}: + * + *

{@code
+ * apply plugin: "org.nativescript.api"
+ * }
+ * + *

{@code include.gradle} cannot see the library's classes (see {@link + * org.nativescript.gradle.NativeScript}), so it uses the extension dynamically: by its name, {@code + * nativescript}, or through {@code project.extensions.findByName("nativescript")}. The extension's + * documentation lists what works without the facts file the CLI writes. + * + *

Everything outside this package is internal. + */ +package org.nativescript.gradle; diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/BuildInputsTest.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/BuildInputsTest.java new file mode 100644 index 0000000000..c25759c7f6 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/BuildInputsTest.java @@ -0,0 +1,30 @@ +package org.nativescript.gradle.internal; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class BuildInputsTest { + @TempDir + Path tempDir; + + @Test + void fileContentsAreNullUnlessThereIsARegularFile() throws IOException { + BuildInputs inputs = BuildInputs.of( + ProjectBuilder.builder().withProjectDir(tempDir.resolve("gradle").toFile()).build()); + Path file = tempDir.resolve("facts.json"); + Files.write(file, "{}".getBytes(StandardCharsets.UTF_8)); + Path dir = Files.createDirectories(tempDir.resolve("dir.json")); + + assertArrayEquals("{}".getBytes(StandardCharsets.UTF_8), inputs.fileContents(file.toFile())); + assertNull(inputs.fileContents(tempDir.resolve("missing.json").toFile())); + assertNull(inputs.fileContents(dir.toFile())); + } +} diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/DefaultNativeScriptExtensionTest.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/DefaultNativeScriptExtensionTest.java new file mode 100644 index 0000000000..2239f67d40 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/DefaultNativeScriptExtensionTest.java @@ -0,0 +1,131 @@ +package org.nativescript.gradle.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.nativescript.gradle.internal.TestFiles.plugin; +import static org.nativescript.gradle.internal.TestFiles.writeFacts; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.function.Consumer; +import org.gradle.api.GradleException; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.nativescript.gradle.NativeScriptExtension; + +class DefaultNativeScriptExtensionTest { + @TempDir + Path tempDir; + + private Path project; + private Path platformsAndroid; + private Path factsFile; + + @BeforeEach + void setUp() throws IOException { + project = tempDir.toRealPath().resolve("proj"); + platformsAndroid = Files.createDirectories(project.resolve("platforms/android")); + factsFile = platformsAndroid.resolve(Resolution.FACTS_FILE_NAME); + } + + @ParameterizedTest(name = "plugin build: {0}") + @ValueSource(booleans = {false, true}) + void answersBuildQuestionsWithoutFacts(boolean pluginBuild) { + NativeScriptExtension ns = extension(pluginBuild); + + assertEquals(1, ns.getApiLevel()); + assertEquals(pluginBuild, ns.isPluginBuild()); + assertEquals(pluginBuild, ns.isBuildingPlugin("@scope/p")); + assertFalse(ns.isBuildingPlugin("other")); + } + + @ParameterizedTest(name = "plugin build: {0}") + @ValueSource(booleans = {false, true}) + void needsFactsForEverythingAboutTheProject(boolean pluginBuild) { + NativeScriptExtension ns = extension(pluginBuild); + Map> members = Map.of( + "has", e -> e.has("x"), + "projectRoot", NativeScriptExtension::getProjectRoot, + "appDir", NativeScriptExtension::getAppDir, + "appResourcesDir", NativeScriptExtension::getAppResourcesDir, + "plugin", e -> e.plugin("@nativescript/core"), + "findPlugin", e -> e.findPlugin("@nativescript/core"), + "resolvePackage", e -> e.resolvePackage("@nativescript/core"), + "findPackage", e -> e.findPackage("@nativescript/core")); + + members.forEach((member, call) -> { + GradleException e = assertThrows(GradleException.class, () -> call.accept(ns), member); + assertEquals( + pluginBuild + ? ResolutionTest.noFactsMessage(project.resolve("platforms/tempPlugin/p"), platformsAndroid) + : ResolutionTest.noFactsMessage(platformsAndroid), + e.getMessage(), + member); + }); + } + + @Test + void selfNeedsFactsOnlyInAPluginBuild() { + assertNull(extension(false).getSelf()); + + GradleException e = assertThrows(GradleException.class, extension(true)::getSelf); + assertEquals( + ResolutionTest.noFactsMessage(project.resolve("platforms/tempPlugin/p"), platformsAndroid), + e.getMessage()); + } + + @Test + void readsTheFactsAgainAfterAFailure() throws IOException { + NativeScriptExtension ns = extension(false); + assertThrows(GradleException.class, ns::getProjectRoot); + + writeFacts(factsFile, project, "[]"); + + assertEquals(project.toFile(), ns.getProjectRoot()); + assertEquals(project.resolve("src").toFile(), ns.getAppDir()); + assertEquals(project.resolve("src/App_Resources").toFile(), ns.getAppResourcesDir()); + assertTrue(ns.has("some.capability")); + } + + @Test + void selfIsTheListedPluginBeingBuilt() throws IOException { + writeFacts(factsFile, project, "[" + plugin("@scope/p", "../../node_modules/@scope/p") + "]"); + + assertEquals("@scope/p", extension(true).getSelf().getName()); + assertNull(extension(false).getSelf()); + } + + @Test + void pluginErrorListsTheListedPlugins() throws IOException { + writeFacts(factsFile, project, "[" + plugin("a", "../a") + ", " + plugin("@s/b", "../b") + "]"); + + GradleException e = assertThrows(GradleException.class, () -> extension(false).plugin("c")); + + assertEquals( + "NativeScript plugin 'c' is not listed in " + factsFile + ". Known plugins: a, @s/b. Only packages" + + " that declare Android support in their package.json are plugins; find any other package with" + + " resolvePackage.", + e.getMessage()); + } + + private NativeScriptExtension extension(boolean pluginBuild) { + FakeInputs inputs = pluginBuild + ? new FakeInputs(project.resolve("platforms/tempPlugin/p").toFile()) + .property("tempBuild", "true") + .property("PLUGIN_NAME", "@scope/p") + .property("USER_PROJECT_PLATFORMS_ANDROID", platformsAndroid.toString()) + : new FakeInputs(platformsAndroid.toFile()); + return new DefaultNativeScriptExtension( + inputs, + ProjectBuilder.builder().withProjectDir(tempDir.resolve("gradle").toFile()).build().getObjects()); + } +} diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/FactsTest.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/FactsTest.java new file mode 100644 index 0000000000..6e0d1c22e0 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/FactsTest.java @@ -0,0 +1,256 @@ +package org.nativescript.gradle.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.gradle.api.GradleException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class FactsTest { + private static final String MIN_READER = "\"minReaderSchemaVersion\": 1"; + private static final String SCHEMA = "\"schemaVersion\": 1"; + private static final String DEPENDENCIES_JSON = + "\"dependenciesJson\": {\"sha256\": \"" + TestFiles.EMPTY_DEPENDENCIES_JSON_SHA256 + "\"}"; + private static final String PROJECT = "\"project\": {\"root\": \"../..\", \"appDir\": \"../../app\"," + + " \"appResourcesDir\": \"../../app/App_Resources\"}"; + private static final String NO_PLUGINS = "\"plugins\": []"; + + @TempDir + Path tempDir; + + private Path projectDir; + private Path platformsAndroid; + private File factsFile; + + @BeforeEach + void setUp() throws IOException { + projectDir = tempDir.toRealPath(); + platformsAndroid = projectDir.resolve("platforms/android"); + Files.createDirectories(platformsAndroid); + factsFile = platformsAndroid.resolve("nativescript-gradle.json").toFile(); + } + + @Test + void sha256MatchesTheCli() { + // The CLI writes dependenciesJson.sha256 from its own TypeScript implementation; this literal is + // that implementation's digest of the same bytes. + assertEquals( + "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + Facts.sha256("[]\n".getBytes(StandardCharsets.UTF_8))); + } + + @Test + void readsNewerSchemaVersionAndIgnoresUnknownFields() throws IOException { + try (InputStream in = getClass().getResourceAsStream("/facts/v2-unknown-fields.json")) { + Files.copy(in, factsFile.toPath()); + } + + Facts facts = Facts.read(factsFile, Files.readAllBytes(factsFile.toPath())); + + assertEquals(Collections.singleton("some.future.capability"), facts.getCapabilities()); + assertEquals(projectDir.toFile(), facts.getProjectRoot()); + assertEquals(projectDir.resolve("app").toFile(), facts.getAppDir()); + assertEquals(projectDir.resolve("app/App_Resources").toFile(), facts.getAppResourcesDir()); + assertEquals(Collections.singleton("nativescript-plugin"), facts.getPlugins().keySet()); + PluginData plugin = facts.getPlugins().get("nativescript-plugin"); + assertEquals(Collections.singletonMap("someOption", Arrays.asList("a", "b")), plugin.getOptions()); + assertThrows(UnsupportedOperationException.class, () -> plugin.getOptions().put("k", "v")); + } + + @Test + void optionalFieldsDefaultToEmpty() { + Facts facts = parse(withPlugins(plugin("p"))); + + assertTrue(facts.getPlugins().get("p").getOptions().isEmpty()); + assertTrue(facts.getCapabilities().isEmpty()); + } + + @Test + void resolvesRelativePathsAgainstTheFileAndKeepsAbsoluteOnes() { + Path elsewhere = projectDir.resolve("elsewhere"); + String project = "\"project\": {\"root\": \"" + elsewhere.toString().replace("\\", "\\\\") + "\"," + + " \"appDir\": \"../../x/./y/../app\", \"appResourcesDir\": \"res/\"}"; + + Facts facts = parse(object(MIN_READER, SCHEMA, DEPENDENCIES_JSON, project, NO_PLUGINS)); + + assertEquals(elsewhere.toFile(), facts.getProjectRoot()); + assertEquals(projectDir.resolve("x/app").toFile(), facts.getAppDir()); + assertEquals(platformsAndroid.resolve("res").toFile(), facts.getAppResourcesDir()); + } + + static Stream invalidFacts() { + return Stream.of( + Arguments.of( + "{\n " + SCHEMA + ",\n}", + "Unexpected character '}', expected a string key at line 3, column 1"), + Arguments.of("[]", "the top level must be an object"), + Arguments.of( + object(SCHEMA, DEPENDENCIES_JSON, PROJECT, NO_PLUGINS), + "minReaderSchemaVersion must be an integer"), + Arguments.of(withMinReaderSchemaVersion("\"1\""), "minReaderSchemaVersion must be an integer"), + Arguments.of(withMinReaderSchemaVersion("0"), "minReaderSchemaVersion must be at least 1"), + Arguments.of( + object(MIN_READER, DEPENDENCIES_JSON, PROJECT, NO_PLUGINS), "schemaVersion must be an integer"), + Arguments.of(withSchemaVersion("\"1\""), "schemaVersion must be an integer"), + Arguments.of(withSchemaVersion("1.5"), "schemaVersion must be an integer"), + Arguments.of(withSchemaVersion("0"), "schemaVersion must be at least 1"), + Arguments.of( + object("\"minReaderSchemaVersion\": 3", "\"schemaVersion\": 2", DEPENDENCIES_JSON, PROJECT, NO_PLUGINS), + "minReaderSchemaVersion must not be greater than schemaVersion"), + Arguments.of(object(MIN_READER, SCHEMA, PROJECT, NO_PLUGINS), "dependenciesJson must be an object"), + Arguments.of(withField("\"dependenciesJson\": \"x\""), "dependenciesJson must be an object"), + Arguments.of(withField("\"dependenciesJson\": {}"), "dependenciesJson.sha256 must be a string"), + Arguments.of(withSha256("A".repeat(64)), "dependenciesJson.sha256 must be 64 lowercase hex digits"), + Arguments.of(withSha256("37517e5f"), "dependenciesJson.sha256 must be 64 lowercase hex digits"), + Arguments.of(withField("\"capabilities\": \"a\""), "capabilities must be an array"), + Arguments.of(withField("\"capabilities\": [\"a\", 1]"), "capabilities[1] must be a string"), + Arguments.of(object(MIN_READER, SCHEMA, DEPENDENCIES_JSON, NO_PLUGINS), "project must be an object"), + Arguments.of( + withProject("\"root\": 1, \"appDir\": \"a\", \"appResourcesDir\": \"r\""), + "project.root must be a string"), + Arguments.of( + withProject("\"root\": \".\", \"appResourcesDir\": \"r\""), + "project.appDir must be a string"), + Arguments.of( + withProject("\"root\": \".\", \"appDir\": \"a\", \"appResourcesDir\": \"\""), + "project.appResourcesDir must not be empty"), + Arguments.of(object(MIN_READER, SCHEMA, DEPENDENCIES_JSON, PROJECT), "plugins must be an array"), + Arguments.of(withPlugins(plugin("a"), "\"b\""), "plugins[1] must be an object"), + Arguments.of(withPlugins(plugin("p", "name", null)), "plugins[0].name must be a string"), + Arguments.of(withPlugins(plugin("p", "packageDir", null)), "plugins[0].packageDir must be a string"), + Arguments.of(withPlugins(plugin("p", "nativeDir", null)), "plugins[0].nativeDir must be a string"), + Arguments.of(withPlugins(plugin("p", "aarName", null)), "plugins[0].aarName must be a string"), + Arguments.of(withPlugins(plugin("p", "aarName", "\"\"")), "plugins[0].aarName must not be empty"), + Arguments.of(withPlugins(plugin("p", "aar", null)), "plugins[0].aar must be a string"), + Arguments.of( + withPlugins(plugin("p", "dependencies", null)), + "plugins[0].dependencies must be an array"), + Arguments.of( + withPlugins(plugin("p", "dependencies", "[\"a\", 1]")), + "plugins[0].dependencies[1] must be a string"), + Arguments.of(withPlugins(plugin("p", "options", "[]")), "plugins[0].options must be an object"), + Arguments.of( + withPlugins(plugin("a"), plugin("b"), plugin("a")), + "plugin 'a' is listed more than once")); + } + + @ParameterizedTest(name = "{1}") + @MethodSource("invalidFacts") + void reportsInvalidFacts(String text, String problem) { + GradleException e = assertThrows(GradleException.class, () -> parse(text)); + assertEquals("Invalid NativeScript facts file " + factsFile + ": " + problem, e.getMessage()); + } + + @Test + void refusesAFileThatNeedsANewerReaderBeforeValidatingIt() { + int needed = Facts.SUPPORTED_SCHEMA_VERSION + 1; + String text = object("\"minReaderSchemaVersion\": " + needed, "\"schemaVersion\": " + needed); + + GradleException e = assertThrows(GradleException.class, () -> parse(text)); + + assertEquals( + "The NativeScript facts file " + factsFile + " needs org.nativescript:gradle-api supporting facts" + + " schema " + needed + ", but this version of the library supports up to " + + Facts.SUPPORTED_SCHEMA_VERSION + ". Update the plugins of this app that use" + + " org.nativescript:gradle-api: any one that pins a newer version of the library is enough.", + e.getMessage()); + } + + @Test + void readsAFileThatNeedsExactlyThisReader() { + Facts facts = parse(withMinReaderSchemaVersion(String.valueOf(Facts.SUPPORTED_SCHEMA_VERSION))); + + assertEquals(projectDir.toFile(), facts.getProjectRoot()); + } + + @Test + void readReusesTheResultUntilTheContentChanges() { + byte[] a = withField("\"capabilities\": [\"a\"]").getBytes(StandardCharsets.UTF_8); + Facts first = Facts.read(factsFile, a); + assertSame(first, Facts.read(factsFile, a.clone())); + + byte[] b = withField("\"capabilities\": [\"b\"]").getBytes(StandardCharsets.UTF_8); + assertEquals(Collections.singleton("b"), Facts.read(factsFile, b).getCapabilities()); + } + + private static String plugin(String name) { + return plugin(name, null, null); + } + + /** A valid plugin entry, with {@code field} set to the JSON {@code value}, or removed if it is null. */ + private static String plugin(String name, String field, String value) { + Map fields = new LinkedHashMap<>(); + fields.put("name", "\"" + name + "\""); + fields.put("packageDir", "\"../../node_modules/" + name + "\""); + fields.put("nativeDir", "\"../../node_modules/" + name + "/platforms/android\""); + fields.put("aarName", "\"" + name + "\""); + fields.put("aar", "\"../../node_modules/" + name + "/platforms/android/" + name + ".aar\""); + fields.put("dependencies", "[]"); + if (field != null) { + if (value == null) { + fields.remove(field); + } else { + fields.put(field, value); + } + } + return fields.entrySet().stream() + .map(e -> "\"" + e.getKey() + "\": " + e.getValue()) + .collect(Collectors.joining(", ", "{", "}")); + } + + private static String plugins(String... plugins) { + return "\"plugins\": [" + String.join(", ", plugins) + "]"; + } + + private static String withMinReaderSchemaVersion(String version) { + return object("\"minReaderSchemaVersion\": " + version, SCHEMA, DEPENDENCIES_JSON, PROJECT, NO_PLUGINS); + } + + private static String withSchemaVersion(String version) { + return object(MIN_READER, "\"schemaVersion\": " + version, DEPENDENCIES_JSON, PROJECT, NO_PLUGINS); + } + + /** Valid facts with {@code field} added, or replacing the field of the same name. */ + private static String withField(String field) { + return object(MIN_READER, SCHEMA, DEPENDENCIES_JSON, field, PROJECT, NO_PLUGINS); + } + + private static String withSha256(String sha256) { + return withField("\"dependenciesJson\": {\"sha256\": \"" + sha256 + "\"}"); + } + + private static String withProject(String fields) { + return object(MIN_READER, SCHEMA, DEPENDENCIES_JSON, "\"project\": {" + fields + "}", NO_PLUGINS); + } + + private static String withPlugins(String... plugins) { + return object(MIN_READER, SCHEMA, DEPENDENCIES_JSON, PROJECT, plugins(plugins)); + } + + private static String object(String... fields) { + return "{" + String.join(", ", fields) + "}"; + } + + private Facts parse(String text) { + return Facts.parse(factsFile, text); + } +} diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/FakeInputs.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/FakeInputs.java new file mode 100644 index 0000000000..c5ab55f924 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/FakeInputs.java @@ -0,0 +1,60 @@ +package org.nativescript.gradle.internal; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +final class FakeInputs implements BuildInputs { + private final Map properties = new HashMap<>(); + private final Map environment = new HashMap<>(); + private final File rootDir; + + FakeInputs(File rootDir) { + this.rootDir = rootDir; + } + + /** Does nothing if {@code value} is null, so tables can leave inputs out. */ + FakeInputs property(String name, Object value) { + if (value != null) { + properties.put(name, value); + } + return this; + } + + FakeInputs env(String name, String value) { + if (value != null) { + environment.put(name, value); + } + return this; + } + + @Override + public Object property(String name) { + return properties.get(name); + } + + @Override + public String environmentVariable(String name) { + return environment.get(name); + } + + @Override + public File rootDir() { + return rootDir; + } + + @Override + public byte[] fileContents(File file) { + if (!file.isFile()) { + return null; + } + try { + return Files.readAllBytes(file.toPath()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/JsonTest.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/JsonTest.java new file mode 100644 index 0000000000..08c58e0cf5 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/JsonTest.java @@ -0,0 +1,158 @@ +package org.nativescript.gradle.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class JsonTest { + private static final String MIXED_512_LEVELS = "{\"a\":[".repeat(256) + "]}".repeat(256); + + static Stream validDocuments() { + return Stream.of( + Arguments.of("true", true), + Arguments.of("false", false), + Arguments.of("null", null), + Arguments.of("\"\"", ""), + Arguments.of("{ \n }", Collections.emptyMap()), + Arguments.of("[\t]", Collections.emptyList()), + Arguments.of("0", 0), + Arguments.of("-0", 0), + Arguments.of("2147483647", Integer.MAX_VALUE), + Arguments.of("-2147483648", Integer.MIN_VALUE), + Arguments.of("2147483648", 2147483648L), + Arguments.of("-2147483649", -2147483649L), + Arguments.of("9223372036854775807", Long.MAX_VALUE), + Arguments.of("-9223372036854775808", Long.MIN_VALUE), + Arguments.of("9223372036854775808", new BigInteger("9223372036854775808")), + Arguments.of("-9223372036854775809", new BigInteger("-9223372036854775809")), + Arguments.of("1.0", new BigDecimal("1.0")), + Arguments.of("-0.25", new BigDecimal("-0.25")), + Arguments.of("1e3", new BigDecimal("1e3")), + Arguments.of("3.5E+2", new BigDecimal("3.5E+2")), + Arguments.of("2e-2", new BigDecimal("2e-2")), + Arguments.of("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"", "\"\\/\b\f\n\r\t"), + Arguments.of("\"\\u00e9\\u00E9\"", "\u00e9\u00e9"), + Arguments.of("\"\\uD83D\\uDE00\"", "\uD83D\uDE00"), + Arguments.of("\"a\\u0000b\"", "a\u0000b"), + Arguments.of("\"caf\u00e9 \uD83D\uDE00 \u65e5\u672c\"", "caf\u00e9 \uD83D\uDE00 \u65e5\u672c"), + Arguments.of("\uFEFF 1 ", 1), + Arguments.of(" \t\r\n[ 1 ,\n\t2\r\n]\n ", Arrays.asList(1, 2)), + Arguments.of("{\n\t\"a\"\r\n :\t\"b\" }", Collections.singletonMap("a", "b")), + Arguments.of( + "{\"a\": [1, {\"b\": null, \"c\": [true]}], \"d\": {\"e\": {}}, \"f\": [[]]}", + map("a", Arrays.asList(1, map("b", null, "c", List.of(true))), + "d", map("e", Collections.emptyMap()), + "f", List.of(List.of())))); + } + + @ParameterizedTest + @MethodSource("validDocuments") + void parses(String text, Object expected) { + assertEquals(expected, Json.parse(text)); + } + + @Test + void keepsKeyOrderAndTheLastValueOfARepeatedKey() { + Map map = asMap(Json.parse("{\"z\": 1, \"a\": 2, \"z\": 3}")); + assertEquals(Arrays.asList("z", "a"), new ArrayList<>(map.keySet())); + assertEquals(3, map.get("z")); + } + + @Test + void resultsAreUnmodifiable() { + List list = asList(Json.parse("[[1], [], {\"k\": 1}, {}]")); + assertThrows(UnsupportedOperationException.class, () -> list.add(0)); + assertThrows(UnsupportedOperationException.class, () -> asList(list.get(1)).add(0)); + assertThrows(UnsupportedOperationException.class, () -> asMap(list.get(2)).put("x", 1)); + assertThrows(UnsupportedOperationException.class, () -> asMap(list.get(3)).put("x", 1)); + } + + @Test + void acceptsNestingOf512Levels() { + Json.parse("[".repeat(512) + "]".repeat(512)); + Json.parse(MIXED_512_LEVELS); + } + + static Stream invalidDocuments() { + return Stream.of( + Arguments.of("trailing comma in object", "{\"a\":1,}", 7, 1, 8, "expected a string key"), + Arguments.of("trailing comma in array", "[1,]", 3, 1, 4, "expected a value"), + Arguments.of("leading zero", "01", 1, 1, 2, "Leading zeros"), + Arguments.of("no digit after dot", "1.", 2, 1, 3, "after '.'"), + Arguments.of("no exponent digit after sign", "1e+", 3, 1, 4, "exponent"), + Arguments.of("lone minus", "-", 1, 1, 2, "expected a digit"), + Arguments.of("leading plus", "+1", 0, 1, 1, "expected a value"), + Arguments.of("unterminated string", "\"abc", 4, 1, 5, "Unterminated string"), + Arguments.of("unterminated after backslash", "\"abc\\", 5, 1, 6, "Unterminated string"), + Arguments.of("raw newline in string", "\"a\nb\"", 2, 1, 3, "U+000A"), + Arguments.of("invalid escape", "\"\\x\"", 2, 1, 3, "Invalid escape sequence '\\x'"), + Arguments.of("bad hex digit", "\"\\u12G4\"", 5, 1, 6, "Invalid hex digit character 'G'"), + Arguments.of("incomplete unicode escape", "\"\\u12\"", 2, 1, 3, "Incomplete \\u escape"), + Arguments.of("single quotes", "'a'", 0, 1, 1, "character '''"), + Arguments.of("NaN", "NaN", 0, 1, 1, "expected a value"), + Arguments.of("Infinity", "-Infinity", 1, 1, 2, "expected a digit"), + Arguments.of("misspelled literal", "nul1", 3, 1, 4, "expected 'null'"), + Arguments.of("trailing garbage", "{} x", 3, 1, 4, "after the JSON value"), + Arguments.of("comment", "[1] // no", 4, 1, 5, "after the JSON value"), + Arguments.of("empty input", "", 0, 1, 1, "end of input"), + Arguments.of("missing colon", "{\"a\" 1}", 5, 1, 6, "expected ':'"), + Arguments.of("unquoted key", "{a:1}", 1, 1, 2, "expected a string key"), + Arguments.of("missing comma in array", "[1 2]", 3, 1, 4, "expected ',' or ']'"), + Arguments.of("missing comma in object", "{\"a\":1 \"b\":2}", 7, 1, 8, "expected ',' or '}'"), + Arguments.of("unclosed array", "[1", 2, 1, 3, "end of input"), + Arguments.of("unclosed object", "{\"a\":1", 6, 1, 7, "end of input"), + Arguments.of("multi-line", "{\n \"a\": 1,\n \"b\": x\n}", 19, 3, 8, "character 'x'"), + Arguments.of("CRLF line ending", "[\r\n x]", 4, 2, 2, "character 'x'"), + Arguments.of("byte order mark after whitespace", " \uFEFF1", 1, 1, 2, "expected a value"), + Arguments.of("form feed", "\f1", 0, 1, 1, "character U+000C"), + Arguments.of("no-break space", "\u00a01", 0, 1, 1, "expected a value"), + Arguments.of("vertical tab", "1\u000b", 1, 1, 2, "character U+000B after the JSON value"), + Arguments.of("513 nested arrays", "[".repeat(513) + "]".repeat(513), 512, 1, 513, "Nesting deeper"), + Arguments.of("513 nested mixed", "[" + MIXED_512_LEVELS + "]", 1536, 1, 1537, "Nesting deeper")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("invalidDocuments") + void reportsWhereInvalidJsonFails( + String description, String text, int offset, int line, int column, String messagePart) { + Json.ParseException e = assertThrows(Json.ParseException.class, () -> Json.parse(text)); + assertEquals(offset, e.getOffset(), "offset"); + assertEquals(line, e.getLine(), "line"); + assertEquals(column, e.getColumn(), "column"); + assertTrue(e.getMessage().contains(messagePart), e.getMessage()); + assertTrue(e.getMessage().endsWith(" at line " + line + ", column " + column), e.getMessage()); + } + + private static Map map(Object... keysAndValues) { + Map map = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + map.put((String) keysAndValues[i], keysAndValues[i + 1]); + } + return map; + } + + @SuppressWarnings("unchecked") + private static Map asMap(Object value) { + return (Map) assertInstanceOf(Map.class, value); + } + + @SuppressWarnings("unchecked") + private static List asList(Object value) { + return (List) assertInstanceOf(List.class, value); + } +} diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/ResolutionTest.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/ResolutionTest.java new file mode 100644 index 0000000000..affd6a8ef2 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/ResolutionTest.java @@ -0,0 +1,220 @@ +package org.nativescript.gradle.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.nativescript.gradle.internal.TestFiles.installPackage; +import static org.nativescript.gradle.internal.TestFiles.plugin; +import static org.nativescript.gradle.internal.TestFiles.write; +import static org.nativescript.gradle.internal.TestFiles.writeFacts; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import org.gradle.api.GradleException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class ResolutionTest { + private static final String PLATFORMS_ANDROID_VARIABLE = "USER_PROJECT_PLATFORMS_ANDROID"; + private static final String RERUN = " Run `ns prepare android` again with the NativeScript CLI the project uses."; + + @TempDir + Path tempDir; + + /** Real path of the temp dir, which on macOS sits behind the /var symlink. */ + private Path base; + + private Path project; + private Path platformsAndroid; + private Path tempPluginRoot; + + @BeforeEach + void setUp() throws IOException { + base = tempDir.toRealPath(); + project = base.resolve("proj"); + platformsAndroid = project.resolve("platforms/android"); + tempPluginRoot = project.resolve("platforms/tempPlugin/p"); + Files.createDirectories(platformsAndroid); + Files.createDirectories(tempPluginRoot); + } + + static String noFactsMessage(Path... searched) { + StringBuilder paths = new StringBuilder(); + for (Path path : searched) { + paths.append(paths.length() == 0 ? "" : " or ").append(path.resolve(Resolution.FACTS_FILE_NAME)); + } + return "A plugin of this app uses org.nativescript:gradle-api, which needs the project to be prepared by" + + " NativeScript CLI 9.2 or newer, but there is no facts file at " + paths + + ". Update the project's CLI with `npm i -D nativescript@latest`, then run `ns prepare android`."; + } + + @ParameterizedTest(name = "{0} build") + @ValueSource(strings = {"app", "plugin"}) + void reportsMissingFacts(String build) { + FakeInputs inputs = build.equals("app") + ? appBuild() + : pluginBuild().property(PLATFORMS_ANDROID_VARIABLE, platformsAndroid.toString()); + + GradleException e = assertThrows(GradleException.class, () -> Resolution.resolve(inputs)); + + assertEquals( + build.equals("app") ? noFactsMessage(platformsAndroid) : noFactsMessage(tempPluginRoot, platformsAndroid), + e.getMessage()); + } + + // The hash recorded is that of "[]\n"; dependencies.json gets the given text plus a newline. + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + // case | facts passed with -Pnativescript.factsFile | dependencies.json | error + "hash matches | false | [] |", + "hash differs | false | [ ] | mismatch", + "dependencies.json missing | false | | missing", + "stale -Pnativescript.factsFile | true | [ ] | mismatch", + }) + void checksFactsAgainstDependenciesJson(String description, boolean explicit, String dependenciesJson, String error) + throws IOException { + Path dir = explicit ? base.resolve("explicit") : platformsAndroid; + Path dependencies = dir.resolve("dependencies.json"); + if (dependenciesJson != null) { + write(dependencies, dependenciesJson + "\n"); + } + Path facts = writeFacts( + dir.resolve(Resolution.FACTS_FILE_NAME), project, "[]", TestFiles.EMPTY_DEPENDENCIES_JSON_SHA256); + FakeInputs inputs = appBuild().property(Resolution.FACTS_FILE_PROPERTY, explicit ? facts.toString() : null); + + if (error == null) { + assertEquals(facts.toFile(), Resolution.resolve(inputs).getFacts().getFile()); + return; + } + GradleException e = assertThrows(GradleException.class, () -> Resolution.resolve(inputs)); + String expected = error.equals("missing") + ? "There is no " + dependencies + " next to the NativeScript facts file " + facts + "." + RERUN + : "The NativeScript facts file " + facts + " does not match " + dependencies + + ": a different NativeScript CLI rewrote dependencies.json after the facts file was written." + + RERUN; + assertEquals(expected, e.getMessage()); + } + + @Test + void explicitFactsFileIsResolvedAgainstRootDirAndWins() throws IOException { + writeFacts(platformsAndroid.resolve(Resolution.FACTS_FILE_NAME), project, "[]"); + Path explicit = writeFacts(platformsAndroid.resolve("sub/facts.json"), project, "[]"); + + Resolution resolution = + Resolution.resolve(appBuild().property(Resolution.FACTS_FILE_PROPERTY, "sub/facts.json")); + + assertEquals(explicit.toFile(), resolution.getFacts().getFile()); + } + + @Test + void reportsMissingExplicitFactsFile() throws IOException { + writeFacts(platformsAndroid.resolve(Resolution.FACTS_FILE_NAME), project, "[]"); + Path missing = base.resolve("missing.json"); + + GradleException e = assertThrows( + GradleException.class, + () -> Resolution.resolve(appBuild().property(Resolution.FACTS_FILE_PROPERTY, missing.toString()))); + assertEquals("-Pnativescript.factsFile points to " + missing + ", which does not exist.", e.getMessage()); + } + + @ParameterizedTest(name = "{0} build, {1}") + @CsvSource({"plugin, property, true", "plugin, environment variable, true", "app, environment variable, false"}) + void looksForFactsInUserProjectPlatformsAndroid(String build, String source, boolean found) throws IOException { + Path elsewhere = base.resolve("elsewhere"); + Path facts = writeFacts(elsewhere.resolve(Resolution.FACTS_FILE_NAME), project, "[]"); + FakeInputs inputs = build.equals("plugin") ? pluginBuild() : appBuild(); + if (source.equals("property")) { + inputs.property(PLATFORMS_ANDROID_VARIABLE, elsewhere.toString()); + } else { + inputs.env(PLATFORMS_ANDROID_VARIABLE, elsewhere.toString()); + } + + if (found) { + assertEquals(facts.toFile(), Resolution.resolve(inputs).getFacts().getFile()); + } else { + GradleException e = assertThrows(GradleException.class, () -> Resolution.resolve(inputs)); + assertEquals(noFactsMessage(platformsAndroid), e.getMessage()); + } + } + + @Test + void reportsInvalidFacts() throws IOException { + Path factsFile = platformsAndroid.resolve(Resolution.FACTS_FILE_NAME); + write(factsFile, "{}"); + + GradleException e = assertThrows(GradleException.class, () -> Resolution.resolve(appBuild())); + assertTrue(e.getMessage().startsWith("Invalid NativeScript facts file " + factsFile), e.getMessage()); + } + + @Test + void findsOnlyListedPlugins() throws IOException { + Files.createDirectories(installPackage(project, "listed").resolve("platforms/android")); + Path unlisted = installPackage(project, "@s/unlisted"); + Files.createDirectories(unlisted.resolve("platforms/android")); + writeFacts( + platformsAndroid.resolve(Resolution.FACTS_FILE_NAME), + project, + "[" + plugin("listed", "../../vendor/listed") + "]"); + + Resolution resolution = Resolution.resolve(appBuild()); + + PluginData listed = resolution.findPlugin("listed"); + assertEquals(project.resolve("vendor/listed/platforms/android").toFile(), listed.getNativeDir()); + assertEquals(project.resolve("vendor/listed").toFile(), resolution.findPackage("listed")); + assertNull(resolution.findPlugin("@s/unlisted"), "an installed package the CLI does not list"); + assertEquals(unlisted.toFile(), resolution.findPackage("@s/unlisted")); + assertNull(resolution.findPlugin("not-installed")); + } + + @Test + void findsPackagesLikeNode() throws IOException { + Path hoisted = installPackage(base, "hoisted"); + installPackage(base, "dup"); + Path near = installPackage(project, "dup"); + Files.createDirectories(project.resolve("node_modules/no-package-json")); + writeFacts(platformsAndroid.resolve(Resolution.FACTS_FILE_NAME), project, "[]"); + + Resolution resolution = Resolution.resolve(appBuild()); + + assertEquals(hoisted.toFile(), resolution.findPackage("hoisted")); + assertEquals(near.toFile(), resolution.findPackage("dup")); + assertNull(resolution.findPackage("no-package-json")); + } + + @Test + void lookupStartsAtFactsProjectRoot() throws IOException { + Path otherProject = Files.createDirectories(base.resolve("other")); + Path pkg = installPackage(otherProject, "elsewhere"); + writeFacts(platformsAndroid.resolve(Resolution.FACTS_FILE_NAME), otherProject, "[]"); + + assertEquals(pkg.toFile(), Resolution.resolve(appBuild()).findPackage("elsewhere")); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"../x", "@scope", "@scope/", "a/b", "@a/b/c", "a\\b", "..", ".", "@/x", "@s/..", "c:x"}) + void rejectsInvalidNames(String name) throws IOException { + writeFacts(platformsAndroid.resolve(Resolution.FACTS_FILE_NAME), project, "[]"); + Resolution resolution = Resolution.resolve(appBuild()); + + assertThrows(IllegalArgumentException.class, () -> resolution.findPlugin(name)); + assertThrows(IllegalArgumentException.class, () -> resolution.findPackage(name)); + } + + private FakeInputs appBuild() { + return new FakeInputs(platformsAndroid.toFile()); + } + + private FakeInputs pluginBuild() { + return new FakeInputs(tempPluginRoot.toFile()) + .property("tempBuild", "true") + .property("PLUGIN_NAME", "@scope/p"); + } +} diff --git a/gradle-api/src/test/java/org/nativescript/gradle/internal/TestFiles.java b/gradle-api/src/test/java/org/nativescript/gradle/internal/TestFiles.java new file mode 100644 index 0000000000..d48e231847 --- /dev/null +++ b/gradle-api/src/test/java/org/nativescript/gradle/internal/TestFiles.java @@ -0,0 +1,49 @@ +package org.nativescript.gradle.internal; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +final class TestFiles { + /** The SHA-256 of {@code "[]\n"}. */ + static final String EMPTY_DEPENDENCIES_JSON_SHA256 = "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570"; + + private TestFiles() {} + + /** {@link #writeFacts(Path, Path, String, String)} with a matching dependencies.json next to the file. */ + static Path writeFacts(Path file, Path root, String plugins) throws IOException { + write(file.resolveSibling("dependencies.json"), "[]\n"); + return writeFacts(file, root, plugins, EMPTY_DEPENDENCIES_JSON_SHA256); + } + + /** Facts for the project at {@code root}, whose app is in {@code src}. */ + static Path writeFacts(Path file, Path root, String plugins, String dependenciesJsonSha256) throws IOException { + String rootPath = root.toString().replace('\\', '/'); + write(file, "{\"minReaderSchemaVersion\": 1, \"schemaVersion\": 1, " + + "\"dependenciesJson\": {\"sha256\": \"" + dependenciesJsonSha256 + "\"}, " + + "\"capabilities\": [\"some.capability\"], " + + "\"project\": {\"root\": \"" + rootPath + "\", \"appDir\": \"" + rootPath + "/src\"," + + " \"appResourcesDir\": \"" + rootPath + "/src/App_Resources\"}," + + " \"plugins\": " + plugins + "}"); + return file; + } + + /** A plugin entry whose package is at {@code packageDir}, relative to the facts file. */ + static String plugin(String name, String packageDir) { + return "{\"name\": \"" + name + "\", \"packageDir\": \"" + packageDir + "\"," + + " \"nativeDir\": \"" + packageDir + "/platforms/android\", \"aarName\": \"" + name.replaceAll("\\W", "_") + + "\", \"aar\": \"" + packageDir + "/platforms/android/x.aar\", \"dependencies\": []}"; + } + + static Path installPackage(Path dir, String name) throws IOException { + Path pkg = dir.resolve("node_modules").resolve(name); + write(pkg.resolve("package.json"), "{\"name\": \"" + name + "\"}"); + return pkg; + } + + static void write(Path file, String text) throws IOException { + Files.createDirectories(file.getParent()); + Files.write(file, text.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/gradle-api/src/test/resources/facts/v2-unknown-fields.json b/gradle-api/src/test/resources/facts/v2-unknown-fields.json new file mode 100644 index 0000000000..986e3f6c4c --- /dev/null +++ b/gradle-api/src/test/resources/facts/v2-unknown-fields.json @@ -0,0 +1,25 @@ +{ + "schemaVersion": 2, + "minReaderSchemaVersion": 1, + "dependenciesJson": { "sha256": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570" }, + "capabilities": ["some.future.capability"], + "someFutureSection": { "nested": [1, 2, { "deep": true }], "flag": null }, + "project": { + "root": "../..", + "appDir": "../../app", + "appResourcesDir": "../../app/App_Resources", + "futureField": "ignored" + }, + "plugins": [ + { + "name": "nativescript-plugin", + "packageDir": "../../node_modules/nativescript-plugin", + "nativeDir": "../../node_modules/nativescript-plugin/platforms/android", + "aarName": "nativescript_plugin", + "aar": "../../node_modules/nativescript-plugin/platforms/android/nativescript_plugin.aar", + "dependencies": [], + "options": { "someOption": ["a", "b"] }, + "futureField": 3.5e2 + } + ] +} diff --git a/vendor/gradle-plugin/build.gradle b/vendor/gradle-plugin/build.gradle index 1f46258d5f..bf42fd2048 100644 --- a/vendor/gradle-plugin/build.gradle +++ b/vendor/gradle-plugin/build.gradle @@ -130,6 +130,15 @@ buildscript { } +// Only the dependencies {} and repositories {} blocks of the plugin's include.gradle are copied +// into this build, so its `apply plugin: "org.nativescript.api"` line never runs here. Those blocks +// can use the library only if it is applied here, whenever a buildscript.gradle put it on the +// classpath. +try { + apply plugin: Class.forName("org.nativescript.gradle.NativeScriptPlugin", true, buildscript.classLoader) +} catch (ClassNotFoundException ignored) { +} + def pluginDependencies allprojects { From cd61584e5aedf512ad0dfba98ab77ea0dd10bb6b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 10:17:57 -0300 Subject: [PATCH 2/9] feat(android): Gradle facts file and opt-in plugin builds in platforms - `ns prepare android` writes platforms/android/nativescript-gradle.json right after dependencies.json: the project's root, app and App_Resources dirs and, for every native plugin, its package dir, native dir, aar name and location and native dependencies, with paths relative to the file and the hash of dependencies.json. It is only rewritten when its content changes, and is passed as -Pnativescript.factsFile to app and plugin Gradle builds. org.nativescript:gradle-api reads it. - `android.pluginBuildLocation` in nativescript.config: "node_modules" (the default) keeps today's behaviour; "platforms" copies each native plugin's platforms/android and package.json into platforms/android/.ns-plugins, builds its aar and migrates include.gradle there, and points dependencies.json at the copies, so node_modules is never written to. The copy is incremental and keeps upstream mtimes. Aars the CLI built for a plugin under another of its aar names are left out of the copy, and an aar that differs from the CLI's build under that name is left out without failing prepare; prebuilt-only plugins are copied as they are. Any other value fails prepare. Switching back to "node_modules" removes .ns-plugins. - @nativescript/core and its native dependencies are prepared before other plugins, so plugins can compile against core's aar. - A plugin whose copy changed stays marked for a rebuild until its aar build succeeds, and each plugin file is hashed once per prepare. --- lib/bootstrap.ts | 5 + lib/constants.ts | 2 + lib/definitions/android-plugin-migrator.d.ts | 57 ++ lib/definitions/files-hash-service.d.ts | 19 +- lib/definitions/gradle-facts.d.ts | 39 + lib/definitions/project.d.ts | 14 + lib/services/android-plugin-build-service.ts | 73 +- lib/services/android-project-service.ts | 375 +++++++- .../android/android-plugin-mirror-service.ts | 191 ++++ .../android/gradle-build-args-service.ts | 32 +- lib/services/android/gradle-facts.ts | 91 ++ lib/services/native-file-hashes-memo.ts | 24 + lib/services/plugins-service.ts | 41 +- package-lock.json | 59 ++ package.json | 1 + test/plugins-service.ts | 32 +- test/services/android-gradle-facts.ts | 869 ++++++++++++++++++ test/services/android-plugin-build-service.ts | 81 ++ test/services/android-project-service.ts | 14 +- .../android/android-plugin-mirror-service.ts | 230 +++++ .../android/gradle-build-args-service.ts | 47 + .../gradle-api-include-gradle-extraction.ts | 42 + test/stubs.ts | 5 + 23 files changed, 2270 insertions(+), 73 deletions(-) create mode 100644 lib/definitions/gradle-facts.d.ts create mode 100644 lib/services/android/android-plugin-mirror-service.ts create mode 100644 lib/services/android/gradle-facts.ts create mode 100644 lib/services/native-file-hashes-memo.ts create mode 100644 test/services/android-gradle-facts.ts create mode 100644 test/services/android/android-plugin-mirror-service.ts create mode 100644 test/services/gradle-api-include-gradle-extraction.ts diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 154a325910..08d77b06f0 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -48,6 +48,10 @@ injector.require( "gradleBuildArgsService", "./services/android/gradle-build-args-service", ); +injector.require( + "androidPluginMirrorService", + "./services/android/android-plugin-mirror-service", +); injector.require( "androidBundleToolService", "./services/android/android-bundle-tool-service", @@ -653,6 +657,7 @@ injector.requirePublic( ); injector.require("filesHashService", "./services/files-hash-service"); +injector.require("nativeFileHashesMemo", "./services/native-file-hashes-memo"); injector.require("logParserService", "./services/log-parser-service"); injector.require( "iOSDebuggerPortService", diff --git a/lib/constants.ts b/lib/constants.ts index 7420893fab..6a595c714c 100644 --- a/lib/constants.ts +++ b/lib/constants.ts @@ -73,6 +73,8 @@ export const CONFIG_FILE_NAME_DISPLAY = "nativescript.config.(js|ts)"; export const CONFIG_FILE_NAME_JS = "nativescript.config.js"; export const CONFIG_FILE_NAME_TS = "nativescript.config.ts"; export const DEPENDENCIES_JSON_NAME = "dependencies.json"; +export const GRADLE_FACTS_FILE_NAME = "nativescript-gradle.json"; +export const ANDROID_PLUGIN_MIRRORS_DIR_NAME = ".ns-plugins"; export const APK_EXTENSION_NAME = ".apk"; export const AAB_EXTENSION_NAME = ".aab"; export const APKS_EXTENSION_NAME = ".apks"; diff --git a/lib/definitions/android-plugin-migrator.d.ts b/lib/definitions/android-plugin-migrator.d.ts index be3acf3a7d..d80383e5de 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -1,5 +1,6 @@ import { IAndroidToolsInfoData } from "../declarations"; import { IProjectDir } from "../common/declarations"; +import { AndroidPluginBuildLocation } from "./project"; interface IPluginBuildOptions extends IAndroidBuildOptions { projectDir?: string; @@ -8,6 +9,15 @@ interface IPluginBuildOptions extends IAndroidBuildOptions { * Defaults to the plugin's short name. */ aarName?: string; + /** + * When `"platforms"`, `aarOutputDir` is a CLI-owned copy of the plugin's + * platforms/android. Absent means `"node_modules"`. + */ + pluginBuildLocation?: AndroidPluginBuildLocation; + /** + * The project's nativescript-gradle.json, passed to the plugin's Gradle build when it exists. + */ + gradleFactsFile?: string; } interface IAndroidBuildOptions { @@ -32,6 +42,43 @@ interface IAndroidPluginBuildService { * or still holds one the CLI built under another of its candidate names. */ hasOutdatedAar(options: IPluginBuildOptions): boolean; + /** + * Aars in `dir` (default: `aarOutputDir`) that the CLI built for this plugin + * under another of its candidate aar names. Only meaningful for a plugin + * with aar sources; aars the package ships are not included. + */ + getStaleAars(options: IPluginBuildOptions, dir?: string): IStaleAar[]; +} + +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; +} + +interface IAndroidPluginMirror { + pluginName: string; + /** + * The installed npm package. + */ + packageDir: string; + mirrorDir: string; + /** + * Paths relative to the package's platforms/android that are not copied. + */ + excludedNativeFiles?: string[]; +} + +interface IAndroidPluginMirrorService { + /** + * Brings `/` in line with each plugin's package.json and + * platforms/android, and removes mirrors of plugins not in `mirrors`. + * @returns The names of the plugins whose mirror changed. + */ + syncMirrors(mirrorsRoot: string, mirrors: IAndroidPluginMirror[]): string[]; } /** @@ -64,4 +111,14 @@ interface IBuildAndroidPluginData extends Partial { * Optional custom Gradle arguments. */ gradleArgs?: string; + + /** + * The project's `android.pluginBuildLocation`. Absent means `"node_modules"`. + */ + pluginBuildLocation?: AndroidPluginBuildLocation; + + /** + * Absolute path of the project's nativescript-gradle.json, when it exists. + */ + gradleFactsFile?: string; } diff --git a/lib/definitions/files-hash-service.d.ts b/lib/definitions/files-hash-service.d.ts index b52dc9ada8..a494b2208f 100644 --- a/lib/definitions/files-hash-service.d.ts +++ b/lib/definitions/files-hash-service.d.ts @@ -10,7 +10,7 @@ interface IFilesHashService { * A map with key file's path and value - file's hash */ generateHashesForProject( - platformData: IPlatformData + platformData: IPlatformData, ): Promise; /** * Generates hashes for all prepared files (all files from app folder under platforms folder) @@ -21,15 +21,26 @@ interface IFilesHashService { */ saveHashesForProject( platformData: IPlatformData, - hashesFileDirectory: string + hashesFileDirectory: string, ): Promise; saveHashes(hashes: IStringDictionary, hashesFileDirectory: string): void; getChanges( files: string[], - oldHashes: IStringDictionary + oldHashes: IStringDictionary, ): Promise; hasChangesInShasums( oldHashes: IStringDictionary, - newHashes: IStringDictionary + newHashes: IStringDictionary, ): boolean; } + +/** + * sha1 hashes of plugins' native files computed earlier in the same prepare, + * so a later step does not read the same files again. Cleared when a prepare + * starts; each hash is served once. + */ +interface INativeFileHashesMemo { + clear(): void; + remember(filePath: string, sha1: string): void; + take(filePath: string): string | undefined; +} diff --git a/lib/definitions/gradle-facts.d.ts b/lib/definitions/gradle-facts.d.ts new file mode 100644 index 0000000000..b4d711d6a1 --- /dev/null +++ b/lib/definitions/gradle-facts.d.ts @@ -0,0 +1,39 @@ +/** + * Contents of platforms/android/nativescript-gradle.json, read by + * org.nativescript:gradle-api. Mirrors gradle-api/schema/nativescript-gradle.schema.json: + * fields are only ever added, and every path is relative to the file's + * directory with forward slashes. + */ +export interface INativeScriptGradleFacts { + schemaVersion: number; + /** + * The lowest schemaVersion a reader must understand to use this file. + */ + minReaderSchemaVersion: number; + cli?: { version?: string }; + runtime?: { name?: string; version?: string }; + capabilities?: string[]; + /** + * Identifies the dependencies.json written together with these facts, so a + * reader can tell when a CLI that does not write facts has replaced it since. + */ + dependenciesJson: { sha256: string }; + project: INativeScriptGradleFactsProject; + plugins: INativeScriptGradleFactsPlugin[]; +} + +export interface INativeScriptGradleFactsProject { + root: string; + appDir: string; + appResourcesDir: string; +} + +export interface INativeScriptGradleFactsPlugin { + name: string; + packageDir: string; + nativeDir: string; + aarName: string; + aar: string; + dependencies: string[]; + options?: Record; +} diff --git a/lib/definitions/project.d.ts b/lib/definitions/project.d.ts index 53c0d2d10d..032b27e3e5 100644 --- a/lib/definitions/project.d.ts +++ b/lib/definitions/project.d.ts @@ -124,6 +124,7 @@ export interface IOSLocalSPMPackage extends IOSSPMPackageBase { export type IOSSPMPackage = IOSRemoteSPMPackage | IOSLocalSPMPackage; export type BundlerType = "webpack" | "rspack" | "vite"; +export type AndroidPluginBuildLocation = "node_modules" | "platforms"; interface INsConfigIOS extends INsConfigPlaform { discardUncaughtJsExceptions?: boolean; @@ -179,6 +180,19 @@ interface INsConfigAndroid extends INsConfigPlaform { * Custom runtime package name */ runtimePackageName?: string; + + /** + * Where the CLI builds plugins' native Android code. + * + * - `"node_modules"` (default): each plugin's aar is built into its own + * `platforms/android` folder inside node_modules. + * - `"platforms"`: node_modules is left untouched. Each plugin's Android files + * are copied to `platforms/android/.ns-plugins/` and its aar is built there. + * + * `"platforms"` is opt-in while plugins adopt `org.nativescript:gradle-api`, + * and is expected to become the default in a future major version. + */ + pluginBuildLocation?: AndroidPluginBuildLocation; } interface INsConfigHooks { diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index c557ac410c..43bda0dad9 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -27,6 +27,7 @@ import { IAndroidPluginBuildService, IPluginBuildOptions, IBuildAndroidPluginData, + IStaleAar, } from "../definitions/android-plugin-migrator"; import { IFileSystem, @@ -44,15 +45,6 @@ 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"); @@ -243,18 +235,26 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { const hasAarSources = this.hasAarSources(options.platformsAndroidDirPath); const aarName = this.getAarName(options); const pluginTempDir = path.join(options.tempPluginDirPath, aarName); - const staleAars = - options.aarName && hasAarSources - ? this.getStaleAars(options, aarName) - : []; + const inMirror = options.pluginBuildLocation === "platforms"; + const findStaleAars = (dir?: string) => + options.aarName && hasAarSources ? this.getStaleAars(options, dir) : []; + const staleAars = findStaleAars(); + // In a mirror the leftovers are in the copy, but the sources are read from + // the package, whose leftovers the mirror leaves out. + const staleSourceAars = inMirror + ? findStaleAars(options.platformsAndroidDirPath) + : staleAars; const pluginSourceFileHashesInfo = await this.getSourceFilesHashes( options.platformsAndroidDirPath, [ path.join(options.platformsAndroidDirPath, `${aarName}.aar`), - ...staleAars.map((staleAar) => staleAar.aarPath), + ...staleSourceAars.map((staleAar) => staleAar.aarPath), ], ); - this.ensureStaleAarsAreBuildOutputs(options.pluginName, staleAars); + // The mirror is CLI-owned, so nothing in it needs the user's decision. + if (!inMirror) { + this.ensureStaleAarsAreBuildOutputs(options.pluginName, staleAars); + } const shouldBuildAar = await this.shouldBuildAar({ hasAarSources, @@ -283,21 +283,30 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { options.pluginName, aarName, ); - await this.buildPlugin({ + const pluginBuildData: IBuildAndroidPluginData = { gradlePath: options.gradlePath, gradleArgs: options.gradleArgs, pluginDir: pluginTempDir, pluginName: options.pluginName, projectDir: options.projectDir, - }); - this.$watchIgnoreListService.addFileToIgnoreList( - path.join(options.aarOutputDir, `${aarName}.aar`), - ); + }; + if (inMirror) { + pluginBuildData.pluginBuildLocation = "platforms"; + } + if (options.gradleFactsFile && this.$fs.exists(options.gradleFactsFile)) { + pluginBuildData.gradleFactsFile = path.resolve(options.gradleFactsFile); + } + await this.buildPlugin(pluginBuildData); + if (!inMirror) { + this.$watchIgnoreListService.addFileToIgnoreList( + path.join(options.aarOutputDir, `${aarName}.aar`), + ); + } this.copyAar(aarName, pluginTempDir, options.aarOutputDir); this.writePluginHashInfo(pluginSourceFileHashesInfo, pluginTempDir); } - this.removeStaleAars(staleAars); + this.removeStaleAars(staleAars, inMirror); return shouldBuildAar; } @@ -319,7 +328,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { return ( !this.$fs.exists( path.join(this.getAarOutputDir(options), `${aarName}.aar`), - ) || this.getStaleAars(options, aarName).length > 0 + ) || this.getStaleAars(options).length > 0 ); } @@ -336,15 +345,15 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { * every build. A package may ship a scope-qualified name itself, so that one * only counts when its temp project was built for this plugin. */ - private getStaleAars( + public getStaleAars( options: IPluginBuildOptions, - aarName: string, + dir: string = this.getAarOutputDir(options), ): IStaleAar[] { - const aarOutputDir = this.getAarOutputDir(options); + const aarName = this.getAarName(options); const shortName = getShortPluginName(options.pluginName); const staleAars: IStaleAar[] = []; for (const candidate of getCandidateAarNames(options.pluginName)) { - const aarPath = path.join(aarOutputDir, `${candidate}.aar`); + const aarPath = path.join(dir, `${candidate}.aar`); if (candidate === aarName || !this.$fs.exists(aarPath)) { continue; } @@ -412,9 +421,11 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { * duplicate its classes. Only call once the aar under the current name * exists, so a failed build leaves the plugin with its previous aar. */ - private removeStaleAars(staleAars: IStaleAar[]): void { + private removeStaleAars(staleAars: IStaleAar[], inMirror: boolean): void { for (const { aarPath } of staleAars) { - this.$watchIgnoreListService.addFileToIgnoreList(aarPath); + if (!inMirror) { + this.$watchIgnoreListService.addFileToIgnoreList(aarPath); + } this.$logger.trace(`Removing stale plugin aar ${aarPath}`); this.$fs.deleteFile(aarPath); } @@ -956,6 +967,12 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { `-PappResourcesPath=${this.$projectData.getAppResourcesDirectoryPath()}`, ]; + if (pluginBuildSettings.gradleFactsFile) { + localArgs.push( + `-Pnativescript.factsFile=${pluginBuildSettings.gradleFactsFile}`, + ); + } + if (pluginBuildSettings.gradleArgs) { localArgs.push(pluginBuildSettings.gradleArgs); } diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index d44dcf8f9d..b7a789adb6 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -6,9 +6,10 @@ 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 { getUniqueAarNames, hook } from "../common/helpers"; +import { getShortPluginName, getUniqueAarNames, hook } from "../common/helpers"; import { performanceLog } from ".././common/decorators"; import { + AndroidPluginBuildLocation, IProjectData, IProjectDataService, IValidatePlatformOutput, @@ -38,9 +39,18 @@ import { } from "../common/declarations"; import { IAndroidPluginBuildService, + IAndroidPluginMirrorService, IPluginBuildOptions, } from "../definitions/android-plugin-migrator"; -import { IFilesHashService } from "../definitions/files-hash-service"; +import { + createGradleFacts, + getGradleFactsFilePath, + serializeGradleFacts, +} from "./android/gradle-facts"; +import { + IFilesHashService, + INativeFileHashesMemo, +} from "../definitions/files-hash-service"; import { IGradleCommandService, IGradleBuildService, @@ -55,6 +65,34 @@ interface NativeDependency { dependencies: string[]; } +interface IAndroidPluginLocation { + /** + * For a plugin without aar sources, the name its aar would get if it had + * some: such plugins take no part in making aar names unique. + */ + aarName: string; + packageDir: string; + /** + * Where Gradle reads the plugin's Android files and where its aar is built to. + */ + nativeDir: string; + /** + * Set when plugins are built in platforms/android. + */ + mirrorDir?: string; +} + +interface IAndroidPluginLayout { + key: string; + platformDir: string; + pluginBuildLocation: AndroidPluginBuildLocation; + plugins: Map; + /** + * Plugins whose mirror changed since they were last prepared. + */ + changedMirrors: Set; +} + // // we sort the native dependencies topologically to make sure they are processed in the right order // native dependenciess need to be sorted so the deepst dependencies are built before it's parents @@ -130,6 +168,31 @@ function topologicalSortNativeDependencies( return sortedDeps; } +/** + * Plugins may compile against @nativescript/core's aar without declaring a + * dependency on it (`nativescript.plugin("@nativescript/core").artifacts`), so + * core and its own native dependencies are prepared before everything else. + * Keeps the topological order within both groups. + */ +function withCoreFirst(sortedDeps: NativeDependency[]): NativeDependency[] { + const byName = new Map(sortedDeps.map((dep) => [dep.name, dep])); + const coreClosure = new Set(); + const visit = (name: string) => { + if (coreClosure.has(name) || !byName.has(name)) { + return; + } + + coreClosure.add(name); + byName.get(name).dependencies.forEach(visit); + }; + visit(constants.SCOPED_TNS_CORE_MODULES); + + return [ + ...sortedDeps.filter((dep) => coreClosure.has(dep.name)), + ...sortedDeps.filter((dep) => !coreClosure.has(dep.name)), + ]; +} + export class AndroidProjectService extends projectServiceBaseLib.PlatformProjectServiceBase implements IPlatformProjectService @@ -157,6 +220,9 @@ export class AndroidProjectService private $gradleBuildService: IGradleBuildService, private $analyticsService: IAnalyticsService, private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder, + private $androidPluginMirrorService: IAndroidPluginMirrorService, + private $staticConfig: Config.IStaticConfig, + private $nativeFileHashesMemo: INativeFileHashesMemo, ) { super($fs, $projectDataService); } @@ -166,6 +232,8 @@ export class AndroidProjectService names: Map; } = null; + private pluginLayout: IAndroidPluginLayout = null; + private _platformData: IPlatformData = null; public getPlatformData(projectData: IProjectData): IPlatformData { if (!projectData && !this._platformData) { @@ -701,37 +769,66 @@ export class AndroidProjectService pluginData, AndroidProjectService.ANDROID_PLATFORM_NAME, ); - if (this.$fs.exists(pluginPlatformsFolderPath)) { - const options = this.getPluginBuildOptions( - pluginData, - pluginPlatformsFolderPath, - projectData, + if (!this.$fs.exists(pluginPlatformsFolderPath)) { + return; + } + + const layout = this.getPluginLayout(projectData); + const plugin = layout.plugins.get(pluginData.name); + if (!plugin && layout.pluginBuildLocation === "platforms") { + // Gradle only reads the plugins listed in dependencies.json, and only + // those get a copy in platforms/android to build into. + this.$logger.trace( + `Skipping ${pluginData.name}: it does not declare Android support in its package.json.`, ); + return; + } - if (await this.$androidPluginBuildService.buildAar(options)) { - this.$logger.info(`Built aar for ${options.pluginName}`); - } + const options = this.getPluginBuildOptions( + pluginData, + pluginPlatformsFolderPath, + projectData, + layout, + ); - this.$androidPluginBuildService.migrateIncludeGradle(options); + if (await this.$androidPluginBuildService.buildAar(options)) { + this.$logger.info(`Built aar for ${options.pluginName}`); } + layout.changedMirrors.delete(pluginData.name); + + this.$androidPluginBuildService.migrateIncludeGradle({ + ...options, + platformsAndroidDirPath: options.aarOutputDir, + }); } public shouldRepreparePlugin( pluginData: IPluginData, projectData: IProjectData, ): boolean { - if (!this.getPluginAarNames(projectData).has(pluginData.name)) { + const pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath( + pluginData, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ); + const layout = this.getPluginLayout(projectData); + if (layout.changedMirrors.has(pluginData.name)) { + return true; + } + + if ( + !this.getPluginAarNames(projectData).has(pluginData.name) || + (layout.pluginBuildLocation === "platforms" && + !layout.plugins.has(pluginData.name)) + ) { return false; } return this.$androidPluginBuildService.hasOutdatedAar( this.getPluginBuildOptions( pluginData, - this.getPluginPlatformsFolderPath( - pluginData, - AndroidProjectService.ANDROID_PLATFORM_NAME, - ), + pluginPlatformsFolderPath, projectData, + layout, ), ); } @@ -740,6 +837,7 @@ export class AndroidProjectService pluginData: IPluginData, pluginPlatformsFolderPath: string, projectData: IProjectData, + layout: IAndroidPluginLayout, ): IPluginBuildOptions { const options: IPluginBuildOptions = { gradlePath: this.$options.gradlePath, @@ -747,8 +845,12 @@ export class AndroidProjectService projectDir: projectData.projectDir, pluginName: pluginData.name, platformsAndroidDirPath: pluginPlatformsFolderPath, - aarOutputDir: pluginPlatformsFolderPath, - tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), + aarOutputDir: + layout.pluginBuildLocation === "platforms" + ? layout.plugins.get(pluginData.name).nativeDir + : pluginPlatformsFolderPath, + tempPluginDirPath: this.getTempPluginDirPath(projectData), + gradleFactsFile: getGradleFactsFilePath(layout.platformDir), }; const aarName = this.getPluginAarNames(projectData).get(pluginData.name); @@ -756,9 +858,184 @@ export class AndroidProjectService options.aarName = aarName; } + if (layout.pluginBuildLocation === "platforms") { + options.pluginBuildLocation = "platforms"; + } + return options; } + private getAndroidPlatformDir(projectData: IProjectData): string { + return this.$options.hostProjectPath + ? this.$options.hostProjectPath + : path.join( + projectData.platformsDir, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ); + } + + private getPluginBuildLocation( + projectData: IProjectData, + ): AndroidPluginBuildLocation { + const location = + projectData.nsConfig?.android?.pluginBuildLocation ?? "node_modules"; + if (location !== "node_modules" && location !== "platforms") { + this.$errors.fail( + 'Invalid value %s for android.pluginBuildLocation in nativescript.config: use "node_modules" or "platforms".', + JSON.stringify(location), + ); + } + + return location; + } + + private getPluginLayoutKey(projectData: IProjectData): string { + return JSON.stringify([ + projectData.projectDir, + this.getAndroidPlatformDir(projectData), + this.getPluginBuildLocation(projectData), + ]); + } + + /** + * Normally computed by beforePrepareAllPlugins; computed here from the + * project's production dependencies when a plugin is prepared without it. + */ + private getPluginLayout(projectData: IProjectData): IAndroidPluginLayout { + if ( + !this.pluginLayout || + this.pluginLayout.key !== this.getPluginLayoutKey(projectData) + ) { + const dependencies = this.filterUniqueDependencies( + this.$nodeModulesDependenciesBuilder.getProductionDependencies( + projectData.projectDir, + projectData.ignoredDependencies, + ), + ); + if (this.pluginAarNames?.projectDir !== projectData.projectDir) { + this.setPluginAarNames(projectData, dependencies); + } + + this.pluginLayout = this.createPluginLayout( + projectData, + dependencies.filter(AndroidProjectService.isNativeAndroidDependency), + ); + } + + return this.pluginLayout; + } + + private createPluginLayout( + projectData: IProjectData, + nativeDependencyData: IDependencyData[], + ): IAndroidPluginLayout { + this.$nativeFileHashesMemo.clear(); + const platformDir = this.getAndroidPlatformDir(projectData); + const pluginBuildLocation = this.getPluginBuildLocation(projectData); + const mirrorsRoot = path.join( + platformDir, + constants.ANDROID_PLUGIN_MIRRORS_DIR_NAME, + ); + + const aarNames = this.getPluginAarNames(projectData); + // Every mirrored plugin needs its own directory, including those without + // aar sources, which have no aar name. + let mirrorNames: Map; + if (pluginBuildLocation === "platforms") { + try { + mirrorNames = getUniqueAarNames( + nativeDependencyData.map((dep) => dep.name), + ); + } catch (err) { + this.$errors.fail(err.message); + } + } + + const plugins = new Map(); + for (const dep of nativeDependencyData) { + const mirrorDir = mirrorNames + ? path.join(mirrorsRoot, mirrorNames.get(dep.name)) + : undefined; + plugins.set(dep.name, { + aarName: aarNames.get(dep.name) ?? getShortPluginName(dep.name), + packageDir: dep.directory, + mirrorDir, + nativeDir: path.join( + mirrorDir ?? dep.directory, + constants.PLATFORMS_DIR_NAME, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ), + }); + } + + const key = this.getPluginLayoutKey(projectData); + const changedMirrors = new Set(); + if (pluginBuildLocation === "platforms") { + // A sync reports a mirror as changed only once, so a plugin whose build + // failed keeps its marker from the previous layout. + if (this.pluginLayout?.key === key) { + for (const name of this.pluginLayout.changedMirrors) { + if (plugins.has(name)) { + changedMirrors.add(name); + } + } + } + + const tempPluginDirPath = this.getTempPluginDirPath(projectData); + const synced = this.$androidPluginMirrorService.syncMirrors( + mirrorsRoot, + nativeDependencyData.map((dep) => { + const upstreamNativeDir = path.join( + dep.directory, + constants.PLATFORMS_DIR_NAME, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ); + // Only plugins with aar sources have an aar name, and only those can + // have leftovers: a prebuilt-only plugin keeps every file it ships. + const staleAars = aarNames.has(dep.name) + ? this.$androidPluginBuildService.getStaleAars({ + pluginName: dep.name, + aarName: aarNames.get(dep.name), + platformsAndroidDirPath: upstreamNativeDir, + aarOutputDir: upstreamNativeDir, + tempPluginDirPath, + }) + : []; + for (const { aarPath } of staleAars) { + this.$logger.trace( + `Not copying ${aarPath} into the plugin mirror: it is an aar the CLI built for ${dep.name} under another name.`, + ); + } + return { + pluginName: dep.name, + packageDir: dep.directory, + mirrorDir: plugins.get(dep.name).mirrorDir, + excludedNativeFiles: staleAars.map((staleAar) => + path.basename(staleAar.aarPath), + ), + }; + }), + ); + for (const name of synced) { + changedMirrors.add(name); + } + } else if (this.$fs.exists(mirrorsRoot)) { + this.$fs.deleteDirectory(mirrorsRoot); + } + + return { + key, + platformDir, + pluginBuildLocation, + plugins, + changedMirrors, + }; + } + + private getTempPluginDirPath(projectData: IProjectData): string { + return path.join(projectData.platformsDir, "tempPlugin"); + } + /** * Normally computed by beforePrepareAllPlugins; computed here from the * project's production dependencies when a plugin is prepared without it. @@ -862,12 +1139,7 @@ export class AndroidProjectService projectData: IProjectData, dependencies: IDependencyData[], ): IDependencyData[] { - const platformDir = this.$options.hostProjectPath - ? this.$options.hostProjectPath - : path.join( - projectData.platformsDir, - AndroidProjectService.ANDROID_PLATFORM_NAME, - ); + const platformDir = this.getAndroidPlatformDir(projectData); const dependenciesJsonPath = path.join( platformDir, constants.DEPENDENCIES_JSON_NAME, @@ -876,11 +1148,17 @@ export class AndroidProjectService AndroidProjectService.isNativeAndroidDependency, ); + const layout = this.createPluginLayout(projectData, nativeDependencyData); + this.pluginLayout = layout; + let nativeDependencies = nativeDependencyData.map( ({ name, directory, dependencies }) => { return { name, - directory: path.relative(platformDir, directory), + directory: path.relative( + platformDir, + layout.plugins.get(name).mirrorDir ?? directory, + ), dependencies: dependencies.filter((dep) => { // filter out transient dependencies that don't have native dependencies return ( @@ -895,16 +1173,59 @@ export class AndroidProjectService nativeDependencies = topologicalSortNativeDependencies(nativeDependencies); const jsonContent = JSON.stringify(nativeDependencies, null, 4); this.$fs.writeFile(dependenciesJsonPath, jsonContent); + this.writeGradleFacts(projectData, layout, nativeDependencies, jsonContent); // we sort all the dependencies to respect the topological sorting of the native dependencies + const buildOrder = withCoreFirst(nativeDependencies); return dependencies.sort(function (a, b) { return ( - nativeDependencies.findIndex((n) => n.name === a.name) - - nativeDependencies.findIndex((n) => n.name === b.name) + buildOrder.findIndex((n) => n.name === a.name) - + buildOrder.findIndex((n) => n.name === b.name) ); }); } + private writeGradleFacts( + projectData: IProjectData, + layout: IAndroidPluginLayout, + sortedNativeDependencies: NativeDependency[], + dependenciesJsonContent: string, + ): void { + const runtimePackage = this.$projectDataService.getRuntimePackage( + projectData.projectDir, + constants.PlatformTypes.android, + ); + const facts = createGradleFacts({ + factsDir: path.resolve(layout.platformDir), + cliVersion: this.$staticConfig.version, + runtime: { name: runtimePackage?.name, version: runtimePackage?.version }, + projectDir: path.resolve(projectData.projectDir), + appDir: path.resolve(projectData.getAppDirectoryPath()), + appResourcesDir: path.resolve(projectData.getAppResourcesDirectoryPath()), + dependenciesJsonContent, + plugins: sortedNativeDependencies.map((dep) => { + const plugin = layout.plugins.get(dep.name); + return { + name: dep.name, + packageDir: path.resolve(plugin.packageDir), + nativeDir: path.resolve(plugin.nativeDir), + aarName: plugin.aarName, + dependencies: dep.dependencies, + }; + }), + }); + + // Rewritten only on change so Gradle tasks that take it as an input stay up to date. + const factsPath = getGradleFactsFilePath(layout.platformDir); + const content = serializeGradleFacts(facts); + if ( + !this.$fs.exists(factsPath) || + this.$fs.readText(factsPath) !== content + ) { + this.$fs.writeFile(factsPath, content); + } + } + private static isNativeAndroidDependency({ nativescript, }: IDependencyData): boolean { diff --git a/lib/services/android/android-plugin-mirror-service.ts b/lib/services/android/android-plugin-mirror-service.ts new file mode 100644 index 0000000000..7c698d1ec3 --- /dev/null +++ b/lib/services/android/android-plugin-mirror-service.ts @@ -0,0 +1,191 @@ +import * as path from "path"; +import { createHash } from "crypto"; +import { IFileSystem } from "../../common/declarations"; +import { injector } from "../../common/yok"; +import { + IAndroidPluginMirror, + IAndroidPluginMirrorService, +} from "../../definitions/android-plugin-migrator"; +import { PACKAGE_JSON_FILE_NAME, PLATFORMS_DIR_NAME } from "../../constants"; +import { INativeFileHashesMemo } from "../../definitions/files-hash-service"; + +interface IMirroredFile { + sha1: string; +} + +interface IMirrorManifest { + files: { [relativePath: string]: IMirroredFile }; +} + +const MIRROR_MANIFEST_FILE_NAME = ".ns-mirror.json"; +const NATIVE_DIR = `${PLATFORMS_DIR_NAME}/android`; + +/** + * Keeps CLI-owned copies of plugins' Android files so prepare and build never + * write into node_modules. + * + * The manifest records the upstream content of every copied file. Mirror + * files are compared against it rather than against their own content because + * the CLI rewrites some of them (include.gradle) and adds its own (the built + * aar). Copies keep the upstream mtime, and files whose upstream content is + * unchanged are never rewritten, so Gradle's path and mtime based inputs stay + * up to date across syncs. + */ +export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { + constructor( + private $fs: IFileSystem, + private $logger: ILogger, + private $nativeFileHashesMemo: INativeFileHashesMemo, + ) {} + + public syncMirrors( + mirrorsRoot: string, + mirrors: IAndroidPluginMirror[], + ): string[] { + this.removeUnknownMirrors(mirrorsRoot, mirrors); + + return mirrors + .filter((mirror) => this.syncMirror(mirror)) + .map((mirror) => mirror.pluginName); + } + + private removeUnknownMirrors( + mirrorsRoot: string, + mirrors: IAndroidPluginMirror[], + ): void { + if (!this.$fs.exists(mirrorsRoot)) { + return; + } + + const knownDirs = new Set( + mirrors.map((mirror) => path.resolve(mirror.mirrorDir)), + ); + for (const entry of this.$fs.readDirectory(mirrorsRoot)) { + const entryPath = path.join(mirrorsRoot, entry); + if (!knownDirs.has(path.resolve(entryPath))) { + this.$logger.trace(`Removing unused plugin mirror ${entryPath}`); + this.$fs.deleteDirectory(entryPath); + } + } + } + + private syncMirror(mirror: IAndroidPluginMirror): boolean { + const manifestPath = path.join(mirror.mirrorDir, MIRROR_MANIFEST_FILE_NAME); + const previous = this.readManifest(manifestPath); + const next: IMirrorManifest = { files: {} }; + const excluded = new Set( + (mirror.excludedNativeFiles ?? []).map( + (file) => `${NATIVE_DIR}/${toPosix(file)}`, + ), + ); + const upstreamFiles = this.getUpstreamFiles(mirror.packageDir).filter( + (relativePath) => !excluded.has(relativePath), + ); + let changed = false; + + // Before copying, so a path that turned from a file into a directory (or + // back) upstream is free when its replacement is copied. + const upstream = new Set(upstreamFiles); + for (const relativePath of Object.keys(previous.files)) { + if (!upstream.has(relativePath)) { + this.deleteMirroredFile(mirror.mirrorDir, relativePath); + changed = true; + } + } + + for (const relativePath of upstreamFiles) { + const source = path.join(mirror.packageDir, relativePath); + const destination = path.join(mirror.mirrorDir, relativePath); + const known = previous.files[relativePath]; + // Always hashed: some installers give every file the same fixed mtime, so a + // same-size edit (a version bump in include.gradle) would look unchanged. + const sha1 = this.getSha1(source); + if (relativePath !== PACKAGE_JSON_FILE_NAME) { + this.$nativeFileHashesMemo.remember(source, sha1); + } + + if (!known || known.sha1 !== sha1 || !this.$fs.exists(destination)) { + const stat = this.$fs.getFsStats(source); + this.$fs.deleteFile(destination); + this.$fs.copyFile(source, destination); + // Read-only stores (pnpm, Nix, Bazel) ship 0444 files; the CLI rewrites + // some mirrored files and replaces others on the next sync. + this.$fs.chmod(destination, stat.mode | 0o200); + this.$fs.utimes(destination, stat.atime, stat.mtime); + changed = true; + } + + next.files[relativePath] = { sha1 }; + } + + const manifestContent = JSON.stringify(next, null, "\t"); + if ( + !this.$fs.exists(manifestPath) || + this.$fs.readText(manifestPath) !== manifestContent + ) { + this.$fs.writeFile(manifestPath, manifestContent); + } + + return changed; + } + + private getUpstreamFiles(packageDir: string): string[] { + const files: string[] = []; + if (this.$fs.exists(path.join(packageDir, PACKAGE_JSON_FILE_NAME))) { + files.push(PACKAGE_JSON_FILE_NAME); + } + + const nativeDir = path.join(packageDir, NATIVE_DIR); + if (this.$fs.exists(nativeDir)) { + for (const file of this.$fs.enumerateFilesInDirectorySync(nativeDir)) { + files.push(toPosix(path.relative(packageDir, file))); + } + } + + return files.sort(); + } + + private deleteMirroredFile(mirrorDir: string, relativePath: string): void { + const filePath = path.join(mirrorDir, relativePath); + this.$fs.deleteFile(filePath); + + const root = path.resolve(mirrorDir); + let dir = path.dirname(path.resolve(filePath)); + while ( + dir !== root && + dir.startsWith(root) && + this.$fs.exists(dir) && + this.$fs.isEmptyDir(dir) + ) { + this.$fs.deleteDirectory(dir); + dir = path.dirname(dir); + } + } + + private readManifest(manifestPath: string): IMirrorManifest { + try { + if (this.$fs.exists(manifestPath)) { + const manifest = this.$fs.readJson(manifestPath); + if (manifest && manifest.files) { + return manifest; + } + } + } catch (err) { + this.$logger.trace( + `Ignoring unreadable plugin mirror manifest ${manifestPath}: ${err}`, + ); + } + + return { files: {} }; + } + + private getSha1(filePath: string): string { + return createHash("sha1").update(this.$fs.readFile(filePath)).digest("hex"); + } +} + +function toPosix(filePath: string): string { + return filePath.split(path.sep).join("/"); +} + +injector.register("androidPluginMirrorService", AndroidPluginMirrorService); diff --git a/lib/services/android/gradle-build-args-service.ts b/lib/services/android/gradle-build-args-service.ts index eef6461fd8..9dcdb15356 100644 --- a/lib/services/android/gradle-build-args-service.ts +++ b/lib/services/android/gradle-build-args-service.ts @@ -2,9 +2,16 @@ import * as path from "path"; import { Configurations } from "../../common/constants"; import { IGradleBuildArgsService } from "../../definitions/gradle"; import { IAndroidBuildData } from "../../definitions/build"; -import { IHooksService, IAnalyticsService } from "../../common/declarations"; +import { + IHooksService, + IAnalyticsService, + IFileSystem, +} from "../../common/declarations"; import { injector } from "../../common/yok"; -import { IProjectDataService } from "../../definitions/project"; +import { IProjectData, IProjectDataService } from "../../definitions/project"; +import { IOptions } from "../../declarations"; +import { PlatformTypes } from "../../constants"; +import { getGradleFactsFilePath } from "./gradle-facts"; export class GradleBuildArgsService implements IGradleBuildArgsService { constructor( @@ -13,6 +20,8 @@ export class GradleBuildArgsService implements IGradleBuildArgsService { private $staticConfig: Config.IStaticConfig, private $projectDataService: IProjectDataService, private $logger: ILogger, + private $fs: IFileSystem, + private $options: IOptions, ) {} public async getBuildTaskArgs( @@ -55,6 +64,12 @@ export class GradleBuildArgsService implements IGradleBuildArgsService { `-PappPath=${projectData.getAppDirectoryPath()}`, `-PappResourcesPath=${projectData.getAppResourcesDirectoryPath()}`, ); + + const factsFile = this.getGradleFactsFile(projectData); + if (factsFile) { + args.push(`-Pnativescript.factsFile=${factsFile}`); + } + if (buildData.gradleArgs) { args.push(buildData.gradleArgs); } @@ -72,6 +87,19 @@ export class GradleBuildArgsService implements IGradleBuildArgsService { return args; } + private getGradleFactsFile(projectData: IProjectData): string | null { + const platformDir = + this.$options.hostProjectPath || + (projectData.platformsDir && + path.join(projectData.platformsDir, PlatformTypes.android)); + if (!platformDir) { + return null; + } + + const factsFile = getGradleFactsFilePath(platformDir); + return this.$fs.exists(factsFile) ? factsFile : null; + } + private getBuildLoggingArgs(): string[] { const args = []; diff --git a/lib/services/android/gradle-facts.ts b/lib/services/android/gradle-facts.ts new file mode 100644 index 0000000000..2e9619053b --- /dev/null +++ b/lib/services/android/gradle-facts.ts @@ -0,0 +1,91 @@ +import * as path from "path"; +import { createHash } from "crypto"; +import { GRADLE_FACTS_FILE_NAME } from "../../constants"; +import { + INativeScriptGradleFacts, + INativeScriptGradleFactsPlugin, +} from "../../definitions/gradle-facts"; + +export const GRADLE_FACTS_SCHEMA_VERSION = 1; +export const GRADLE_FACTS_MIN_READER_SCHEMA_VERSION = 1; + +export interface IGradleFactsPluginInput { + name: string; + packageDir: string; + nativeDir: string; + aarName: string; + dependencies: string[]; +} + +export interface IGradleFactsInput { + /** + * Directory of the facts file; every path in the facts is relative to it. + */ + factsDir: string; + cliVersion: string; + runtime: { name?: string; version?: string }; + projectDir: string; + appDir: string; + appResourcesDir: string; + /** + * The exact text written to dependencies.json alongside these facts. + */ + dependenciesJsonContent: string; + /** + * In dependency order. + */ + plugins: IGradleFactsPluginInput[]; +} + +export function toFactsPath(factsDir: string, target: string): string { + return path.relative(factsDir, target).split(path.sep).join("/") || "."; +} + +export function createGradleFacts( + input: IGradleFactsInput, +): INativeScriptGradleFacts { + const rel = (target: string) => toFactsPath(input.factsDir, target); + + const runtime: INativeScriptGradleFacts["runtime"] = {}; + if (input.runtime?.name) { + runtime.name = input.runtime.name; + } + if (input.runtime?.version) { + runtime.version = input.runtime.version; + } + + return { + schemaVersion: GRADLE_FACTS_SCHEMA_VERSION, + minReaderSchemaVersion: GRADLE_FACTS_MIN_READER_SCHEMA_VERSION, + cli: { version: input.cliVersion }, + runtime, + capabilities: [], + dependenciesJson: { + sha256: createHash("sha256") + .update(input.dependenciesJsonContent, "utf8") + .digest("hex"), + }, + project: { + root: rel(input.projectDir), + appDir: rel(input.appDir), + appResourcesDir: rel(input.appResourcesDir), + }, + plugins: input.plugins.map((plugin): INativeScriptGradleFactsPlugin => ({ + name: plugin.name, + packageDir: rel(plugin.packageDir), + nativeDir: rel(plugin.nativeDir), + aarName: plugin.aarName, + aar: rel(path.join(plugin.nativeDir, `${plugin.aarName}.aar`)), + dependencies: plugin.dependencies, + options: {}, + })), + }; +} + +export function serializeGradleFacts(facts: INativeScriptGradleFacts): string { + return JSON.stringify(facts, null, "\t") + "\n"; +} + +export function getGradleFactsFilePath(androidPlatformDir: string): string { + return path.resolve(androidPlatformDir, GRADLE_FACTS_FILE_NAME); +} diff --git a/lib/services/native-file-hashes-memo.ts b/lib/services/native-file-hashes-memo.ts new file mode 100644 index 0000000000..bc896d9734 --- /dev/null +++ b/lib/services/native-file-hashes-memo.ts @@ -0,0 +1,24 @@ +import * as path from "path"; +import { injector } from "../common/yok"; +import { INativeFileHashesMemo } from "../definitions/files-hash-service"; + +export class NativeFileHashesMemo implements INativeFileHashesMemo { + private hashes = new Map(); + + public clear(): void { + this.hashes.clear(); + } + + public remember(filePath: string, sha1: string): void { + this.hashes.set(path.resolve(filePath), sha1); + } + + public take(filePath: string): string | undefined { + const key = path.resolve(filePath); + const sha1 = this.hashes.get(key); + this.hashes.delete(key); + return sha1; + } +} + +injector.register("nativeFileHashesMemo", NativeFileHashesMemo); diff --git a/lib/services/plugins-service.ts b/lib/services/plugins-service.ts index 43c843e59a..0ba8c663f9 100644 --- a/lib/services/plugins-service.ts +++ b/lib/services/plugins-service.ts @@ -28,7 +28,10 @@ import { IDictionary, IStringDictionary, } from "../common/declarations"; -import { IFilesHashService } from "../definitions/files-hash-service"; +import { + IFilesHashService, + INativeFileHashesMemo, +} from "../definitions/files-hash-service"; import * as _ from "lodash"; import { IInjector } from "../common/definitions/yok"; import { injector } from "../common/yok"; @@ -81,6 +84,7 @@ export class PluginsService implements IPluginsService { private $injector: IInjector, private $mobileHelper: Mobile.IMobileHelper, private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder, + private $nativeFileHashesMemo: INativeFileHashesMemo, ) {} public async add(plugin: string, projectData: IProjectData): Promise { @@ -254,6 +258,7 @@ export class PluginsService implements IPluginsService { const oldPluginNativeHashes = allPluginsNativeHashes[pluginData.name]; const currentPluginNativeHashes = await this.getPluginNativeHashes( pluginPlatformsFolderPath, + { useMemo: true }, ); const needsReprepare = @@ -877,17 +882,39 @@ This framework comes from ${dependencyName} plugin, which is installed multiple return isValid; } + /** + * `useMemo` only before the platform prepares the plugin: preparing can + * write into the plugin's platforms folder. + */ private async getPluginNativeHashes( pluginPlatformsDir: string, + opts?: { useMemo?: boolean }, ): Promise { - let data: IStringDictionary = {}; - if (this.$fs.exists(pluginPlatformsDir)) { - const pluginNativeDataFiles = - this.$fs.enumerateFilesInDirectorySync(pluginPlatformsDir); - data = await this.$filesHashService.generateHashes(pluginNativeDataFiles); + if (!this.$fs.exists(pluginPlatformsDir)) { + return {}; } - return data; + const pluginNativeDataFiles = + this.$fs.enumerateFilesInDirectorySync(pluginPlatformsDir); + if (!opts?.useMemo) { + return this.$filesHashService.generateHashes(pluginNativeDataFiles); + } + + const data: IStringDictionary = {}; + const unknownFiles: string[] = []; + for (const file of pluginNativeDataFiles) { + const sha1 = this.$nativeFileHashesMemo.take(file); + if (sha1 === undefined) { + unknownFiles.push(file); + } else { + data[file] = sha1; + } + } + + return { + ...data, + ...(await this.$filesHashService.generateHashes(unknownFiles)), + }; } private getAllPluginsNativeHashes( diff --git a/package-lock.json b/package-lock.json index ad930f06ed..b5138b21a2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -96,6 +96,7 @@ "@types/xml2js": "0.4.14", "@types/yargs": "17.0.33", "@types/yazl": "^3.3.0", + "ajv": "8.20.0", "braces": ">=3.0.3", "chai": "5.3.3", "chai-as-promised": "8.0.2", @@ -2136,6 +2137,23 @@ "node": ">= 14" } }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/ansi-escapes": { "version": "7.3.0", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", @@ -3657,6 +3675,13 @@ "node": ">=8.0.0" } }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, "node_modules/fast-glob": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", @@ -3673,6 +3698,23 @@ "node": ">=8.6.0" } }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fastq": { "version": "1.20.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", @@ -4704,6 +4746,13 @@ "node": "^20.17.0 || >=22.9.0" } }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/json-stringify-nice": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/json-stringify-nice/-/json-stringify-nice-1.1.4.tgz", @@ -6827,6 +6876,16 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve": { "version": "1.1.7", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", diff --git a/package.json b/package.json index 41f0ff4676..bc0ac5b452 100644 --- a/package.json +++ b/package.json @@ -122,6 +122,7 @@ "@types/xml2js": "0.4.14", "@types/yargs": "17.0.33", "@types/yazl": "^3.3.0", + "ajv": "8.20.0", "braces": ">=3.0.3", "chai": "5.3.3", "chai-as-promised": "8.0.2", diff --git a/test/plugins-service.ts b/test/plugins-service.ts index edf62e97b0..d0ebec693c 100644 --- a/test/plugins-service.ts +++ b/test/plugins-service.ts @@ -19,6 +19,7 @@ import { ProjectDataService } from "../lib/services/project-data-service"; import { ProjectFilesManager } from "../lib/common/services/project-files-manager"; import { ResourceLoader } from "../lib/common/resource-loader"; import { PluginsService } from "../lib/services/plugins-service"; +import { NativeFileHashesMemo } from "../lib/services/native-file-hashes-memo"; import { addPluginCommandDefinition } from "../lib/commands/plugin/add-plugin"; import { registerCommand } from "../lib/common/services/command-definition-adapter"; import { MessagesService } from "../lib/common/services/messages-service"; @@ -180,6 +181,8 @@ function createTestInjector() { "androidPluginBuildService", stubs.AndroidPluginBuildServiceStub, ); + testInjector.register("androidPluginMirrorService", {}); + testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); testInjector.register("analyticsSettingsService", {}); testInjector.register( "androidResourcesMigrationService", @@ -701,6 +704,7 @@ describe("Plugins service", () => { pluginsService: null, isPreparePluginNativeCodeCalled: false, dataPassedToWriteJson: null, + hashedFiles: [], }; const unitTestsInjector = new Yok(); @@ -733,11 +737,13 @@ describe("Plugins service", () => { oldPluginNativeHashes: IStringDictionary, currentPluginNativeHashes: IStringDictionary, ) => !!opts.hasChangesInShasums, - generateHashes: async (files: string[]): Promise => - testData.isPreparePluginNativeCodeCalled && - opts.pluginHashesAfterPrepare + generateHashes: async (files: string[]): Promise => { + testData.hashedFiles.push(files); + return testData.isPreparePluginNativeCodeCalled && + opts.pluginHashesAfterPrepare ? opts.pluginHashesAfterPrepare - : pluginHashes, + : pluginHashes; + }, }); unitTestsInjector.register("fs", { @@ -773,10 +779,12 @@ describe("Plugins service", () => { ); unitTestsInjector.register("nodeModulesDependenciesBuilder", {}); unitTestsInjector.register("tempService", stubs.TempServiceStub); + unitTestsInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); const pluginsService: PluginsService = unitTestsInjector.resolve(PluginsService); testData.pluginsService = pluginsService; + testData.memo = unitTestsInjector.resolve("nativeFileHashesMemo"); testData.pluginData = samplePluginData; return testData; }; @@ -830,6 +838,21 @@ describe("Plugins service", () => { }); }); + it("reuses hashes remembered earlier in the prepare only before preparing the plugin", async () => { + const testData = setupTest({ hasPluginPlatformsDir: true }); + testData.memo.remember("some_file", "remembered"); + + await testData.pluginsService.preparePluginNativeCode({ + pluginData: testData.pluginData, + platform, + projectData, + }); + + assert.isTrue(testData.isPreparePluginNativeCodeCalled); + assert.deepStrictEqual(testData.hashedFiles, [[], ["some_file"]]); + assert.isUndefined(testData.memo.take("some_file")); + }); + it("does not prepare the files when plugin has platforms dir and files have not changed since then", async () => { const testData = setupTest({ hasChangesInShasums: false, @@ -866,6 +889,7 @@ describe("Plugins service", () => { ); unitTestsInjector.register("nodeModulesDependenciesBuilder", {}); unitTestsInjector.register("tempService", stubs.TempServiceStub); + unitTestsInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); return unitTestsInjector; }; diff --git a/test/services/android-gradle-facts.ts b/test/services/android-gradle-facts.ts new file mode 100644 index 0000000000..6c82a6302b --- /dev/null +++ b/test/services/android-gradle-facts.ts @@ -0,0 +1,869 @@ +import { assert } from "chai"; +import * as path from "path"; +import { mkdtempSync, readFileSync, realpathSync, statSync } from "fs"; +import { tmpdir } from "os"; +import { createHash } from "crypto"; +import Ajv2020, { ValidateFunction } from "ajv/dist/2020"; +import { Yok } from "../../lib/common/yok"; +import { FileSystem } from "../../lib/common/file-system"; +import { AndroidProjectService } from "../../lib/services/android-project-service"; +import { AndroidPluginMirrorService } from "../../lib/services/android/android-plugin-mirror-service"; +import { AndroidPluginBuildService } from "../../lib/services/android-plugin-build-service"; +import { NativeFileHashesMemo } from "../../lib/services/native-file-hashes-memo"; +import { IFileSystem } from "../../lib/common/declarations"; +import { IDependencyData } from "../../lib/declarations"; +import { IPluginData } from "../../lib/definitions/plugins"; +import { IProjectData } from "../../lib/definitions/project"; +import { + IAndroidPluginBuildService, + IPluginBuildOptions, +} from "../../lib/definitions/android-plugin-migrator"; +import { INativeFileHashesMemo } from "../../lib/definitions/files-hash-service"; +import { INativeScriptGradleFacts } from "../../lib/definitions/gradle-facts"; +import * as stubs from "../stubs"; + +const schemaPath = path.resolve( + __dirname, + "../../../gradle-api/schema/nativescript-gradle.schema.json", +); + +interface IFixturePlugin { + name: string; + dependencies?: string[]; + nativeFiles?: { [relativePath: string]: string }; + native?: boolean; +} + +describe("android plugin layout and Gradle facts", () => { + let fs: IFileSystem; + let service: AndroidProjectService; + let projectDir: string; + let platformDir: string; + let dependencies: IDependencyData[]; + let buildAarCalls: IPluginBuildOptions[]; + let migrateIncludeGradleCalls: IPluginBuildOptions[]; + let outdatedAar: boolean; + let buildAarError: Error; + let memo: INativeFileHashesMemo; + + const validateFacts = (() => { + let validate: ValidateFunction; + return (facts: unknown) => { + if (!validate) { + const ajv = new Ajv2020({ allErrors: true }); + validate = ajv.compile(JSON.parse(readFileSync(schemaPath, "utf8"))); + } + const valid = validate(facts); + assert.isTrue(valid, JSON.stringify(validate.errors, null, 2)); + }; + })(); + + function createProjectData(pluginBuildLocation?: unknown): IProjectData { + return ({ + projectDir, + platformsDir: path.join(projectDir, "platforms"), + nsConfig: + pluginBuildLocation === undefined + ? {} + : { android: { pluginBuildLocation } }, + ignoredDependencies: [], + getAppDirectoryPath: () => path.join(projectDir, "src"), + getAppResourcesDirectoryPath: () => + path.join(projectDir, "App_Resources"), + }); + } + + function addPlugin(plugin: IFixturePlugin): IDependencyData { + const directory = path.join(projectDir, "node_modules", plugin.name); + const nativescript = + plugin.native === false ? {} : { platforms: { android: "8.0.0" } }; + fs.writeJson(path.join(directory, "package.json"), { + name: plugin.name, + version: "1.0.0", + nativescript, + }); + for (const [file, content] of Object.entries(plugin.nativeFiles ?? {})) { + fs.writeFile( + path.join(directory, "platforms", "android", ...file.split("/")), + content, + ); + } + + const dependency = { + name: plugin.name, + directory, + depth: 0, + version: "1.0.0", + nativescript, + dependencies: plugin.dependencies ?? [], + }; + dependencies.push(dependency); + return dependency; + } + + 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), + }); + } + + const readFacts = (): INativeScriptGradleFacts => + fs.readJson(path.join(platformDir, "nativescript-gradle.json")); + const readDependenciesJson = () => + fs.readText(path.join(platformDir, "dependencies.json")); + const dependenciesJsonSha256 = () => + createHash("sha256") + .update(readFileSync(path.join(platformDir, "dependencies.json"))) + .digest("hex"); + + beforeEach(() => { + projectDir = realpathSync( + mkdtempSync(path.join(tmpdir(), "gradle-facts-")), + ); + platformDir = path.join(projectDir, "platforms", "android"); + dependencies = []; + buildAarCalls = []; + migrateIncludeGradleCalls = []; + outdatedAar = false; + buildAarError = null; + + const injector = new Yok(); + injector.register("injector", injector); + injector.register("fs", FileSystem); + injector.register("logger", stubs.LoggerStub); + injector.register("errors", stubs.ErrorsStub); + injector.register("options", {}); + injector.register("staticConfig", { version: "9.9.9" }); + injector.register("projectDataService", { + getRuntimePackage: () => ({ + name: "@nativescript/android", + version: "9.0.0", + }), + }); + injector.register("nodeModulesDependenciesBuilder", { + getProductionDependencies: () => dependencies, + }); + injector.register("androidPluginBuildService", { + buildAar: async (options: IPluginBuildOptions) => { + buildAarCalls.push(options); + if (buildAarError) { + throw buildAarError; + } + return false; + }, + migrateIncludeGradle: (options: IPluginBuildOptions) => { + migrateIncludeGradleCalls.push(options); + return false; + }, + hasOutdatedAar: () => outdatedAar, + hasAarSources: (platformsAndroidDirPath: string) => + (( + injector.resolve("realAndroidPluginBuildService") + )).hasAarSources(platformsAndroidDirPath), + getStaleAars: (options: IPluginBuildOptions, dir?: string) => + (( + injector.resolve("realAndroidPluginBuildService") + )).getStaleAars(options, dir), + }); + injector.register( + "realAndroidPluginBuildService", + AndroidPluginBuildService, + ); + injector.register("nativeFileHashesMemo", NativeFileHashesMemo); + injector.register("androidPluginMirrorService", AndroidPluginMirrorService); + for (const unused of [ + "childProcess", + "hostInfo", + "packageManager", + "projectData", + "hooksService", + "watchIgnoreListService", + "androidToolsInfo", + "devicePlatformsConstants", + "platformEnvironmentRequirements", + "androidResourcesMigrationService", + "filesHashService", + "gradleCommandService", + "gradleBuildService", + "analyticsService", + ]) { + injector.register(unused, {}); + } + injector.register("androidProjectService", AndroidProjectService); + + fs = injector.resolve("fs"); + memo = injector.resolve("nativeFileHashesMemo"); + service = injector.resolve("androidProjectService"); + }); + + function addFixturePlugins() { + addPlugin({ + name: "@nativescript/core", + nativeFiles: { "include.gradle": "android {}" }, + }); + addPlugin({ + name: "@foo/plugin-x", + dependencies: ["@nativescript/core", "lodash"], + nativeFiles: { + "AndroidManifest.xml": "", + "libs/x.jar": "jar", + }, + }); + addPlugin({ + name: "@bar/plugin-x", + nativeFiles: { "res/values/strings.xml": "" }, + }); + addPlugin({ name: "lodash", native: false }); + } + + describe("default mode", () => { + it("writes the same dependencies.json as before", async () => { + addPlugin({ + name: "nativescript-plugin", + dependencies: ["@nativescript/core", "lodash"], + nativeFiles: { "AndroidManifest.xml": "" }, + }); + addPlugin({ + name: "@nativescript/core", + nativeFiles: { "include.gradle": "android {}" }, + }); + 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( + readDependenciesJson(), + JSON.stringify( + [ + { + name: "@nativescript/core", + directory: relative("@nativescript/core"), + dependencies: [], + }, + { + name: "nativescript-plugin", + directory: relative("nativescript-plugin"), + dependencies: ["@nativescript/core"], + }, + ], + null, + 4, + ), + ); + assert.isFalse(fs.exists(path.join(platformDir, ".ns-plugins"))); + }); + + it("writes facts that point at the packages and match the schema", async () => { + addFixturePlugins(); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + const facts = readFacts(); + validateFacts(facts); + assert.deepStrictEqual(Object.keys(facts), [ + "schemaVersion", + "minReaderSchemaVersion", + "cli", + "runtime", + "capabilities", + "dependenciesJson", + "project", + "plugins", + ]); + assert.deepStrictEqual(facts, { + schemaVersion: 1, + minReaderSchemaVersion: 1, + cli: { version: "9.9.9" }, + runtime: { name: "@nativescript/android", version: "9.0.0" }, + capabilities: [], + dependenciesJson: { sha256: dependenciesJsonSha256() }, + project: { + root: "../..", + appDir: "../../src", + appResourcesDir: "../../App_Resources", + }, + plugins: [ + { + name: "@nativescript/core", + packageDir: "../../node_modules/@nativescript/core", + nativeDir: + "../../node_modules/@nativescript/core/platforms/android", + aarName: "core", + aar: "../../node_modules/@nativescript/core/platforms/android/core.aar", + dependencies: [], + options: {}, + }, + { + name: "@foo/plugin-x", + packageDir: "../../node_modules/@foo/plugin-x", + nativeDir: "../../node_modules/@foo/plugin-x/platforms/android", + aarName: "foo_plugin_x", + aar: "../../node_modules/@foo/plugin-x/platforms/android/foo_plugin_x.aar", + dependencies: ["@nativescript/core"], + options: {}, + }, + { + name: "@bar/plugin-x", + packageDir: "../../node_modules/@bar/plugin-x", + nativeDir: "../../node_modules/@bar/plugin-x/platforms/android", + aarName: "bar_plugin_x", + aar: "../../node_modules/@bar/plugin-x/platforms/android/bar_plugin_x.aar", + dependencies: [], + options: {}, + }, + ], + }); + assert.deepStrictEqual( + JSON.parse(readDependenciesJson()).map((dep: any) => dep.name), + facts.plugins.map((plugin) => plugin.name), + ); + }); + + it("does not rewrite unchanged facts", async () => { + addFixturePlugins(); + const factsPath = path.join(platformDir, "nativescript-gradle.json"); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + fs.utimes(factsPath, new Date(1_000_000), new Date(1_000_000)); + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + assert.equal(statSync(factsPath).mtime.getTime(), 1_000_000); + }); + + it("builds each plugin into its own package under its unique aar name", async () => { + addFixturePlugins(); + const projectData = createProjectData(); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + + const nativeDir = path.join( + projectDir, + "node_modules", + "@foo", + "plugin-x", + "platforms", + "android", + ); + assert.deepStrictEqual(buildAarCalls, [ + { + gradlePath: undefined, + gradleArgs: undefined, + projectDir, + pluginName: "@foo/plugin-x", + platformsAndroidDirPath: nativeDir, + aarOutputDir: nativeDir, + tempPluginDirPath: path.join(projectDir, "platforms", "tempPlugin"), + gradleFactsFile: path.join(platformDir, "nativescript-gradle.json"), + aarName: "foo_plugin_x", + }, + ]); + assert.equal( + migrateIncludeGradleCalls[0].platformsAndroidDirPath, + nativeDir, + ); + }); + + it("works out the aar names when plugins are prepared on their own", async () => { + addFixturePlugins(); + + 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 () => { + addFixturePlugins(); + 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 when two plugins cannot get distinct aar names", async () => { + const manifest = { "AndroidManifest.xml": "" }; + addPlugin({ name: "@foo/plugin-x", nativeFiles: manifest }); + addPlugin({ name: "@foo/plugin_x", nativeFiles: manifest }); + + await assert.isRejected( + service.beforePrepareAllPlugins(createProjectData(), dependencies), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + }); + + it("gives a plugin without sources to build its short name, which clashes with nothing", async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { "AndroidManifest.xml": "" }, + }); + addPlugin({ + name: "@bar/plugin-x", + nativeFiles: { "plugin_x.aar": "shipped" }, + }); + const projectData = createProjectData(); + + await service.beforePrepareAllPlugins(projectData, dependencies); + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + + const facts = readFacts(); + validateFacts(facts); + assert.deepStrictEqual( + Object.fromEntries( + facts.plugins.map((plugin) => [plugin.name, plugin.aarName]), + ), + { "@foo/plugin-x": "plugin_x", "@bar/plugin-x": "plugin_x" }, + ); + assert.equal(buildAarCalls[0].aarName, "plugin_x"); + }); + + it("prepares @nativescript/core and its native dependencies first without changing dependencies.json", async () => { + const manifest = { "AndroidManifest.xml": "" }; + addPlugin({ name: "peer-plugin", nativeFiles: manifest }); + addPlugin({ + name: "other-plugin", + dependencies: ["peer-plugin"], + nativeFiles: manifest, + }); + addPlugin({ + name: "@nativescript/core", + dependencies: ["core-native-dep"], + nativeFiles: { "include.gradle": "android {}" }, + }); + addPlugin({ name: "core-native-dep", nativeFiles: manifest }); + addPlugin({ name: "lodash", native: false }); + + const prepareOrder = await service.beforePrepareAllPlugins( + createProjectData(), + dependencies, + ); + + assert.deepStrictEqual( + prepareOrder.map((dep) => dep.name), + [ + "lodash", + "core-native-dep", + "@nativescript/core", + "peer-plugin", + "other-plugin", + ], + ); + assert.deepStrictEqual( + JSON.parse(readDependenciesJson()).map((dep: any) => dep.name), + [ + "peer-plugin", + "other-plugin", + "core-native-dep", + "@nativescript/core", + ], + ); + }); + + it("forgets file hashes remembered by an earlier prepare", async () => { + addFixturePlugins(); + const file = path.join( + projectDir, + "node_modules", + "@nativescript/core", + "platforms", + "android", + "include.gradle", + ); + memo.remember(file, "stale"); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + assert.isUndefined(memo.take(file)); + }); + }); + + describe('pluginBuildLocation: "platforms"', () => { + it("points dependencies.json and the facts at CLI-owned copies", async () => { + addFixturePlugins(); + + await service.beforePrepareAllPlugins( + createProjectData("platforms"), + dependencies, + ); + + assert.deepStrictEqual(JSON.parse(readDependenciesJson()), [ + { + name: "@nativescript/core", + directory: path.join(".ns-plugins", "core"), + dependencies: [], + }, + { + name: "@foo/plugin-x", + directory: path.join(".ns-plugins", "foo_plugin_x"), + dependencies: ["@nativescript/core"], + }, + { + name: "@bar/plugin-x", + directory: path.join(".ns-plugins", "bar_plugin_x"), + dependencies: [], + }, + ]); + + const facts = readFacts(); + validateFacts(facts); + assert.equal(facts.dependenciesJson.sha256, dependenciesJsonSha256()); + assert.deepStrictEqual(facts.plugins[1], { + name: "@foo/plugin-x", + packageDir: "../../node_modules/@foo/plugin-x", + nativeDir: ".ns-plugins/foo_plugin_x/platforms/android", + aarName: "foo_plugin_x", + aar: ".ns-plugins/foo_plugin_x/platforms/android/foo_plugin_x.aar", + dependencies: ["@nativescript/core"], + options: {}, + }); + + const mirrorDir = path.join(platformDir, ".ns-plugins", "foo_plugin_x"); + assert.equal( + fs.readJson(path.join(mirrorDir, "package.json")).name, + "@foo/plugin-x", + ); + assert.equal( + fs.readText( + path.join(mirrorDir, "platforms", "android", "libs", "x.jar"), + ), + "jar", + ); + }); + + it("builds from the package into the copy", async () => { + addFixturePlugins(); + const projectData = createProjectData("platforms"); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + + const mirrorNativeDir = path.join( + platformDir, + ".ns-plugins", + "foo_plugin_x", + "platforms", + "android", + ); + assert.deepInclude(buildAarCalls[0], { + platformsAndroidDirPath: path.join( + projectDir, + "node_modules", + "@foo", + "plugin-x", + "platforms", + "android", + ), + aarOutputDir: mirrorNativeDir, + aarName: "foo_plugin_x", + pluginBuildLocation: "platforms", + }); + assert.equal( + migrateIncludeGradleCalls[0].platformsAndroidDirPath, + mirrorNativeDir, + ); + }); + + it("gives every copy its own directory, also for plugins without sources to build", async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { "AndroidManifest.xml": "" }, + }); + addPlugin({ + name: "@bar/plugin-x", + nativeFiles: { "plugin_x.aar": "shipped" }, + }); + const projectData = createProjectData("platforms"); + + await service.beforePrepareAllPlugins(projectData, dependencies); + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, + ); + + assert.sameMembers( + JSON.parse(readDependenciesJson()).map((dep: any) => dep.directory), + [ + path.join(".ns-plugins", "foo_plugin_x"), + path.join(".ns-plugins", "bar_plugin_x"), + ], + ); + const facts = readFacts(); + validateFacts(facts); + assert.equal( + facts.plugins.find((plugin) => plugin.name === "@foo/plugin-x").aar, + ".ns-plugins/foo_plugin_x/platforms/android/plugin_x.aar", + ); + assert.deepInclude(buildAarCalls[0], { + aarName: "plugin_x", + aarOutputDir: path.join( + platformDir, + ".ns-plugins", + "foo_plugin_x", + "platforms", + "android", + ), + }); + }); + + it("asks for a reprepare of plugins whose copy changed until they are prepared", async () => { + addFixturePlugins(); + const projectData = createProjectData("platforms"); + const foo = pluginData("@foo/plugin-x"); + + await service.beforePrepareAllPlugins(projectData, dependencies); + assert.isTrue(service.shouldRepreparePlugin(foo, projectData)); + + await service.preparePluginNativeCode(foo, projectData); + assert.isFalse(service.shouldRepreparePlugin(foo, projectData)); + + await service.beforePrepareAllPlugins(projectData, dependencies); + assert.isFalse(service.shouldRepreparePlugin(foo, projectData)); + }); + + it("skips plugins that Gradle does not read", async () => { + addFixturePlugins(); + fs.writeFile( + path.join( + projectDir, + "node_modules", + "lodash", + "platforms", + "android", + "AndroidManifest.xml", + ), + "", + ); + const projectData = createProjectData("platforms"); + await service.beforePrepareAllPlugins(projectData, dependencies); + + await service.preparePluginNativeCode(pluginData("lodash"), projectData); + + assert.deepStrictEqual(buildAarCalls, []); + }); + + it('drops the copies when switched back to "node_modules"', async () => { + addFixturePlugins(); + await service.beforePrepareAllPlugins( + createProjectData("platforms"), + dependencies, + ); + assert.isTrue(fs.exists(path.join(platformDir, ".ns-plugins"))); + + await service.beforePrepareAllPlugins( + createProjectData("node_modules"), + dependencies, + ); + + assert.isFalse(fs.exists(path.join(platformDir, ".ns-plugins"))); + validateFacts(readFacts()); + assert.equal( + readFacts().plugins[0].nativeDir, + "../../node_modules/@nativescript/core/platforms/android", + ); + }); + + it("remembers the hashes of the plugins' native files for this prepare", async () => { + addFixturePlugins(); + const upstream = (...parts: string[]) => + path.join(projectDir, "node_modules", "@foo", "plugin-x", ...parts); + const manifest = upstream("platforms", "android", "AndroidManifest.xml"); + + await service.beforePrepareAllPlugins( + createProjectData("platforms"), + dependencies, + ); + + assert.equal(memo.take(manifest), await fs.getFileShasum(manifest)); + assert.isUndefined(memo.take(manifest)); + assert.isUndefined(memo.take(upstream("package.json"))); + }); + + it("rebuilds a plugin whose copy changed on the next prepare when its build failed", async () => { + addFixturePlugins(); + const projectData = createProjectData("platforms"); + const foo = pluginData("@foo/plugin-x"); + await service.beforePrepareAllPlugins(projectData, dependencies); + + buildAarError = new Error("Gradle failed"); + await assert.isRejected( + service.preparePluginNativeCode(foo, projectData), + /Gradle failed/, + ); + await service.beforePrepareAllPlugins(projectData, dependencies); + assert.isTrue(service.shouldRepreparePlugin(foo, projectData)); + + buildAarError = null; + await service.preparePluginNativeCode(foo, projectData); + await service.beforePrepareAllPlugins(projectData, dependencies); + assert.isFalse(service.shouldRepreparePlugin(foo, projectData)); + }); + + describe("aars under another of a plugin's candidate names", () => { + const manifest = { "AndroidManifest.xml": "" }; + const mirroredAar = (mirrorName: string, aar: string) => + path.join( + platformDir, + ".ns-plugins", + mirrorName, + "platforms", + "android", + aar, + ); + + function writeTempBuild(name: string, builtFor: string, content: string) { + const tempProjectDir = path.join( + projectDir, + "platforms", + "tempPlugin", + name, + ); + fs.writeFile( + path.join(tempProjectDir, "build.gradle"), + `project.ext.PLUGIN_NAME = "${builtFor}"\n`, + ); + fs.writeFile( + path.join( + tempProjectDir, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ), + content, + ); + } + + const prepare = () => + service.beforePrepareAllPlugins( + createProjectData("platforms"), + dependencies, + ); + + it("copies the aar a prebuilt-only plugin ships under the name another plugin now builds", async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { "plugin_x.aar": "shipped", "include.gradle": "" }, + }); + addPlugin({ name: "plugin-x", nativeFiles: manifest }); + writeTempBuild("plugin_x", "plugin-x", "built for plugin-x"); + + await prepare(); + + assert.equal( + fs.readText(mirroredAar("foo_plugin_x", "plugin_x.aar")), + "shipped", + ); + }); + + it("leaves out an aar under the short name of a plugin it builds", async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { ...manifest, "plugin_x.aar": "shipped" }, + }); + addPlugin({ name: "plugin-x", nativeFiles: manifest }); + writeTempBuild("plugin_x", "plugin-x", "built for plugin-x"); + + await prepare(); + + assert.isFalse(fs.exists(mirroredAar("foo_plugin_x", "plugin_x.aar"))); + assert.isTrue( + fs.exists(mirroredAar("foo_plugin_x", "AndroidManifest.xml")), + ); + }); + + it("leaves out every clashing plugin's old aar after an upgrade", async () => { + for (const name of ["@foo/plugin-x", "@bar/plugin-x"]) { + addPlugin({ + name, + nativeFiles: { ...manifest, "plugin_x.aar": "old" }, + }); + } + writeTempBuild("plugin_x", "@bar/plugin-x", "old"); + + await prepare(); + + for (const mirrorName of ["foo_plugin_x", "bar_plugin_x"]) { + assert.isFalse(fs.exists(mirroredAar(mirrorName, "plugin_x.aar"))); + } + }); + + for (const { title, previousBuild } of [ + { title: "identical to", previousBuild: "previous build" }, + { title: "different from", previousBuild: "another build" }, + ]) { + it(`leaves out a scope-qualified aar ${title} the plugin's previous build output`, async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { ...manifest, "foo_plugin_x.aar": "previous build" }, + }); + writeTempBuild("foo_plugin_x", "@foo/plugin-x", previousBuild); + + await prepare(); + + assert.isFalse( + fs.exists(mirroredAar("plugin_x", "foo_plugin_x.aar")), + ); + }); + } + + for (const { title, writeTemp } of [ + { title: "without a previous build output", writeTemp: () => {} }, + { + title: "whose temp project another plugin built", + writeTemp: () => + writeTempBuild("foo_plugin_x", "@other/plugin", "shipped"), + }, + ]) { + it(`copies a scope-qualified aar ${title}`, async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { ...manifest, "foo_plugin_x.aar": "shipped" }, + }); + writeTemp(); + + await prepare(); + + assert.equal( + fs.readText(mirroredAar("plugin_x", "foo_plugin_x.aar")), + "shipped", + ); + }); + } + }); + }); + + describe("invalid pluginBuildLocation", () => { + it("fails prepare and names the allowed values", async () => { + addFixturePlugins(); + + await assert.isRejected( + service.beforePrepareAllPlugins(createProjectData(true), dependencies), + /Invalid value true for android\.pluginBuildLocation .*"node_modules" or "platforms"/, + ); + assert.isFalse(fs.exists(path.join(platformDir, "dependencies.json"))); + }); + }); +}); diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index 8600a390df..feacae75a1 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -27,6 +27,7 @@ describe("androidPluginBuildService", () => { let failGradleBuild = false; let ignoredFiles: string[] = []; let hashedFiles: string[] = []; + let lastGradleArgs: string[] = []; let fs: IFileSystem; let androidBuildPluginService: AndroidPluginBuildService; let tempFolder: string; @@ -86,6 +87,7 @@ describe("androidPluginBuildService", () => { if (failGradleBuild) { throw new Error("Gradle build failed"); } + lastGradleArgs = args; const pluginDir = args[args.indexOf("-p") + 1]; const aar = path.join( pluginDir, @@ -747,6 +749,85 @@ dependencies { ); }); + it("looks for the previous aar in aarOutputDir", async () => { + const outputDir = mkdtempSync(path.join(tmpdir(), "aar-output-")); + const config: IPluginBuildOptions = { + ...setup({ addManifest: true, addPreviousBuildInfo: true }), + aarOutputDir: outputDir, + }; + + await androidBuildPluginService.buildAar(config); + assert.isTrue(spawnFromEventCalled); + assert.isTrue(fs.exists(path.join(outputDir, `${shortPluginName}.aar`))); + + spawnFromEventCalled = false; + await androidBuildPluginService.buildAar(config); + assert.isFalse(spawnFromEventCalled); + }); + + describe('pluginBuildLocation: "platforms"', () => { + let mirrorDir: string; + const setupInMirror = (overrides?: Partial) => { + const config = setupScoped({ + pluginBuildLocation: "platforms", + ...overrides, + }); + mirrorDir = mkdtempSync(path.join(tmpdir(), "aar-mirror-")); + config.aarOutputDir = mirrorDir; + return config; + }; + + it("deletes a short-name aar from the copy but leaves the package alone", async () => { + const config = setupInMirror(); + const packageAar = path.join(pluginFolder, `${shortPluginName}.aar`); + const mirrorAar = path.join(mirrorDir, `${shortPluginName}.aar`); + fs.writeFile(packageAar, "old build"); + fs.writeFile(mirrorAar, "old build"); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(mirrorAar)); + assert.isTrue(fs.exists(path.join(mirrorDir, `${qualifiedName}.aar`))); + assert.equal(fs.readText(packageAar), "old build"); + assert.notInclude(hashedFiles, packageAar); + assert.deepStrictEqual(ignoredFiles, []); + }); + + it("deletes a differing scope-qualified aar from the copy without failing", async () => { + const config = setupInMirror({ aarName: shortPluginName }); + const staleAar = path.join(mirrorDir, `${qualifiedName}.aar`); + fs.writeFile(staleAar, "something else"); + writePreviousOutput(qualifiedName, "previous build"); + + await androidBuildPluginService.buildAar(config); + + assert.isTrue(spawnFromEventCalled); + assert.isFalse(fs.exists(staleAar)); + assert.isTrue( + fs.exists(path.join(mirrorDir, `${shortPluginName}.aar`)), + ); + }); + }); + + it("passes the facts file to Gradle only when it exists", async () => { + const factsFile = path.join( + mkdtempSync(path.join(tmpdir(), "facts-")), + "nativescript-gradle.json", + ); + const config = setupScoped({ gradleFactsFile: factsFile }); + + await androidBuildPluginService.buildAar(config); + assert.isTrue(spawnFromEventCalled); + assert.isFalse( + lastGradleArgs.some((arg) => arg.startsWith("-Pnativescript.")), + ); + + fs.writeFile(factsFile, "{}"); + fs.deleteDirectory(path.join(tempFolder, qualifiedName)); + await androidBuildPluginService.buildAar(config); + assert.include(lastGradleArgs, `-Pnativescript.factsFile=${factsFile}`); + }); + describe("hasAarSources", () => { it("is true for a manifest or Android source directories", () => { const withManifest = setup({ addManifest: true }); diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index 4cd34ceb24..eea096d69f 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -1,4 +1,5 @@ import { AndroidProjectService } from "../../lib/services/android-project-service"; +import { NativeFileHashesMemo } from "../../lib/services/native-file-hashes-memo"; import { Yok } from "../../lib/common/yok"; import * as stubs from "../stubs"; import { assert } from "chai"; @@ -69,6 +70,8 @@ const createTestInjector = (): IInjector => { testInjector.register("staticConfig", { TRACK_FEATURE_USAGE_SETTING_NAME: "TrackFeatureUsage", }); + testInjector.register("androidPluginMirrorService", {}); + testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); return testInjector; }; @@ -426,6 +429,9 @@ describe("androidProjectService plugin aar names", () => { projectDir, platformsDir: path.join(projectDir, "platforms"), ignoredDependencies: [], + getAppDirectoryPath: () => path.join(projectDir, "app"), + getAppResourcesDirectoryPath: () => + path.join(projectDir, "App_Resources"), }); } @@ -485,7 +491,11 @@ describe("androidProjectService plugin aar names", () => { testInjector.register("logger", stubs.LoggerStub); testInjector.register("errors", stubs.ErrorsStub); testInjector.register("options", {}); - testInjector.register("projectDataService", {}); + testInjector.register("projectDataService", { + getRuntimePackage: (): null => null, + }); + testInjector.register("staticConfig", { version: "9.9.9" }); + testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); testInjector.register("nodeModulesDependenciesBuilder", { getProductionDependencies: () => dependencies, }); @@ -508,6 +518,7 @@ describe("androidProjectService plugin aar names", () => { "gradleCommandService", "gradleBuildService", "analyticsService", + "androidPluginMirrorService", ]) { testInjector.register(unused, {}); } @@ -590,6 +601,7 @@ describe("androidProjectService plugin aar names", () => { platformsAndroidDirPath: nativeDir, aarOutputDir: nativeDir, tempPluginDirPath: path.join(projectDir, "platforms", "tempPlugin"), + gradleFactsFile: path.join(platformDir, "nativescript-gradle.json"), aarName: "core", }, ]); diff --git a/test/services/android/android-plugin-mirror-service.ts b/test/services/android/android-plugin-mirror-service.ts new file mode 100644 index 0000000000..e157c58fba --- /dev/null +++ b/test/services/android/android-plugin-mirror-service.ts @@ -0,0 +1,230 @@ +import { assert } from "chai"; +import * as path from "path"; +import { mkdtempSync, statSync, utimesSync } from "fs"; +import { tmpdir } from "os"; +import { Yok } from "../../../lib/common/yok"; +import { FileSystem } from "../../../lib/common/file-system"; +import { AndroidPluginMirrorService } from "../../../lib/services/android/android-plugin-mirror-service"; +import { NativeFileHashesMemo } from "../../../lib/services/native-file-hashes-memo"; +import { IFileSystem } from "../../../lib/common/declarations"; +import { IAndroidPluginMirror } from "../../../lib/definitions/android-plugin-migrator"; +import * as stubs from "../../stubs"; + +describe("androidPluginMirrorService", () => { + let fs: IFileSystem; + let mirrorService: AndroidPluginMirrorService; + let packageDir: string; + let mirrorsRoot: string; + let mirror: IAndroidPluginMirror; + + const upstream = (...parts: string[]) => path.join(packageDir, ...parts); + const mirrored = (...parts: string[]) => + path.join(mirror.mirrorDir, ...parts); + const mtimeOf = (file: string) => statSync(file).mtime.getTime(); + const setMtime = (file: string, seconds: number) => + utimesSync(file, seconds, seconds); + + beforeEach(() => { + const injector = new Yok(); + injector.register("injector", injector); + injector.register("fs", FileSystem); + injector.register("logger", stubs.LoggerStub); + injector.register("nativeFileHashesMemo", NativeFileHashesMemo); + injector.register("androidPluginMirrorService", AndroidPluginMirrorService); + fs = injector.resolve("fs"); + mirrorService = injector.resolve("androidPluginMirrorService"); + + const root = mkdtempSync(path.join(tmpdir(), "plugin-mirror-")); + packageDir = path.join(root, "node_modules", "@foo", "plugin-x"); + mirrorsRoot = path.join(root, "platforms", "android", ".ns-plugins"); + mirror = { + pluginName: "@foo/plugin-x", + packageDir, + mirrorDir: path.join(mirrorsRoot, "foo_plugin_x"), + excludedNativeFiles: ["plugin_x.aar"], + }; + + fs.writeJson(upstream("package.json"), { name: "@foo/plugin-x" }); + fs.writeFile(upstream("README.md"), "not mirrored"); + fs.writeFile(upstream("platforms", "android", "include.gradle"), "a"); + fs.writeFile(upstream("platforms", "android", "libs", "x.jar"), "jar"); + fs.writeFile(upstream("platforms", "android", "plugin_x.aar"), "stale"); + fs.writeFile(upstream("platforms", "ios", "Podfile"), "not mirrored"); + for (const file of [ + upstream("package.json"), + upstream("platforms", "android", "include.gradle"), + upstream("platforms", "android", "libs", "x.jar"), + ]) { + setMtime(file, 1_000_000); + } + }); + + it("copies package.json and platforms/android, keeping upstream mtimes", () => { + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + + assert.deepStrictEqual(fs.readJson(mirrored("package.json")), { + name: "@foo/plugin-x", + }); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "a", + ); + assert.equal( + fs.readText(mirrored("platforms", "android", "libs", "x.jar")), + "jar", + ); + assert.equal( + mtimeOf(mirrored("platforms", "android", "libs", "x.jar")), + 1_000_000_000, + ); + assert.isFalse(fs.exists(mirrored("README.md"))); + assert.isFalse(fs.exists(mirrored("platforms", "ios"))); + assert.isFalse(fs.exists(mirrored("platforms", "android", "plugin_x.aar"))); + }); + + it("only rewrites files whose upstream content changed", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.writeFile( + mirrored("platforms", "android", "include.gradle"), + "rewritten by the CLI", + ); + setMtime(upstream("package.json"), 2_000_000); + + assert.deepStrictEqual( + mirrorService.syncMirrors(mirrorsRoot, [mirror]), + [], + ); + assert.equal(mtimeOf(mirrored("package.json")), 1_000_000_000); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "rewritten by the CLI", + ); + + fs.writeFile(upstream("platforms", "android", "include.gradle"), "b"); + setMtime(upstream("platforms", "android", "include.gradle"), 3_000_000); + + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "b", + ); + assert.equal( + mtimeOf(mirrored("platforms", "android", "include.gradle")), + 3_000_000_000, + ); + assert.equal( + mtimeOf(mirrored("platforms", "android", "libs", "x.jar")), + 1_000_000_000, + ); + }); + + it("restores a mirrored file that was deleted", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.deleteFile(mirrored("platforms", "android", "libs", "x.jar")); + + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + assert.equal( + fs.readText(mirrored("platforms", "android", "libs", "x.jar")), + "jar", + ); + }); + + it("deletes files removed upstream but keeps files the CLI added", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.writeFile(mirrored("platforms", "android", "foo_plugin_x.aar"), "built"); + fs.deleteDirectory(upstream("platforms", "android", "libs")); + + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + assert.isFalse(fs.exists(mirrored("platforms", "android", "libs"))); + assert.equal( + fs.readText(mirrored("platforms", "android", "foo_plugin_x.aar")), + "built", + ); + }); + + it("recopies a file whose content changed without changing its size or mtime", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + const includeGradle = upstream("platforms", "android", "include.gradle"); + fs.writeFile(includeGradle, "b"); + setMtime(includeGradle, 1_000_000); + + const changed = mirrorService.syncMirrors(mirrorsRoot, [mirror]); + + assert.deepStrictEqual(changed, ["@foo/plugin-x"]); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "b", + ); + }); + + it("follows a file that turned into a directory upstream", () => { + const config = upstream("platforms", "android", "assets", "config"); + fs.writeFile(config, "file"); + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.deleteFile(config); + fs.writeFile(path.join(config, "settings.json"), "{}"); + + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + assert.equal( + fs.readText( + mirrored("platforms", "android", "assets", "config", "settings.json"), + ), + "{}", + ); + }); + + it("follows a directory that turned into a file upstream", () => { + const config = upstream("platforms", "android", "assets", "config"); + fs.writeFile(path.join(config, "settings.json"), "{}"); + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.deleteDirectory(config); + fs.writeFile(config, "file"); + + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + assert.equal( + fs.readText(mirrored("platforms", "android", "assets", "config")), + "file", + ); + }); + + it("removes the mirrors of plugins that are gone", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + assert.isTrue(fs.exists(mirror.mirrorDir)); + + mirrorService.syncMirrors(mirrorsRoot, []); + + assert.isFalse(fs.exists(mirror.mirrorDir)); + assert.isTrue(fs.exists(packageDir)); + }); + + it("never writes into the package", () => { + const before = fs.enumerateFilesInDirectorySync(packageDir).map((file) => ({ + file, + content: fs.readText(file), + mtime: mtimeOf(file), + })); + + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.writeFile(mirrored("platforms", "android", "include.gradle"), "x"); + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + + const after = fs.enumerateFilesInDirectorySync(packageDir).map((file) => ({ + file, + content: fs.readText(file), + mtime: mtimeOf(file), + })); + assert.deepStrictEqual(after, before); + }); +}); diff --git a/test/services/android/gradle-build-args-service.ts b/test/services/android/gradle-build-args-service.ts index ab87f5bbb2..8bb7c5764c 100644 --- a/test/services/android/gradle-build-args-service.ts +++ b/test/services/android/gradle-build-args-service.ts @@ -27,6 +27,8 @@ function createTestInjector(): IInjector { getProjectData: () => projectData, }); injector.register("hooksService", stubs.HooksServiceStub); + injector.register("fs", { exists: () => false }); + injector.register("options", {}); injector.register("gradleBuildArgsService", GradleBuildArgsService); injector.register("analyticsService", stubs.AnalyticsService); injector.register("staticConfig", { @@ -216,6 +218,51 @@ describe("GradleBuildArgsService", () => { } }); + describe("Gradle facts", () => { + const factsFile = path.resolve( + "/path/to/projectDir/platforms/android/nativescript-gradle.json", + ); + + const getArgs = async (existing: string[], options: object = {}) => { + const injector = createTestInjector(); + injector.resolve("logger").getLevel = (): string => "INFO"; + injector.register("fs", { + exists: (file: string) => existing.includes(file), + }); + injector.register("options", options); + const service: IGradleBuildArgsService = injector.resolve( + "gradleBuildArgsService", + ); + return service.getBuildTaskArgs({ release: false }); + }; + + it("passes the facts file when it exists", async () => { + const args = await getArgs([factsFile]); + assert.deepStrictEqual( + args, + ["assembleDebug"] + .concat(expectedInfoLoggingArgs) + .concat(expectedDebugBuildArgs) + .concat(`-Pnativescript.factsFile=${factsFile}`), + ); + }); + + it("does not pass a facts file that does not exist", async () => { + const args = await getArgs([]); + assert.isFalse(args.some((arg) => arg.includes("factsFile"))); + }); + + it("looks for the facts file in the host project", async () => { + const hostProjectPath = path.resolve("/path/to/host"); + const hostFactsFile = path.join( + hostProjectPath, + "nativescript-gradle.json", + ); + const args = await getArgs([hostFactsFile], { hostProjectPath }); + assert.include(args, `-Pnativescript.factsFile=${hostFactsFile}`); + }); + }); + describe("getCleanTaskArgs", async () => { const testCases = [ { diff --git a/test/services/gradle-api-include-gradle-extraction.ts b/test/services/gradle-api-include-gradle-extraction.ts new file mode 100644 index 0000000000..f71f379710 --- /dev/null +++ b/test/services/gradle-api-include-gradle-extraction.ts @@ -0,0 +1,42 @@ +import { assert } from "chai"; +import { readFileSync } from "fs"; +import * as path from "path"; +import { AndroidPluginBuildService } from "../../lib/services/android-plugin-build-service"; + +// gradle-api's plugin-build functional tests run this golden file in place of the CLI's +// extraction, so the two must not drift. +describe("include.gradle extraction used by gradle-api's functional tests", () => { + // Tests run compiled from dist/test, three levels below the repo root. + const gradleApiDir = path.join(__dirname, "..", "..", "..", "gradle-api"); + + it("extracts exactly the golden blocks from the sample plugin's include.gradle", () => { + const includeGradle = readFileSync( + path.join( + gradleApiDir, + "samples", + "sample-plugin", + "platforms", + "android", + "include.gradle", + ), + "utf8", + ); + const golden = readFileSync( + path.join( + gradleApiDir, + "src", + "functionalTest", + "resources", + "extracted", + "sample-plugin-include.gradle", + ), + "utf8", + ); + + const service = Object.create(AndroidPluginBuildService.prototype); + const blocks: string[] = + service.getIncludeGradleCompileDependenciesScope(includeGradle); + + assert.equal(blocks.join("\n"), golden); + }); +}); diff --git a/test/stubs.ts b/test/stubs.ts index de7d9a9f60..4019b7d393 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -75,6 +75,7 @@ import { } from "../lib/common/declarations"; import { IAndroidPluginBuildService, + IStaleAar, IPluginBuildOptions, } from "../lib/definitions/android-plugin-migrator"; import { IInjector } from "../lib/common/definitions/yok"; @@ -758,6 +759,10 @@ export class AndroidPluginBuildServiceStub implements IAndroidPluginBuildService hasAarSources(platformsAndroidDirPath: string): boolean { return false; } + + getStaleAars(options: IPluginBuildOptions, dir?: string): IStaleAar[] { + return []; + } } export class PlatformProjectServiceStub From 0955a2e12d7302edc20870a5a6fdf958e670c766 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 10:17:59 -0300 Subject: [PATCH 3/9] ci(gradle-api): test org.nativescript:gradle-api and publish tagged releases The gradle_api workflow runs the library's checks on changes, with the unit tests also on Windows, and publishes to Maven Central from the protected maven-central environment only for a gradle-api-v* tag on a commit that is on main. --- .github/workflows/gradle_api.yml | 176 +++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 .github/workflows/gradle_api.yml diff --git a/.github/workflows/gradle_api.yml b/.github/workflows/gradle_api.yml new file mode 100644 index 0000000000..c7c4ce2a76 --- /dev/null +++ b/.github/workflows/gradle_api.yml @@ -0,0 +1,176 @@ +name: 'org.nativescript:gradle-api' + +on: + workflow_dispatch: + pull_request: + paths: + - 'gradle-api/**' + - 'vendor/gradle-plugin/**' + - 'lib/services/android-plugin-build-service.ts' + - 'lib/services/android-project-service.ts' + - 'lib/services/android/**' + - '.github/workflows/gradle_api.yml' + push: + branches: [ 'main' ] + # Path filters do not apply to tag pushes. + tags: [ 'gradle-api-v*' ] + paths: + - 'gradle-api/**' + - 'vendor/gradle-plugin/**' + - 'lib/services/android-plugin-build-service.ts' + - 'lib/services/android-project-service.ts' + - 'lib/services/android/**' + - '.github/workflows/gradle_api.yml' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }} + +jobs: + test: + name: Test + runs-on: ubuntu-latest + timeout-minutes: 45 + + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: gradle/actions/wrapper-validation@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + # vendor/gradle-plugin/gradle/wrapper/gradle-wrapper.jar, which the CLI copies into + # plugin builds, matches no published Gradle wrapper checksum. + allow-checksums: 414142e6bc3b156908436f13b29e198bb3d59824f9c245ef145c809ddd5fe0a3 + + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: temurin + java-version: '17' + + - uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + cache-provider: basic + # Done by the wrapper-validation step, which can allow the vendored jar. + validate-wrappers: false + + # The Android SDK preinstalled on the runner (ANDROID_HOME) enables the plugin build tests. + - name: Check + working-directory: gradle-api + run: ./gradlew check --console=plain + + test-windows: + name: Unit tests (Windows) + runs-on: windows-latest + timeout-minutes: 30 + + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: temurin + java-version: '17' + + # The Test job validates the wrappers. + - uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + cache-provider: basic + validate-wrappers: false + + - name: Test + working-directory: gradle-api + run: .\gradlew.bat test --console=plain + + publish: + name: Publish to Maven Central + if: startsWith(github.ref, 'refs/tags/gradle-api-v') + needs: [ test, test-windows ] + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: maven-central + + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # Full history of every branch, for the main ancestry check. + fetch-depth: 0 + + # A tag can point at any commit, and publishing releases it immediately. + - name: Check the tagged commit is on main + run: | + commit="$(git rev-parse "$GITHUB_SHA^{commit}")" + if ! git merge-base --is-ancestor "$commit" origin/main; then + echo "::error::$GITHUB_REF_NAME points at $commit, which is not on main" + exit 1 + fi + + - uses: gradle/actions/wrapper-validation@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + allow-checksums: 414142e6bc3b156908436f13b29e198bb3d59824f9c245ef145c809ddd5fe0a3 + + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: temurin + java-version: '17' + + - uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + cache-provider: basic + cache-read-only: true + validate-wrappers: false + + - name: Check the tag matches the version + working-directory: gradle-api + env: + TAG: ${{ github.ref_name }} + run: | + version="$(sed -n 's/^VERSION_NAME=//p' gradle.properties)" + if [ "$TAG" != "gradle-api-v$version" ]; then + echo "::error::Tag $TAG does not match VERSION_NAME=$version in gradle-api/gradle.properties" + exit 1 + fi + case "$version" in + *-SNAPSHOT) + echo "::error::$version is a snapshot version" + exit 1 + ;; + esac + + - name: Publish + working-directory: gradle-api + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.MAVEN_CENTRAL_SIGNING_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.MAVEN_CENTRAL_SIGNING_KEY_PASSWORD }} + run: | + # The build skips signing without a key, which Maven Central would only reject later. + for name in ORG_GRADLE_PROJECT_mavenCentralUsername ORG_GRADLE_PROJECT_mavenCentralPassword ORG_GRADLE_PROJECT_signingInMemoryKey; do + if [ -z "${!name}" ]; then + echo "::error::$name is empty; check the maven-central environment's secrets" + exit 1 + fi + done + ./gradlew publishAndReleaseToMavenCentral --no-configuration-cache --console=plain From 8769ccfe9f197514ef1631707ea372585cdadbe1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:36:08 -0300 Subject: [PATCH 4/9] fix(android): reset a plugin mirror when another package takes it over Mirror directories under .ns-plugins are named after aar names, so a different package with the same name can reuse one. Files the CLI added (the built aar) are not in the mirror manifest and would survive, letting Gradle pick up the previous package's aar. The manifest now records the owning package; a mirror without it, or owned by another package, is recreated. --- .../android/android-plugin-mirror-service.ts | 28 +++++++- .../android/android-plugin-mirror-service.ts | 65 +++++++++++++++++++ 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/lib/services/android/android-plugin-mirror-service.ts b/lib/services/android/android-plugin-mirror-service.ts index 7c698d1ec3..52b17c7a89 100644 --- a/lib/services/android/android-plugin-mirror-service.ts +++ b/lib/services/android/android-plugin-mirror-service.ts @@ -14,6 +14,11 @@ interface IMirroredFile { } interface IMirrorManifest { + /** + * The npm package the mirror holds. Mirror directories are named after + * aar names, which another package can take over. + */ + pluginName?: string; files: { [relativePath: string]: IMirroredFile }; } @@ -71,8 +76,26 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { private syncMirror(mirror: IAndroidPluginMirror): boolean { const manifestPath = path.join(mirror.mirrorDir, MIRROR_MANIFEST_FILE_NAME); - const previous = this.readManifest(manifestPath); - const next: IMirrorManifest = { files: {} }; + let previous = this.readManifest(manifestPath); + let changed = false; + // Files the CLI added (the built aar) are not in the manifest, so a + // mirror taken over by another package would keep them. + if ( + previous.pluginName !== mirror.pluginName && + this.$fs.exists(mirror.mirrorDir) + ) { + this.$logger.trace( + `Resetting plugin mirror ${mirror.mirrorDir} for ${mirror.pluginName}.`, + ); + this.$fs.deleteDirectory(mirror.mirrorDir); + previous = { files: {} }; + changed = true; + } + + const next: IMirrorManifest = { + pluginName: mirror.pluginName, + files: {}, + }; const excluded = new Set( (mirror.excludedNativeFiles ?? []).map( (file) => `${NATIVE_DIR}/${toPosix(file)}`, @@ -81,7 +104,6 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { const upstreamFiles = this.getUpstreamFiles(mirror.packageDir).filter( (relativePath) => !excluded.has(relativePath), ); - let changed = false; // Before copying, so a path that turned from a file into a directory (or // back) upstream is free when its replacement is copied. diff --git a/test/services/android/android-plugin-mirror-service.ts b/test/services/android/android-plugin-mirror-service.ts index e157c58fba..44bcc778bf 100644 --- a/test/services/android/android-plugin-mirror-service.ts +++ b/test/services/android/android-plugin-mirror-service.ts @@ -209,6 +209,71 @@ describe("androidPluginMirrorService", () => { assert.isTrue(fs.exists(packageDir)); }); + describe("a mirror directory another package used", () => { + const builtAar = () => mirrored("platforms", "android", "foo_plugin_x.aar"); + const otherPackage = () => { + const otherPackageDir = path.join( + path.dirname(path.dirname(packageDir)), + "@bar", + "plugin-x", + ); + fs.writeJson(path.join(otherPackageDir, "package.json"), { + name: "@bar/plugin-x", + }); + fs.writeFile( + path.join(otherPackageDir, "platforms", "android", "include.gradle"), + "b", + ); + return otherPackageDir; + }; + + it("drops the files the CLI added for the previous package", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.writeFile(builtAar(), "built for @foo/plugin-x"); + mirror = { + pluginName: "@bar/plugin-x", + packageDir: otherPackage(), + mirrorDir: mirror.mirrorDir, + }; + + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@bar/plugin-x", + ]); + + assert.isFalse(fs.exists(builtAar())); + assert.isFalse(fs.exists(mirrored("platforms", "android", "libs"))); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "b", + ); + }); + + it("is reset when it does not record which package it holds", () => { + fs.writeFile(builtAar(), "built by an unknown package"); + fs.writeJson(mirrored(".ns-mirror.json"), { files: {} }); + + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + + assert.isFalse(fs.exists(builtAar())); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "a", + ); + }); + + it("keeps the files the CLI added while the package stays the same", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.writeFile(builtAar(), "built"); + + assert.deepStrictEqual( + mirrorService.syncMirrors(mirrorsRoot, [mirror]), + [], + ); + + assert.equal(fs.readText(builtAar()), "built"); + }); + }); + it("never writes into the package", () => { const before = fs.enumerateFilesInDirectorySync(packageDir).map((file) => ({ file, From 9fd181cb92ed779814527a0207dbc4e297e95b85 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:36:17 -0300 Subject: [PATCH 5/9] docs(gradle-api): allow absolute facts paths where no relative path exists path.relative returns an absolute path when the target is on another Windows drive than the facts file. toFactsPath now writes that case as an absolute path with forward slashes on purpose, and the schema, README and type docs say paths are relative when possible and absolute otherwise, which the reader already supports. Also describe a plugin's `aar` as the path the CLI builds its aar to: a plugin without sources builds nothing there but may ship a file at it. --- gradle-api/README.md | 8 ++++++-- .../schema/nativescript-gradle.schema.json | 5 +++-- lib/definitions/gradle-facts.d.ts | 5 +++-- lib/services/android/gradle-facts.ts | 19 ++++++++++++++++--- 4 files changed, 28 insertions(+), 9 deletions(-) diff --git a/gradle-api/README.md b/gradle-api/README.md index a8f7c17ebb..9842f10420 100644 --- a/gradle-api/README.md +++ b/gradle-api/README.md @@ -372,7 +372,11 @@ built. The schema is [`schema/nativescript-gradle.schema.json`](schema/nativescr } ``` -- Paths are relative to the file, with forward slashes, so the folder can move. +- Paths use forward slashes and are relative to the file, so the folder can move. When there is no + relative path (on Windows, a project on another drive than the file) the path is absolute, e.g. + `D:/app/node_modules/x`. The library handles both. +- `aar` is where the CLI puts the `.aar` it builds from the plugin's sources. A plugin without + sources builds nothing, but may ship a file at that path itself. - `minReaderSchemaVersion` is the lowest `schemaVersion` a reader must understand to use the file, never above the file's own `schemaVersion`. A library that supports only older schema versions refuses it (see [Errors](#errors)) instead of @@ -393,7 +397,7 @@ These are what keep old plugins working on new CLIs, and new plugins working on `schemaVersion` goes up when fields are added; readers accept any version and read what they know, as long as it isn't below the file's `minReaderSchemaVersion`. A CLI raises `minReaderSchemaVersion` only for a change that old readers would get wrong if they ignored it, which should be never: it is -the one way to tell libraries already published "you can't read this". Paths are relative. Anything a newer CLI does differently is expressed as data in the file, not as a +the one way to tell libraries already published "you can't read this". Paths are relative where possible. Anything a newer CLI does differently is expressed as data in the file, not as a rule readers must know. A facts file that doesn't match the `dependencies.json` next to it is an error, never used. diff --git a/gradle-api/schema/nativescript-gradle.schema.json b/gradle-api/schema/nativescript-gradle.schema.json index 8696acbf0e..1360068acd 100644 --- a/gradle-api/schema/nativescript-gradle.schema.json +++ b/gradle-api/schema/nativescript-gradle.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://nativescript.org/schemas/nativescript-gradle.schema.json", "title": "NativeScript Gradle facts", - "description": "Written by the NativeScript CLI at prepare time to platforms/android/nativescript-gradle.json and read by org.nativescript:gradle-api. Fields are only ever added: readers must ignore unknown fields, and a field never changes meaning. Every path is relative to the directory containing this file and uses forward slashes.", + "description": "Written by the NativeScript CLI at prepare time to platforms/android/nativescript-gradle.json and read by org.nativescript:gradle-api. Fields are only ever added: readers must ignore unknown fields, and a field never changes meaning. Every path uses forward slashes and is relative to the directory containing this file, or absolute when no relative path exists (on Windows, a target on another drive). Readers resolve relative paths against that directory and take absolute ones as they are.", "type": "object", "required": ["schemaVersion", "minReaderSchemaVersion", "dependenciesJson", "project", "plugins"], "properties": { @@ -67,6 +67,7 @@ }, "$defs": { "path": { + "description": "Forward slashes only. Relative to the directory containing this file, or absolute (e.g. C:/app) when no relative path exists.", "type": "string", "pattern": "^[^\\\\]*$" }, @@ -91,7 +92,7 @@ "type": "string" }, "aar": { - "description": "Where the CLI puts that aar. The file only exists if the plugin has sources to build.", + "description": "Where the CLI puts the aar it builds from the plugin's sources. Says nothing about whether a file is there: a plugin without sources builds nothing, but may ship a file at this path itself.", "$ref": "#/$defs/path" }, "dependencies": { diff --git a/lib/definitions/gradle-facts.d.ts b/lib/definitions/gradle-facts.d.ts index b4d711d6a1..262a2f0aad 100644 --- a/lib/definitions/gradle-facts.d.ts +++ b/lib/definitions/gradle-facts.d.ts @@ -1,8 +1,9 @@ /** * Contents of platforms/android/nativescript-gradle.json, read by * org.nativescript:gradle-api. Mirrors gradle-api/schema/nativescript-gradle.schema.json: - * fields are only ever added, and every path is relative to the file's - * directory with forward slashes. + * fields are only ever added, and every path uses forward slashes and is + * relative to the file's directory, or absolute when no relative path exists + * (another drive on Windows). */ export interface INativeScriptGradleFacts { schemaVersion: number; diff --git a/lib/services/android/gradle-facts.ts b/lib/services/android/gradle-facts.ts index 2e9619053b..720e94a582 100644 --- a/lib/services/android/gradle-facts.ts +++ b/lib/services/android/gradle-facts.ts @@ -19,7 +19,8 @@ export interface IGradleFactsPluginInput { export interface IGradleFactsInput { /** - * Directory of the facts file; every path in the facts is relative to it. + * Directory of the facts file; paths in the facts are relative to it when + * there is a relative path to them. */ factsDir: string; cliVersion: string; @@ -37,8 +38,20 @@ export interface IGradleFactsInput { plugins: IGradleFactsPluginInput[]; } -export function toFactsPath(factsDir: string, target: string): string { - return path.relative(factsDir, target).split(path.sep).join("/") || "."; +/** + * `target` relative to `factsDir`, or absolute when no relative path exists + * (another drive on Windows), with forward slashes either way. + */ +export function toFactsPath( + factsDir: string, + target: string, + pathApi: path.PlatformPath = path, +): string { + const relative = pathApi.relative(factsDir, target); + const factsPath = pathApi.isAbsolute(relative) + ? pathApi.resolve(target) + : relative; + return factsPath.split(pathApi.sep).join("/") || "."; } export function createGradleFacts( From 96326f41e4af2cc68357c48358afa196704492f0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:36:24 -0300 Subject: [PATCH 6/9] fix(android): rebuild plugin aars per output dir and warn about shipped ones The aar build record in platforms/tempPlugin is shared by both android.pluginBuildLocation values, so after building into the mirror, switching back to "node_modules" could skip a needed rebuild and leave an aar built from older sources in the package. The record now holds the output dir it was copied to, and a different one means rebuild (also in hasOutdatedAar, so the plugin is re-prepared). Records without it count as builds into the package's platforms/android, as older CLIs did. Packages sometimes publish the aar the CLI built in the author's repo (e.g. platforms/android/core.aar). The CLI replaces or drops it, so warn before building: an aar in the package's platforms/android under the plugin's current aar name or short name, or under a scope-qualified name the CLI built the plugin as, that differs from this project's last build of the plugin. Tests now remove their temp projects. --- lib/definitions/android-plugin-migrator.d.ts | 6 + lib/services/android-plugin-build-service.ts | 154 ++++++++++++--- lib/services/android-project-service.ts | 47 +++++ test/services/android-gradle-facts.ts | 183 +++++++++++++++--- test/services/android-plugin-build-service.ts | 122 ++++++++++++ test/services/android-project-service.ts | 1 + test/stubs.ts | 4 + 7 files changed, 470 insertions(+), 47 deletions(-) diff --git a/lib/definitions/android-plugin-migrator.d.ts b/lib/definitions/android-plugin-migrator.d.ts index d80383e5de..6299510e6e 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -48,6 +48,12 @@ interface IAndroidPluginBuildService { * with aar sources; aars the package ships are not included. */ getStaleAars(options: IPluginBuildOptions, dir?: string): IStaleAar[]; + /** + * Aars in `platformsAndroidDirPath` under a name the CLI builds or removes + * for this plugin that differ from this project's last build of it, i.e. + * the package ships them. Only meaningful for a plugin with aar sources. + */ + getShippedBuildOutputAars(options: IPluginBuildOptions): string[]; } interface IStaleAar { diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index 43bda0dad9..614a063126 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -45,6 +45,14 @@ import * as _ from "lodash"; import { resolvePackageJSONPath } from "@rigor789/resolve-package-path"; import { cwd } from "process"; +interface IPluginBuildRecord { + /** + * Resolved directory the aar built from `files` was copied to. + */ + aarOutputDir: string; + files: IStringDictionary; +} + export class AndroidPluginBuildService implements IAndroidPluginBuildService { private get $platformsDataService(): IPlatformsDataService { return this.$injector.resolve("platformsDataService"); @@ -261,6 +269,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { pluginTempDir, aarPath: path.join(this.getAarOutputDir(options), `${aarName}.aar`), fileHashesInfo: pluginSourceFileHashesInfo, + options, }); if (shouldBuildAar) { @@ -303,7 +312,10 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { ); } this.copyAar(aarName, pluginTempDir, options.aarOutputDir); - this.writePluginHashInfo(pluginSourceFileHashesInfo, pluginTempDir); + this.writePluginBuildRecord(pluginTempDir, { + aarOutputDir: path.resolve(this.getAarOutputDir(options)), + files: pluginSourceFileHashesInfo, + }); } this.removeStaleAars(staleAars, inMirror); @@ -328,7 +340,26 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { return ( !this.$fs.exists( path.join(this.getAarOutputDir(options), `${aarName}.aar`), - ) || this.getStaleAars(options).length > 0 + ) || + this.getStaleAars(options).length > 0 || + this.isBuildRecordForAnotherOutputDir(options) + ); + } + + /** + * The temp project is shared by every aarOutputDir the plugin is built into, + * so its record only vouches for the aar in the dir it was last copied to. + */ + private isBuildRecordForAnotherOutputDir( + options: IPluginBuildOptions, + ): boolean { + const record = this.readPluginBuildRecord( + path.join(options.tempPluginDirPath, this.getAarName(options)), + options.platformsAndroidDirPath, + ); + return ( + !!record && + record.aarOutputDir !== path.resolve(this.getAarOutputDir(options)) ); } @@ -363,18 +394,11 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { continue; } - const tempProjectDir = path.join(options.tempPluginDirPath, candidate); - const previousOutputPath = path.join( - tempProjectDir, - "build", - "outputs", - "aar", - `${candidate}-release.aar`, + const previousOutputPath = this.getPreviousBuildOutput( + options, + candidate, ); - if ( - this.$fs.exists(previousOutputPath) && - this.getTempProjectPluginName(tempProjectDir) === options.pluginName - ) { + if (previousOutputPath) { staleAars.push({ aarPath, previousOutputPath }); } } @@ -382,6 +406,64 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { return staleAars; } + public getShippedBuildOutputAars(options: IPluginBuildOptions): string[] { + const aarName = this.getAarName(options); + const shortName = getShortPluginName(options.pluginName); + const shippedAars: string[] = []; + for (const candidate of _.uniq([ + aarName, + ...getCandidateAarNames(options.pluginName), + ])) { + const aarPath = path.join( + options.platformsAndroidDirPath, + `${candidate}.aar`, + ); + if (!this.$fs.exists(aarPath)) { + continue; + } + + const previousOutputPath = this.getPreviousBuildOutput( + options, + candidate, + ); + if ( + previousOutputPath + ? this.isSameFileContent(aarPath, previousOutputPath) + : candidate !== aarName && candidate !== shortName + ) { + // Either this project's own build, or a scope-qualified aar the CLI + // never built for the plugin, which stays in the app as the package's. + continue; + } + + shippedAars.push(aarPath); + } + + return shippedAars; + } + + /** + * The aar the CLI last built for this plugin under `name`, if the temp + * project under that name was set up for this plugin. + */ + private getPreviousBuildOutput( + options: IPluginBuildOptions, + name: string, + ): string | null { + const tempProjectDir = path.join(options.tempPluginDirPath, name); + const previousOutputPath = path.join( + tempProjectDir, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ); + return this.$fs.exists(previousOutputPath) && + this.getTempProjectPluginName(tempProjectDir) === options.pluginName + ? previousOutputPath + : null; + } + /** * The npm name setupGradle substituted into the temp project's build.gradle. */ @@ -455,12 +537,34 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { return this.$filesHashService.generateHashes(pluginNativeDataFiles); } - private writePluginHashInfo( - fileHashesInfo: IStringDictionary, + private writePluginBuildRecord( pluginTempDir: string, + record: IPluginBuildRecord, ): void { const buildDataFile = this.getPathToPluginBuildDataFile(pluginTempDir); - this.$fs.writeJson(buildDataFile, fileHashesInfo); + this.$fs.writeJson(buildDataFile, record); + } + + /** + * Records written before the output dir was recorded hold only the hashes, + * and CLIs that wrote them always built into the package's platforms/android. + */ + private readPluginBuildRecord( + pluginTempDir: string, + platformsAndroidDirPath: string, + ): IPluginBuildRecord | null { + const buildDataFile = this.getPathToPluginBuildDataFile(pluginTempDir); + if (!this.$fs.exists(buildDataFile)) { + return null; + } + + const content = this.$fs.readJson(buildDataFile) ?? {}; + return typeof content.aarOutputDir === "string" && content.files + ? content + : { + aarOutputDir: path.resolve(platformsAndroidDirPath), + files: content, + }; } private async shouldBuildAar(opts: { @@ -468,6 +572,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { pluginTempDir: string; aarPath: string; fileHashesInfo: IStringDictionary; + options: IPluginBuildOptions; }): Promise { let shouldBuildAar = opts.hasAarSources; @@ -476,15 +581,18 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { this.$fs.exists(opts.pluginTempDir) && this.$fs.exists(opts.aarPath) ) { - const buildDataFile = this.getPathToPluginBuildDataFile( + const record = this.readPluginBuildRecord( opts.pluginTempDir, + opts.options.platformsAndroidDirPath, ); - if (this.$fs.exists(buildDataFile)) { - const oldHashes = this.$fs.readJson(buildDataFile); - shouldBuildAar = this.$filesHashService.hasChangesInShasums( - oldHashes, - opts.fileHashesInfo, - ); + if (record) { + shouldBuildAar = + record.aarOutputDir !== + path.resolve(this.getAarOutputDir(opts.options)) || + this.$filesHashService.hasChangesInShasums( + record.files, + opts.fileHashesInfo, + ); } } diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index b7a789adb6..d878f54cc9 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -1107,10 +1107,57 @@ export class AndroidProjectService if (dependencies) { dependencies = this.filterUniqueDependencies(dependencies); this.setPluginAarNames(projectData, dependencies); + this.warnAboutShippedBuildOutputs(projectData, dependencies); return this.provideDependenciesJson(projectData, dependencies); } } + /** + * Must run before any plugin is built: a build replaces the temp project + * the package's aars are compared with, and in "node_modules" mode + * overwrites the package's aar. + */ + private warnAboutShippedBuildOutputs( + projectData: IProjectData, + dependencies: IDependencyData[], + ): void { + const aarNames = this.getPluginAarNames(projectData); + const tempPluginDirPath = this.getTempPluginDirPath(projectData); + for (const dep of dependencies) { + const aarName = aarNames.get(dep.name); + if (!aarName) { + continue; + } + + const nativeDir = path.join( + dep.directory, + constants.PLATFORMS_DIR_NAME, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ); + const files = this.$androidPluginBuildService + .getShippedBuildOutputAars({ + pluginName: dep.name, + aarName, + platformsAndroidDirPath: nativeDir, + aarOutputDir: nativeDir, + tempPluginDirPath, + }) + .map( + (aarPath) => + `${constants.PLATFORMS_DIR_NAME}/${AndroidProjectService.ANDROID_PLATFORM_NAME}/${path.basename(aarPath)}`, + ); + if (files.length === 1) { + this.$logger.warn( + `${dep.name} ships ${files[0]}, which looks like an aar the NativeScript CLI builds from the plugin's sources. The CLI replaces it with its own build. Plugin authors: leave it out of the published package (package.json "files" or .npmignore).`, + ); + } else if (files.length > 1) { + this.$logger.warn( + `${dep.name} ships ${files.join(" and ")}, which look like aars the NativeScript CLI builds from the plugin's sources. The CLI replaces them with its own build. Plugin authors: leave them out of the published package (package.json "files" or .npmignore).`, + ); + } + } + } + public async handleNativeDependenciesChange( projectData: IProjectData, opts: IRelease, diff --git a/test/services/android-gradle-facts.ts b/test/services/android-gradle-facts.ts index 6c82a6302b..56a08a91e6 100644 --- a/test/services/android-gradle-facts.ts +++ b/test/services/android-gradle-facts.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import * as path from "path"; -import { mkdtempSync, readFileSync, realpathSync, statSync } from "fs"; +import { mkdtempSync, readFileSync, realpathSync, rmSync, statSync } from "fs"; import { tmpdir } from "os"; import { createHash } from "crypto"; import Ajv2020, { ValidateFunction } from "ajv/dist/2020"; @@ -20,6 +20,7 @@ import { } from "../../lib/definitions/android-plugin-migrator"; import { INativeFileHashesMemo } from "../../lib/definitions/files-hash-service"; import { INativeScriptGradleFacts } from "../../lib/definitions/gradle-facts"; +import { toFactsPath } from "../../lib/services/android/gradle-facts"; import * as stubs from "../stubs"; const schemaPath = path.resolve( @@ -45,6 +46,7 @@ describe("android plugin layout and Gradle facts", () => { let outdatedAar: boolean; let buildAarError: Error; let memo: INativeFileHashesMemo; + let logger: stubs.LoggerStub; const validateFacts = (() => { let validate: ValidateFunction; @@ -111,6 +113,29 @@ describe("android plugin layout and Gradle facts", () => { }); } + function writeTempBuild(name: string, builtFor: string, content: string) { + const tempProjectDir = path.join( + projectDir, + "platforms", + "tempPlugin", + name, + ); + fs.writeFile( + path.join(tempProjectDir, "build.gradle"), + `project.ext.PLUGIN_NAME = "${builtFor}"\n`, + ); + fs.writeFile( + path.join( + tempProjectDir, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ), + content, + ); + } + const readFacts = (): INativeScriptGradleFacts => fs.readJson(path.join(platformDir, "nativescript-gradle.json")); const readDependenciesJson = () => @@ -168,6 +193,10 @@ describe("android plugin layout and Gradle facts", () => { (( injector.resolve("realAndroidPluginBuildService") )).getStaleAars(options, dir), + getShippedBuildOutputAars: (options: IPluginBuildOptions) => + (( + injector.resolve("realAndroidPluginBuildService") + )).getShippedBuildOutputAars(options), }); injector.register( "realAndroidPluginBuildService", @@ -197,9 +226,14 @@ describe("android plugin layout and Gradle facts", () => { fs = injector.resolve("fs"); memo = injector.resolve("nativeFileHashesMemo"); + logger = injector.resolve("logger"); service = injector.resolve("androidProjectService"); }); + afterEach(() => { + rmSync(projectDir, { recursive: true, force: true }); + }); + function addFixturePlugins() { addPlugin({ name: "@nativescript/core", @@ -733,29 +767,6 @@ describe("android plugin layout and Gradle facts", () => { aar, ); - function writeTempBuild(name: string, builtFor: string, content: string) { - const tempProjectDir = path.join( - projectDir, - "platforms", - "tempPlugin", - name, - ); - fs.writeFile( - path.join(tempProjectDir, "build.gradle"), - `project.ext.PLUGIN_NAME = "${builtFor}"\n`, - ); - fs.writeFile( - path.join( - tempProjectDir, - "build", - "outputs", - "aar", - `${name}-release.aar`, - ), - content, - ); - } - const prepare = () => service.beforePrepareAllPlugins( createProjectData("platforms"), @@ -855,6 +866,130 @@ describe("android plugin layout and Gradle facts", () => { }); }); + describe("aars a package ships under a name the CLI builds", () => { + const manifest = { "AndroidManifest.xml": "" }; + const shippedWarning = (pluginName: string, file: string) => + `${pluginName} ships platforms/android/${file}, which looks like an aar the NativeScript CLI builds from the plugin's sources. The CLI replaces it with its own build. Plugin authors: leave it out of the published package (package.json "files" or .npmignore).\n`; + + for (const pluginBuildLocation of ["node_modules", "platforms"]) { + it(`warns about a shipped short-name aar of a plugin with sources (${pluginBuildLocation})`, async () => { + addPlugin({ + name: "plugin-x", + nativeFiles: { ...manifest, "plugin_x.aar": "shipped" }, + }); + + await service.beforePrepareAllPlugins( + createProjectData(pluginBuildLocation), + dependencies, + ); + + assert.equal( + logger.warnOutput, + shippedWarning("plugin-x", "plugin_x.aar"), + ); + }); + } + + it("does not warn about this project's previous build of the plugin", async () => { + addPlugin({ + name: "plugin-x", + nativeFiles: { ...manifest, "plugin_x.aar": "built" }, + }); + writeTempBuild("plugin_x", "plugin-x", "built"); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + assert.equal(logger.warnOutput, ""); + }); + + it("does not warn about the aars of a plugin without sources to build", async () => { + addPlugin({ + name: "plugin-x", + nativeFiles: { "plugin_x.aar": "shipped", "include.gradle": "" }, + }); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + assert.equal(logger.warnOutput, ""); + }); + + it('compares the package, not its copy, with the previous build in "platforms" mode', async () => { + addPlugin({ + name: "plugin-x", + nativeFiles: { ...manifest, "plugin_x.aar": "shipped" }, + }); + writeTempBuild("plugin_x", "plugin-x", "built"); + fs.writeFile( + path.join( + platformDir, + ".ns-plugins", + "plugin_x", + "platforms", + "android", + "plugin_x.aar", + ), + "built", + ); + + await service.beforePrepareAllPlugins( + createProjectData("platforms"), + dependencies, + ); + + assert.equal( + logger.warnOutput, + shippedWarning("plugin-x", "plugin_x.aar"), + ); + }); + + it("warns once about every such aar of a plugin", async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { + ...manifest, + "plugin_x.aar": "shipped", + "foo_plugin_x.aar": "shipped", + }, + }); + addPlugin({ name: "plugin-x", nativeFiles: manifest }); + + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + + assert.equal( + logger.warnOutput, + `@foo/plugin-x ships platforms/android/foo_plugin_x.aar and platforms/android/plugin_x.aar, which look like aars the NativeScript CLI builds from the plugin's sources. The CLI replaces them with its own build. Plugin authors: leave them out of the published package (package.json "files" or .npmignore).\n`, + ); + }); + }); + + describe("toFactsPath", () => { + it("is relative to the facts file, with forward slashes", () => { + assert.equal( + toFactsPath( + "C:\\app\\platforms\\android", + "C:\\app\\node_modules\\x", + path.win32, + ), + "../../node_modules/x", + ); + }); + + it("is absolute, with forward slashes, when there is no relative path", async () => { + const factsPath = toFactsPath( + "C:\\app\\platforms\\android", + "D:\\shared\\node_modules\\x", + path.win32, + ); + assert.equal(factsPath, "D:/shared/node_modules/x"); + + addFixturePlugins(); + await service.beforePrepareAllPlugins(createProjectData(), dependencies); + const facts = readFacts(); + facts.plugins[0].packageDir = factsPath; + validateFacts(facts); + }); + }); + describe("invalid pluginBuildLocation", () => { it("fails prepare and names the allowed values", async () => { addFixturePlugins(); diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index feacae75a1..43d67cc6b1 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -334,6 +334,42 @@ dependencies { assert.isFalse(spawnFromEventCalled); }); + it("rebuilds into an output dir the previous build was not copied to", async () => { + const config: IPluginBuildOptions = setup({ addManifest: true }); + const mirrorConfig: IPluginBuildOptions = { + ...config, + aarOutputDir: mkdtempSync(path.join(tmpdir(), "aar-mirror-")), + pluginBuildLocation: "platforms", + }; + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + assert.isTrue(await androidBuildPluginService.buildAar(mirrorConfig)); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + spawnFromEventCalled = false; + assert.isTrue(await androidBuildPluginService.buildAar(config)); + assert.isTrue(spawnFromEventCalled); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + + spawnFromEventCalled = false; + assert.isFalse(await androidBuildPluginService.buildAar(config)); + assert.isFalse(spawnFromEventCalled); + }); + + it("takes a build record without an output dir as a build into the plugin's platforms/android", async () => { + const config: IPluginBuildOptions = setup({ + addManifest: true, + addPreviousBuildInfo: true, + }); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + + const otherOutputDir = mkdtempSync(path.join(tmpdir(), "aar-output-")); + fs.writeFile(path.join(otherOutputDir, `${shortPluginName}.aar`), "{}"); + const otherConfig = { ...config, aarOutputDir: otherOutputDir }; + assert.isTrue(androidBuildPluginService.hasOutdatedAar(otherConfig)); + assert.isTrue(await androidBuildPluginService.buildAar(otherConfig)); + }); + it("builds aar with the latest runtime gradle versions when no project dir is specified", async () => { const expectedGradleVersion = "4.4"; const expectedAndroidVersion = "4.5.6"; @@ -879,6 +915,92 @@ dependencies { }); }); + describe("getShippedBuildOutputAars", () => { + const scopedPluginName = "@foo/my-plugin"; + const qualifiedName = "foo_my_plugin"; + + function writePreviousOutput(name: string, content: string) { + fs.writeFile( + path.join(tempFolder, name, "build.gradle"), + `project.ext.PLUGIN_NAME = "${scopedPluginName}"\n`, + ); + fs.writeFile( + path.join( + tempFolder, + name, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ), + content, + ); + } + + it("reports an aar under the name the CLI builds that is not its previous build", () => { + const config = setup({ addManifest: true }); + const shippedAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(shippedAar, "shipped"); + + assert.deepStrictEqual( + androidBuildPluginService.getShippedBuildOutputAars(config), + [shippedAar], + ); + }); + + it("does not report the aar this project built", async () => { + const config = setup({ addManifest: true }); + assert.isTrue(await androidBuildPluginService.buildAar(config)); + assert.deepStrictEqual( + androidBuildPluginService.getShippedBuildOutputAars(config), + [], + ); + + assert.isFalse(await androidBuildPluginService.buildAar(config)); + assert.deepStrictEqual( + androidBuildPluginService.getShippedBuildOutputAars(config), + [], + ); + }); + + it("reports the short-name aar of a plugin built under its scope-qualified name", () => { + const config: IPluginBuildOptions = { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + aarName: qualifiedName, + }; + const shippedAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(shippedAar, "shipped"); + writePreviousOutput(qualifiedName, "built"); + fs.writeFile(path.join(pluginFolder, `${qualifiedName}.aar`), "built"); + + assert.deepStrictEqual( + androidBuildPluginService.getShippedBuildOutputAars(config), + [shippedAar], + ); + }); + + it("reports a scope-qualified aar only once the CLI built the plugin under that name", () => { + const config: IPluginBuildOptions = { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + aarName: shortPluginName, + }; + const shippedAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(shippedAar, "shipped"); + assert.deepStrictEqual( + androidBuildPluginService.getShippedBuildOutputAars(config), + [], + ); + + writePreviousOutput(qualifiedName, "built"); + assert.deepStrictEqual( + androidBuildPluginService.getShippedBuildOutputAars(config), + [shippedAar], + ); + }); + }); + 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 eea096d69f..cdc2d6e36b 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -508,6 +508,7 @@ describe("androidProjectService plugin aar names", () => { hasOutdatedAar: () => outdatedAar, hasAarSources: (platformsAndroidDirPath: string) => fs.exists(path.join(platformsAndroidDirPath, "AndroidManifest.xml")), + getShippedBuildOutputAars: (): string[] => [], }); for (const unused of [ "androidToolsInfo", diff --git a/test/stubs.ts b/test/stubs.ts index 4019b7d393..c8b9bf3663 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -763,6 +763,10 @@ export class AndroidPluginBuildServiceStub implements IAndroidPluginBuildService getStaleAars(options: IPluginBuildOptions, dir?: string): IStaleAar[] { return []; } + + getShippedBuildOutputAars(options: IPluginBuildOptions): string[] { + return []; + } } export class PlatformProjectServiceStub From ea89ed352366e263e6a0a229cbaba8d7a8cd4e25 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:54:08 -0300 Subject: [PATCH 7/9] fix(android): retry a plugin aar build whose previous attempt failed A build deletes the plugin's temp project, record included, before running Gradle. When a rebuild for another output dir failed, the next prepare found the old aar and no record, so hasOutdatedAar was false and the rebuild was never retried. For a plugin with sources, a missing or unreadable build record now makes its aar outdated; records in the old hashes-only format still count as builds into the package. --- lib/services/android-plugin-build-service.ts | 27 ++++++---- test/services/android-plugin-build-service.ts | 52 ++++++++++++++++++- 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/lib/services/android-plugin-build-service.ts b/lib/services/android-plugin-build-service.ts index 614a063126..5b834c5c9c 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -342,24 +342,24 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { path.join(this.getAarOutputDir(options), `${aarName}.aar`), ) || this.getStaleAars(options).length > 0 || - this.isBuildRecordForAnotherOutputDir(options) + !this.hasBuildRecordFor(options) ); } /** - * The temp project is shared by every aarOutputDir the plugin is built into, - * so its record only vouches for the aar in the dir it was last copied to. + * A build deletes the record before running Gradle, so a missing record + * means the last build failed or never ran. The temp project is shared by + * every aarOutputDir the plugin is built into, so a record only vouches for + * the aar in the dir it was last copied to. */ - private isBuildRecordForAnotherOutputDir( - options: IPluginBuildOptions, - ): boolean { + private hasBuildRecordFor(options: IPluginBuildOptions): boolean { const record = this.readPluginBuildRecord( path.join(options.tempPluginDirPath, this.getAarName(options)), options.platformsAndroidDirPath, ); return ( !!record && - record.aarOutputDir !== path.resolve(this.getAarOutputDir(options)) + record.aarOutputDir === path.resolve(this.getAarOutputDir(options)) ); } @@ -554,11 +554,20 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { platformsAndroidDirPath: string, ): IPluginBuildRecord | null { const buildDataFile = this.getPathToPluginBuildDataFile(pluginTempDir); - if (!this.$fs.exists(buildDataFile)) { + let content: any; + try { + content = this.$fs.exists(buildDataFile) + ? this.$fs.readJson(buildDataFile) + : null; + } catch (err) { + this.$logger.trace( + `Ignoring unreadable plugin build record ${buildDataFile}: ${err}`, + ); + } + if (!content || typeof content !== "object") { return null; } - const content = this.$fs.readJson(buildDataFile) ?? {}; return typeof content.aarOutputDir === "string" && content.files ? content : { diff --git a/test/services/android-plugin-build-service.ts b/test/services/android-plugin-build-service.ts index 43d67cc6b1..6d9b122046 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -356,6 +356,34 @@ dependencies { assert.isFalse(spawnFromEventCalled); }); + it("retries a rebuild for another output dir that failed", async () => { + const config: IPluginBuildOptions = setup({ addManifest: true }); + const mirrorConfig: IPluginBuildOptions = { + ...config, + aarOutputDir: mkdtempSync(path.join(tmpdir(), "aar-mirror-")), + pluginBuildLocation: "platforms", + }; + assert.isTrue(await androidBuildPluginService.buildAar(mirrorConfig)); + fs.writeFile(path.join(pluginFolder, `${shortPluginName}.aar`), "old"); + + failGradleBuild = true; + await assert.isRejected( + androidBuildPluginService.buildAar(config), + /Gradle build failed/, + ); + failGradleBuild = false; + + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + spawnFromEventCalled = false; + assert.isTrue(await androidBuildPluginService.buildAar(config)); + assert.isTrue(spawnFromEventCalled); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + + spawnFromEventCalled = false; + assert.isFalse(await androidBuildPluginService.buildAar(config)); + assert.isFalse(spawnFromEventCalled); + }); + it("takes a build record without an output dir as a build into the plugin's platforms/android", async () => { const config: IPluginBuildOptions = setup({ addManifest: true, @@ -905,11 +933,31 @@ dependencies { assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); }); - it("is true while the aar is missing", () => { + it("is true while the aar is missing", async () => { + const config = setupScoped(); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + await androidBuildPluginService.buildAar(config); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + + fs.deleteFile(path.join(pluginFolder, `${qualifiedName}.aar`)); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("is true while the aar has no build record, until a build succeeds", async () => { const config = setupScoped(); + fs.writeFile( + path.join(pluginFolder, `${qualifiedName}.aar`), + "shipped", + ); assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); - fs.writeFile(path.join(pluginFolder, `${qualifiedName}.aar`), ""); + fs.writeFile( + path.join(tempFolder, qualifiedName, PLUGIN_BUILD_DATA_FILENAME), + "not json", + ); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + assert.isTrue(await androidBuildPluginService.buildAar(config)); assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); }); }); From 1c87ff688d7f6e74a61836d84d39eaf3a91c91d6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 16:06:58 -0300 Subject: [PATCH 8/9] refactor(android): follow the DI and options guidelines in the new plugin code The plugin mirror and the native file hashes memo are internal contracts without a name, registered lazily and injected by token. The Gradle args service reads hostProjectPath from the build data instead of the process-wide options. --- lib/bootstrap.ts | 21 ++++- .../internal/android-plugin-mirror-service.ts | 18 +++++ .../internal/native-file-hashes-memo.ts | 15 ++++ lib/definitions/android-plugin-migrator.d.ts | 9 --- lib/definitions/build.d.ts | 19 +++-- lib/definitions/files-hash-service.d.ts | 11 --- lib/services/android-project-service.ts | 18 ++--- .../android/android-plugin-mirror-service.ts | 81 +++++++++---------- .../android/gradle-build-args-service.ts | 24 +++--- lib/services/native-file-hashes-memo.ts | 7 +- lib/services/plugins-service.ts | 12 +-- test/plugins-service.ts | 21 +++-- test/services/android-gradle-facts.ts | 18 +++-- test/services/android-project-service.ts | 20 +++-- .../android/android-plugin-mirror-service.ts | 15 ++-- .../android/gradle-build-args-service.ts | 6 +- 16 files changed, 179 insertions(+), 136 deletions(-) create mode 100644 lib/contracts/internal/android-plugin-mirror-service.ts create mode 100644 lib/contracts/internal/native-file-hashes-memo.ts diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 08d77b06f0..4251bb5e95 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -1,6 +1,9 @@ +import { provideLazy } from "./common/di"; import { injector } from "./common/yok"; import { registerBuiltInCommand } from "./common/services/command-definition-adapter"; import type { fontsCommandDefinition } from "./commands/fonts"; +import { AndroidPluginMirrorService } from "./contracts/internal/android-plugin-mirror-service"; +import { NativeFileHashesMemo } from "./contracts/internal/native-file-hashes-memo"; require("./common/bootstrap"); @@ -48,9 +51,13 @@ injector.require( "gradleBuildArgsService", "./services/android/gradle-build-args-service", ); -injector.require( - "androidPluginMirrorService", - "./services/android/android-plugin-mirror-service", +injector.register( + provideLazy( + AndroidPluginMirrorService, + () => + require("./services/android/android-plugin-mirror-service") + .AndroidPluginMirrorServiceImpl, + ), ); injector.require( "androidBundleToolService", @@ -657,7 +664,13 @@ injector.requirePublic( ); injector.require("filesHashService", "./services/files-hash-service"); -injector.require("nativeFileHashesMemo", "./services/native-file-hashes-memo"); +injector.register( + provideLazy( + NativeFileHashesMemo, + () => + require("./services/native-file-hashes-memo").NativeFileHashesMemoImpl, + ), +); injector.require("logParserService", "./services/log-parser-service"); injector.require( "iOSDebuggerPortService", diff --git a/lib/contracts/internal/android-plugin-mirror-service.ts b/lib/contracts/internal/android-plugin-mirror-service.ts new file mode 100644 index 0000000000..79c2f5d466 --- /dev/null +++ b/lib/contracts/internal/android-plugin-mirror-service.ts @@ -0,0 +1,18 @@ +import { Contract } from "../../common/di/contract"; +import type { IAndroidPluginMirror } from "../../definitions/android-plugin-migrator"; + +/** + * Keeps CLI-owned copies of plugins' Android files. + */ +@Contract() +export abstract class AndroidPluginMirrorService { + /** + * Brings `/` in line with each plugin's package.json and + * platforms/android, and removes mirrors of plugins not in `mirrors`. + * @returns The names of the plugins whose mirror changed. + */ + abstract syncMirrors( + mirrorsRoot: string, + mirrors: IAndroidPluginMirror[], + ): string[]; +} diff --git a/lib/contracts/internal/native-file-hashes-memo.ts b/lib/contracts/internal/native-file-hashes-memo.ts new file mode 100644 index 0000000000..7de80685cd --- /dev/null +++ b/lib/contracts/internal/native-file-hashes-memo.ts @@ -0,0 +1,15 @@ +import { Contract } from "../../common/di/contract"; + +/** + * sha1 hashes of plugins' native files computed earlier in the same prepare, + * so a later step does not read the same files again. Cleared when a prepare + * starts; each hash is served once. + */ +@Contract() +export abstract class NativeFileHashesMemo { + abstract clear(): void; + + abstract remember(filePath: string, sha1: string): void; + + abstract take(filePath: string): string | undefined; +} diff --git a/lib/definitions/android-plugin-migrator.d.ts b/lib/definitions/android-plugin-migrator.d.ts index 6299510e6e..da54c58fbd 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -78,15 +78,6 @@ interface IAndroidPluginMirror { excludedNativeFiles?: string[]; } -interface IAndroidPluginMirrorService { - /** - * Brings `/` in line with each plugin's package.json and - * platforms/android, and removes mirrors of plugins not in `mirrors`. - * @returns The names of the plugins whose mirror changed. - */ - syncMirrors(mirrorsRoot: string, mirrors: IAndroidPluginMirror[]): string[]; -} - /** * Describes data required for building plugin for Android. * The data can be consumed in the buildAndroidPlugin hook. diff --git a/lib/definitions/build.d.ts b/lib/definitions/build.d.ts index 391cb672c1..b9d50ccab1 100644 --- a/lib/definitions/build.d.ts +++ b/lib/definitions/build.d.ts @@ -28,12 +28,11 @@ interface IiOSBuildData extends IBuildData { } interface IAndroidBuildData - extends IBuildData, - IAndroidSigningData, - IHasAndroidBundle { + extends IBuildData, IAndroidSigningData, IHasAndroidBundle { gradleFlavor?: string; gradlePath?: string; gradleArgs?: string; + hostProjectPath?: string; } interface IAndroidSigningData { @@ -57,35 +56,35 @@ interface IBuildDataService { interface IBuildArtifactsService { getAllAppPackages( buildOutputPath: string, - validBuildOutputData: IValidBuildOutputData + validBuildOutputData: IValidBuildOutputData, ): IApplicationPackage[]; getLatestAppPackagePath( platformData: IPlatformData, - buildOutputOptions: IBuildOutputOptions + buildOutputOptions: IBuildOutputOptions, ): Promise; copyLatestAppPackage( targetPath: string, platformData: IPlatformData, - buildOutputOptions: IBuildOutputOptions + buildOutputOptions: IBuildOutputOptions, ): void; } interface IBuildInfoFileService { getLocalBuildInfo( platformData: IPlatformData, - buildData: IBuildData + buildData: IBuildData, ): IBuildInfo; getDeviceBuildInfo( device: Mobile.IDevice, - projectData: IProjectData + projectData: IProjectData, ): Promise; saveLocalBuildInfo( platformData: IPlatformData, - buildInfoFileDirname: string + buildInfoFileDirname: string, ): void; saveDeviceBuildInfo( device: Mobile.IDevice, projectData: IProjectData, - outputFilePath: string + outputFilePath: string, ): Promise; } diff --git a/lib/definitions/files-hash-service.d.ts b/lib/definitions/files-hash-service.d.ts index a494b2208f..90ff1fca63 100644 --- a/lib/definitions/files-hash-service.d.ts +++ b/lib/definitions/files-hash-service.d.ts @@ -33,14 +33,3 @@ interface IFilesHashService { newHashes: IStringDictionary, ): boolean; } - -/** - * sha1 hashes of plugins' native files computed earlier in the same prepare, - * so a later step does not read the same files again. Cleared when a prepare - * starts; each hash is served once. - */ -interface INativeFileHashesMemo { - clear(): void; - remember(filePath: string, sha1: string): void; - take(filePath: string): string | undefined; -} diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index d878f54cc9..cffb68e6bd 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -39,7 +39,6 @@ import { } from "../common/declarations"; import { IAndroidPluginBuildService, - IAndroidPluginMirrorService, IPluginBuildOptions, } from "../definitions/android-plugin-migrator"; import { @@ -47,16 +46,16 @@ import { getGradleFactsFilePath, serializeGradleFacts, } from "./android/gradle-facts"; -import { - IFilesHashService, - INativeFileHashesMemo, -} from "../definitions/files-hash-service"; +import { IFilesHashService } from "../definitions/files-hash-service"; import { IGradleCommandService, IGradleBuildService, } from "../definitions/gradle"; import { IInjector } from "../common/definitions/yok"; +import { inject } from "../common/di"; import { injector } from "../common/yok"; +import { AndroidPluginMirrorService } from "../contracts/internal/android-plugin-mirror-service"; +import { NativeFileHashesMemo } from "../contracts/internal/native-file-hashes-memo"; import { INotConfiguredEnvOptions } from "../common/definitions/commands"; interface NativeDependency { @@ -203,6 +202,9 @@ export class AndroidProjectService private static ANDROID_PLATFORM_NAME = "android"; private static MIN_RUNTIME_VERSION_WITH_GRADLE = "1.5.0"; + private androidPluginMirrorService = inject(AndroidPluginMirrorService); + private nativeFileHashesMemo = inject(NativeFileHashesMemo); + constructor( private $androidToolsInfo: IAndroidToolsInfo, private $errors: IErrors, @@ -220,9 +222,7 @@ export class AndroidProjectService private $gradleBuildService: IGradleBuildService, private $analyticsService: IAnalyticsService, private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder, - private $androidPluginMirrorService: IAndroidPluginMirrorService, private $staticConfig: Config.IStaticConfig, - private $nativeFileHashesMemo: INativeFileHashesMemo, ) { super($fs, $projectDataService); } @@ -929,7 +929,7 @@ export class AndroidProjectService projectData: IProjectData, nativeDependencyData: IDependencyData[], ): IAndroidPluginLayout { - this.$nativeFileHashesMemo.clear(); + this.nativeFileHashesMemo.clear(); const platformDir = this.getAndroidPlatformDir(projectData); const pluginBuildLocation = this.getPluginBuildLocation(projectData); const mirrorsRoot = path.join( @@ -982,7 +982,7 @@ export class AndroidProjectService } const tempPluginDirPath = this.getTempPluginDirPath(projectData); - const synced = this.$androidPluginMirrorService.syncMirrors( + const synced = this.androidPluginMirrorService.syncMirrors( mirrorsRoot, nativeDependencyData.map((dep) => { const upstreamNativeDir = path.join( diff --git a/lib/services/android/android-plugin-mirror-service.ts b/lib/services/android/android-plugin-mirror-service.ts index 52b17c7a89..baf6f1be4e 100644 --- a/lib/services/android/android-plugin-mirror-service.ts +++ b/lib/services/android/android-plugin-mirror-service.ts @@ -1,13 +1,12 @@ import * as path from "path"; import { createHash } from "crypto"; -import { IFileSystem } from "../../common/declarations"; -import { injector } from "../../common/yok"; -import { - IAndroidPluginMirror, - IAndroidPluginMirrorService, -} from "../../definitions/android-plugin-migrator"; +import { inject } from "../../common/di"; +import { FileSystem } from "../../contracts/file-system"; +import { AndroidPluginMirrorService } from "../../contracts/internal/android-plugin-mirror-service"; +import { NativeFileHashesMemo } from "../../contracts/internal/native-file-hashes-memo"; +import { Logger } from "../../contracts/logger"; +import { IAndroidPluginMirror } from "../../definitions/android-plugin-migrator"; import { PACKAGE_JSON_FILE_NAME, PLATFORMS_DIR_NAME } from "../../constants"; -import { INativeFileHashesMemo } from "../../definitions/files-hash-service"; interface IMirroredFile { sha1: string; @@ -36,12 +35,10 @@ const NATIVE_DIR = `${PLATFORMS_DIR_NAME}/android`; * unchanged are never rewritten, so Gradle's path and mtime based inputs stay * up to date across syncs. */ -export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { - constructor( - private $fs: IFileSystem, - private $logger: ILogger, - private $nativeFileHashesMemo: INativeFileHashesMemo, - ) {} +export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorService { + private fs = inject(FileSystem); + private logger = inject(Logger); + private nativeFileHashesMemo = inject(NativeFileHashesMemo); public syncMirrors( mirrorsRoot: string, @@ -58,18 +55,18 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { mirrorsRoot: string, mirrors: IAndroidPluginMirror[], ): void { - if (!this.$fs.exists(mirrorsRoot)) { + if (!this.fs.exists(mirrorsRoot)) { return; } const knownDirs = new Set( mirrors.map((mirror) => path.resolve(mirror.mirrorDir)), ); - for (const entry of this.$fs.readDirectory(mirrorsRoot)) { + for (const entry of this.fs.readDirectory(mirrorsRoot)) { const entryPath = path.join(mirrorsRoot, entry); if (!knownDirs.has(path.resolve(entryPath))) { - this.$logger.trace(`Removing unused plugin mirror ${entryPath}`); - this.$fs.deleteDirectory(entryPath); + this.logger.trace(`Removing unused plugin mirror ${entryPath}`); + this.fs.deleteDirectory(entryPath); } } } @@ -82,12 +79,12 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { // mirror taken over by another package would keep them. if ( previous.pluginName !== mirror.pluginName && - this.$fs.exists(mirror.mirrorDir) + this.fs.exists(mirror.mirrorDir) ) { - this.$logger.trace( + this.logger.trace( `Resetting plugin mirror ${mirror.mirrorDir} for ${mirror.pluginName}.`, ); - this.$fs.deleteDirectory(mirror.mirrorDir); + this.fs.deleteDirectory(mirror.mirrorDir); previous = { files: {} }; changed = true; } @@ -123,17 +120,17 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { // same-size edit (a version bump in include.gradle) would look unchanged. const sha1 = this.getSha1(source); if (relativePath !== PACKAGE_JSON_FILE_NAME) { - this.$nativeFileHashesMemo.remember(source, sha1); + this.nativeFileHashesMemo.remember(source, sha1); } - if (!known || known.sha1 !== sha1 || !this.$fs.exists(destination)) { - const stat = this.$fs.getFsStats(source); - this.$fs.deleteFile(destination); - this.$fs.copyFile(source, destination); + if (!known || known.sha1 !== sha1 || !this.fs.exists(destination)) { + const stat = this.fs.getFsStats(source); + this.fs.deleteFile(destination); + this.fs.copyFile(source, destination); // Read-only stores (pnpm, Nix, Bazel) ship 0444 files; the CLI rewrites // some mirrored files and replaces others on the next sync. - this.$fs.chmod(destination, stat.mode | 0o200); - this.$fs.utimes(destination, stat.atime, stat.mtime); + this.fs.chmod(destination, stat.mode | 0o200); + this.fs.utimes(destination, stat.atime, stat.mtime); changed = true; } @@ -142,10 +139,10 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { const manifestContent = JSON.stringify(next, null, "\t"); if ( - !this.$fs.exists(manifestPath) || - this.$fs.readText(manifestPath) !== manifestContent + !this.fs.exists(manifestPath) || + this.fs.readText(manifestPath) !== manifestContent ) { - this.$fs.writeFile(manifestPath, manifestContent); + this.fs.writeFile(manifestPath, manifestContent); } return changed; @@ -153,13 +150,13 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { private getUpstreamFiles(packageDir: string): string[] { const files: string[] = []; - if (this.$fs.exists(path.join(packageDir, PACKAGE_JSON_FILE_NAME))) { + if (this.fs.exists(path.join(packageDir, PACKAGE_JSON_FILE_NAME))) { files.push(PACKAGE_JSON_FILE_NAME); } const nativeDir = path.join(packageDir, NATIVE_DIR); - if (this.$fs.exists(nativeDir)) { - for (const file of this.$fs.enumerateFilesInDirectorySync(nativeDir)) { + if (this.fs.exists(nativeDir)) { + for (const file of this.fs.enumerateFilesInDirectorySync(nativeDir)) { files.push(toPosix(path.relative(packageDir, file))); } } @@ -169,31 +166,31 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { private deleteMirroredFile(mirrorDir: string, relativePath: string): void { const filePath = path.join(mirrorDir, relativePath); - this.$fs.deleteFile(filePath); + this.fs.deleteFile(filePath); const root = path.resolve(mirrorDir); let dir = path.dirname(path.resolve(filePath)); while ( dir !== root && dir.startsWith(root) && - this.$fs.exists(dir) && - this.$fs.isEmptyDir(dir) + this.fs.exists(dir) && + this.fs.isEmptyDir(dir) ) { - this.$fs.deleteDirectory(dir); + this.fs.deleteDirectory(dir); dir = path.dirname(dir); } } private readManifest(manifestPath: string): IMirrorManifest { try { - if (this.$fs.exists(manifestPath)) { - const manifest = this.$fs.readJson(manifestPath); + if (this.fs.exists(manifestPath)) { + const manifest = this.fs.readJson(manifestPath); if (manifest && manifest.files) { return manifest; } } } catch (err) { - this.$logger.trace( + this.logger.trace( `Ignoring unreadable plugin mirror manifest ${manifestPath}: ${err}`, ); } @@ -202,12 +199,10 @@ export class AndroidPluginMirrorService implements IAndroidPluginMirrorService { } private getSha1(filePath: string): string { - return createHash("sha1").update(this.$fs.readFile(filePath)).digest("hex"); + return createHash("sha1").update(this.fs.readFile(filePath)).digest("hex"); } } function toPosix(filePath: string): string { return filePath.split(path.sep).join("/"); } - -injector.register("androidPluginMirrorService", AndroidPluginMirrorService); diff --git a/lib/services/android/gradle-build-args-service.ts b/lib/services/android/gradle-build-args-service.ts index 9dcdb15356..d1ac7f1a77 100644 --- a/lib/services/android/gradle-build-args-service.ts +++ b/lib/services/android/gradle-build-args-service.ts @@ -2,26 +2,23 @@ import * as path from "path"; import { Configurations } from "../../common/constants"; import { IGradleBuildArgsService } from "../../definitions/gradle"; import { IAndroidBuildData } from "../../definitions/build"; -import { - IHooksService, - IAnalyticsService, - IFileSystem, -} from "../../common/declarations"; +import { IHooksService, IAnalyticsService } from "../../common/declarations"; +import { inject } from "../../common/di"; import { injector } from "../../common/yok"; +import { FileSystem } from "../../contracts/file-system"; import { IProjectData, IProjectDataService } from "../../definitions/project"; -import { IOptions } from "../../declarations"; import { PlatformTypes } from "../../constants"; import { getGradleFactsFilePath } from "./gradle-facts"; export class GradleBuildArgsService implements IGradleBuildArgsService { + private fs = inject(FileSystem); + constructor( private $hooksService: IHooksService, private $analyticsService: IAnalyticsService, private $staticConfig: Config.IStaticConfig, private $projectDataService: IProjectDataService, private $logger: ILogger, - private $fs: IFileSystem, - private $options: IOptions, ) {} public async getBuildTaskArgs( @@ -65,7 +62,7 @@ export class GradleBuildArgsService implements IGradleBuildArgsService { `-PappResourcesPath=${projectData.getAppResourcesDirectoryPath()}`, ); - const factsFile = this.getGradleFactsFile(projectData); + const factsFile = this.getGradleFactsFile(projectData, buildData); if (factsFile) { args.push(`-Pnativescript.factsFile=${factsFile}`); } @@ -87,9 +84,12 @@ export class GradleBuildArgsService implements IGradleBuildArgsService { return args; } - private getGradleFactsFile(projectData: IProjectData): string | null { + private getGradleFactsFile( + projectData: IProjectData, + buildData: IAndroidBuildData, + ): string | null { const platformDir = - this.$options.hostProjectPath || + buildData.hostProjectPath || (projectData.platformsDir && path.join(projectData.platformsDir, PlatformTypes.android)); if (!platformDir) { @@ -97,7 +97,7 @@ export class GradleBuildArgsService implements IGradleBuildArgsService { } const factsFile = getGradleFactsFilePath(platformDir); - return this.$fs.exists(factsFile) ? factsFile : null; + return this.fs.exists(factsFile) ? factsFile : null; } private getBuildLoggingArgs(): string[] { diff --git a/lib/services/native-file-hashes-memo.ts b/lib/services/native-file-hashes-memo.ts index bc896d9734..4cba41b9d5 100644 --- a/lib/services/native-file-hashes-memo.ts +++ b/lib/services/native-file-hashes-memo.ts @@ -1,8 +1,7 @@ import * as path from "path"; -import { injector } from "../common/yok"; -import { INativeFileHashesMemo } from "../definitions/files-hash-service"; +import { NativeFileHashesMemo } from "../contracts/internal/native-file-hashes-memo"; -export class NativeFileHashesMemo implements INativeFileHashesMemo { +export class NativeFileHashesMemoImpl implements NativeFileHashesMemo { private hashes = new Map(); public clear(): void { @@ -20,5 +19,3 @@ export class NativeFileHashesMemo implements INativeFileHashesMemo { return sha1; } } - -injector.register("nativeFileHashesMemo", NativeFileHashesMemo); diff --git a/lib/services/plugins-service.ts b/lib/services/plugins-service.ts index 0ba8c663f9..dfd302251d 100644 --- a/lib/services/plugins-service.ts +++ b/lib/services/plugins-service.ts @@ -28,13 +28,12 @@ import { IDictionary, IStringDictionary, } from "../common/declarations"; -import { - IFilesHashService, - INativeFileHashesMemo, -} from "../definitions/files-hash-service"; +import { IFilesHashService } from "../definitions/files-hash-service"; import * as _ from "lodash"; import { IInjector } from "../common/definitions/yok"; +import { inject } from "../common/di"; import { injector } from "../common/yok"; +import { NativeFileHashesMemo } from "../contracts/internal/native-file-hashes-memo"; import { resolvePackagePath, resolvePackageJSONPath, @@ -55,6 +54,8 @@ export class PluginsService implements IPluginsService { "pnpm-lock.yaml", ]; + private nativeFileHashesMemo = inject(NativeFileHashesMemo); + private get $platformsDataService(): IPlatformsDataService { return this.$injector.resolve("platformsDataService"); } @@ -84,7 +85,6 @@ export class PluginsService implements IPluginsService { private $injector: IInjector, private $mobileHelper: Mobile.IMobileHelper, private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder, - private $nativeFileHashesMemo: INativeFileHashesMemo, ) {} public async add(plugin: string, projectData: IProjectData): Promise { @@ -903,7 +903,7 @@ This framework comes from ${dependencyName} plugin, which is installed multiple const data: IStringDictionary = {}; const unknownFiles: string[] = []; for (const file of pluginNativeDataFiles) { - const sha1 = this.$nativeFileHashesMemo.take(file); + const sha1 = this.nativeFileHashesMemo.take(file); if (sha1 === undefined) { unknownFiles.push(file); } else { diff --git a/test/plugins-service.ts b/test/plugins-service.ts index d0ebec693c..c50cda4926 100644 --- a/test/plugins-service.ts +++ b/test/plugins-service.ts @@ -19,7 +19,10 @@ import { ProjectDataService } from "../lib/services/project-data-service"; import { ProjectFilesManager } from "../lib/common/services/project-files-manager"; import { ResourceLoader } from "../lib/common/resource-loader"; import { PluginsService } from "../lib/services/plugins-service"; -import { NativeFileHashesMemo } from "../lib/services/native-file-hashes-memo"; +import { provide } from "../lib/common/di"; +import { NativeFileHashesMemo } from "../lib/contracts/internal/native-file-hashes-memo"; +import { NativeFileHashesMemoImpl } from "../lib/services/native-file-hashes-memo"; +import { AndroidPluginMirrorService } from "../lib/contracts/internal/android-plugin-mirror-service"; import { addPluginCommandDefinition } from "../lib/commands/plugin/add-plugin"; import { registerCommand } from "../lib/common/services/command-definition-adapter"; import { MessagesService } from "../lib/common/services/messages-service"; @@ -181,8 +184,10 @@ function createTestInjector() { "androidPluginBuildService", stubs.AndroidPluginBuildServiceStub, ); - testInjector.register("androidPluginMirrorService", {}); - testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); + testInjector.register({ provide: AndroidPluginMirrorService, useValue: {} }); + testInjector.register( + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + ); testInjector.register("analyticsSettingsService", {}); testInjector.register( "androidResourcesMigrationService", @@ -779,12 +784,14 @@ describe("Plugins service", () => { ); unitTestsInjector.register("nodeModulesDependenciesBuilder", {}); unitTestsInjector.register("tempService", stubs.TempServiceStub); - unitTestsInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); + unitTestsInjector.register( + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + ); const pluginsService: PluginsService = unitTestsInjector.resolve(PluginsService); testData.pluginsService = pluginsService; - testData.memo = unitTestsInjector.resolve("nativeFileHashesMemo"); + testData.memo = unitTestsInjector.get(NativeFileHashesMemo); testData.pluginData = samplePluginData; return testData; }; @@ -889,7 +896,9 @@ describe("Plugins service", () => { ); unitTestsInjector.register("nodeModulesDependenciesBuilder", {}); unitTestsInjector.register("tempService", stubs.TempServiceStub); - unitTestsInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); + unitTestsInjector.register( + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + ); return unitTestsInjector; }; diff --git a/test/services/android-gradle-facts.ts b/test/services/android-gradle-facts.ts index 56a08a91e6..9e5287127e 100644 --- a/test/services/android-gradle-facts.ts +++ b/test/services/android-gradle-facts.ts @@ -7,9 +7,12 @@ import Ajv2020, { ValidateFunction } from "ajv/dist/2020"; import { Yok } from "../../lib/common/yok"; import { FileSystem } from "../../lib/common/file-system"; import { AndroidProjectService } from "../../lib/services/android-project-service"; -import { AndroidPluginMirrorService } from "../../lib/services/android/android-plugin-mirror-service"; +import { provide } from "../../lib/common/di"; +import { AndroidPluginMirrorService } from "../../lib/contracts/internal/android-plugin-mirror-service"; +import { AndroidPluginMirrorServiceImpl } from "../../lib/services/android/android-plugin-mirror-service"; import { AndroidPluginBuildService } from "../../lib/services/android-plugin-build-service"; -import { NativeFileHashesMemo } from "../../lib/services/native-file-hashes-memo"; +import { NativeFileHashesMemo } from "../../lib/contracts/internal/native-file-hashes-memo"; +import { NativeFileHashesMemoImpl } from "../../lib/services/native-file-hashes-memo"; import { IFileSystem } from "../../lib/common/declarations"; import { IDependencyData } from "../../lib/declarations"; import { IPluginData } from "../../lib/definitions/plugins"; @@ -18,7 +21,6 @@ import { IAndroidPluginBuildService, IPluginBuildOptions, } from "../../lib/definitions/android-plugin-migrator"; -import { INativeFileHashesMemo } from "../../lib/definitions/files-hash-service"; import { INativeScriptGradleFacts } from "../../lib/definitions/gradle-facts"; import { toFactsPath } from "../../lib/services/android/gradle-facts"; import * as stubs from "../stubs"; @@ -45,7 +47,7 @@ describe("android plugin layout and Gradle facts", () => { let migrateIncludeGradleCalls: IPluginBuildOptions[]; let outdatedAar: boolean; let buildAarError: Error; - let memo: INativeFileHashesMemo; + let memo: NativeFileHashesMemo; let logger: stubs.LoggerStub; const validateFacts = (() => { @@ -202,8 +204,10 @@ describe("android plugin layout and Gradle facts", () => { "realAndroidPluginBuildService", AndroidPluginBuildService, ); - injector.register("nativeFileHashesMemo", NativeFileHashesMemo); - injector.register("androidPluginMirrorService", AndroidPluginMirrorService); + injector.register([ + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + provide(AndroidPluginMirrorService, AndroidPluginMirrorServiceImpl), + ]); for (const unused of [ "childProcess", "hostInfo", @@ -225,7 +229,7 @@ describe("android plugin layout and Gradle facts", () => { injector.register("androidProjectService", AndroidProjectService); fs = injector.resolve("fs"); - memo = injector.resolve("nativeFileHashesMemo"); + memo = injector.get(NativeFileHashesMemo); logger = injector.resolve("logger"); service = injector.resolve("androidProjectService"); }); diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index cdc2d6e36b..ae705c77df 100644 --- a/test/services/android-project-service.ts +++ b/test/services/android-project-service.ts @@ -1,5 +1,8 @@ import { AndroidProjectService } from "../../lib/services/android-project-service"; -import { NativeFileHashesMemo } from "../../lib/services/native-file-hashes-memo"; +import { provide } from "../../lib/common/di"; +import { NativeFileHashesMemo } from "../../lib/contracts/internal/native-file-hashes-memo"; +import { NativeFileHashesMemoImpl } from "../../lib/services/native-file-hashes-memo"; +import { AndroidPluginMirrorService } from "../../lib/contracts/internal/android-plugin-mirror-service"; import { Yok } from "../../lib/common/yok"; import * as stubs from "../stubs"; import { assert } from "chai"; @@ -70,8 +73,10 @@ const createTestInjector = (): IInjector => { testInjector.register("staticConfig", { TRACK_FEATURE_USAGE_SETTING_NAME: "TrackFeatureUsage", }); - testInjector.register("androidPluginMirrorService", {}); - testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); + testInjector.register({ provide: AndroidPluginMirrorService, useValue: {} }); + testInjector.register( + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + ); return testInjector; }; @@ -495,7 +500,9 @@ describe("androidProjectService plugin aar names", () => { getRuntimePackage: (): null => null, }); testInjector.register("staticConfig", { version: "9.9.9" }); - testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); + testInjector.register( + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + ); testInjector.register("nodeModulesDependenciesBuilder", { getProductionDependencies: () => dependencies, }); @@ -519,10 +526,13 @@ describe("androidProjectService plugin aar names", () => { "gradleCommandService", "gradleBuildService", "analyticsService", - "androidPluginMirrorService", ]) { testInjector.register(unused, {}); } + testInjector.register({ + provide: AndroidPluginMirrorService, + useValue: {}, + }); testInjector.register("androidProjectService", AndroidProjectService); fs = testInjector.resolve("fs"); diff --git a/test/services/android/android-plugin-mirror-service.ts b/test/services/android/android-plugin-mirror-service.ts index 44bcc778bf..4d3b9398bb 100644 --- a/test/services/android/android-plugin-mirror-service.ts +++ b/test/services/android/android-plugin-mirror-service.ts @@ -4,8 +4,11 @@ import { mkdtempSync, statSync, utimesSync } from "fs"; import { tmpdir } from "os"; import { Yok } from "../../../lib/common/yok"; import { FileSystem } from "../../../lib/common/file-system"; -import { AndroidPluginMirrorService } from "../../../lib/services/android/android-plugin-mirror-service"; -import { NativeFileHashesMemo } from "../../../lib/services/native-file-hashes-memo"; +import { provide } from "../../../lib/common/di"; +import { AndroidPluginMirrorService } from "../../../lib/contracts/internal/android-plugin-mirror-service"; +import { AndroidPluginMirrorServiceImpl } from "../../../lib/services/android/android-plugin-mirror-service"; +import { NativeFileHashesMemo } from "../../../lib/contracts/internal/native-file-hashes-memo"; +import { NativeFileHashesMemoImpl } from "../../../lib/services/native-file-hashes-memo"; import { IFileSystem } from "../../../lib/common/declarations"; import { IAndroidPluginMirror } from "../../../lib/definitions/android-plugin-migrator"; import * as stubs from "../../stubs"; @@ -29,10 +32,12 @@ describe("androidPluginMirrorService", () => { injector.register("injector", injector); injector.register("fs", FileSystem); injector.register("logger", stubs.LoggerStub); - injector.register("nativeFileHashesMemo", NativeFileHashesMemo); - injector.register("androidPluginMirrorService", AndroidPluginMirrorService); + injector.register([ + provide(NativeFileHashesMemo, NativeFileHashesMemoImpl), + provide(AndroidPluginMirrorService, AndroidPluginMirrorServiceImpl), + ]); fs = injector.resolve("fs"); - mirrorService = injector.resolve("androidPluginMirrorService"); + mirrorService = injector.get(AndroidPluginMirrorService); const root = mkdtempSync(path.join(tmpdir(), "plugin-mirror-")); packageDir = path.join(root, "node_modules", "@foo", "plugin-x"); diff --git a/test/services/android/gradle-build-args-service.ts b/test/services/android/gradle-build-args-service.ts index 8bb7c5764c..d0c23fb262 100644 --- a/test/services/android/gradle-build-args-service.ts +++ b/test/services/android/gradle-build-args-service.ts @@ -28,7 +28,6 @@ function createTestInjector(): IInjector { }); injector.register("hooksService", stubs.HooksServiceStub); injector.register("fs", { exists: () => false }); - injector.register("options", {}); injector.register("gradleBuildArgsService", GradleBuildArgsService); injector.register("analyticsService", stubs.AnalyticsService); injector.register("staticConfig", { @@ -223,17 +222,16 @@ describe("GradleBuildArgsService", () => { "/path/to/projectDir/platforms/android/nativescript-gradle.json", ); - const getArgs = async (existing: string[], options: object = {}) => { + const getArgs = async (existing: string[], buildData: object = {}) => { const injector = createTestInjector(); injector.resolve("logger").getLevel = (): string => "INFO"; injector.register("fs", { exists: (file: string) => existing.includes(file), }); - injector.register("options", options); const service: IGradleBuildArgsService = injector.resolve( "gradleBuildArgsService", ); - return service.getBuildTaskArgs({ release: false }); + return service.getBuildTaskArgs({ release: false, ...buildData }); }; it("passes the facts file when it exists", async () => { From aa90354f5fe3c01a2f4d58740018f2532d5a6715 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 16:36:48 -0300 Subject: [PATCH 9/9] fix(android): start an interrupted plugin mirror over A mirror's manifest is removed before a sync changes it and written back once every file is in place and include.gradle is migrated. An interrupted or failed sync then resets the mirror instead of failing on paths whose type changed, keeping stray files or skipping the migration. --- .../internal/android-plugin-mirror-service.ts | 3 + lib/services/android-project-service.ts | 16 ++- .../android/android-plugin-mirror-service.ts | 27 +++- test/services/android-gradle-facts.ts | 46 ++++++- .../android/android-plugin-mirror-service.ts | 128 ++++++++++++++++++ 5 files changed, 208 insertions(+), 12 deletions(-) diff --git a/lib/contracts/internal/android-plugin-mirror-service.ts b/lib/contracts/internal/android-plugin-mirror-service.ts index 79c2f5d466..9082d3935f 100644 --- a/lib/contracts/internal/android-plugin-mirror-service.ts +++ b/lib/contracts/internal/android-plugin-mirror-service.ts @@ -9,10 +9,13 @@ export abstract class AndroidPluginMirrorService { /** * Brings `/` in line with each plugin's package.json and * platforms/android, and removes mirrors of plugins not in `mirrors`. + * @param onChanged Adapts a mirror whose files changed. If it throws, the + * next sync starts that mirror over. * @returns The names of the plugins whose mirror changed. */ abstract syncMirrors( mirrorsRoot: string, mirrors: IAndroidPluginMirror[], + onChanged?: (mirror: IAndroidPluginMirror) => void, ): string[]; } diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index cffb68e6bd..5b5ea370d6 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -796,10 +796,9 @@ export class AndroidProjectService } layout.changedMirrors.delete(pluginData.name); - this.$androidPluginBuildService.migrateIncludeGradle({ - ...options, - platformsAndroidDirPath: options.aarOutputDir, - }); + if (layout.pluginBuildLocation !== "platforms") { + this.$androidPluginBuildService.migrateIncludeGradle(options); + } } public shouldRepreparePlugin( @@ -1015,6 +1014,15 @@ export class AndroidProjectService ), }; }), + ({ pluginName }) => { + const { nativeDir } = plugins.get(pluginName); + this.$androidPluginBuildService.migrateIncludeGradle({ + pluginName, + platformsAndroidDirPath: nativeDir, + aarOutputDir: nativeDir, + tempPluginDirPath, + }); + }, ); for (const name of synced) { changedMirrors.add(name); diff --git a/lib/services/android/android-plugin-mirror-service.ts b/lib/services/android/android-plugin-mirror-service.ts index baf6f1be4e..96f629edcd 100644 --- a/lib/services/android/android-plugin-mirror-service.ts +++ b/lib/services/android/android-plugin-mirror-service.ts @@ -34,6 +34,9 @@ const NATIVE_DIR = `${PLATFORMS_DIR_NAME}/android`; * aar). Copies keep the upstream mtime, and files whose upstream content is * unchanged are never rewritten, so Gradle's path and mtime based inputs stay * up to date across syncs. + * + * A mirror has no manifest while a sync is changing it, so one that was + * interrupted is started over. */ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorService { private fs = inject(FileSystem); @@ -43,11 +46,12 @@ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorServic public syncMirrors( mirrorsRoot: string, mirrors: IAndroidPluginMirror[], + onChanged?: (mirror: IAndroidPluginMirror) => void, ): string[] { this.removeUnknownMirrors(mirrorsRoot, mirrors); return mirrors - .filter((mirror) => this.syncMirror(mirror)) + .filter((mirror) => this.syncMirror(mirror, onChanged)) .map((mirror) => mirror.pluginName); } @@ -71,10 +75,19 @@ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorServic } } - private syncMirror(mirror: IAndroidPluginMirror): boolean { + private syncMirror( + mirror: IAndroidPluginMirror, + onChanged?: (mirror: IAndroidPluginMirror) => void, + ): boolean { const manifestPath = path.join(mirror.mirrorDir, MIRROR_MANIFEST_FILE_NAME); let previous = this.readManifest(manifestPath); let changed = false; + const beginChange = () => { + if (!changed) { + this.fs.deleteFile(manifestPath); + changed = true; + } + }; // Files the CLI added (the built aar) are not in the manifest, so a // mirror taken over by another package would keep them. if ( @@ -84,9 +97,9 @@ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorServic this.logger.trace( `Resetting plugin mirror ${mirror.mirrorDir} for ${mirror.pluginName}.`, ); + beginChange(); this.fs.deleteDirectory(mirror.mirrorDir); previous = { files: {} }; - changed = true; } const next: IMirrorManifest = { @@ -107,8 +120,8 @@ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorServic const upstream = new Set(upstreamFiles); for (const relativePath of Object.keys(previous.files)) { if (!upstream.has(relativePath)) { + beginChange(); this.deleteMirroredFile(mirror.mirrorDir, relativePath); - changed = true; } } @@ -124,6 +137,7 @@ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorServic } if (!known || known.sha1 !== sha1 || !this.fs.exists(destination)) { + beginChange(); const stat = this.fs.getFsStats(source); this.fs.deleteFile(destination); this.fs.copyFile(source, destination); @@ -131,12 +145,15 @@ export class AndroidPluginMirrorServiceImpl implements AndroidPluginMirrorServic // some mirrored files and replaces others on the next sync. this.fs.chmod(destination, stat.mode | 0o200); this.fs.utimes(destination, stat.atime, stat.mtime); - changed = true; } next.files[relativePath] = { sha1 }; } + if (changed) { + onChanged?.(mirror); + } + const manifestContent = JSON.stringify(next, null, "\t"); if ( !this.fs.exists(manifestPath) || diff --git a/test/services/android-gradle-facts.ts b/test/services/android-gradle-facts.ts index 9e5287127e..5d98a4ca3e 100644 --- a/test/services/android-gradle-facts.ts +++ b/test/services/android-gradle-facts.ts @@ -47,6 +47,7 @@ describe("android plugin layout and Gradle facts", () => { let migrateIncludeGradleCalls: IPluginBuildOptions[]; let outdatedAar: boolean; let buildAarError: Error; + let migrateIncludeGradleError: Error; let memo: NativeFileHashesMemo; let logger: stubs.LoggerStub; @@ -157,6 +158,7 @@ describe("android plugin layout and Gradle facts", () => { migrateIncludeGradleCalls = []; outdatedAar = false; buildAarError = null; + migrateIncludeGradleError = null; const injector = new Yok(); injector.register("injector", injector); @@ -184,6 +186,9 @@ describe("android plugin layout and Gradle facts", () => { }, migrateIncludeGradle: (options: IPluginBuildOptions) => { migrateIncludeGradleCalls.push(options); + if (migrateIncludeGradleError) { + throw migrateIncludeGradleError; + } return false; }, hasOutdatedAar: () => outdatedAar, @@ -618,10 +623,45 @@ describe("android plugin layout and Gradle facts", () => { aarName: "foo_plugin_x", pluginBuildLocation: "platforms", }); - assert.equal( - migrateIncludeGradleCalls[0].platformsAndroidDirPath, - mirrorNativeDir, + assert.sameMembers( + migrateIncludeGradleCalls.map((call) => call.platformsAndroidDirPath), + ["core", "foo_plugin_x", "bar_plugin_x"].map((name) => + path.join(platformDir, ".ns-plugins", name, "platforms", "android"), + ), + ); + }); + + it("migrates the include.gradle of a copy without preparing the plugin", async () => { + addPlugin({ + name: "@foo/plugin-x", + nativeFiles: { "include.gradle": "dependencies {}" }, + }); + const projectData = createProjectData("platforms"); + const copies = () => + migrateIncludeGradleCalls.map((call) => call.platformsAndroidDirPath); + const copy = path.join( + platformDir, + ".ns-plugins", + "plugin_x", + "platforms", + "android", + ); + + migrateIncludeGradleError = new Error("cannot write"); + await assert.isRejected( + service.beforePrepareAllPlugins(projectData, dependencies), + /cannot write/, + ); + migrateIncludeGradleError = null; + await service.beforePrepareAllPlugins(projectData, dependencies); + assert.deepStrictEqual(copies(), [copy, copy]); + + await service.beforePrepareAllPlugins(projectData, dependencies); + await service.preparePluginNativeCode( + pluginData("@foo/plugin-x"), + projectData, ); + assert.deepStrictEqual(copies(), [copy, copy]); }); it("gives every copy its own directory, also for plugins without sources to build", async () => { diff --git a/test/services/android/android-plugin-mirror-service.ts b/test/services/android/android-plugin-mirror-service.ts index 4d3b9398bb..0f65315e67 100644 --- a/test/services/android/android-plugin-mirror-service.ts +++ b/test/services/android/android-plugin-mirror-service.ts @@ -204,6 +204,134 @@ describe("androidPluginMirrorService", () => { ); }); + describe("an interrupted sync", () => { + const interruptSync = () => { + const copyFile = fs.copyFile; + fs.copyFile = function (source: string, destination: string) { + if (path.basename(source) === "zzz.txt") { + throw new Error("interrupted"); + } + return copyFile.call(this, source, destination); + }; + fs.writeFile(upstream("platforms", "android", "zzz.txt"), "z"); + try { + assert.throws( + () => mirrorService.syncMirrors(mirrorsRoot, [mirror]), + "interrupted", + ); + } finally { + fs.copyFile = copyFile; + } + }; + const assertRecovers = () => { + assert.deepStrictEqual(mirrorService.syncMirrors(mirrorsRoot, [mirror]), [ + "@foo/plugin-x", + ]); + assert.deepStrictEqual( + mirrorService.syncMirrors(mirrorsRoot, [mirror]), + [], + ); + }; + let config: string; + + beforeEach(() => { + config = upstream("platforms", "android", "assets", "config"); + }); + + it("recovers when a file turned into a directory upstream", () => { + fs.writeFile(config, "file"); + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.deleteFile(config); + fs.writeFile(path.join(config, "settings.json"), "{}"); + interruptSync(); + + assertRecovers(); + + assert.equal( + fs.readText( + mirrored("platforms", "android", "assets", "config", "settings.json"), + ), + "{}", + ); + }); + + it("recovers when a directory turned into a file upstream", () => { + fs.writeFile(path.join(config, "settings.json"), "{}"); + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + fs.deleteDirectory(config); + fs.writeFile(config, "file"); + interruptSync(); + + assertRecovers(); + + assert.equal( + fs.readText(mirrored("platforms", "android", "assets", "config")), + "file", + ); + }); + + it("does not leave files behind that upstream removed before the next sync", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + const extra = upstream("platforms", "android", "libs", "extra.aar"); + fs.writeFile(extra, "extra"); + interruptSync(); + fs.deleteFile(extra); + + assertRecovers(); + + assert.isFalse( + fs.exists(mirrored("platforms", "android", "libs", "extra.aar")), + ); + }); + }); + + describe("onChanged", () => { + let changed: string[]; + const onChanged = ({ pluginName }: IAndroidPluginMirror) => { + changed.push(pluginName); + }; + + beforeEach(() => { + changed = []; + }); + + it("is called once the files of a changed mirror are in place", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror], (syncedMirror) => { + onChanged(syncedMirror); + assert.equal( + fs.readText(mirrored("platforms", "android", "include.gradle")), + "a", + ); + }); + + assert.deepStrictEqual(changed, ["@foo/plugin-x"]); + }); + + it("is not called for an unchanged mirror", () => { + mirrorService.syncMirrors(mirrorsRoot, [mirror]); + + mirrorService.syncMirrors(mirrorsRoot, [mirror], onChanged); + + assert.deepStrictEqual(changed, []); + }); + + it("is called again after it failed", () => { + assert.throws( + () => + mirrorService.syncMirrors(mirrorsRoot, [mirror], () => { + throw new Error("failed"); + }), + "failed", + ); + + assert.deepStrictEqual( + mirrorService.syncMirrors(mirrorsRoot, [mirror], onChanged), + ["@foo/plugin-x"], + ); + assert.deepStrictEqual(changed, ["@foo/plugin-x"]); + }); + }); + it("removes the mirrors of plugins that are gone", () => { mirrorService.syncMirrors(mirrorsRoot, [mirror]); assert.isTrue(fs.exists(mirror.mirrorDir));