Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/kotlin/mod.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::{BindingGenerator, Component, GenerationSettings, Result};
6 use camino::{Utf8Path, Utf8PathBuf};
7 use fs_err as fs;
8 use std::collections::HashMap;
9 use std::process::Command;
10
11 mod gen_kotlin;
12 use gen_kotlin::{generate_bindings, Config};
13 #[cfg(feature = "bindgen-tests")]
14 pub mod test;
15
16 pub struct KotlinBindingGenerator;
17 impl BindingGenerator for KotlinBindingGenerator {
18 type Config = Config;
19
20 fn new_config(&self, root_toml: &toml::Value) -> Result<Self::Config> {
21 Ok(
22 match root_toml.get("bindings").and_then(|b| b.get("kotlin")) {
23 Some(v) => v.clone().try_into()?,
24 None => Default::default(),
25 },
26 )
27 }
28
29 fn update_component_configs(
30 &self,
31 settings: &GenerationSettings,
32 components: &mut Vec<Component<Self::Config>>,
33 ) -> Result<()> {
34 for c in &mut *components {
35 c.config
36 .package_name
37 .get_or_insert_with(|| format!("uniffi.{}", c.ci.namespace()));
38 c.config.cdylib_name.get_or_insert_with(|| {
39 settings
40 .cdylib
41 .clone()
42 .unwrap_or_else(|| format!("uniffi_{}", c.ci.namespace()))
43 });
44 }
45 // We need to update package names
46 let packages = HashMap::<String, String>::from_iter(
47 components
48 .iter()
49 .map(|c| (c.ci.crate_name().to_string(), c.config.package_name())),
50 );
51 for c in components {
52 for (ext_crate, ext_package) in &packages {
53 if ext_crate != c.ci.crate_name()
54 && !c.config.external_packages.contains_key(ext_crate)
55 {
56 c.config
57 .external_packages
58 .insert(ext_crate.to_string(), ext_package.clone());
59 }
60 }
61 }
62 Ok(())
63 }
64
65 fn write_bindings(
66 &self,
67 settings: &GenerationSettings,
68 components: &[Component<Self::Config>],
69 ) -> Result<()> {
70 for Component { ci, config, .. } in components {
71 let mut kt_file = full_bindings_path(config, &settings.out_dir);
72 fs::create_dir_all(&kt_file)?;
73 kt_file.push(format!("{}.kt", ci.namespace()));
74 fs::write(&kt_file, generate_bindings(config, ci)?)?;
75 if settings.try_format_code {
76 println!(
77 "Code generation complete, formatting with ktlint (use --no-format to disable)"
78 );
79 if let Err(e) = Command::new("ktlint").arg("-F").arg(&kt_file).output() {
80 println!(
81 "Warning: Unable to auto-format {} using ktlint: {e:?}",
82 kt_file.file_name().unwrap(),
83 );
84 }
85 }
86 }
87 Ok(())
88 }
89 }
90
91 fn full_bindings_path(config: &Config, out_dir: &Utf8Path) -> Utf8PathBuf {
92 let package_path: Utf8PathBuf = config.package_name().split('.').collect();
93 Utf8PathBuf::from(out_dir).join(package_path)
94 }