build-rs 0.3.4

API for writing Cargo `build.rs` files
Documentation
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Inputs from the build system to the build script.
//!
//! This crate does not do any caching or interpreting of the values provided by
//! Cargo beyond the communication protocol itself. It is up to the build script
//! to interpret the string values and decide what to do with them.
//!
//! Reference: <https://doc.rust-lang.org/stable/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>

use std::path::PathBuf;

use crate::ident::{is_ascii_ident, is_crate_name, is_feature_name};
use crate::output::rerun_if_env_changed;

/// [`ProcessEnv`] wrapper that implicit calls [`rerun_if_env_changed`]
const ENV: RerunIfEnvChanged<ProcessEnv> = RerunIfEnvChanged::new();

/// Abstraction over environment variables
trait Env {
    /// Fetches the environment variable `key`, returning `None` if the variable isn’t set or if
    /// there is another error.
    ///
    /// It may return `None` if the environment variable’s name contains the equal sign character
    /// (`=`) or the NUL character.
    ///
    /// Note that this function will not check if the environment variable is valid Unicode.
    fn get(&self, key: &str) -> Option<std::ffi::OsString>;

    /// Checks the environment variable `key` is present
    ///
    /// It may not be considered present if the environment variable’s name contains the equal sign character
    /// (`=`) or the NUL character.
    fn is_present(&self, key: &str) -> bool;
}

/// Fetches environment variables from the current process
struct ProcessEnv;

impl Env for ProcessEnv {
    fn get(&self, key: &str) -> Option<std::ffi::OsString> {
        std::env::var_os(key)
    }

    fn is_present(&self, key: &str) -> bool {
        self.get(key).is_some()
    }
}

/// [`Env`] wrapper that implicitly calls [`rerun_if_env_changed`]
struct RerunIfEnvChanged<E: Env>(E);

impl RerunIfEnvChanged<ProcessEnv> {
    const fn new() -> Self {
        Self(ProcessEnv)
    }
}

impl<E: Env> Env for RerunIfEnvChanged<E> {
    #[track_caller]
    fn get(&self, key: &str) -> Option<std::ffi::OsString> {
        rerun_if_env_changed(key);
        self.0.get(key)
    }

    #[track_caller]
    fn is_present(&self, key: &str) -> bool {
        self.get(key).is_some()
    }
}

/// Path to the `cargo` binary performing the build.
#[track_caller]
pub fn cargo() -> PathBuf {
    to_path(var_or_panic("CARGO"))
}

/// The directory containing the manifest for the package being built (the package
/// containing the build script).
///
/// Also note that this is the value of the current
/// working directory of the build script when it starts.
#[track_caller]
pub fn cargo_manifest_dir() -> PathBuf {
    to_path(var_or_panic("CARGO_MANIFEST_DIR"))
}

/// The path to the manifest of your package.
#[track_caller]
pub fn cargo_manifest_path() -> PathBuf {
    ENV.get("CARGO_MANIFEST_PATH")
        .map(to_path)
        .unwrap_or_else(|| {
            let mut path = cargo_manifest_dir();
            path.push("Cargo.toml");
            path
        })
}

/// The manifest `links` value.
#[track_caller]
pub fn cargo_manifest_links() -> Option<String> {
    ENV.get("CARGO_MANIFEST_LINKS").map(to_string)
}

/// Contains parameters needed for Cargo’s [jobserver] implementation to parallelize
/// subprocesses.
///
/// Rustc or cargo invocations from build.rs can already read
/// `CARGO_MAKEFLAGS`, but GNU Make requires the flags to be specified either
/// directly as arguments, or through the `MAKEFLAGS` environment variable.
/// Currently Cargo doesn’t set the `MAKEFLAGS` variable, but it’s free for build
/// scripts invoking GNU Make to set it to the contents of `CARGO_MAKEFLAGS`.
///
/// [jobserver]: https://www.gnu.org/software/make/manual/html_node/Job-Slots.html
#[track_caller]
pub fn cargo_makeflags() -> Option<String> {
    ENV.get("CARGO_MAKEFLAGS").map(to_string)
}

/// For each activated feature of the package being built, this will be `true`.
#[track_caller]
pub fn cargo_feature(name: &str) -> bool {
    if !is_feature_name(name) {
        panic!("invalid feature name {name:?}")
    }
    let name = name.to_uppercase().replace('-', "_");
    let key = format!("CARGO_FEATURE_{name}");
    ENV.is_present(&key)
}

