Skip to content

Commit 8cf2855

Browse files
committed
fix(android): apply a plugin's own buildscript.gradle in its aar build
The plugin-build template only applied the buildscript.gradle files of the plugin's dependencies; the $rootDir/buildscript.gradle step never ran because the CLI never copies that file into the temp build folder. The plugin's own buildscript.gradle is now applied there, and org.nativescript:gradle-api is applied when that puts it on the classpath, so the dependencies {} and repositories {} blocks copied from include.gradle can use it. The plugin-build functional tests run against both this template and a frozen copy of the 9.1 one, and compile against a class from core's aar. The README gains a 'Supporting CLIs before 9.2' section.
1 parent 325ce47 commit 8cf2855

12 files changed

Lines changed: 545 additions & 102 deletions

File tree

‎gradle-api/README.md‎

Lines changed: 53 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,9 @@ In that build, **only the `dependencies {}` and `repositories {}` blocks of your
7676
run**: the CLI copies them out of the file. Nothing else in the file runs there, including the
7777
`apply plugin:` line.
7878

79-
On CLI 9.2+ with `android.pluginBuildLocation: "platforms"`, the CLI loads your `buildscript.gradle` in
80-
that build and applies the library for you. On older CLIs it doesn't, so the library isn't
81-
available there. Inside those two blocks, look the extension up instead of assuming it exists, and
82-
keep the old code as the fallback:
83-
84-
```groovy
85-
dependencies {
86-
def ns = project.extensions.findByName("nativescript")
87-
if (ns != null && ns.pluginBuild) {
88-
compileOnly ns.plugin("@nativescript/core").artifacts
89-
} else if (project.hasProperty("tempBuild")) {
90-
compileOnly fileTree(dir: "$USER_PROJECT_ROOT/node_modules/@nativescript/core/platforms/android", include: "*.aar")
91-
}
92-
}
93-
```
79+
CLI 9.2+ also runs your `buildscript.gradle` in that build and applies the library for you, so
80+
`nativescript` is available in those two blocks. Older CLIs don't, so if your plugin supports them,
81+
write those two blocks as shown in [Supporting CLIs before 9.2](#supporting-clis-before-92).
9482

9583
Elsewhere in `include.gradle` (outside those two blocks) you can use `nativescript` directly.
9684

@@ -103,6 +91,45 @@ The CLI finds those blocks by searching for the first occurrence of the words `d
10391
`repositories` in the file, so keep those words out of comments and code above the real blocks, and
10492
never put a `buildscript {}` block in `include.gradle`.
10593

94+
### Supporting CLIs before 9.2
95+
96+
Before 9.2, the CLI doesn't run your own `buildscript.gradle` in your `.aar` build, so the
97+
extension is usually missing in your copied `dependencies {}` / `repositories {}` blocks. (It is
98+
there when a plugin yours depends on loaded the library, so don't treat its presence as a CLI
99+
version check.) Look it up, and fall back to what those CLIs provide when it's missing:
100+
101+
```groovy
102+
dependencies {
103+
if (project.hasProperty("tempBuild")) {
104+
def ns = project.extensions.findByName("nativescript")
105+
if (ns != null) {
106+
compileOnly ns.plugin("@nativescript/core").artifacts
107+
} else {
108+
compileOnly fileTree(dir: "$USER_PROJECT_ROOT/node_modules/@nativescript/core/platforms/android", include: ["**/*.aar", "**/*.jar"])
109+
}
110+
}
111+
}
112+
```
113+
114+
- `tempBuild` is set in every plugin `.aar` build by every CLI since 8.4: your own build, and the
115+
builds of plugins that depend on yours, where your full `include.gradle` runs. It needs no
116+
library, so it is the outer check.
117+
- Each copied block runs on its own, without the rest of the file: blocks can't share variables,
118+
so each looks the extension up itself.
119+
120+
What older CLIs provide in those blocks:
121+
122+
| Library | CLIs before 9.2 |
123+
|---|---|
124+
| `ns.pluginBuild` | `project.hasProperty("tempBuild")` |
125+
| `ns.projectDir` | `file(USER_PROJECT_ROOT)` |
126+
| `ns.appResourcesDir` | `file(getAppResourcesPath())` |
127+
| `ns.findPackage("<name>")` | `file("$USER_PROJECT_ROOT/node_modules/<name>")` |
128+
| `ns.plugin("<name>").artifacts` | `fileTree(dir: "$USER_PROJECT_ROOT/node_modules/<name>/platforms/android", include: ["**/*.aar", "**/*.jar"])` |
129+
130+
The right-hand column only holds in a plugin's `.aar` build, and assumes a hoisted `node_modules`
131+
at the project root.
132+
106133
## API
107134

108135
`apiLevel` is `1` for everything below. New methods raise it; nothing is ever removed or changed.
@@ -156,7 +183,7 @@ your app doesn't depend on directly.
156183
## Recipes
157184

158185
**Compile against another plugin's Android library (e.g. core's widgets) in your own `.aar` build:**
159-
the guarded block in [The one thing to know](#the-one-thing-to-know-your-plugins-own-aar-build).
186+
the block in [Supporting CLIs before 9.2](#supporting-clis-before-92).
160187
Use `compileOnly`, not `implementation`: an Android library can't bundle local `.aar` files, and the
161188
app build already links every plugin.
162189

@@ -180,11 +207,14 @@ repositories {
180207

181208
## Compatibility
182209

183-
| | CLI 9.1 and older | CLI 9.2+ | CLI 9.2+ with `pluginBuildLocation: "platforms"` |
184-
|---|---|---|---|
185-
| Plugin not using the library | Unchanged | Unchanged | Gradle reads its files from a copy in `platforms/android/.ns-plugins/`, and its own `buildscript.gradle` also runs in its own `.aar` build |
186-
| Plugin using the library, app build | Fallback rules | Facts from the CLI | Facts from the CLI |
187-
| Plugin using the library, its own `.aar` build | Library not loaded: the guarded fallback runs | Library not loaded: the guarded fallback runs | Library loaded |
210+
| | CLI 9.1 and older | CLI 9.2+ |
211+
|---|---|---|
212+
| Plugin not using the library | Unchanged | Its own `buildscript.gradle` also runs in its own `.aar` build |
213+
| Plugin using the library, app build | Fallback rules | Facts from the CLI |
214+
| Plugin using the library, its own `.aar` build | Library not applied unless a plugin it depends on loaded it: the [fallback branch](#supporting-clis-before-92) runs | Library applied |
215+
216+
With [`pluginBuildLocation: "platforms"`](#for-app-developers-building-plugins-in-platformsandroid-opt-in)
217+
(CLI 9.2+), Gradle also reads every plugin's files from a copy in `platforms/android/.ns-plugins/`.
188218

189219
The fallback rules are exactly what CLIs up to 9.1 do: plugins live in
190220
`node_modules/<name>/platforms/android`, the project root is `USER_PROJECT_ROOT`, the app and
@@ -222,7 +252,8 @@ future major version of the CLI.
222252
an older one. To use something newer only when it's available, check `apiLevel` (or `has(...)`)
223253
first.
224254
- Never build paths into `node_modules` or into the CLI's output folders; ask the library.
225-
- In `dependencies {}` / `repositories {}`, use the guarded lookup shown above.
255+
- In `dependencies {}` / `repositories {}`, look the extension up and keep a fallback while you
256+
support CLIs before 9.2 ([how](#supporting-clis-before-92)).
226257

227258
## How it works
228259

‎gradle-api/samples/sample-plugin/platforms/android/buildscript.gradle‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Applied to the app's buildscript (and, with newer CLIs, to this plugin's own aar build), so the
1+
// Applied to the app's buildscript and, with CLI 9.2+, to this plugin's own aar build, so the
22
// library is on the classpath before include.gradle runs. When several plugins declare it, Gradle
33
// uses the highest version.
44
repositories {
Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
apply plugin: "org.nativescript.api"
22

3-
// The CLI builds this plugin's aar in a separate project that runs only the first block below, not
4-
// the rest of this file, and newer CLIs apply the library there only on request. Look the extension
5-
// up by name and keep the old CLI branch so the block works in every such build.
3+
// The CLI builds this plugin's aar in a separate project that runs only the next block, not the
4+
// rest of this file. CLI 9.2+ applies the library there; older CLIs may not, so the block falls
5+
// back to what they provide when the extension is missing.
66
dependencies {
7-
def ns = project.extensions.findByName("nativescript")
8-
if (ns != null && ns.pluginBuild) {
9-
compileOnly ns.plugin("@nativescript/core").artifacts
10-
} else if (project.hasProperty("tempBuild")) {
11-
compileOnly fileTree(dir: "$USER_PROJECT_ROOT/node_modules/@nativescript/core/platforms/android", include: "*.aar")
7+
if (project.hasProperty("tempBuild")) {
8+
def ns = project.extensions.findByName("nativescript")
9+
if (ns != null) {
10+
compileOnly ns.plugin("@nativescript/core").artifacts
11+
} else {
12+
compileOnly fileTree(dir: "$USER_PROJECT_ROOT/node_modules/@nativescript/core/platforms/android", include: ["**/*.aar", "**/*.jar"])
13+
}
1214
}
1315
}

‎gradle-api/src/functionalTest/java/org/nativescript/gradle/Fixtures.java‎

Lines changed: 75 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.nativescript.gradle;
22

3+
import java.io.ByteArrayOutputStream;
34
import java.io.File;
45
import java.io.IOException;
56
import java.io.UncheckedIOException;
@@ -15,6 +16,10 @@
1516
import java.util.Map;
1617
import java.util.stream.Collectors;
1718
import java.util.stream.Stream;
19+
import java.util.zip.ZipEntry;
20+
import java.util.zip.ZipOutputStream;
21+
import javax.tools.JavaCompiler;
22+
import javax.tools.ToolProvider;
1823
import org.gradle.testkit.runner.BuildResult;
1924

2025
final class Fixtures {
@@ -78,15 +83,82 @@ static Path installSample(Path projectDir) {
7883
return target;
7984
}
8085

81-
/** A stand-in for @nativescript/core: a package whose native directory holds archives. */
86+
/**
87+
* A stand-in for @nativescript/core: a package whose native directory holds Android libraries,
88+
* one of them below the top level. {@code widgets-release.aar} contains {@link #CORE_CLASS}.
89+
*/
8290
static Path installCore(Path projectDir) {
8391
Path core = projectDir.resolve("node_modules/@nativescript/core");
8492
write(core.resolve("package.json"), "{ \"name\": \"@nativescript/core\", \"version\": \"9.0.0\" }\n");
85-
write(core.resolve("platforms/android/widgets-release.aar"), "not really an aar");
86-
write(core.resolve("platforms/android/nested/inner.aar"), "not really an aar");
93+
Path classes = projectDir.resolve("core-classes");
94+
writeAar(core.resolve("platforms/android/widgets-release.aar"), compile(classes, CORE_CLASS));
95+
writeAar(core.resolve("platforms/android/nested/inner.aar"), compile(classes, "org.nativescript.widgets.nested.Inner"));
8796
return core;
8897
}
8998

99+
static final String CORE_CLASS = "org.nativescript.widgets.Probe";
100+
101+
private static Map<String, byte[]> compile(Path workDir, String className) {
102+
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
103+
if (javac == null) {
104+
throw new IllegalStateException("The functional tests need a JDK, not a JRE");
105+
}
106+
int dot = className.lastIndexOf('.');
107+
String packageName = className.substring(0, dot);
108+
String simpleName = className.substring(dot + 1);
109+
Path out = workDir.resolve(simpleName + "-classes");
110+
Path source = write(workDir.resolve(simpleName + "-src").resolve(className.replace('.', '/') + ".java"),
111+
"package " + packageName + ";\npublic final class " + simpleName + " {}\n");
112+
try {
113+
Files.createDirectories(out);
114+
} catch (IOException e) {
115+
throw new UncheckedIOException(e);
116+
}
117+
int exit = javac.run(null, null, null, "--release", "11", "-d", path(out), path(source));
118+
if (exit != 0) {
119+
throw new IllegalStateException("javac failed for " + source);
120+
}
121+
String entry = className.replace('.', '/') + ".class";
122+
return Map.of(entry, readBytes(out.resolve(entry)));
123+
}
124+
125+
private static void writeAar(Path aar, Map<String, byte[]> classes) {
126+
ByteArrayOutputStream classesJar = new ByteArrayOutputStream();
127+
try (ZipOutputStream jar = new ZipOutputStream(classesJar)) {
128+
for (Map.Entry<String, byte[]> entry : classes.entrySet()) {
129+
putEntry(jar, entry.getKey(), entry.getValue());
130+
}
131+
} catch (IOException e) {
132+
throw new UncheckedIOException(e);
133+
}
134+
String packageName = classes.keySet().iterator().next().replaceFirst("/[^/]+$", "").replace('/', '.');
135+
try {
136+
Files.createDirectories(aar.getParent());
137+
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(aar))) {
138+
putEntry(zip, "AndroidManifest.xml", ("<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\""
139+
+ packageName + "\" />\n").getBytes(StandardCharsets.UTF_8));
140+
putEntry(zip, "classes.jar", classesJar.toByteArray());
141+
putEntry(zip, "R.txt", new byte[0]);
142+
}
143+
} catch (IOException e) {
144+
throw new UncheckedIOException(e);
145+
}
146+
}
147+
148+
private static void putEntry(ZipOutputStream zip, String name, byte[] content) throws IOException {
149+
zip.putNextEntry(new ZipEntry(name));
150+
zip.write(content);
151+
zip.closeEntry();
152+
}
153+
154+
private static byte[] readBytes(Path file) {
155+
try {
156+
return Files.readAllBytes(file);
157+
} catch (IOException e) {
158+
throw new UncheckedIOException(e);
159+
}
160+
}
161+
90162
static Path write(Path file, String content) {
91163
try {
92164
Files.createDirectories(file.getParent());

0 commit comments

Comments
 (0)