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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,18 @@ Rust Analyzer and anything else with JSON-based environment handling:

For configuring rust-analyzer, add the `--json` flag and paste the blob into the relevant place in the config.

By default, `cargo ndk-env` omits cargo-ndk's internal linker wrapper variables from its output. If you want to source
the generated environment and then build directly with Cargo using the exported linker configuration, add
`--include-internal` so the linker wrapper receives its required metadata. Run this in a subshell, or unset the
`_CARGO_NDK_*` variables before running `cargo ndk` again in the same shell:

```
(
source <(cargo ndk-env --target arm64-v8a --include-internal)
cargo build --target aarch64-linux-android
)
```

## Troubleshooting

### The build is complaining that some compiler builtins are missing. What do I do?
Expand Down
117 changes: 100 additions & 17 deletions src/cli/env.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::{collections::BTreeMap, ffi::OsString};

use clap::Parser;

Expand Down Expand Up @@ -35,6 +35,37 @@ struct EnvArgs {
/// Print output in JSON format
#[arg(long)]
json: bool,

/// Include internal cargo-ndk linker wrapper variables
#[arg(long)]
include_internal: bool,
}

fn filter_env(
env: BTreeMap<String, OsString>,
include_internal: bool,
) -> BTreeMap<String, OsString> {
if include_internal {
env
} else {
env.into_iter()
.filter(|(k, _)| !k.starts_with('_'))
.collect()
}
}

fn env_value(value: &OsString) -> &str {
value
.to_str()
.expect("cargo-ndk environment values should be valid UTF-8")
}

fn shell_quote(value: &OsString) -> String {
format!("'{}'", env_value(value).replace('\'', "'\\''"))
}

fn powershell_quote(value: &OsString) -> String {
format!("'{}'", env_value(value).replace('\'', "''"))
}

pub fn run(args: Vec<String>) -> anyhow::Result<()> {
Expand All @@ -56,40 +87,40 @@ pub fn run(args: Vec<String>) -> anyhow::Result<()> {
let clang_target = clang_target(args.target.triple(), args.platform);

// Try command line, then config. Config falls back to defaults in any case.
let env = build_env(
args.target.triple(),
&ndk_home,
&ndk_version,
&clang_target,
args.platform,
&args.target.to_string(),
args.link_builtins,
args.link_libcxx_shared,
)
.into_iter()
.filter(|(k, _)| !k.starts_with('_'))
.collect::<BTreeMap<_, _>>();
let env = filter_env(
build_env(
args.target.triple(),
&ndk_home,
&ndk_version,
&clang_target,
args.platform,
&args.target.to_string(),
args.link_builtins,
args.link_libcxx_shared,
),
args.include_internal,
);

if args.json {
println!(
"{}",
serde_json::to_string_pretty(
&env.into_iter()
.map(|(k, v)| (k, v.to_str().unwrap().to_string()))
.map(|(k, v)| (k, env_value(&v).to_string()))
.collect::<BTreeMap<_, _>>()
)
.unwrap()
);
} else if args.powershell {
for (k, v) in env {
println!("${{env:{k}}}={v:?}");
println!("${{env:{k}}}={}", powershell_quote(&v));
}
println!();
println!("# To import with PowerShell:");
println!("# cargo ndk-env --powershell | Invoke-Expression");
} else {
for (k, v) in env {
println!("export {}={:?}", k.replace('-', "_"), v);
println!("export {}={}", k.replace('-', "_"), shell_quote(&v));
}
println!();
println!("# To import with bash/zsh/etc:");
Expand All @@ -98,3 +129,55 @@ pub fn run(args: Vec<String>) -> anyhow::Result<()> {

Ok(())
}

#[cfg(test)]
mod tests {
use std::{collections::BTreeMap, ffi::OsString};

use super::{filter_env, powershell_quote, shell_quote};

fn sample_env() -> BTreeMap<String, OsString> {
BTreeMap::from([
("ANDROID_PLATFORM".to_string(), OsString::from("28")),
(
"_CARGO_NDK_LINK_TARGET".to_string(),
OsString::from("--target=aarch64-linux-android28"),
),
])
}

#[test]
fn filter_env_hides_internal_values_by_default() {
let env = filter_env(sample_env(), false);

assert!(env.contains_key("ANDROID_PLATFORM"));
assert!(!env.contains_key("_CARGO_NDK_LINK_TARGET"));
}

#[test]
fn filter_env_keeps_internal_values_when_requested() {
let env = filter_env(sample_env(), true);

assert!(env.contains_key("ANDROID_PLATFORM"));
assert_eq!(
env["_CARGO_NDK_LINK_TARGET"],
OsString::from("--target=aarch64-linux-android28")
);
}

#[test]
fn shell_quote_preserves_internal_ldflag_separator() {
assert_eq!(
shell_quote(&OsString::from("-L/path with spaces\x1f-lbuiltins's")),
"'-L/path with spaces\x1f-lbuiltins'\\''s'"
);
}

#[test]
fn powershell_quote_preserves_internal_ldflag_separator() {
assert_eq!(
powershell_quote(&OsString::from("-L/path with spaces\x1f-lbuiltins's")),
"'-L/path with spaces\x1f-lbuiltins''s'"
);
}
}
1 change: 1 addition & 0 deletions tests/cli_help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ fn cargo_ndk_env_help_shows_env_format_options() {
assert!(help.contains("Usage: cargo-ndk-env"));
assert!(help.contains("--powershell"));
assert!(help.contains("--json"));
assert!(help.contains("--include-internal"));
assert!(!help.contains("--output-dir"));
}
}
Loading