/// For each [configuration option] of the package being built, this will contain
/// the value of the configuration.
///
/// This includes values built-in to the compiler
/// (which can be seen with `rustc --print=cfg`) and values set by build scripts
/// and extra flags passed to rustc (such as those defined in `RUSTFLAGS`).
///
/// [configuration option]: https://doc.rust-lang.org/stable/reference/conditional-compilation.html
#[track_caller]
pub fn cargo_cfg(cfg: &str) -> Option<Vec<String>> {
    let var = cargo_cfg_var(cfg);
    ENV.get(&var).map(|v| to_strings(v, ','))
}

#[track_caller]
fn cargo_cfg_var(cfg: &str) -> String {
    if !is_ascii_ident(cfg) {
        panic!("invalid configuration option {cfg:?}")
    }
    let cfg = cfg.to_uppercase().replace('-', "_");
    let key = format!("CARGO_CFG_{cfg}");
    key
}

pub use self::cfg::*;
mod cfg {
    use super::*;

    // those disabled with #[cfg(any())] don't seem meaningfully useful
    // but we list all cfg that are default known to check-cfg

    /// Each activated feature of the package being built
    #[doc = requires_msrv!("1.85")]
    #[track_caller]
    pub fn cargo_cfg_feature() -> Vec<String> {
        to_strings(var_or_panic(&cargo_cfg_var("feature")), ',')
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_clippy() -> bool {
        ENV.is_present("CARGO_CFG_CLIPPY")
    }

    /// If we are compiling with debug assertions enabled.
    #[track_caller]
    pub fn cargo_cfg_debug_assertions() -> bool {
        ENV.is_present("CARGO_CFG_DEBUG_ASSERTIONS")
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_doc() -> bool {
        ENV.is_present("CARGO_CFG_DOC")
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_docsrs() -> bool {
        ENV.is_present("CARGO_CFG_DOCSRS")
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_doctest() -> bool {
        ENV.is_present("CARGO_CFG_DOCTEST")
    }

    /// The level of detail provided by derived [`Debug`] implementations.
    #[doc = unstable!(fmt_dbg, 129709)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_fmt_debug() -> String {
        to_string(var_or_panic("CARGO_CFG_FMT_DEBUG"))
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_miri() -> bool {
        ENV.is_present("CARGO_CFG_MIRI")
    }

    /// If we are compiling with overflow checks enabled.
    #[doc = unstable!(cfg_overflow_checks, 111466)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_overflow_checks() -> bool {
        ENV.is_present("CARGO_CFG_OVERFLOW_CHECKS")
    }

    /// The [panic strategy](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#panic).
    #[track_caller]
    pub fn cargo_cfg_panic() -> String {
        to_string(var_or_panic("CARGO_CFG_PANIC"))
    }

    /// If the crate is being compiled as a procedural macro.
    #[track_caller]
    pub fn cargo_cfg_proc_macro() -> bool {
        ENV.is_present("CARGO_CFG_PROC_MACRO")
    }

    /// The target relocation model.
    #[doc = unstable!(cfg_relocation_model, 114929)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_relocation_model() -> String {
        to_string(var_or_panic("CARGO_CFG_RELOCATION_MODEL"))
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_rustfmt() -> bool {
        ENV.is_present("CARGO_CFG_RUSTFMT")
    }

    /// Sanitizers enabled for the crate being compiled.
    #[doc = unstable!(cfg_sanitize, 39699)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_sanitize() -> Option<Vec<String>> {
        ENV.get("CARGO_CFG_SANITIZE").map(|v| to_strings(v, ','))
    }

    /// If CFI sanitization is generalizing pointers.
    #[doc = unstable!(cfg_sanitizer_cfi, 89653)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_sanitizer_cfi_generalize_pointers() -> bool {
        ENV.is_present("CARGO_CFG_SANITIZER_CFI_GENERALIZE_POINTERS")
    }

    /// If CFI sanitization is normalizing integers.
    #[doc = unstable!(cfg_sanitizer_cfi, 89653)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_sanitizer_cfi_normalize_integers() -> bool {
        ENV.is_present("CARGO_CFG_SANITIZER_CFI_NORMALIZE_INTEGERS")
    }

    /// Disambiguation of the [target ABI](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_abi)
    /// when the [target env](cargo_cfg_target_env) isn't sufficient.
    ///
    /// For historical reasons, this value is only defined as `Some` when
    /// actually needed for disambiguation. Thus, for example, on many GNU platforms,
    /// this value will be `None`.
    #[track_caller]
    pub fn cargo_cfg_target_abi() -> Option<String> {
        to_opt(var_or_panic("CARGO_CFG_TARGET_ABI")).map(to_string)
    }

