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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use std::path::PathBuf;

use cargo::util::command_prelude::AppExt;
use cargo::util::command_prelude::{multi_opt, opt};
use cargo::util::{CliError, CliResult};

use cargo_util::{ProcessBuilder, ProcessError};

use clap::{Arg, ArgMatches, Command, CommandFactory, Parser};

// TODO: convert to a function using cargo opt()
#[allow(dead_code)]
#[derive(Clone, Debug, Parser)]
struct Common {
    /// Path to directory where target should be copied to
    #[clap(long = "destdir", parse(from_os_str))]
    destdir: Option<PathBuf>,
    /// Directory path used to construct default values of
    /// includedir, libdir, bindir, pkgconfigdir
    #[clap(long = "prefix", parse(from_os_str))]
    prefix: Option<PathBuf>,
    /// Path to directory for installing generated library files
    #[clap(long = "libdir", parse(from_os_str))]
    libdir: Option<PathBuf>,
    /// Path to directory for installing generated headers files
    #[clap(long = "includedir", parse(from_os_str))]
    includedir: Option<PathBuf>,
    /// Path to directory for installing generated executable files
    #[clap(long = "bindir", parse(from_os_str))]
    bindir: Option<PathBuf>,
    /// Path to directory for installing generated pkg-config .pc files
    #[clap(long = "pkgconfigdir", parse(from_os_str))]
    pkgconfigdir: Option<PathBuf>,
    /// Path to directory for installing read-only data (defaults to {prefix}/share)
    #[clap(long = "datarootdir", parse(from_os_str))]
    datarootdir: Option<PathBuf>,
    /// Path to directory for installing read-only application-specific data
    /// (defaults to {datarootdir})
    #[clap(long = "datadir", parse(from_os_str))]
    datadir: Option<PathBuf>,
    #[clap(long = "dlltool", parse(from_os_str))]
    /// Use the provided dlltool when building for the windows-gnu targets.
    dlltool: Option<PathBuf>,
    #[clap(long = "crt-static")]
    /// Build the library embedding the C runtime
    crt_static: bool,
}

fn base_cli() -> Command<'static> {
    Common::command()
        .allow_external_subcommands(true)
        .arg(opt("version", "Print version info and exit").short('V'))
        .arg(
            opt(
                "verbose",
                "Use verbose output (-vv very verbose/build.rs output)",
            )
            .short('v')
            .multiple_occurrences(true)
            .global(true),
        )
        .arg(opt("quiet", "No output printed to stdout").short('q'))
        .arg(
            opt("color", "Coloring: auto, always, never")
                .value_name("WHEN")
                .global(true),
        )
        .arg(opt("frozen", "Require Cargo.lock and cache are up to date").global(true))
        .arg(opt("locked", "Require Cargo.lock is up to date").global(true))
        .arg(opt("offline", "Run without accessing the network").global(true))
        .arg(
            multi_opt("config", "KEY=VALUE", "Override a configuration value")
                .global(true)
                .hide(true),
        )
        .arg(
            Arg::new("unstable-features")
                .help("Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details")
                .short('Z')
                .value_name("FLAG")
                .multiple_occurrences(true)
                .global(true),
        )
        .arg_jobs()
        .arg_targets_all(
            "Build only this package's library",
            "Build only the specified binary",
            "Build all binaries",
            "Build only the specified example",
            "Build all examples",
            "Build only the specified test target",
            "Build all tests",
            "Build only the specified bench target",
            "Build all benches",
            "Build all targets",
        )
        .arg_profile("Build artifacts with the specified profile")
        .arg_features()
        .arg_target_triple("Build for the target triple")
        .arg_target_dir()
        .arg_manifest_path()
        .arg_message_format()
        .arg_build_plan()
}

pub fn subcommand_build(name: &str, about: &'static str) -> Command<'static> {
    base_cli()
        .name(name)
        .about(about)
        .arg(
            multi_opt(
                "library-type",
                "LIBRARY-TYPE",
                "Build only a type of library",
            )
            .global(true)
            .ignore_case(true)
            .possible_values(&["cdylib", "staticlib"]),
        )
        .arg_release("Build artifacts in release mode, with optimizations")
        .arg_package_spec_no_all(
            "Package to build (see `cargo help pkgid`)",
            "Build all packages in the workspace",
            "Exclude packages from the build",
        )
        .after_help(
            "
Compilation can be configured via the use of profiles which are configured in
the manifest. The default profile for this command is `dev`, but passing
the --release flag will use the `release` profile instead.
",
        )
}

pub fn subcommand_install(name: &str, about: &'static str) -> Command<'static> {
    base_cli()
        .name(name)
        .about(about)
        .arg(
            multi_opt(
                "library-type",
                "LIBRARY-TYPE",
                "Build only a type of library",
            )
            .global(true)
            .ignore_case(true)
            .possible_values(&["cdylib", "staticlib"]),
        )
        .arg(opt("debug", "Build in debug mode instead of release mode"))
        .arg_release(
            "Build artifacts in release mode, with optimizations. This is the default behavior.",
        )
        .arg_package_spec_no_all(
            "Package to install (see `cargo help pkgid`)",
            "Install all packages in the workspace",
            "Exclude packages from being installed",
        )
        .after_help(
            "
Compilation can be configured via the use of profiles which are configured in
the manifest. The default profile for this command is `release`, but passing
the --debug flag will use the `dev` profile instead.
",
        )
}

pub fn subcommand_test(name: &str) -> Command<'static> {
    base_cli()
        .trailing_var_arg(true)
        .name(name)
        .about("Test the crate C-API")
        .arg(
            Arg::new("args")
                .help("Arguments for the test binary")
                .multiple_values(true)
                .last(true),
        )
        .arg_release("Build artifacts in release mode, with optimizations")
        .arg_package_spec_no_all(
            "Package to run tests for",
            "Test all packages in the workspace",
            "Exclude packages from the test",
        )
        .arg(opt("no-run", "Compile, but don't run tests"))
        .arg(opt("no-fail-fast", "Run all tests regardless of failure"))
}

pub fn run_cargo_fallback(subcommand: &str, subcommand_args: &ArgMatches) -> CliResult {
    let cargo = std::env::var("CARGO_C_CARGO").unwrap_or_else(|_| "cargo".to_owned());
    let mut args = vec![subcommand];

    args.extend(subcommand_args.values_of("").unwrap_or_default());
    let err = match ProcessBuilder::new(&cargo).args(&args).exec_replace() {
        Ok(()) => return Ok(()),
        Err(e) => e,
    };

    if let Some(perr) = err.downcast_ref::<ProcessError>() {
        if let Some(code) = perr.code {
            return Err(CliError::code(code));
        }
    }
    Err(CliError::new(err, 101))
}