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 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 0000000000..1b33c55baa Binary files /dev/null and b/gradle-api/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle-api/gradle/wrapper/gradle-wrapper.properties b/gradle-api/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..78cb6e16a4 --- /dev/null +++ b/gradle-api/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradle-api/gradlew b/gradle-api/gradlew new file mode 100755 index 0000000000..23d15a9367 --- /dev/null +++ b/gradle-api/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + 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..a90891b6c7 --- /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 across the project.", + "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/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/common/helpers.ts b/lib/common/helpers.ts index 9ee0886f8f..f10e720172 100644 --- a/lib/common/helpers.ts +++ b/lib/common/helpers.ts @@ -125,6 +125,71 @@ function sanitizePluginName(pluginName: string): string { return pluginName.split("/").pop(); } +function getScopeQualifiedPluginName(pluginName: string): string | null { + const parts = pluginName.split("/"); + if (parts.length < 2 || !parts[0].startsWith("@")) { + return null; + } + + const scope = parts[0].slice(1).replace(/[^A-Za-z0-9_]/g, "_"); + return `${scope}_${getShortPluginName(pluginName)}`; +} + +// The aar name doubles as a Java package segment (the `org.nativescript.` +// namespace fallback), which cannot start with a digit. +function withoutLeadingDigit(name: string): string { + return /^[0-9]/.test(name) ? `_${name}` : name; +} + +/** + * Maps each plugin name to a file-system and Java-package safe name for its aar + * that is unique among `pluginNames`. A plugin whose short name is not shared + * keeps `getShortPluginName(name)`, so projects without clashes keep their names. + * Throws if two plugins still end up with the same name. + */ +export function getUniqueShortPluginNames( + pluginNames: string[], +): Map { + const sortedNames = _.sortBy(_.uniq(pluginNames)); + const namesByShortName = _.groupBy(sortedNames, getShortPluginName); + const result = new Map(); + const owners = new Map(); + + for (const pluginName of sortedNames) { + const shortName = getShortPluginName(pluginName); + const aarName = + namesByShortName[shortName].length === 1 + ? shortName + : withoutLeadingDigit( + getScopeQualifiedPluginName(pluginName) ?? shortName, + ); + + const owner = owners.get(aarName); + if (owner !== undefined) { + throw new Error( + `The plugins "${owner}" and "${pluginName}" both need the Android aar name "${aarName}". Remove one of them from the project.`, + ); + } + + owners.set(aarName, pluginName); + result.set(pluginName, aarName); + } + + return result; +} + +/** + * Every aar name `getUniqueShortPluginNames` can give this plugin, depending on + * which other plugins are installed. + */ +export function getCandidateAarNames(pluginName: string): string[] { + const shortName = getShortPluginName(pluginName); + return _.uniq([ + shortName, + withoutLeadingDigit(getScopeQualifiedPluginName(pluginName) ?? shortName), + ]); +} + export async function executeActionByChunks( initialData: T[] | IDictionary, chunkSize: number, diff --git a/lib/common/test/unit-tests/helpers.ts b/lib/common/test/unit-tests/helpers.ts index 39db1dbdf2..ee5aa542f3 100644 --- a/lib/common/test/unit-tests/helpers.ts +++ b/lib/common/test/unit-tests/helpers.ts @@ -1111,4 +1111,129 @@ const test = require("./test");`, assert.deepStrictEqual(seen.sink, ["kept"]); }); }); + + describe("getUniqueShortPluginNames", () => { + const toObject = (names: string[]) => + Object.fromEntries(helpers.getUniqueShortPluginNames(names)); + + it("keeps the short name of plugins without a clash", () => { + assert.deepStrictEqual( + toObject([ + "@nativescript/core", + "nativescript-plugin", + "@scope/my-plugin", + "9-lives", + ]), + { + "@nativescript/core": "core", + "nativescript-plugin": "nativescript_plugin", + "@scope/my-plugin": "my_plugin", + "9-lives": "9_lives", + }, + ); + }); + + it("qualifies clashing scoped plugins with their scope", () => { + assert.deepStrictEqual( + toObject(["@foo/plugin-x", "@bar/plugin-x", "@nativescript/core"]), + { + "@foo/plugin-x": "foo_plugin_x", + "@bar/plugin-x": "bar_plugin_x", + "@nativescript/core": "core", + }, + ); + }); + + it("lets an unscoped plugin keep its name when it clashes with a scoped one", () => { + assert.deepStrictEqual(toObject(["plugin-x", "@foo/plugin-x"]), { + "plugin-x": "plugin_x", + "@foo/plugin-x": "foo_plugin_x", + }); + }); + + it("replaces characters a scope may contain but a name may not", () => { + assert.deepStrictEqual(toObject(["@my.org~x/plugin", "@a/plugin"]), { + "@my.org~x/plugin": "my_org_x_plugin", + "@a/plugin": "a_plugin", + }); + }); + + it("prefixes clashing names that would start with a digit", () => { + assert.deepStrictEqual(toObject(["@1password/plugin", "@a/plugin"]), { + "@1password/plugin": "_1password_plugin", + "@a/plugin": "a_plugin", + }); + assert.deepStrictEqual(toObject(["9-lives", "@a/9-lives"]), { + "9-lives": "_9_lives", + "@a/9-lives": "a_9_lives", + }); + }); + + it("fails when two plugins still share a name", () => { + assert.throws( + () => + helpers.getUniqueShortPluginNames(["@foo/plugin-x", "@foo/plugin_x"]), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + assert.throws( + () => + helpers.getUniqueShortPluginNames([ + "foo-plugin-x", + "@foo/plugin-x", + "@bar/plugin-x", + ]), + /"@foo\/plugin-x" and "foo-plugin-x".*"foo_plugin_x"/, + ); + }); + + it("does not depend on the order of the plugins", () => { + const names = ["@foo/plugin-x", "plugin-x", "@bar/plugin-x", "other"]; + const expected = toObject(names); + assert.deepStrictEqual(toObject([...names].reverse()), expected); + assert.deepStrictEqual( + toObject([names[2], names[0], names[3], names[1]]), + expected, + ); + assert.throws( + () => + helpers.getUniqueShortPluginNames(["@foo/plugin_x", "@foo/plugin-x"]), + /"@foo\/plugin-x" and "@foo\/plugin_x"/, + ); + }); + }); + + describe("getCandidateAarNames", () => { + it("lists the short and the scope-qualified name of a scoped plugin", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("@foo/plugin-x"), [ + "plugin_x", + "foo_plugin_x", + ]); + }); + + it("lists the short name of an unscoped plugin", () => { + assert.deepStrictEqual(helpers.getCandidateAarNames("plugin-x"), [ + "plugin_x", + ]); + assert.deepStrictEqual(helpers.getCandidateAarNames("9-lives"), [ + "9_lives", + "_9_lives", + ]); + }); + + it("covers every name getUniqueShortPluginNames gives", () => { + const projects = [ + ["@foo/plugin-x"], + ["@foo/plugin-x", "@bar/plugin-x"], + ["plugin-x", "@foo/plugin-x"], + ["@1a/plugin", "@b/plugin", "plugin", "9-lives", "@c/9-lives"], + ]; + for (const project of projects) { + for (const [name, aarName] of helpers.getUniqueShortPluginNames( + project, + )) { + assert.include(helpers.getCandidateAarNames(name), aarName); + } + } + }); + }); }); diff --git a/lib/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 f5ad873307..d0440d4107 100644 --- a/lib/definitions/android-plugin-migrator.d.ts +++ b/lib/definitions/android-plugin-migrator.d.ts @@ -1,8 +1,23 @@ import { IAndroidToolsInfoData } from "../declarations"; import { IProjectDir } from "../common/declarations"; +import { AndroidPluginBuildLocation } from "./project"; interface IPluginBuildOptions extends IAndroidBuildOptions { projectDir?: string; + /** + * File name (without extension) of the built aar and of its temp build dir. + * Defaults to the plugin's short name. + */ + aarName?: string; + /** + * 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 { @@ -17,6 +32,52 @@ interface IAndroidBuildOptions { interface IAndroidPluginBuildService { buildAar(options: IPluginBuildOptions): Promise; migrateIncludeGradle(options: IPluginBuildOptions): boolean; + /** + * Whether `aarOutputDir` lacks the aar of a plugin with sources to build, or + * still holds one of `getStaleAars`. + */ + hasOutdatedAar(options: IPluginBuildOptions): boolean; + /** + * Aars in `dir` (default: `aarOutputDir`) that the CLI built for this plugin + * under another of its candidate aar names. Aars the package ships are not + * included. + */ + getStaleAars(options: IPluginBuildOptions, dir?: string): IStaleAar[]; +} + +interface IStaleAar { + aarPath: string; + /** + * The CLI's previous build output under that name, when the leftover is + * recognised by it rather than by its name alone. + */ + previousOutputPath?: string; + /** + * The file differs from `previousOutputPath`. + */ + differs: boolean; +} + +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[]; } /** @@ -49,4 +110,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 cd2a931617..299e3769f4 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 88098d55b0..2e0370f318 100644 --- a/lib/services/android-plugin-build-service.ts +++ b/lib/services/android-plugin-build-service.ts @@ -8,7 +8,12 @@ import { PLUGIN_BUILD_DATA_FILENAME, SCOPED_ANDROID_RUNTIME_NAME, } from "../constants"; -import { getShortPluginName, hook, quoteString } from "../common/helpers"; +import { + getCandidateAarNames, + getShortPluginName, + hook, + quoteString, +} from "../common/helpers"; import { Builder, parseString } from "xml2js"; import { IRuntimeGradleVersions, @@ -22,6 +27,7 @@ import { IAndroidPluginBuildService, IPluginBuildOptions, IBuildAndroidPluginData, + IStaleAar, } from "../definitions/android-plugin-migrator"; import { IFileSystem, @@ -226,19 +232,23 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { const androidSourceDirectories = this.getAndroidSourceDirectories( options.platformsAndroidDirPath, ); - const shortPluginName = getShortPluginName(options.pluginName); - const pluginTempDir = path.join(options.tempPluginDirPath, shortPluginName); + const aarName = this.getAarName(options); + const pluginTempDir = path.join(options.tempPluginDirPath, aarName); const pluginSourceFileHashesInfo = await this.getSourceFilesHashes( options.platformsAndroidDirPath, - shortPluginName, + options.pluginName, + aarName, ); + if (options.aarName && options.aarOutputDir) { + this.removeStaleAars(options); + } + const shouldBuildAar = await this.shouldBuildAar({ manifestFilePath, androidSourceDirectories, pluginTempDir, - pluginSourceDir: options.platformsAndroidDirPath, - shortPluginName, + aarPath: path.join(this.getAarOutputDir(options), `${aarName}.aar`), fileHashesInfo: pluginSourceFileHashesInfo, }); @@ -249,7 +259,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { await this.updateManifest( manifestFilePath, pluginTempMainSrcDir, - shortPluginName, + aarName, ); this.copySourceSetDirectories( androidSourceDirectories, @@ -260,24 +270,184 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { options.platformsAndroidDirPath, options.projectDir, 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, `${shortPluginName}.aar`), - ); - this.copyAar(shortPluginName, pluginTempDir, options.aarOutputDir); + }; + if (options.pluginBuildLocation === "platforms") { + pluginBuildData.pluginBuildLocation = "platforms"; + } + if (options.gradleFactsFile && this.$fs.exists(options.gradleFactsFile)) { + pluginBuildData.gradleFactsFile = path.resolve(options.gradleFactsFile); + } + await this.buildPlugin(pluginBuildData); + if (options.pluginBuildLocation !== "platforms") { + this.$watchIgnoreListService.addFileToIgnoreList( + path.join(options.aarOutputDir, `${aarName}.aar`), + ); + } + this.copyAar(aarName, pluginTempDir, options.aarOutputDir); this.writePluginHashInfo(pluginSourceFileHashesInfo, pluginTempDir); } return shouldBuildAar; } + public hasOutdatedAar(options: IPluginBuildOptions): boolean { + if (!this.$fs.exists(options.platformsAndroidDirPath)) { + return false; + } + + if (this.getStaleAars(options).length) { + return true; + } + + return ( + !this.$fs.exists( + path.join( + this.getAarOutputDir(options), + `${this.getAarName(options)}.aar`, + ), + ) && this.hasSourcesToBuild(options.platformsAndroidDirPath) + ); + } + + /** + * Gradle templates add every aar in a plugin's platforms/android to the app, + * so an aar the CLI built for this plugin under another of its candidate + * names duplicates its classes. Only plugins the CLI builds have such + * leftovers: + * - CLIs before unique aar names copied every build to `.aar`, + * replacing any file the package shipped under that name, so that file is + * always a leftover. + * - `_.aar` is a leftover only when the temp project of + * that name was set up for this plugin and still has its build output; + * otherwise the package ships it. + */ + public getStaleAars( + options: IPluginBuildOptions, + dir: string = this.getAarOutputDir(options), + ): IStaleAar[] { + const aarName = this.getAarName(options); + const shortName = getShortPluginName(options.pluginName); + const existing = getCandidateAarNames(options.pluginName) + .filter((candidate) => candidate !== aarName) + .map((candidate) => ({ + candidate, + aarPath: path.join(dir, `${candidate}.aar`), + })) + .filter(({ aarPath }) => this.$fs.exists(aarPath)); + if ( + !existing.length || + !this.hasSourcesToBuild(options.platformsAndroidDirPath) + ) { + return []; + } + + const staleAars: IStaleAar[] = []; + for (const { candidate, aarPath } of existing) { + if (candidate === shortName) { + staleAars.push({ aarPath, differs: false }); + continue; + } + + if (!options.tempPluginDirPath) { + continue; + } + + const tempProjectDir = path.join(options.tempPluginDirPath, candidate); + const previousOutputPath = path.join( + tempProjectDir, + "build", + "outputs", + "aar", + `${candidate}-release.aar`, + ); + if ( + this.$fs.exists(previousOutputPath) && + this.getTempProjectPluginName(tempProjectDir) === options.pluginName + ) { + staleAars.push({ + aarPath, + previousOutputPath, + differs: !this.isSameFileContent(aarPath, previousOutputPath), + }); + } + } + + return staleAars; + } + + private hasSourcesToBuild(platformsAndroidDirPath: string): boolean { + return ( + !!this.getManifest(platformsAndroidDirPath) || + this.getAndroidSourceDirectories(platformsAndroidDirPath).length > 0 + ); + } + + private getAarName(options: IPluginBuildOptions): string { + return options.aarName ?? getShortPluginName(options.pluginName); + } + + private getAarOutputDir(options: IPluginBuildOptions): string { + return options.aarOutputDir || options.platformsAndroidDirPath; + } + + /** + * The npm name setupGradle substituted into the temp project's build.gradle. + * Temp projects are keyed by aar name, so another plugin may now build in the + * one of this plugin's old name. + */ + private getTempProjectPluginName(tempProjectDir: string): string | null { + try { + const buildGradle = this.$fs.readText( + path.join(tempProjectDir, "build.gradle"), + ); + return ( + buildGradle.match(/project\.ext\.PLUGIN_NAME\s*=\s*"([^"]*)"/)?.[1] ?? + null + ); + } catch (err) { + return null; + } + } + + private removeStaleAars(options: IPluginBuildOptions): void { + const inMirror = options.pluginBuildLocation === "platforms"; + for (const { aarPath, previousOutputPath, differs } of this.getStaleAars( + options, + )) { + // The mirror is CLI-owned, so nothing in it needs the user's decision. + if (differs && !inMirror) { + this.$errors.fail( + `${aarPath} has a name the CLI built ${options.pluginName}'s aar under before, but differs from that build's output at ${previousOutputPath}. If it is an old build it would add duplicate classes to the app. Delete it or run \`ns clean\`.`, + ); + } + + if (!inMirror) { + this.$watchIgnoreListService.addFileToIgnoreList(aarPath); + } + + this.$logger.trace(`Removing stale plugin aar ${aarPath}`); + this.$fs.deleteFile(aarPath); + } + } + + private isSameFileContent(first: string, second: string): boolean { + if (this.$fs.getFsStats(first).size !== this.$fs.getFsStats(second).size) { + return false; + } + + const firstContent = this.$fs.readFile(first) as Buffer; + const secondContent = this.$fs.readFile(second) as Buffer; + return firstContent.equals(secondContent); + } + private cleanPluginDir(pluginTempDir: string): void { // In case plugin was already built in the current process, we need to clean the old sources as they may break the new build. this.$fs.deleteDirectory(pluginTempDir); @@ -286,15 +456,17 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { private getSourceFilesHashes( pluginTempPlatformsAndroidDir: string, - shortPluginName: string, + pluginName: string, + aarName: string, ): Promise { - const pathToAar = path.join( - pluginTempPlatformsAndroidDir, - `${shortPluginName}.aar`, + const aarPaths = new Set( + _.uniq([aarName, ...getCandidateAarNames(pluginName)]).map((name) => + path.join(pluginTempPlatformsAndroidDir, `${name}.aar`), + ), ); const pluginNativeDataFiles = this.$fs.enumerateFilesInDirectorySync( pluginTempPlatformsAndroidDir, - (file: string, stat: IFsStats) => file !== pathToAar, + (file: string, stat: IFsStats) => !aarPaths.has(file), ); return this.$filesHashService.generateHashes(pluginNativeDataFiles); } @@ -311,8 +483,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { manifestFilePath: string; androidSourceDirectories: string[]; pluginTempDir: string; - pluginSourceDir: string; - shortPluginName: string; + aarPath: string; fileHashesInfo: IStringDictionary; }): Promise { let shouldBuildAar = @@ -321,9 +492,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { if ( shouldBuildAar && this.$fs.exists(opts.pluginTempDir) && - this.$fs.exists( - path.join(opts.pluginSourceDir, `${opts.shortPluginName}.aar`), - ) + this.$fs.exists(opts.aarPath) ) { const buildDataFile = this.getPathToPluginBuildDataFile( opts.pluginTempDir, @@ -401,6 +570,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { platformsAndroidDirPath: string, projectDir: string, pluginName: string, + aarName: string, ): Promise { const gradleTemplatePath = path.resolve( path.join(__dirname, "../../vendor/gradle-plugin"), @@ -424,9 +594,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { this.replaceFileContent(buildGradlePath, "{{pluginName}}", pluginName); this.replaceFileContent(settingsGradlePath, "{{pluginName}}", pluginName); - // gets the package from the AndroidManifest to use as the namespace or fallback to the `org.nativescript.${shortPluginName}` - const shortPluginName = getShortPluginName(pluginName); - + // gets the package from the AndroidManifest to use as the namespace or fallback to the `org.nativescript.${aarName}` const manifestPath = path.join( pluginTempDir, "src", @@ -435,7 +603,7 @@ export class AndroidPluginBuildService implements IAndroidPluginBuildService { ); const manifestContent = this.$fs.readText(manifestPath); - let packageName = `org.nativescript.${shortPluginName}`; + let packageName = `org.nativescript.${aarName}`; const xml = await this.getXml(manifestContent); if (xml["manifest"]) { if (xml["manifest"]["$"]["package"]) { @@ -817,6 +985,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 d4ba573a08..59bb1e490e 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 { hook } from "../common/helpers"; +import { getUniqueShortPluginNames, hook } from "../common/helpers"; import { performanceLog } from ".././common/decorators"; import { + AndroidPluginBuildLocation, IProjectData, IProjectDataService, IValidatePlatformOutput, @@ -37,9 +38,19 @@ import { } from "../common/declarations"; import { IAndroidPluginBuildService, + IAndroidPluginMirrorService, IPluginBuildOptions, } from "../definitions/android-plugin-migrator"; -import { IFilesHashService } from "../definitions/files-hash-service"; +import { INodeModulesDependenciesBuilder } from "../definitions/platform"; +import { + createGradleFacts, + getGradleFactsFilePath, + serializeGradleFacts, +} from "./android/gradle-facts"; +import { + IFilesHashService, + INativeFileHashesMemo, +} from "../definitions/files-hash-service"; import { IGradleCommandService, IGradleBuildService, @@ -54,6 +65,30 @@ interface NativeDependency { dependencies: string[]; } +interface IAndroidPluginLocation { + 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 @@ -129,6 +164,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 @@ -155,10 +215,15 @@ export class AndroidProjectService private $gradleCommandService: IGradleCommandService, private $gradleBuildService: IGradleBuildService, private $analyticsService: IAnalyticsService, + private $androidPluginMirrorService: IAndroidPluginMirrorService, + private $staticConfig: Config.IStaticConfig, + private $nativeFileHashesMemo: INativeFileHashesMemo, ) { super($fs, $projectDataService); } + private pluginLayout: IAndroidPluginLayout = null; + private _platformData: IPlatformData = null; public getPlatformData(projectData: IProjectData): IPlatformData { if (!projectData && !this._platformData) { @@ -694,23 +759,261 @@ export class AndroidProjectService pluginData, AndroidProjectService.ANDROID_PLATFORM_NAME, ); - if (this.$fs.exists(pluginPlatformsFolderPath)) { - const options: IPluginBuildOptions = { - gradlePath: this.$options.gradlePath, - gradleArgs: this.$options.gradleArgs, - projectDir: projectData.projectDir, - pluginName: pluginData.name, - platformsAndroidDirPath: pluginPlatformsFolderPath, - aarOutputDir: pluginPlatformsFolderPath, - tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), - }; + 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; + } + + const options = this.getPluginBuildOptions( + pluginData, + pluginPlatformsFolderPath, + projectData, + layout, + ); + + 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, + }); + } - if (await this.$androidPluginBuildService.buildAar(options)) { - this.$logger.info(`Built aar for ${options.pluginName}`); + public shouldRepreparePlugin( + pluginData: IPluginData, + projectData: IProjectData, + ): boolean { + const pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath( + pluginData, + AndroidProjectService.ANDROID_PLATFORM_NAME, + ); + const layout = this.getPluginLayout(projectData); + if (!layout.plugins.has(pluginData.name)) { + return false; + } + + return ( + layout.changedMirrors.has(pluginData.name) || + this.$androidPluginBuildService.hasOutdatedAar( + this.getPluginBuildOptions( + pluginData, + pluginPlatformsFolderPath, + projectData, + layout, + ), + ) + ); + } + + private getPluginBuildOptions( + pluginData: IPluginData, + pluginPlatformsFolderPath: string, + projectData: IProjectData, + layout: IAndroidPluginLayout, + ): IPluginBuildOptions { + const plugin = layout.plugins.get(pluginData.name); + const options: IPluginBuildOptions = { + gradlePath: this.$options.gradlePath, + gradleArgs: this.$options.gradleArgs, + projectDir: projectData.projectDir, + pluginName: pluginData.name, + platformsAndroidDirPath: pluginPlatformsFolderPath, + aarOutputDir: + layout.pluginBuildLocation === "platforms" + ? plugin.nativeDir + : pluginPlatformsFolderPath, + tempPluginDirPath: this.getTempPluginDirPath(projectData), + gradleFactsFile: getGradleFactsFilePath(layout.platformDir), + }; + + if (plugin) { + options.aarName = plugin.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.$injector + .resolve( + "nodeModulesDependenciesBuilder", + ) + .getProductionDependencies( + projectData.projectDir, + projectData.ignoredDependencies, + ); + this.pluginLayout = this.createPluginLayout( + projectData, + this.filterUniqueDependencies(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, + ); + + let aarNames: Map; + try { + aarNames = getUniqueShortPluginNames( + nativeDependencyData.map((dep) => dep.name), + ); + } catch (err) { + this.$errors.fail(err.message); + } + + const plugins = new Map(); + for (const dep of nativeDependencyData) { + const aarName = aarNames.get(dep.name); + const mirrorDir = + pluginBuildLocation === "platforms" + ? path.join(mirrorsRoot, aarName) + : undefined; + plugins.set(dep.name, { + aarName, + 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); + } + } } - this.$androidPluginBuildService.migrateIncludeGradle(options); + 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, + ); + const staleAars = this.$androidPluginBuildService.getStaleAars({ + pluginName: dep.name, + aarName: aarNames.get(dep.name), + platformsAndroidDirPath: upstreamNativeDir, + aarOutputDir: upstreamNativeDir, + tempPluginDirPath, + }); + for (const { aarPath, previousOutputPath, differs } of staleAars) { + this.$logger.trace( + differs + ? `Not copying ${aarPath} into the plugin mirror: it has a name the CLI built ${dep.name}'s aar under before, and differs from that build's output at ${previousOutputPath}.` + : `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"); } public async processConfigurationFilesFromAppResources(): Promise { @@ -762,12 +1065,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, @@ -776,11 +1074,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 ( @@ -795,16 +1099,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 7c7063478f..d01ff023a9 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 fbc3f41dd6..d8556adf77 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..ec9239cd60 --- /dev/null +++ b/test/services/android-gradle-facts.ts @@ -0,0 +1,794 @@ +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, + 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 () => { + addPlugin({ name: "@foo/plugin-x", nativeFiles: { "a.txt": "" } }); + addPlugin({ name: "@foo/plugin_x", nativeFiles: { "a.txt": "" } }); + + await assert.isRejected( + service.beforePrepareAllPlugins(createProjectData(), dependencies), + /"@foo\/plugin-x" and "@foo\/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("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 c2107cf4c1..902e5671e6 100644 --- a/test/services/android-plugin-build-service.ts +++ b/test/services/android-plugin-build-service.ts @@ -24,6 +24,10 @@ describe("androidPluginBuildService", () => { const pluginName = "my-plugin"; const shortPluginName = getShortPluginName(pluginName); let spawnFromEventCalled = false; + let lastGradleArgs: string[] = []; + let builtAarContent = ""; + let ignoredFiles: string[] = []; + let hashedFiles: string[] = []; let fs: IFileSystem; let androidBuildPluginService: AndroidPluginBuildService; let tempFolder: string; @@ -46,6 +50,8 @@ describe("androidPluginBuildService", () => { }): IPluginBuildOptions { options = options || {}; spawnFromEventCalled = false; + lastGradleArgs = []; + builtAarContent = ""; tempFolder = mkdtempSync( path.join(tmpdir(), "androidPluginBuildService-temp-"), ); @@ -75,27 +81,31 @@ describe("androidPluginBuildService", () => { const testInjector: IInjector = new stubs.InjectorStub(); testInjector.register("fs", FsLib.FileSystem); testInjector.register("childProcess", { - spawnFromEvent: async (command: string): Promise => { - const finalAarName = `${shortPluginName}-release.aar`; + spawnFromEvent: async ( + command: string, + args: string[], + ): Promise => { + const pluginDir = args[args.indexOf("-p") + 1]; const aar = path.join( - tempFolder, - shortPluginName, + pluginDir, "build", "outputs", "aar", - finalAarName, + `${path.basename(pluginDir)}-release.aar`, ); - fs.writeFile(aar, ""); + fs.writeFile(aar, builtAarContent); spawnFromEventCalled = command.indexOf("gradlew") !== -1; + lastGradleArgs = args; return null; }, }); testInjector.register("packageManager", setupNpm(options)); testInjector.register("projectData", stubs.ProjectDataStub); testInjector.register("filesHashService", { - generateHashes: async ( - files: string[], - ): Promise => ({}), + generateHashes: async (files: string[]): Promise => { + hashedFiles = files; + return {}; + }, getChanges: async ( files: string[], oldHashes: IStringDictionary, @@ -106,8 +116,9 @@ describe("androidPluginBuildService", () => { ): boolean => !!options.hasChangesInShasums, }); + ignoredFiles = []; testInjector.register("watchIgnoreListService", { - addFileToIgnoreList: () => ({}), + addFileToIgnoreList: (file: string) => ignoredFiles.push(file), }); fs = testInjector.resolve("fs"); @@ -415,6 +426,352 @@ dependencies { }); }); + describe("aar names", () => { + const scopedPluginName = "@foo/my-plugin"; + const qualifiedName = "foo_my_plugin"; + + function setupScoped( + overrides?: Partial, + ): IPluginBuildOptions { + return { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + aarName: qualifiedName, + ...overrides, + }; + } + + function writePreviousOutput( + name: string, + content: string, + builtFor = scopedPluginName, + ) { + fs.writeFile( + path.join(tempFolder, name, "build.gradle"), + `buildscript {\n project.ext.PLUGIN_NAME = "${builtFor}"\n}\n`, + ); + fs.writeFile( + path.join( + tempFolder, + name, + "build", + "outputs", + "aar", + `${name}-release.aar`, + ), + content, + ); + } + + async function buildError(config: IPluginBuildOptions): Promise { + try { + await androidBuildPluginService.buildAar(config); + } catch (err) { + return err; + } + + return null; + } + + it("uses aarName for the temp project, the aar and the namespace fallback", async () => { + const config = setupScoped(); + + assert.isTrue(await androidBuildPluginService.buildAar(config)); + + const buildGradle = fs.readText( + path.join(tempFolder, qualifiedName, "build.gradle"), + ); + assert.include( + buildGradle, + `namespace "org.nativescript.${qualifiedName}"`, + ); + assert.include( + buildGradle, + `project.ext.PLUGIN_NAME = "${scopedPluginName}"`, + ); + assert.isTrue(fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`))); + assert.isFalse(fs.exists(path.join(tempFolder, shortPluginName))); + assert.isFalse( + fs.exists(path.join(pluginFolder, `${shortPluginName}.aar`)), + ); + assert.deepStrictEqual(ignoredFiles, [ + path.join(pluginFolder, `${qualifiedName}.aar`), + ]); + }); + + it("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); + }); + + it("does not hash any aar the plugin could have been built to", async () => { + const config = setupScoped(); + for (const name of [shortPluginName, qualifiedName, "unrelated"]) { + fs.writeFile(path.join(pluginFolder, `${name}.aar`), name); + } + + await androidBuildPluginService.buildAar(config); + + assert.include(hashedFiles, path.join(pluginFolder, "unrelated.aar")); + assert.notInclude( + hashedFiles, + path.join(pluginFolder, `${shortPluginName}.aar`), + ); + assert.notInclude( + hashedFiles, + path.join(pluginFolder, `${qualifiedName}.aar`), + ); + }); + + describe("under the plugin's short name", () => { + it("deletes the aar whatever its content: older CLIs always built there", async () => { + const config = setupScoped(); + const staleAar = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "shipped or built, it was replaced"); + writePreviousOutput(shortPluginName, "unscoped build", "my-plugin"); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${qualifiedName}.aar`)), + ); + }); + + it('deletes it from the CLI-owned output dir when pluginBuildLocation is "platforms"', async () => { + const mirrorDir = mkdtempSync(path.join(tmpdir(), "aar-mirror-")); + const config = setupScoped({ + aarOutputDir: mirrorDir, + pluginBuildLocation: "platforms", + }); + const staleAar = path.join(mirrorDir, `${shortPluginName}.aar`); + fs.writeFile(staleAar, "old build"); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.isTrue(fs.exists(path.join(mirrorDir, `${qualifiedName}.aar`))); + assert.deepStrictEqual(fs.readDirectory(pluginFolder), [ + "AndroidManifest.xml", + ]); + assert.deepStrictEqual(ignoredFiles, []); + }); + + it("keeps it for a plugin without sources to build", async () => { + const config: IPluginBuildOptions = { + ...setup({ addIncludeGradle: true }), + pluginName: scopedPluginName, + aarName: qualifiedName, + }; + const shipped = path.join(pluginFolder, `${shortPluginName}.aar`); + fs.writeFile(shipped, "shipped"); + writePreviousOutput(shortPluginName, "other plugin", "my-plugin"); + + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + await androidBuildPluginService.buildAar(config); + + assert.equal(fs.readText(shipped), "shipped"); + assert.isFalse(spawnFromEventCalled); + }); + + it("cleans every clashing plugin's old aar after an upgrade", async () => { + const config = setupScoped(); + const otherFolder = mkdtempSync( + path.join(tmpdir(), "androidPluginBuildService-plugin-"), + ); + fs.copyFile( + path.join(pluginFolder, "AndroidManifest.xml"), + path.join(otherFolder, "AndroidManifest.xml"), + ); + const otherConfig: IPluginBuildOptions = { + ...config, + pluginName: "@bar/my-plugin", + aarName: "bar_my_plugin", + platformsAndroidDirPath: otherFolder, + aarOutputDir: otherFolder, + }; + for (const folder of [pluginFolder, otherFolder]) { + fs.writeFile(path.join(folder, `${shortPluginName}.aar`), "old"); + } + writePreviousOutput(shortPluginName, "old", "@bar/my-plugin"); + + await androidBuildPluginService.buildAar(config); + await androidBuildPluginService.buildAar(otherConfig); + + for (const folder of [pluginFolder, otherFolder]) { + assert.isFalse( + fs.exists(path.join(folder, `${shortPluginName}.aar`)), + ); + } + assert.isTrue(fs.exists(path.join(otherFolder, "bar_my_plugin.aar"))); + }); + }); + + describe("under the plugin's scope-qualified name", () => { + function setupUnclashed(overrides?: Partial): { + config: IPluginBuildOptions; + staleAar: string; + } { + const config = setupScoped({ aarName: shortPluginName, ...overrides }); + const staleAar = path.join(config.aarOutputDir, `${qualifiedName}.aar`); + return { config, staleAar }; + } + + it("deletes an aar identical to this plugin's previous build output", async () => { + const { config, staleAar } = setupUnclashed(); + fs.writeFile(staleAar, "previous build"); + writePreviousOutput(qualifiedName, "previous build"); + + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.include(ignoredFiles, staleAar); + }); + + it("fails on an aar that differs from this plugin's previous build output", async () => { + const { config, staleAar } = setupUnclashed(); + fs.writeFile(staleAar, "something else"); + writePreviousOutput(qualifiedName, "previous build"); + const previousOutput = path.join( + tempFolder, + qualifiedName, + "build", + "outputs", + "aar", + `${qualifiedName}-release.aar`, + ); + + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + const error = await buildError(config); + + assert.include(error?.message, staleAar); + assert.include(error?.message, previousOutput); + assert.include(error?.message, "Delete it or run `ns clean`"); + assert.isTrue(fs.exists(staleAar)); + assert.isFalse(spawnFromEventCalled); + }); + + it('deletes a differing aar without failing when pluginBuildLocation is "platforms"', async () => { + const mirrorDir = mkdtempSync(path.join(tmpdir(), "aar-mirror-")); + const { config, staleAar } = setupUnclashed({ + aarOutputDir: mirrorDir, + pluginBuildLocation: "platforms", + }); + fs.writeFile(staleAar, "something else"); + writePreviousOutput(qualifiedName, "previous build"); + + await androidBuildPluginService.buildAar(config); + + assert.isFalse(fs.exists(staleAar)); + assert.isTrue(spawnFromEventCalled); + }); + + for (const { title, writeTempProject } of [ + { + title: "without a previous build output", + writeTempProject: () => {}, + }, + { + title: "whose temp project was set up for another plugin", + writeTempProject: () => + writePreviousOutput(qualifiedName, "shipped", "@other/plugin"), + }, + { + title: "whose temp project has no build.gradle", + writeTempProject: () => { + writePreviousOutput(qualifiedName, "shipped"); + fs.deleteFile(path.join(tempFolder, qualifiedName, "build.gradle")); + }, + }, + ]) { + it(`keeps an aar ${title}: the package ships it`, async () => { + const { config, staleAar } = setupUnclashed(); + fs.writeFile(staleAar, "shipped"); + fs.writeFile(path.join(pluginFolder, `${shortPluginName}.aar`), ""); + writeTempProject(); + + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + await androidBuildPluginService.buildAar(config); + + assert.equal(fs.readText(staleAar), "shipped"); + }); + } + }); + + it("leaves other candidate aars alone when no aarName is given", async () => { + const config: IPluginBuildOptions = { + ...setup({ addManifest: true }), + pluginName: scopedPluginName, + }; + const otherAar = path.join(pluginFolder, `${qualifiedName}.aar`); + fs.writeFile(otherAar, "kept"); + + await androidBuildPluginService.buildAar(config); + + assert.isTrue(fs.exists(otherAar)); + assert.isTrue( + fs.exists(path.join(pluginFolder, `${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("hasOutdatedAar", () => { + it("is false for a plugin without sources to build", () => { + const config: IPluginBuildOptions = { + ...setup({ addIncludeGradle: true }), + aarName: shortPluginName, + }; + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("is true while the aar is missing", () => { + const config = setupScoped(); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + + fs.writeFile(path.join(pluginFolder, `${qualifiedName}.aar`), ""); + assert.isFalse(androidBuildPluginService.hasOutdatedAar(config)); + }); + + it("is true while an aar under the plugin's short name is there", () => { + const config = setupScoped(); + fs.writeFile(path.join(pluginFolder, `${qualifiedName}.aar`), ""); + fs.writeFile(path.join(pluginFolder, `${shortPluginName}.aar`), ""); + assert.isTrue(androidBuildPluginService.hasOutdatedAar(config)); + }); + }); + }); + describe("migrateIncludeGradle", () => { it("if there is a legacy include.gradle file", async () => { const config: IPluginBuildOptions = setup({ diff --git a/test/services/android-project-service.ts b/test/services/android-project-service.ts index 1961548012..849f578380 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"; @@ -62,6 +63,8 @@ const createTestInjector = (): IInjector => { testInjector.register("staticConfig", { TRACK_FEATURE_USAGE_SETTING_NAME: "TrackFeatureUsage", }); + testInjector.register("androidPluginMirrorService", {}); + testInjector.register("nativeFileHashesMemo", NativeFileHashesMemo); return testInjector; }; @@ -102,7 +105,7 @@ describe("androidProjectService", () => { childProcess = injector.resolve("childProcess"); const getPlatformDataStub: sinon.SinonStub = sandbox.stub( androidProjectService, - "getPlatformData" + "getPlatformData", ); getPlatformDataStub.callsFake(() => { return { @@ -120,7 +123,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -136,7 +139,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -152,7 +155,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -169,7 +172,7 @@ describe("androidProjectService", () => { await androidProjectService.buildProject( "local/local", projectData, - buildConfig + buildConfig, ); //assert @@ -182,30 +185,30 @@ describe("androidProjectService", () => { const pathToAppResourcesDir = path.join(projectDir, "app", "App_Resources"); const pathToAppResourcesAndroid = path.join( pathToAppResourcesDir, - "Android" + "Android", ); const pathToPlatformsAndroid = path.join( projectDir, "platforms", - "android" + "android", ); const pathToResDirInPlatforms = path.join( pathToPlatformsAndroid, "app", "src", "main", - "res" + "res", ); const valuesV27Path = path.join(pathToResDirInPlatforms, "values-v27"); const valuesV28Path = path.join(pathToResDirInPlatforms, "values-v28"); const libsPath = path.join(pathToResDirInPlatforms, "libs"); const drawableHdpiPath = path.join( pathToResDirInPlatforms, - "drawable-hdpi" + "drawable-hdpi", ); const drawableLdpiPath = path.join( pathToResDirInPlatforms, - "drawable-ldpi" + "drawable-ldpi", ); let deletedDirs: string[] = []; let copiedFiles: { @@ -232,7 +235,7 @@ describe("androidProjectService", () => { }; fs.copyFile = ( sourceFileName: string, - destinationFileName: string + destinationFileName: string, ): void => { copiedFiles.push({ sourceFileName, destinationFileName }); }; @@ -245,7 +248,7 @@ describe("androidProjectService", () => { const androidToolsInfo = injector.resolve("androidToolsInfo"); androidToolsInfo.getToolsInfo = ( - config?: IProjectDir + config?: IProjectDir, ): IAndroidToolsInfoData => { return { compileSdkVersion, @@ -256,12 +259,12 @@ describe("androidProjectService", () => { describe("when new Android App_Resources structure is detected (post {N} 4.0 structure)", () => { const pathToSrcDirInAppResources = path.join( pathToAppResourcesAndroid, - "src" + "src", ); beforeEach(() => { const androidResourcesMigrationService = injector.resolve( - "androidResourcesMigrationService" + "androidResourcesMigrationService", ); androidResourcesMigrationService.hasMigrated = () => true; }); @@ -277,7 +280,7 @@ describe("androidProjectService", () => { "platforms", "android", "app", - "src" + "src", ), }, ]); @@ -333,7 +336,7 @@ describe("androidProjectService", () => { beforeEach(() => { const androidResourcesMigrationService = injector.resolve( - "androidResourcesMigrationService" + "androidResourcesMigrationService", ); androidResourcesMigrationService.hasMigrated = () => false; }); 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 c21b07ce22..90dd61fe21 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"; @@ -750,6 +751,14 @@ export class AndroidPluginBuildServiceStub implements IAndroidPluginBuildService migrateIncludeGradle(options: IPluginBuildOptions): boolean { return true; } + + hasOutdatedAar(options: IPluginBuildOptions): boolean { + return false; + } + + getStaleAars(options: IPluginBuildOptions, dir?: string): IStaleAar[] { + return []; + } } export class PlatformProjectServiceStub diff --git a/vendor/gradle-plugin/build.gradle b/vendor/gradle-plugin/build.gradle index ee6de65efd..bf42fd2048 100644 --- a/vendor/gradle-plugin/build.gradle +++ b/vendor/gradle-plugin/build.gradle @@ -120,17 +120,25 @@ 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 + def ownBuildScriptGradle = file("${getDepPlatformDir(pluginData)}/buildscript.gradle") + if (ownBuildScriptGradle.exists()) { + outLogger.withStyle(Style.SuccessHeader).println "\t + applying the plugin's own buildscript from ${ownBuildScriptGradle}" + apply from: ownBuildScriptGradle, to: buildscript } } applyBuildScriptConfigurations() } +// 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 {