    /// The CPU [target architecture](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_arch).
    /// This is similar to the first element of the platform's target triple, but not identical.
    #[track_caller]
    pub fn cargo_cfg_target_arch() -> String {
        to_string(var_or_panic("CARGO_CFG_TARGET_ARCH"))
    }

    /// The CPU [target endianness](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_endian).
    #[track_caller]
    pub fn cargo_cfg_target_endian() -> String {
        to_string(var_or_panic("CARGO_CFG_TARGET_ENDIAN"))
    }

    /// The [target environment](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_env) ABI.
    /// This value is similar to the fourth element of the platform's target triple.
    ///
    /// For historical reasons, this value is only defined as not the empty-string when
    /// actually needed for disambiguation. Thus, for example, on many GNU platforms,
    /// this value will be empty.
    #[track_caller]
    pub fn cargo_cfg_target_env() -> String {
        to_string(var_or_panic("CARGO_CFG_TARGET_ENV"))
    }

    /// The [target family](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_family).
    #[track_caller]
    pub fn cargo_target_family() -> Vec<String> {
        to_strings(var_or_panic(&cargo_cfg_var("target_family")), ',')
    }

    /// List of CPU [target features](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_feature) enabled.
    #[track_caller]
    pub fn cargo_cfg_target_feature() -> Vec<String> {
        to_strings(var_or_panic(&cargo_cfg_var("target_feature")), ',')
    }

    /// List of CPU [supported atomic widths](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_has_atomic).
    #[track_caller]
    pub fn cargo_cfg_target_has_atomic() -> Vec<String> {
        to_strings(var_or_panic(&cargo_cfg_var("target_has_atomic")), ',')
    }

    /// List of atomic widths that have equal alignment requirements.
    #[doc = unstable!(cfg_target_has_atomic_equal_alignment, 93822)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_target_has_atomic_equal_alignment() -> Vec<String> {
        to_strings(
            var_or_panic(&cargo_cfg_var("target_has_atomic_equal_alignment")),
            ',',
        )
    }

    /// List of atomic widths that have atomic load and store operations.
    #[doc = unstable!(cfg_target_has_atomic_load_store, 94039)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_target_has_atomic_load_store() -> Vec<String> {
        to_strings(
            var_or_panic(&cargo_cfg_var("target_has_atomic_load_store")),
            ',',
        )
    }

    /// The [target operating system](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_os).
    /// This value is similar to the second and third element of the platform's target triple.
    #[track_caller]
    pub fn cargo_cfg_target_os() -> String {
        to_string(var_or_panic("CARGO_CFG_TARGET_OS"))
    }

    /// The CPU [pointer width](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_pointer_width).
    #[track_caller]
    pub fn cargo_cfg_target_pointer_width() -> u32 {
        to_parsed(var_or_panic("CARGO_CFG_TARGET_POINTER_WIDTH"))
    }

    /// If the target supports thread-local storage.
    #[doc = unstable!(cfg_target_thread_local, 29594)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_target_thread_local() -> bool {
        ENV.is_present("CARGO_CFG_TARGET_THREAD_LOCAL")
    }

    /// The [target vendor](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#target_vendor).
    #[track_caller]
    pub fn cargo_cfg_target_vendor() -> String {
        to_string(var_or_panic("CARGO_CFG_TARGET_VENDOR"))
    }

    #[cfg(any())]
    #[track_caller]
    pub fn cargo_cfg_test() -> bool {
        ENV.is_present("CARGO_CFG_TEST")
    }

    /// If we are compiling with UB checks enabled.
    #[doc = unstable!(cfg_ub_checks, 123499)]
    #[cfg(feature = "unstable")]
    #[track_caller]
    pub fn cargo_cfg_ub_checks() -> bool {
        ENV.is_present("CARGO_CFG_UB_CHECKS")
    }

    /// Set on [unix-like platforms](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#unix-and-windows).
    #[track_caller]
    pub fn cargo_cfg_unix() -> bool {
        ENV.is_present("CARGO_CFG_UNIX")
    }

    /// Set on [windows-like platforms](https://doc.rust-lang.org/stable/reference/conditional-compilation.html#unix-and-windows).
    #[track_caller]
    pub fn cargo_cfg_windows() -> bool {
        ENV.is_present("CARGO_CFG_WINDOWS")
    }
}

/// The folder in which all output and intermediate artifacts should be placed.
///
/// This folder is inside the build directory for the package being built, and
/// it is unique for the package in question.
#[track_caller]
pub fn out_dir() -> PathBuf {
    to_path(var_or_panic("OUT_DIR"))
}

