1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
mod cabal;
mod cargo;
#[macro_use]
mod errors;
mod flake;
mod hsbindgen;

use cargo::{get_crate_type, CrateType};
use clap::{arg, Parser, Subcommand};
use errors::Error;
use std::{fs, path::Path};

/// A tool that helps you to turn in one command a Rust crate into a Haskell Cabal library
#[derive(Parser)]
#[command(version)]
struct Args {
    #[command(subcommand)]
    cabal: Wrapper,
}

#[derive(Subcommand)]
enum Wrapper {
    #[command(subcommand)]
    Cabal(Commands),
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize the project by generating custom Cabal files
    Init {
        /// Generate a haskell.nix / naersk based flake.nix
        #[arg(long)]
        enable_nix: bool,
        /// Run a clean before generating files
        #[arg(long)]
        overwrite: bool,
    },
    /// Remove files generated by cargo-cabal, except flake.nix
    Clean,
}

// TODO: rather use https://crates.io/crates/cargo_metadata?!
struct CargoMetadata {
    root: cargo::Root,
    version: String,
    name: String,
    module: String,
}

/// Parse Cargo.toml file content ...
fn parse_cargo_toml() -> Result<CargoMetadata, Error> {
    let cargo = fs::read_to_string("Cargo.toml").or(Err(Error::NoCargoToml))?;
    let root: cargo::Root = toml::from_str(&cargo).or(Err(Error::WrongCargoToml))?;
    let package = root.clone().package.ok_or(Error::NotCargoPackage)?;
    let version = package.version.unwrap_or_else(|| "0.1.0.0".to_owned());
    let name = package.name.ok_or(Error::NoCargoNameField)?;
    let module = name
        .split(&['-', '_'])
        .map(|s| format!("{}{}", &s[..1].to_uppercase(), &s[1..]))
        .collect::<Vec<String>>()
        .join("");
    Ok(CargoMetadata {
        root,
        version,
        name,
        module,
    })
}

/// Parse `cargo-cabal` CLI arguments
pub fn parse_cli_args(args: Vec<String>) -> Result<(), Error> {
    let metadata = parse_cargo_toml()?;
    match Args::parse_from(args).cabal {
        Wrapper::Cabal(command) => match command {
            Commands::Init { .. } => cmd_init(command, metadata),
            Commands::Clean => cmd_clean(&metadata.name),
        },
    }
}

/// Initialize the project by generating custom Cabal files
fn cmd_init(args: Commands, metadata: CargoMetadata) -> Result<(), Error> {
    let Commands::Init {
        enable_nix,
        overwrite,
    } = args else { unreachable!() };
    let CargoMetadata {
        root,
        version,
        name,
        module,
    } = metadata;

    // `cargo cabal init --overwrite` == `cargo cabal clean && cargo cabal init`
    if overwrite {
        cmd_clean(&name)?;
    }

    // Check that project have a `crate-type` target ...
    let crate_type = get_crate_type(root).ok_or(Error::NoCargoLibTarget)?;

    // Check that `cargo cabal init` have not been already run ...
    let cabal = format!("{name}.cabal");
    (!(Path::new(&cabal).exists()
        || Path::new(".hsbindgen").exists()
        || Path::new("hsbindgen.toml").exists()
        || Path::new("Setup.hs").exists()
        || Path::new("Setup.lhs").exists()))
    .then_some(())
    .ok_or_else(|| Error::CabalFilesExist(name.to_owned()))?;
    // ... and that no existing file would conflict ...
    if crate_type == CrateType::DynLib {
        (!Path::new("build.rs").exists())
            .then_some(())
            .ok_or(Error::BuildFileExist)?;
    }
    if enable_nix {
        (!Path::new("flake.rs").exists())
            .then_some(())
            .ok_or(Error::FlakeFileExist)?;
    }

    // Generate wanted files from templates ... starting by a `.cabal` ...
    fs::write(
        cabal.clone(),
        cabal::generate(&name, &module, &version, enable_nix),
    )
    .or(Err(Error::FailedToWriteFile(cabal)))?;

    // `hsbindgen.toml` is a config file readed by `#[hs_bindgen]` proc macro ...
    fs::write("hsbindgen.toml", hsbindgen::generate(&module))
        .map_err(|_| Error::FailedToWriteFile("hsbindgen.toml".to_owned()))?;

    // If `crate-type = [ "cdylib" ]` then a custom `build.rs` is needed ...
    if crate_type == CrateType::DynLib {
        fs::write("build.rs", include_str!("build.rs"))
            .map_err(|_| Error::FailedToWriteFile("build.rs".to_owned()))?;
    }

    // `--enable-nix` CLI option generate a `flake.nix` rather than a `Setup.lhs`
    if enable_nix {
        fs::write("flake.nix", flake::generate(&name))
            .map_err(|_| Error::FailedToWriteFile("flake.nix".to_owned()))?;
    } else {
        fs::write("Setup.lhs", include_str!("Setup.lhs"))
            .map_err(|_| Error::FailedToWriteFile("Setup.lhs".to_owned()))?;
    }

    println!(
        "\
Cabal files generated!
**********************
You should now be able to compile your library with `cabal build` and should
add `hs-bindgen` to your crate dependencies list and decorate the Rust function
you want to expose with `#[hs_bindgen]` attribute macro."
    );

    Ok(())
}

/// Remove files generated by cargo-cabal, except flake.nix
fn cmd_clean(name: &str) -> Result<(), Error> {
    let _ = fs::remove_file(format!("{name}.cabal"));
    let _ = fs::remove_file(".hsbindgen");
    let _ = fs::remove_file("hsbindgen.toml");
    let _ = fs::remove_file("Setup.hs");
    let _ = fs::remove_file("Setup.lhs");
    Ok(())
}