uniffi_bindgen_cs/
lib.rs

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
5pub mod gen_cs;
6use camino::{Utf8Path, Utf8PathBuf};
7use clap::Parser;
8use fs_err::File;
9pub use gen_cs::{generate_bindings, Config};
10use std::io::Write;
11use uniffi_bindgen;
12use uniffi_bindgen::interface::ComponentInterface;
13
14#[derive(Parser)]
15#[clap(name = "uniffi-bindgen")]
16#[clap(version = clap::crate_version!())]
17#[clap(propagate_version = true)]
18struct Cli {
19    /// Directory in which to write generated files. Default is same folder as .udl file.
20    #[clap(long, short)]
21    out_dir: Option<Utf8PathBuf>,
22
23    /// Do not try to format the generated bindings.
24    #[clap(long, short)]
25    no_format: bool,
26
27    /// Path to the optional uniffi config file. If not provided, uniffi-bindgen will try to guess it from the UDL's file location.
28    #[clap(long, short)]
29    config: Option<Utf8PathBuf>,
30
31    /// Path to the UDL file.
32    udl_file: Utf8PathBuf,
33}
34
35impl uniffi_bindgen::BindingGeneratorConfig for gen_cs::Config {
36    fn get_entry_from_bindings_table(bindings: &toml::Value) -> Option<toml::Value> {
37        bindings.get("csharp").map(|v| v.clone())
38    }
39
40    fn get_config_defaults(_ci: &ComponentInterface) -> Vec<(String, toml::Value)> {
41        vec![]
42    }
43}
44
45struct BindingGeneratorCs {
46    _try_format_code: bool,
47}
48
49impl uniffi_bindgen::BindingGenerator for BindingGeneratorCs {
50    type Config = gen_cs::Config;
51
52    fn write_bindings(
53        &self,
54        ci: ComponentInterface,
55        config: Self::Config,
56        out_dir: &Utf8Path,
57    ) -> anyhow::Result<()> {
58        let bindings_file = out_dir.join(format!("{}.cs", ci.namespace()));
59        let mut f = File::create(&bindings_file)?;
60        write!(f, "{}", generate_bindings(&config, &ci)?)?;
61
62        // TODO: find a way to easily format standalone C# files
63        // https://github.com/dotnet/format
64
65        Ok(())
66    }
67}
68
69pub fn main() {
70    let cli = Cli::parse();
71    uniffi_bindgen::generate_external_bindings(
72        BindingGeneratorCs {
73            _try_format_code: !cli.no_format,
74        },
75        &cli.udl_file,
76        cli.config,
77        cli.out_dir,
78    )
79    .unwrap();
80}