/// The [target triple] that is being compiled for. Native code should be compiled
///  for this triple.
///
/// [target triple]: https://doc.rust-lang.org/stable/cargo/appendix/glossary.html#target
#[track_caller]
pub fn target() -> String {
    to_string(var_or_panic("TARGET"))
}

/// The host triple of the Rust compiler.
#[track_caller]
pub fn host() -> String {
    to_string(var_or_panic("HOST"))
}

/// The parallelism specified as the top-level parallelism.
///
/// This can be useful to
/// pass a `-j` parameter to a system like `make`. Note that care should be taken
/// when interpreting this value. For historical purposes this is still provided
/// but Cargo, for example, does not need to run `make -j`, and instead can set the
/// `MAKEFLAGS` env var to the content of `CARGO_MAKEFLAGS` to activate the use of
/// Cargo’s GNU Make compatible [jobserver] for sub-make invocations.
///
/// [jobserver]: https://www.gnu.org/software/make/manual/html_node/Job-Slots.html
#[track_caller]
pub fn num_jobs() -> u32 {
    to_parsed(var_or_panic("NUM_JOBS"))
}

/// The [level of optimization](https://doc.rust-lang.org/stable/cargo/reference/profiles.html#opt-level).
#[track_caller]
pub fn opt_level() -> String {
    to_string(var_or_panic("OPT_LEVEL"))
}

/// The amount of [debug information](https://doc.rust-lang.org/stable/cargo/reference/profiles.html#debug) included.
#[track_caller]
pub fn debug() -> String {
    to_string(var_or_panic("DEBUG"))
}

/// `release` for release builds, `debug` for other builds.
///
/// This is determined based
/// on if the [profile] inherits from the [`dev`] or [`release`] profile. Using this
/// function is not recommended. Using other functions like [`opt_level`] provides
/// a more correct view of the actual settings being used.
///
/// [profile]: https://doc.rust-lang.org/stable/cargo/reference/profiles.html
/// [`dev`]: https://doc.rust-lang.org/stable/cargo/reference/profiles.html#dev
/// [`release`]: https://doc.rust-lang.org/stable/cargo/reference/profiles.html#release
#[track_caller]
pub fn profile() -> String {
    to_string(var_or_panic("PROFILE"))
}

/// [Metadata] set by dependencies. For more information, see build script
/// documentation about [the `links` manifest key][links].
///
/// [metadata]: crate::output::metadata
/// [links]: https://doc.rust-lang.org/stable/cargo/reference/build-scripts.html#the-links-manifest-key
#[track_caller]
pub fn dep_metadata(name: &str, key: &str) -> Option<String> {
    if !is_crate_name(name) {
        panic!("invalid dependency name {name:?}")
    }
    if !is_ascii_ident(key) {
        panic!("invalid metadata key {key:?}")
    }

    let name = name.to_uppercase().replace('-', "_");
    let key = key.to_uppercase().replace('-', "_");
    let key = format!("DEP_{name}_{key}");
    ENV.get(&key).map(to_string)
}

/// The compiler that Cargo has resolved to use.
#[track_caller]
pub fn rustc() -> PathBuf {
    to_path(var_or_panic("RUSTC"))
}

/// The documentation generator that Cargo has resolved to use.
#[track_caller]
pub fn rustdoc() -> PathBuf {
    to_path(var_or_panic("RUSTDOC"))
}

/// The rustc wrapper, if any, that Cargo is using. See [`build.rustc-wrapper`].
///
/// [`build.rustc-wrapper`]: https://doc.rust-lang.org/stable/cargo/reference/config.html#buildrustc-wrapper
#[track_caller]
pub fn rustc_wrapper() -> Option<PathBuf> {
    ENV.get("RUSTC_WRAPPER").map(to_path)
}

/// The rustc wrapper, if any, that Cargo is using for workspace members. See
/// [`build.rustc-workspace-wrapper`].
///
/// [`build.rustc-workspace-wrapper`]: https://doc.rust-lang.org/stable/cargo/reference/config.html#buildrustc-workspace-wrapper
#[track_caller]
pub fn rustc_workspace_wrapper() -> Option<PathBuf> {
    ENV.get("RUSTC_WORKSPACE_WRAPPER").map(to_path)
}

/// The linker that Cargo has resolved to use for the current target, if specified.
///
/// [`target.*.linker`]: https://doc.rust-lang.org/stable/cargo/reference/config.html#targettriplelinker
#[track_caller]
pub fn rustc_linker() -> Option<PathBuf> {
    ENV.get("RUSTC_LINKER").map(to_path)
}

