Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
326 changes: 260 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,110 +1,304 @@
# AndroidRust Gradle Plugin
# Gradle Android Rust Plugin

This plugin helps with building Rust JNI libraries with Cargo for use in Android projects.
A Gradle plugin for building Rust libraries with Cargo for Android projects.

Link to the plugin on the gradle repository:
https://plugins.gradle.org/plugin/io.github.MatrixDev.android-rust
## Version 0.8.0 - New Features

# Usage
### 🚀 New in 0.8.0

Add dependencies to the root `build.gradle.kts` file
#### **Cargo Clean Support**
New `cargoClean` feature allows you to run `cargo clean` on your Rust modules:

**Manual clean (always available):**
```bash
./gradlew cargoClean # Clean all Rust modules
./gradlew cargoCleanMyLib # Clean specific module "mylib"
```

**Auto-clean with Gradle clean:**
Enable `cargoClean` to automatically run `cargo clean` when you run `./gradlew clean`:

```kotlin
buildscript {
repositories {
maven("https://plugins.gradle.org/m2/")
}
androidRust {
module("mylib") {
path = file("src/main/jni")
cargoClean = true // Enable auto-clean for this module

dependencies {
classpath("io.github.MatrixDev.android-rust:plugin:0.5.0")
buildType("release") {
cargoClean = true // Or enable only for specific build types
}
}

// Or enable globally for all modules
cargoClean = true
}
```

Add plugin to the module's `build.gradle.kts` file
**New Tasks:**
- `cargoClean` - Runs cargo clean for all Rust modules
- `cargoClean<ModuleName>` - Runs cargo clean for a specific module

```kotlin
plugins {
id("io.github.MatrixDev.android-rust")
}
```
---

## Version 0.7.0 Features

Add `androidRust` configuration
### 🚀 Major Improvements

#### 1. **cargo-ndk Integration**
The plugin now uses `cargo-ndk` instead of raw `cargo` commands for building Android libraries. This eliminates common linking errors and simplifies the build process.

**Benefits:**
- Automatic NDK environment configuration
- No manual environment variable setup needed
- Fewer linking errors and build failures
- Better compatibility with Android NDK
- Automatic rust home finding
- Fixed bugs

The plugin will automatically install `cargo-ndk` if it's not already available.

#### 2. **Full Windows Support**
Complete support for Windows development environment:
- Automatic rustup installation on Windows
- Proper handling of Windows executable paths (.cmd wrappers)
- Windows-specific rustup installation via PowerShell

#### 3. **Gradle Build Cache Support**
Proper Gradle task input/output annotations for intelligent caching:
- `@InputFiles` - Tracks Rust source files (*.rs, Cargo.toml, Cargo.lock)
- `@OutputDirectory` - Tracks JNI libs output directory
- Incremental builds - Only rebuilds when Rust sources change
- Better build performance in CI/CD environments

#### 4. **Parallel ABI Builds**
Multiple ABIs now build in parallel when using Gradle's `--parallel` flag:
- Significantly faster builds when targeting multiple architectures
- Optimal CPU utilization during compilation
- No sequential dependency chains between ABI builds

#### 5. **Enhanced Error Messages**
Detailed, actionable error messages when builds fail:
- Clear indication of what went wrong
- Specific suggestions for common issues
- Direct guidance on how to fix problems
- Better developer experience

#### 6. **Build Validation**
Pre-build validation to catch configuration errors early:
- Validates Rust project paths exist
- Checks for Cargo.toml presence
- Verifies NDK installation
- Ensures module configurations are complete

### 🔧 Configuration

#### Basic Setup

```kotlin
androidRust {
module("rust-library") {
path = file("src/rust_library")
module("mylib") {
path = file("../rust/mylib")
targets = listOf("arm", "arm64", "x86", "x86_64")

buildType("debug") {
profile = "dev"
runTests = true
}

buildType("release") {
profile = "release"
}
}
}
```

# Additional configurations

This is the list of some additional flags that can be configured:
#### Advanced Options

```kotlin
androidRust {
// MSRV, plugin will update rust if installed version is lower than requested
minimumSupportedRustVersion = "1.62.1"
minimumSupportedRustVersion = "1.70.0"

module("rust-library") {
// path to your rust library
path = file("src/rust_library")

// default rust profile
profile = "release"

// default abi targets
targets = listOf("arm", "arm64")

// "debug" build type specific configuration
module("mylib") {
path = file("../rust/mylib")
targets = listOf("arm64")
runTests = true
disableAbiOptimization = false

buildType("debug") {
// use "dev" profile in rust
profile = "dev"
}

// "release" build type specific configuration

buildType("release") {
// run rust tests before build
runTests = true

// build all supported abi versions
targets = listOf("arm", "arm64", "x86", "x86_64")
profile = "release"
}
}

// more than one library can be added
module("additional-library") {
// ...
}
}
```

### Configuration Options

