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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#![doc = include_str!("../README.md")]
//!
//! # Example
//!
//! In simple cases you can just call `BinTest::new()` to build all executables in the current
//! crate and get a reference to a `BinTest` singleton to work with.
//!
//! ```rust
//! #[test]
//! fn test() {
//!   // BinTest::new() will run 'cargo build' and registers all build executables
//!   let executables: &'static BinTest = BinTest::new();
//!
//!   // List the executables build
//!   for (k,v) in executables.list_executables() {
//!     println!("{} @ {}", k, v);
//!   }
//!
//!   // BinTest::command() looks up executable by its name and creates a process::Command from it
//!   let command = executables.command("name");
//!
//!   // this command can then be used for testing
//!   command.arg("help").spawn();
//! }
//! ```
//!
//! In more complex cases you can use the `BinTest::with()` to configure the build process
//! with a `BinTestBuilder` and then call `.build()` on it to get a reference to the
//! `BinTest` singleton.
//!
//! # See also
//!
//! The [testcall crate](https://crates.io/crates/testcall) uses this to build tests and
//! assertions on top of the commands created by bintest. The [testpath
//! crate](https://crates.io/crates/testpath) crate lets you run test in specially created
//! temporary directories to provide an filesystem environment for tests.
use std::env::var_os as env;
use std::ffi::OsString;
use std::{collections::BTreeMap, sync::OnceLock};

pub use std::process::{Command, Stdio};

pub use cargo_metadata::camino::Utf8PathBuf;
use cargo_metadata::Message;

/// Allows configuration of a workspace to find an executable in.
///
/// This builder is completely const constructible.
#[must_use]
#[derive(Debug, PartialEq, Clone, Copy)]
#[allow(clippy::struct_excessive_bools)]
pub struct BinTestBuilder {
    workspace: bool,
    quiet: bool,
    release: bool,
    offline: bool,
    all_targets: bool,
    features: Option<&'static str>,
    profile: Option<&'static str>,
    binaries: MaybeMany<'static, &'static str>,
    examples: MaybeMany<'static, &'static str>,
}

/// Access to binaries build by **`cargo build`**. Starting with version 2.0.0 this is a
/// singleton that is constructed by the first call to `BinTest::new()` or
/// `BinTest::with().build()`.  All calls to `BinTest` must be configured with the same
/// configuration values, otherwise a panic will occur. This is made in anticipation of future
/// versions which will allow building binary artifacts with different configurations while
/// not panicking then.
#[derive(Debug)]
pub struct BinTest {
    configured_with: BinTestBuilder,
    build_executables: BTreeMap<String, Utf8PathBuf>,
}

//PLANNED: needs some better way to figure out what profile is active
#[cfg(not(debug_assertions))]
const RELEASE_BUILD: bool = true;

#[cfg(debug_assertions)]
const RELEASE_BUILD: bool = false;

impl BinTestBuilder {
    /// Constructs a default builder with no configuration options set.
    const fn new() -> BinTestBuilder {
        Self {
            workspace: false,
            quiet: false,
            release: RELEASE_BUILD,
            offline: false,
            all_targets: false,
            features: None,
            profile: None,
            binaries: MaybeMany::None,
            examples: MaybeMany::None,
        }
    }

    /// Build all executables in all workspaces.
    pub const fn workspace(self) -> Self {
        Self {
            workspace: true,
            ..self
        }
    }

    /// Disables extra output from the `cargo build` run.
    pub const fn quiet(self) -> Self {
        Self {
            quiet: true,
            ..self
        }
    }

    /// Build in release mode, this is the default for release builds.
    pub const fn release(self) -> Self {
        Self {
            release: true,
            ..self
        }
    }

    /// Build in debug mode, this is the default for debug builds.
    pub const fn debug(self) -> Self {
        Self {
            release: false,
            ..self
        }
    }

    /// Build in offline mode.
    pub const fn offline(self) -> Self {
        Self {
            offline: true,
            ..self
        }
    }