/// Extra flags that Cargo invokes rustc with. See [`build.rustflags`].
///
/// [`build.rustflags`]: https://doc.rust-lang.org/stable/cargo/reference/config.html#buildrustflags
#[track_caller]
pub fn cargo_encoded_rustflags() -> Vec<String> {
    to_strings(var_or_panic("CARGO_ENCODED_RUSTFLAGS"), '\x1f')
}

/// The full version of your package.
#[track_caller]
pub fn cargo_pkg_version() -> String {
    to_string(var_or_panic("CARGO_PKG_VERSION"))
}

/// The major version of your package.
#[track_caller]
pub fn cargo_pkg_version_major() -> u64 {
    to_parsed(var_or_panic("CARGO_PKG_VERSION_MAJOR"))
}

/// The minor version of your package.
#[track_caller]
pub fn cargo_pkg_version_minor() -> u64 {
    to_parsed(var_or_panic("CARGO_PKG_VERSION_MINOR"))
}

/// The patch version of your package.
#[track_caller]
pub fn cargo_pkg_version_patch() -> u64 {
    to_parsed(var_or_panic("CARGO_PKG_VERSION_PATCH"))
}

/// The pre-release version of your package.
#[track_caller]
pub fn cargo_pkg_version_pre() -> Option<String> {
    to_opt(var_or_panic("CARGO_PKG_VERSION_PRE")).map(to_string)
}

/// The authors from the manifest of your package.
#[track_caller]
pub fn cargo_pkg_authors() -> Vec<String> {
    to_strings(var_or_panic("CARGO_PKG_AUTHORS"), ':')
}

/// The name of your package.
#[track_caller]
pub fn cargo_pkg_name() -> String {
    to_string(var_or_panic("CARGO_PKG_NAME"))
}

/// The description from the manifest of your package.
#[track_caller]
pub fn cargo_pkg_description() -> Option<String> {
    to_opt(var_or_panic("CARGO_PKG_DESCRIPTION")).map(to_string)
}

/// The home page from the manifest of your package.
#[track_caller]
pub fn cargo_pkg_homepage() -> Option<String> {
    to_opt(var_or_panic("CARGO_PKG_HOMEPAGE")).map(to_string)
}

/// The repository from the manifest of your package.
#[track_caller]
pub fn cargo_pkg_repository() -> Option<String> {
    to_opt(var_or_panic("CARGO_PKG_REPOSITORY")).map(to_string)
}

/// The license from the manifest of your package.
#[track_caller]
pub fn cargo_pkg_license() -> Option<String> {
    to_opt(var_or_panic("CARGO_PKG_LICENSE")).map(to_string)
}

/// The license file from the manifest of your package.
#[track_caller]
pub fn cargo_pkg_license_file() -> Option<PathBuf> {
    to_opt(var_or_panic("CARGO_PKG_LICENSE_FILE")).map(to_path)
}

/// The Rust version from the manifest of your package. Note that this is the
/// minimum Rust version supported by the package, not the current Rust version.
#[track_caller]
pub fn cargo_pkg_rust_version() -> Option<String> {
    to_opt(var_or_panic("CARGO_PKG_RUST_VERSION")).map(to_string)
}

/// Path to the README file of your package.
#[track_caller]
pub fn cargo_pkg_readme() -> Option<PathBuf> {
    to_opt(var_or_panic("CARGO_PKG_README")).map(to_path)
}

#[track_caller]
fn var_or_panic(key: &str) -> std::ffi::OsString {
    ENV.get(key)
        .unwrap_or_else(|| panic!("cargo environment variable `{key}` is missing"))
}

fn to_path(value: std::ffi::OsString) -> PathBuf {
    PathBuf::from(value)
}

#[track_caller]
fn to_string(value: std::ffi::OsString) -> String {
    match value.into_string() {
        Ok(s) => s,
        Err(value) => {
            let err = std::str::from_utf8(value.as_encoded_bytes()).unwrap_err();
            panic!("{err}")
        }
    }
}

fn to_opt(value: std::ffi::OsString) -> Option<std::ffi::OsString> {
    (!value.is_empty()).then_some(value)
}

#[track_caller]
fn to_strings(value: std::ffi::OsString, sep: char) -> Vec<String> {
    if value.is_empty() {
        return Vec::new();
    }
    let value = to_string(value);
    value.split(sep).map(str::to_owned).collect()
}

#[track_caller]
fn to_parsed<T>(value: std::ffi::OsString) -> T
where
    T: std::str::FromStr,
    T::Err: std::fmt::Display,
{
    let value = to_string(value);
    match value.parse() {
        Ok(s) => s,
        Err(err) => {
            panic!("{err}")
        }
    }
}