| Option | Description | Default |
|--------|-------------|---------|
| `minimumSupportedRustVersion` | Minimum Rust version required | `""` (no check) |
| `path` | Path to Rust project directory | **Required** |
| `targets` | List of target ABIs | `["arm", "arm64", "x86", "x86_64"]` |
| `profile` | Rust build profile | `"release"` |
| `runTests` | Run `cargo test` before building | `null` (disabled) |
| `disableAbiOptimization` | Disable IDE ABI injection | `null` (false) |
| `cargoClean` | Run `cargo clean` with `./gradlew clean` | `null` (disabled) |

### Supported ABIs

| Rust Name | Android Name | Architecture |
|-----------|--------------|--------------|
| `arm` | `armeabi-v7a` | 32-bit ARM |
| `arm64` | `arm64-v8a` | 64-bit ARM |
| `x86` | `x86` | 32-bit x86 |
| `x86_64` | `x86_64` | 64-bit x86 |

### Requirements

- Android Gradle Plugin 7.0+
- Rust toolchain (will be auto-installed if missing)
- cargo-ndk (will be auto-installed if missing)
- Android NDK (install via Android Studio SDK Manager)

### How It Works

1. **Auto-Installation**: Plugin automatically installs rustup, Rust toolchain, cargo-ndk, and required target triples
2. **Validation**: Pre-build validation ensures all paths and configurations are correct
3. **Parallel Building**: cargo-ndk builds each target ABI, potentially in parallel
4. **Output Placement**: Compiled .so files are automatically placed in jniLibs directories
5. **Integration**: Android build system picks up the libraries automatically

### How to install

The puglin is avaiable here : https://plugins.gradle.org/plugin/io.github.rodroidmods.android-rust

### Cargo.toml Requirements

Your Rust library must be configured as a C dynamic library:

```toml
[package]
name = "mylib"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
# your dependencies here
```

### Custom Rust Binary Paths

If you have Rust installed in a custom location, create `local.properties`:

```properties
cargo.bin=/custom/path/to/cargo/bin
```

# Development support
Plugin will check for a magic property `android.injected.build.abi` set by Android Studio when
running application on device. This will limit ABI targets to only required by the device and
should speedup development quite a bit.
The plugin will look for `cargo`, `cargo-ndk`, `rustc`, and `rustup` in this directory.

In theory this should behave the same as a built-in support for the NdkBuild / CMake.
### Build Tasks

The plugin creates tasks for each build type and ABI combination:

# Goals
- Building multiple rust libraries with ease
- Allow builds to be configurable for common scenarios
- `clean<BuildType>RustJniLibs` - Clean Rust build artifacts
- `test<Module>Rust` - Run Rust tests (if enabled)
- `build<BuildType><Module>Rust[<ABI>]` - Build specific ABI
- `cargoClean` - Run cargo clean for all Rust modules
- `cargoClean<Module>` - Run cargo clean for a specific module

Example tasks:
- `buildReleaseMyLibRust[arm64-v8a]`
- `buildDebugMyLibRust[x86_64]`
- `testMyLibRust`
- `cargoClean`
- `cargoCleanMyLib`

# Non-goals
- Supporting all Gradle versions
- Allow builds to be configurable for exotic scenarios
### Gradle Build Cache

The plugin fully supports Gradle's build cache. To enable:

# IDE Enviroment PATH Workaround
On some systems (notably MacOS) gradle task might fail to locate rust binaries. At this moment there are multiple issues/discussions for both gradle and IntelliJ IDEs.
```bash
./gradlew build --build-cache
```

To solve this problem cargo path can be provided in `local.properties` file:
Or add to `gradle.properties`:
```properties
sdk.dir=...
cargo.bin=/Users/{user}/.cargo/bin/
org.gradle.caching=true
```

### Parallel Builds

To build multiple ABIs in parallel:

```bash
./gradlew build --parallel
```

Or add to `gradle.properties`:
```properties
org.gradle.parallel=true
```

### Troubleshooting

#### cargo-ndk not found
The plugin will automatically install cargo-ndk, but if you see errors, manually install:
```bash
cargo install cargo-ndk

and if you have issues with rust beign not founded, than just ad cargo.bin path in local.prop and problem will be fixed
```

#### NDK not found
Install NDK via Android Studio: Tools → SDK Manager → SDK Tools → NDK (Side by side)

#### Library not found when running from Android Studio
If you see "library not found" errors when running from Android Studio, set:
```kotlin
androidRust {
module("mylib") {
disableAbiOptimization = true
}
}
```

This forces building all ABIs instead of just the IDE-injected target.

#### Windows: rustup installation fails
Ensure PowerShell execution policy allows running scripts:
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```

### Migration from 0.6.0

The plugin now uses `cargo-ndk` internally. No configuration changes are required, but you may need to install cargo-ndk:

```bash
cargo install cargo-ndk
```

All existing configurations will continue to work.

### Note

It is recommended to use the latest version 0.8.0, as previous versions have bugs that have been fixed.

### Credits

+ Rodroid Mods
+ Matrix dev

## License

MIT License

## Contributing

Contributions welcome! Please open an issue or pull request on GitHub.
Loading