    /// Build all targets (--lib --bins --tests --benches --examples).
    pub const fn all_targets(self) -> Self {
        Self {
            all_targets: true,
            ..self
        }
    }

    /// Configure '--features' list of features to build.
    pub const fn features(self, features: &'static str) -> Self {
        assert!(self.features.is_none(), "features() can only be used once");
        Self {
            features: Some(features),
            ..self
        }
    }

    /// Select a '--profile' for building.
    pub const fn profile(self, profile: &'static str) -> Self {
        assert!(self.profile.is_none(), "profile() can only be used once");
        Self {
            profile: Some(profile),
            ..self
        }
    }

    /// Allow only building a specific binary in the case of multiple in a workspace/package.
    pub const fn binary(self, binary: &'static str) -> Self {
        assert!(
            self.binaries.is_none(),
            "binary()/binaries() can only be used once"
        );
        Self {
            binaries: MaybeMany::One(binary),
            ..self
        }
    }

    /// Allow only building specific binaríes in the case of multiple in a workspace/package.
    pub const fn binaries(self, binaries: &'static [&'static str]) -> Self {
        assert!(
            self.binaries.is_none(),
            "binary()/binaries() can only be used once"
        );
        Self {
            binaries: MaybeMany::Many(binaries),
            ..self
        }
    }

    /// Allow only building a specific example in the case of multiple in a workspace/package.
    pub const fn example(self, example: &'static str) -> Self {
        assert!(
            self.examples.is_none(),
            "example()/examples() can only be used once"
        );
        Self {
            examples: MaybeMany::One(example),
            ..self
        }
    }

    /// Allow only building specific examples in the case of multiple in a workspace/package.
    pub const fn examples(self, examples: &'static [&'static str]) -> Self {
        assert!(self.examples.is_none(), "examples() can only be used once");
        Self {
            examples: MaybeMany::Many(examples),
            ..self
        }
    }

    /// Constructs a `BinTest` with from this builder if not already constructed.
    /// Construction runs 'cargo build' and register all build executables.  Executables are
    /// identified by their name, without path and filename extension.
    ///
    /// # Returns
    ///
    /// A reference to a immutable `BinTest` singleton that can be used to access the
    /// executables.
    ///
    /// # Panics
    ///
    /// All tests must run with the same configuration, this can be either achieved by calling
    /// `BinTest::with()` always with the same configuration or by providing a function that
    /// constructs and returns the `BinTest` singleton:
    ///
    /// ```
    /// use bintest::{BinTest, BinTestBuilder};
    ///
    /// // #[cfg(test)]
    /// fn my_bintest() -> &'static BinTest {
    ///     // The Builder can be all const constructed
    ///     static BINTEST_CONFIG: BinTestBuilder = BinTest::with().quiet();
    ///     BINTEST_CONFIG.build()
    /// }
    ///
    /// // #[test]
    /// fn example() {
    ///     let bintest = my_bintest();
    /// }
    /// ```
    #[must_use]
    pub fn build(self) -> &'static BinTest {
        BinTest::new_with_builder(&self)
    }
}

