crossbundle_tools/commands/android/native/aab/
add_libs_into_aapt2.rs

1use crate::{
2    commands::android::native::{get_libs_in_dir, recursively_define_needed_libs, search_dylibs},
3    error::*,
4    types::{AndroidNdk, AndroidTarget, IntoRustTriple, Profile},
5};
6use std::path::{Path, PathBuf};
7
8/// Adds given lib and all reletad libs into APK
9pub fn add_libs_into_aapt2(
10    ndk: &AndroidNdk,
11    lib_path: &Path,
12    build_target: AndroidTarget,
13    profile: Profile,
14    min_sdk_version: u32,
15    build_dir: &Path,
16    target_dir: &Path,
17    package_name: &str,
18) -> Result<PathBuf> {
19    // Get list of android system libs (https://developer.android.com/ndk/guides/stable_apis)
20    let mut system_libs = Vec::new();
21    let sysroot_platform_lib_dir = ndk.sysroot_platform_lib_dir(build_target, min_sdk_version)?;
22    for lib in get_libs_in_dir(&sysroot_platform_lib_dir)? {
23        system_libs.push(lib);
24    }
25
26    // Get list of dylibs_paths
27    let build_path = target_dir
28        .join(build_target.rust_triple())
29        .join(profile.as_ref());
30    let mut dylibs_paths = search_dylibs(&build_path.join("build"))?;
31    dylibs_paths.push(build_path.join("tools"));
32
33    // Get list of libs that main lib need for work
34    let lib_name = lib_path.file_name().unwrap().to_str().unwrap().to_owned();
35    let mut needed_libs = vec![];
36    recursively_define_needed_libs(
37        (lib_name, lib_path.to_owned()),
38        &ndk.toolchain_bin("readelf", build_target)?,
39        &ndk.sysroot_lib_dir(&build_target)?.join("libc++_shared.so"),
40        &system_libs,
41        &dylibs_paths,
42        &mut needed_libs,
43    )?;
44
45    // Add all needed libs into apk archive
46    let abi = build_target.android_abi();
47    let out_dir = build_dir.join("lib").join(abi);
48    let project_dir = target_dir
49        .join("android")
50        .join(package_name)
51        .join("libs")
52        .join(profile)
53        .join(abi);
54    for (_lib_name, lib_path) in needed_libs {
55        add_lib_aapt2(&lib_path, &out_dir, &project_dir)?;
56    }
57    Ok(out_dir)
58}
59
60/// Copy lib into `out_dir` then add this lib into apk file
61pub fn add_lib_aapt2(lib_path: &Path, out_dir: &Path, project_dir: &Path) -> Result<()> {
62    if !lib_path.exists() {
63        return Err(Error::PathNotFound(lib_path.to_owned()));
64    }
65    std::fs::create_dir_all(out_dir)?;
66    if !project_dir.exists() {
67        std::fs::create_dir_all(project_dir)?;
68    }
69    let filename = lib_path.file_name().unwrap();
70    let mut options = fs_extra::file::CopyOptions::new();
71    options.overwrite = true;
72    fs_extra::file::copy(lib_path, out_dir.join(filename), &options)?;
73    fs_extra::file::copy(lib_path, project_dir.join(filename), &options)?;
74    Ok(())
75}