impl BinTest {
    /// Constructs a `BinTest` with the default configuration if not already constructed.
    /// Construction runs 'cargo build' and register all build executables.  Executables are
    /// identified by their name, without path and filename extension.
    ///
    /// # Returns
    ///
    /// A reference to a immutable `BinTest` singleton that can be used to access the
    /// executables.
    ///
    /// # Panics
    ///
    /// All tests must run with the same configuration, when using only `BinTest::new()` this
    /// is infallible. Mixing this with differing configs from `BinTest::with()` will panic.
    ///
    /// # Example
    ///
    /// ```
    /// use bintest::BinTest;
    ///
    /// let executables = BinTest::new();
    /// ```
    #[must_use]
    pub fn new() -> &'static Self {
        Self::new_with_builder(&BinTestBuilder::new())
    }

    /// Creates a `BinTestBuilder` for further customization.
    ///
    /// # Example
    ///
    /// ```
    /// use bintest::BinTest;
    ///
    /// let executables = BinTest::with().quiet().build();
    /// ```
    pub const fn with() -> BinTestBuilder {
        BinTestBuilder::new()
    }

    /// Gives an `(name, path)` iterator over all executables found.
    ///
    /// # Example
    ///
    /// ```
    /// use bintest::BinTest;
    ///
    /// let executables = BinTest::new();
    ///
    /// for (name, path) in executables.list_executables() {
    ///     println!("{} @ {}", name, path);
    /// }
    /// ```
    #[must_use]
    pub fn list_executables(&self) -> std::collections::btree_map::Iter<'_, String, Utf8PathBuf> {
        self.build_executables.iter()
    }

    /// Constructs a [`std::process::Command`] for the given executable name
    #[must_use]
    pub fn command(&self, name: &str) -> Command {
        Command::new(
            self.build_executables
                .get(name)
                .unwrap_or_else(|| panic!("no such executable <<{name}>>")),
        )
    }

    fn new_with_builder(builder: &BinTestBuilder) -> &'static Self {
        static SINGLETON: OnceLock<BinTest> = OnceLock::new();

        let singleton = SINGLETON.get_or_init(|| {
            let mut cargo_build =
                Command::new(env("CARGO").unwrap_or_else(|| OsString::from("cargo")));

            cargo_build
                .args(["build", "--message-format", "json"])
                .stdout(Stdio::piped());

            if builder.workspace {
                cargo_build.arg("--workspace");
            }

            if builder.quiet {
                cargo_build.arg("--quiet");
            }

            if builder.release {
                cargo_build.arg("--release");
            }

            if builder.offline {
                cargo_build.arg("--offline");
            }

            if builder.all_targets {
                cargo_build.arg("--all-targets");
            }

            if let Some(features) = builder.features {
                cargo_build.args(["--features", features]);
            }

            if let Some(profile) = builder.profile {
                cargo_build.args(["--profile", profile]);
            }

            match builder.binaries {
                MaybeMany::None => {}
                MaybeMany::One(binary) => {
                    cargo_build.args(["--bin", binary]);
                }
                MaybeMany::Many(binaries) => {
                    for binary in binaries {
                        cargo_build.args(["--bin", binary]);
                    }
                }
            }

            match builder.examples {
                MaybeMany::None => {}
                MaybeMany::One(example) => {
                    cargo_build.args(["--example", example]);
                }
                MaybeMany::Many(examples) => {
                    for example in examples {
                        cargo_build.args(["--bin", example]);
                    }
                }
            }

            let mut cargo_result = cargo_build.spawn().expect("'cargo build' success");

            let mut build_executables = BTreeMap::<String, Utf8PathBuf>::default();

            let reader = std::io::BufReader::new(cargo_result.stdout.take().unwrap());
            for message in cargo_metadata::Message::parse_stream(reader) {
                if let Message::CompilerArtifact(artifact) = message.unwrap() {
                    if let Some(executable) = artifact.executable {
                        build_executables.insert(
                            String::from(executable.file_stem().expect("filename")),
                            executable.to_path_buf(),
                        );
                    }
                }
            }

            BinTest {
                configured_with: *builder,
                build_executables,
            }
        });

        assert_eq!(
            singleton.configured_with, *builder,
            "All calls to BinTest must be configured with the same values"
        );

        singleton
    }
}

/// Const constructible helper holding `None, T, &[T]`.
#[derive(Debug, PartialEq, Clone, Copy)]
enum MaybeMany<'a, T> {
    None,
    One(T),
    Many(&'a [T]),
}

impl<'a, T> MaybeMany<'a, T> {
    const fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }
}

// The following tests are mutually exclusive since we operate on a global singleton

// #[test]
// fn same_config() {
//     let _executables1 = BinTest::with().workspace(true).build();
//     let _executables2 = BinTest::with().workspace(true).build();
// }

#[test]
#[should_panic(expected = "All calls to BinTest must be configured with the same values")]
fn different_config() {
    let _executables1 = BinTest::new();
    let _executables2 = BinTest::with().workspace().build();
}