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 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
// Copyright (c) 2022 vergen developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use anyhow::Result;
use std::{
env,
io::{self, Write},
};
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
use {crate::key::VergenKey, std::collections::BTreeMap};
#[cfg(feature = "build")]
use crate::feature::build::Config as BuildConfig;
#[cfg(feature = "cargo")]
use crate::feature::cargo::Config as CargoConfig;
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
use crate::feature::git::Config as GitConfig;
#[cfg(feature = "rustc")]
use crate::feature::rustc::Config as RustcConfig;
#[cfg(feature = "si")]
use crate::feature::si::Config as SysinfoConfig;
use std::path::PathBuf;
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
pub(crate) type RustcEnvMap = BTreeMap<VergenKey, String>;
// Everything that can be emitted as cargo build instructions
#[derive(Clone, Debug, Default)]
pub(crate) struct Emitter {
pub(crate) failed: bool,
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
pub(crate) cargo_rustc_env_map: RustcEnvMap,
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
pub(crate) rerun_if_changed: Vec<String>,
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
pub(crate) warnings: Vec<String>,
}
impl Emitter {
#[cfg(feature = "build")]
fn add_build_entries(&mut self, builder: &EmitBuilder) -> Result<()> {
let idem = builder.idempotent;
let fail_on_error = builder.fail_on_error;
let mut empty = BTreeMap::new();
let cargo_rustc_env_map = if builder.disable_build {
&mut empty
} else {
&mut self.cargo_rustc_env_map
};
builder
.add_build_map_entries(idem, cargo_rustc_env_map, &mut self.warnings)
.or_else(|e| {
builder.add_build_default(e, fail_on_error, cargo_rustc_env_map, &mut self.warnings)
})
}
#[cfg(not(feature = "build"))]
#[allow(
clippy::unnecessary_wraps,
clippy::trivially_copy_pass_by_ref,
clippy::unused_self
)]
fn add_build_entries(&mut self, _builder: &EmitBuilder) -> Result<()> {
Ok(())
}
#[cfg(feature = "cargo")]
fn add_cargo_entries(&mut self, builder: &EmitBuilder) -> Result<()> {
let fail_on_error = builder.fail_on_error;
let mut empty = BTreeMap::new();
let cargo_rustc_env_map = if builder.disable_cargo {
&mut empty
} else {
&mut self.cargo_rustc_env_map
};
builder
.add_cargo_map_entries(cargo_rustc_env_map)
.or_else(|e| {
builder.add_cargo_default(e, fail_on_error, cargo_rustc_env_map, &mut self.warnings)
})
}
#[cfg(not(feature = "cargo"))]
#[allow(
clippy::unnecessary_wraps,
clippy::trivially_copy_pass_by_ref,
clippy::unused_self
)]
fn add_cargo_entries(&mut self, _builder: &EmitBuilder) -> Result<()> {
Ok(())
}
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
fn add_git_entries(&mut self, builder: &EmitBuilder, repo_path: Option<PathBuf>) -> Result<()> {
let idem = builder.idempotent;
let fail_on_error = builder.fail_on_error;
let mut empty_cargo_rustc_env_map = BTreeMap::new();
let mut empty_rerun_if_changed = vec![];
let mut empty_warnings = vec![];
let (cargo_rustc_env_map, rerun_if_changed, warnings) = if builder.disable_git {
(
&mut empty_cargo_rustc_env_map,
&mut empty_rerun_if_changed,
&mut empty_warnings,
)
} else {
(
&mut self.cargo_rustc_env_map,
&mut self.rerun_if_changed,
&mut self.warnings,
)
};
builder
.add_git_map_entries(
repo_path,
idem,
cargo_rustc_env_map,
warnings,
rerun_if_changed,
)
.or_else(|e| {
self.failed = true;
builder.add_git_default(
e,
fail_on_error,
cargo_rustc_env_map,
warnings,
rerun_if_changed,
)
})
}
#[cfg(not(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
)))]
#[allow(
clippy::unnecessary_wraps,
clippy::trivially_copy_pass_by_ref,
clippy::unused_self
)]
fn add_git_entries(&mut self, _builder: &EmitBuilder, _path: Option<PathBuf>) -> Result<()> {
Ok(())
}
#[cfg(feature = "rustc")]
fn add_rustc_entries(&mut self, builder: &EmitBuilder) -> Result<()> {
let fail_on_error = builder.fail_on_error;
let mut empty = BTreeMap::new();
let cargo_rustc_env_map = if builder.disable_rustc {
&mut empty
} else {
&mut self.cargo_rustc_env_map
};
builder
.add_rustc_map_entries(cargo_rustc_env_map, &mut self.warnings)
.or_else(|e| {
builder.add_rustc_default(e, fail_on_error, cargo_rustc_env_map, &mut self.warnings)
})
}
#[cfg(not(feature = "rustc"))]
#[allow(
clippy::unnecessary_wraps,
clippy::trivially_copy_pass_by_ref,
clippy::unused_self
)]
fn add_rustc_entries(&mut self, _builder: &EmitBuilder) -> Result<()> {
Ok(())
}
#[cfg(feature = "si")]
fn add_si_entries(&mut self, builder: &EmitBuilder) {
let idem = builder.idempotent;
let mut empty = BTreeMap::new();
let cargo_rustc_env_map = if builder.disable_sysinfo {
&mut empty
} else {
&mut self.cargo_rustc_env_map
};
builder.add_sysinfo_map_entries(idem, cargo_rustc_env_map, &mut self.warnings);
}
#[cfg(not(feature = "si"))]
#[allow(
clippy::unnecessary_wraps,
clippy::trivially_copy_pass_by_ref,
clippy::unused_self
)]
fn add_si_entries(&mut self, _builder: &EmitBuilder) {}
fn emit_output<T>(
&self,
quiet: bool,
custom_buildrs: Option<&'static str>,
stdout: &mut T,
) -> Result<()>
where
T: Write,
{
self.emit_instructions(quiet, custom_buildrs, stdout)
}
#[cfg(not(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
)))]
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
fn emit_instructions<T>(
&self,
_quiet: bool,
_custom_buildrs: Option<&'static str>,
_stdout: &mut T,
) -> Result<()>
where
T: Write,
{
Ok(())
}
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
fn emit_instructions<T>(
&self,
quiet: bool,
custom_buildrs: Option<&'static str>,
stdout: &mut T,
) -> Result<()>
where
T: Write,
{
// Emit the 'cargo:rustc-env' instructions
for (k, v) in &self.cargo_rustc_env_map {
writeln!(stdout, "cargo:rustc-env={}={v}", k.name())?;
}
// Emit the `cargo:warning` instructions
if !quiet {
for warning in &self.warnings {
writeln!(stdout, "cargo:warning={warning}")?;
}
}
// Emit the 'cargo:rerun-if-changed' instructions for the git paths (if added)
for path in &self.rerun_if_changed {
writeln!(stdout, "cargo:rerun-if-changed={path}")?;
}
// Emit the 'cargo:rerun-if-changed' instructions
if !self.cargo_rustc_env_map.is_empty() || !self.warnings.is_empty() {
let buildrs = if let Some(path) = custom_buildrs {
path
} else {
"build.rs"
};
writeln!(stdout, "cargo:rerun-if-changed={buildrs}")?;
writeln!(stdout, "cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT")?;
writeln!(stdout, "cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH")?;
}
Ok(())
}
}
/// Build the `vergen` configuration to enable specific cargo instruction
/// output
#[derive(Clone, Copy, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct EmitBuilder {
idempotent: bool,
fail_on_error: bool,
quiet: bool,
custom_buildrs: Option<&'static str>,
#[cfg(feature = "build")]
disable_build: bool,
#[cfg(feature = "build")]
pub(crate) build_config: BuildConfig,
#[cfg(feature = "cargo")]
disable_cargo: bool,
#[cfg(feature = "cargo")]
pub(crate) cargo_config: CargoConfig,
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
disable_git: bool,
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
pub(crate) git_config: GitConfig,
#[cfg(feature = "rustc")]
disable_rustc: bool,
#[cfg(feature = "rustc")]
pub(crate) rustc_config: RustcConfig,
#[cfg(feature = "si")]
disable_sysinfo: bool,
#[cfg(feature = "si")]
pub(crate) sysinfo_config: SysinfoConfig,
}
impl EmitBuilder {
/// Instantiate the builder to configure the cargo instruction emits
#[must_use]
pub fn builder() -> Self {
let idempotent = matches!(env::var("VERGEN_IDEMPOTENT"), Ok(_val));
Self {
idempotent,
fail_on_error: false,
quiet: false,
custom_buildrs: None,
#[cfg(feature = "build")]
disable_build: false,
#[cfg(feature = "build")]
build_config: BuildConfig::default(),
#[cfg(feature = "cargo")]
disable_cargo: false,
#[cfg(feature = "cargo")]
cargo_config: CargoConfig::default(),
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
disable_git: false,
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
git_config: GitConfig::default(),
#[cfg(feature = "rustc")]
disable_rustc: false,
#[cfg(feature = "rustc")]
rustc_config: RustcConfig::default(),
#[cfg(feature = "si")]
disable_sysinfo: false,
#[cfg(feature = "si")]
sysinfo_config: SysinfoConfig::default(),
}
}
/// Enable the `idempotent` feature
///
/// **NOTE** - This feature can also be enabled via the `VERGEN_IDEMPOTENT`
/// environment variable.
///
/// When this feature is enabled, certain vergen output (i.e. timestamps, sysinfo)
/// will be set to an idempotent default. This will allow systems that
/// depend on deterministic builds to override user requested `vergen`
/// impurities. This will mainly allow for package maintainers to build
/// packages that depend on `vergen` in a deterministic manner.
///
/// See [this issue](https://github.com/rustyhorde/vergen/issues/141) for
/// more details
///
/// | Variable | Sample |
/// | ------- | ------ |
/// | `VERGEN_BUILD_DATE` | `VERGEN_IDEMPOTENT_OUTPUT` |
/// | `VERGEN_BUILD_TIMESTAMP` | `VERGEN_IDEMPOTENT_OUTPUT` |
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use std::env;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "build",
doc = r##"
EmitBuilder::builder().idempotent().all_build().emit()?;
"##
)]
/// // or
/// env::set_var("VERGEN_IDEMPOTENT", "true");
#[cfg_attr(
feature = "build",
doc = r##"
EmitBuilder::builder().all_build().emit()?;
"##
)]
/// # env::remove_var("VERGEN_IDEMPOTENT");
/// # Ok(())
/// # }
/// ```
///
pub fn idempotent(&mut self) -> &mut Self {
self.idempotent = true;
self
}
/// Enable the `fail_on_error` feature
///
/// By default `vergen` will emit the instructions you requested. If for some
/// reason those instructions cannot be generated correctly, placeholder values
/// will be used instead. `vergen` will also emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning)
/// instructions notifying you this has happened.
///
/// For example, if you configure `vergen` to emit `VERGEN_GIT_*` instructions and
/// you run a build from a source tarball with no `.git` directory, the instructions
/// will be populated with placeholder values, rather than information gleaned through git.
///
/// You can turn off this behavior by enabling `fail_on_error`.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "build",
doc = r##"
EmitBuilder::builder().fail_on_error().all_build().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
pub fn fail_on_error(&mut self) -> &mut Self {
self.fail_on_error = true;
self
}
/// Set a custom build.rs path if you are using a non-standard path
///
/// By default `vergen` will use `build.rs` as the build path for the
/// `cargo:rerun-if-changed` emit. You can specify a custom `build.rs`
/// path here if you have changed this default
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "build",
doc = r##"
EmitBuilder::builder().custom_build_rs("my/custom/build.rs").all_build().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
pub fn custom_build_rs(&mut self, path: &'static str) -> &mut Self {
self.custom_buildrs = Some(path);
self
}
/// Enable the quiet feature
///
/// Suppress the emission of the `cargo:warning` instructions.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "build",
doc = r##"
EmitBuilder::builder().quiet().all_build().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
pub fn quiet(&mut self) -> &mut Self {
self.quiet = true;
self
}
/// Disable the build output, even when the build feature is enabled.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "build",
doc = r##"
EmitBuilder::builder().all_build().disable_build().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "build")]
pub fn disable_build(&mut self) -> &mut Self {
self.disable_build = true;
self
}
/// Disable the cargo output, even when the cargo feature is enabled.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "cargo",
doc = r##"
EmitBuilder::builder().all_cargo().disable_cargo().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "cargo")]
pub fn disable_cargo(&mut self) -> &mut Self {
self.disable_cargo = true;
self
}
/// Disable the git output, even when the git feature is enabled.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "git",
doc = r##"
EmitBuilder::builder().all_git().disable_git().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
#[cfg(all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
))]
pub fn disable_git(&mut self) -> &mut Self {
self.disable_git = true;
self
}
/// Disable the rustc output, even when the rustc feature is enabled.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "rustc",
doc = r##"
EmitBuilder::builder().all_rustc().disable_rustc().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "rustc")]
pub fn disable_rustc(&mut self) -> &mut Self {
self.disable_rustc = true;
self
}
/// Disable the sysinfo output, even when the sysinfo feature is enabled.
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
feature = "si",
doc = r##"
EmitBuilder::builder().all_sysinfo().disable_sysinfo().emit()?;
"##
)]
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "si")]
pub fn disable_sysinfo(&mut self) -> &mut Self {
self.disable_sysinfo = true;
self
}
/// Emit cargo instructions from your build script
///
/// - Will emit [`cargo:rustc-env=VAR=VALUE`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-envvarvalue) for each feature you have enabled.
#[cfg_attr(
feature = "git",
doc = r##" - Will emit [`cargo:rerun-if-changed=PATH`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed) if the git feature
is enabled. This is done to ensure any git variables are regenerated when commits are made.
"##
)]
/// - Can emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) outputs if the
/// [`fail_on_error`](Self::fail_on_error) feature is not enabled and the requested variable is defaulted through error or
/// the [`idempotent`](Self::idempotent) flag.
///
/// # Errors
/// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`]
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use std::env;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
all(
feature = "build",
feature = "cargo",
all(feature = "git", feature = "gitcl"),
feature = "rustc",
feature = "si"
),
doc = r##"
# env::set_var("CARGO_FEATURE_BUILD", "build");
# env::set_var("CARGO_FEATURE_GIT", "git");
# env::set_var("DEBUG", "true");
# env::set_var("OPT_LEVEL", "1");
# env::set_var("TARGET", "x86_64-unknown-linux-gnu");
EmitBuilder::builder()
.all_build()
.all_cargo()
.all_git()
.all_rustc()
.all_sysinfo()
.emit()?;
# env::remove_var("CARGO_FEATURE_BUILD");
# env::remove_var("CARGO_FEATURE_GIT");
# env::remove_var("DEBUG");
# env::remove_var("OPT_LEVEL");
# env::remove_var("TARGET");
"##
)]
/// # Ok(())
/// # }
/// ```
///
/// # Sample Output
///
/// **NOTE** - You won't see this output unless you invoke cargo with the `-vv` flag.
/// The instruction output is not displayed by default.
///
/// ```text
/// cargo:rustc-env=VERGEN_BUILD_DATE=2023-01-04
/// cargo:rustc-env=VERGEN_BUILD_TIMESTAMP=2023-01-04T15:38:11.097507114Z
/// cargo:rustc-env=VERGEN_CARGO_DEBUG=true
/// cargo:rustc-env=VERGEN_CARGO_FEATURES=build,git
/// cargo:rustc-env=VERGEN_CARGO_OPT_LEVEL=1
/// cargo:rustc-env=VERGEN_CARGO_TARGET_TRIPLE=x86_64-unknown-linux-gnu
/// cargo:rustc-env=VERGEN_GIT_BRANCH=feature/version8
/// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_EMAIL=your@email.com
/// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_NAME=Yoda
/// cargo:rustc-env=VERGEN_GIT_COMMIT_COUNT=476
/// cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=2023-01-03
/// cargo:rustc-env=VERGEN_GIT_COMMIT_MESSAGE=The best message
/// cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2023-01-03T14:08:12.000000000-05:00
/// cargo:rustc-env=VERGEN_GIT_DESCRIBE=7.4.4-103-g53ae8a6
/// cargo:rustc-env=VERGEN_GIT_SHA=53ae8a69ab7917a2909af40f2e5d015f5b29ae28
/// cargo:rustc-env=VERGEN_RUSTC_CHANNEL=nightly
/// cargo:rustc-env=VERGEN_RUSTC_COMMIT_DATE=2023-01-03
/// cargo:rustc-env=VERGEN_RUSTC_COMMIT_HASH=c7572670a1302f5c7e245d069200e22da9df0316
/// cargo:rustc-env=VERGEN_RUSTC_HOST_TRIPLE=x86_64-unknown-linux-gnu
/// cargo:rustc-env=VERGEN_RUSTC_LLVM_VERSION=15.0
/// cargo:rustc-env=VERGEN_RUSTC_SEMVER=1.68.0-nightly
/// cargo:rustc-env=VERGEN_SYSINFO_NAME=Arch Linux
/// cargo:rustc-env=VERGEN_SYSINFO_OS_VERSION=Linux Arch Linux
/// cargo:rustc-env=VERGEN_SYSINFO_USER=jozias
/// cargo:rustc-env=VERGEN_SYSINFO_TOTAL_MEMORY=31 GiB
/// cargo:rustc-env=VERGEN_SYSINFO_CPU_VENDOR=AuthenticAMD
/// cargo:rustc-env=VERGEN_SYSINFO_CPU_CORE_COUNT=8
/// cargo:rustc-env=VERGEN_SYSINFO_CPU_NAME=cpu0,cpu1,cpu2,cpu3,cpu4,cpu5,cpu6,cpu7
/// cargo:rustc-env=VERGEN_SYSINFO_CPU_BRAND=AMD Ryzen Threadripper 1900X 8-Core Processor
/// cargo:rustc-env=VERGEN_SYSINFO_CPU_FREQUENCY=3792
/// cargo:rerun-if-changed=.git/HEAD
/// cargo:rerun-if-changed=.git/refs/heads/feature/version8
/// cargo:rerun-if-changed=build.rs
/// cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT
/// cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH
/// ```
///
pub fn emit(self) -> Result<()> {
self.inner_emit(None)
.and_then(|x| x.emit_output(self.quiet, self.custom_buildrs, &mut io::stdout()))
}
/// Emit cargo instructions from your build script and set environment variables for use in `build.rs`
///
/// - Will emit [`cargo:rustc-env=VAR=VALUE`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-envvarvalue) for each feature you have enabled.
#[cfg_attr(
feature = "git",
doc = r##" - Will emit [`cargo:rerun-if-changed=PATH`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed) if the git feature
is enabled. This is done to ensure any git variables are regenerated when commits are made.
"##
)]
/// - Can emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) outputs if the
/// [`fail_on_error`](Self::fail_on_error) feature is not enabled and the requested variable is defaulted through error or
/// the [`idempotent`](Self::idempotent) flag.
///
/// # Errors
/// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`]
///
/// # Example
///
/// ```
/// # use anyhow::Result;
/// # use std::env;
/// # use vergen::EmitBuilder;
/// #
/// # fn main() -> Result<()> {
#[cfg_attr(
all(
feature = "build",
feature = "cargo",
all(feature = "git", feature = "gitcl"),
feature = "rustc",
feature = "si"
),
doc = r##"
# env::set_var("CARGO_FEATURE_BUILD", "build");
# env::set_var("CARGO_FEATURE_GIT", "git");
# env::set_var("DEBUG", "true");
# env::set_var("OPT_LEVEL", "1");
# env::set_var("TARGET", "x86_64-unknown-linux-gnu");
EmitBuilder::builder()
.all_build()
.all_cargo()
.all_git()
.all_rustc()
.all_sysinfo()
.emit_and_set()?;
# env::remove_var("CARGO_FEATURE_BUILD");
# env::remove_var("CARGO_FEATURE_GIT");
# env::remove_var("DEBUG");
# env::remove_var("OPT_LEVEL");
# env::remove_var("TARGET");
"##
)]
/// # Ok(())
/// # }
/// ```
#[cfg(any(
feature = "build",
feature = "cargo",
feature = "git",
feature = "rustc",
feature = "si"
))]
pub fn emit_and_set(self) -> Result<()> {
self.inner_emit(None)
.and_then(|x| {
x.emit_output(self.quiet, self.custom_buildrs, &mut io::stdout())
.map(|_| x)
})
.map(|x| {
for (k, v) in &x.cargo_rustc_env_map {
if env::var(k.name()).is_err() {
env::set_var(k.name(), v);
}
}
})
}
#[doc(hidden)]
/// Emit instructions from the given repository path.
///
/// # Errors
///
#[cfg(all(
feature = "git",
any(feature = "gitcl", feature = "git2", feature = "gix")
))]
pub fn emit_at(self, repo_path: PathBuf) -> Result<()> {
self.inner_emit(Some(repo_path))
.and_then(|x| x.emit_output(self.quiet, self.custom_buildrs, &mut io::stdout()))
}
#[cfg(all(
test,
any(
feature = "build",
feature = "cargo",
all(
feature = "git",
any(feature = "gitcl", feature = "git2", feature = "gix")
),
feature = "rustc",
feature = "si"
)
))]
pub(crate) fn test_emit(self) -> Result<Emitter> {
self.inner_emit(None)
}
#[cfg(all(
test,
all(
feature = "git",
any(feature = "gitcl", feature = "git2", feature = "gix")
),
))]
pub(crate) fn test_emit_at(self, repo_path: Option<PathBuf>) -> Result<Emitter> {
self.inner_emit(repo_path)
}
#[doc(hidden)]
/// Emit the cargo build script instructions to the given [`Write`](std::io::Write).
///
/// **NOTE** - This is generally only used for testing and probably shouldn't be used
/// within a `build.rs` file.
///
/// # Errors
/// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`]
///
pub fn emit_to<T>(self, stdout: &mut T) -> Result<bool>
where
T: Write,
{
self.inner_emit(None).and_then(|x| {
x.emit_output(self.quiet, self.custom_buildrs, stdout)
.map(|_| x.failed)
})
}
#[doc(hidden)]
/// Emit the cargo build script instructions to the given [`Write`](std::io::Write) at
/// the given repository path for git instructions
///
/// **NOTE** - This is generally only used for testing and probably shouldn't be used
/// within a `build.rs` file.
///
/// # Errors
/// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`]
///
pub fn emit_to_at<T>(self, stdout: &mut T, path: Option<PathBuf>) -> Result<bool>
where
T: Write,
{
self.inner_emit(path).and_then(|x| {
x.emit_output(self.quiet, self.custom_buildrs, stdout)
.map(|_| x.failed)
})
}
fn inner_emit(self, path: Option<PathBuf>) -> Result<Emitter> {
let mut config = Emitter::default();
config.add_build_entries(&self)?;
config.add_cargo_entries(&self)?;
config.add_git_entries(&self, path)?;
config.add_rustc_entries(&self)?;
config.add_si_entries(&self);
Ok(config)
}
}
#[cfg(test)]
pub(crate) mod test {
use super::EmitBuilder;
use anyhow::Result;
#[cfg(any(
feature = "build",
feature = "cargo",
all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
),
feature = "rustc",
feature = "si",
))]
use {super::RustcEnvMap, crate::constants::VERGEN_IDEMPOTENT_DEFAULT};
#[cfg(any(
feature = "build",
feature = "cargo",
all(
feature = "git",
any(feature = "git2", feature = "gitcl", feature = "gix")
),
feature = "rustc",
feature = "si",
))]
pub(crate) fn count_idempotent(map: &RustcEnvMap) -> usize {
map.values()
.filter(|x| *x == VERGEN_IDEMPOTENT_DEFAULT)
.count()
}
#[test]
#[serial_test::serial]
fn default_is_no_emit() -> Result<()> {
let mut stdout_buf = vec![];
_ = EmitBuilder::builder().emit_to(&mut stdout_buf)?;
assert!(stdout_buf.is_empty());
Ok(())
}
#[test]
#[serial_test::serial]
fn gen_is_ok() -> Result<()> {
assert!(EmitBuilder::builder().emit().is_ok());
Ok(())
}
#[cfg(all(
feature = "build",
feature = "rustc",
feature = "cargo",
feature = "si"
))]
#[test]
#[serial_test::serial]
fn everything_enabled() -> Result<()> {
use crate::utils::testutils::{setup, teardown};
setup();
let mut stdout_buf = vec![];
_ = EmitBuilder::builder()
.idempotent()
.fail_on_error()
.all_build()
.all_cargo()
.all_rustc()
.all_sysinfo()
.emit_to(&mut stdout_buf)?;
teardown();
Ok(())
}
#[cfg(all(
feature = "build",
feature = "rustc",
feature = "cargo",
feature = "si"
))]
#[test]
#[serial_test::serial]
fn all_output_non_git() -> Result<()> {
use crate::utils::testutils::{setup, teardown};
setup();
let mut stdout_buf = vec![];
_ = EmitBuilder::builder()
.all_build()
.all_cargo()
.all_rustc()
.all_sysinfo()
.emit_to(&mut stdout_buf)?;
assert!(!stdout_buf.is_empty());
teardown();
Ok(())
}
#[cfg(all(
feature = "build",
feature = "rustc",
all(
feature = "git",
any(feature = "gitcl", feature = "git2", feature = "gix")
),
feature = "cargo",
feature = "si"
))]
#[test]
#[serial_test::serial]
fn all_output() -> Result<()> {
use crate::utils::testutils::{setup, teardown};
setup();
let mut stdout_buf = vec![];
_ = EmitBuilder::builder()
.all_build()
.all_cargo()
.all_git()
.all_rustc()
.all_sysinfo()
.emit_to(&mut stdout_buf)?;
assert!(!stdout_buf.is_empty());
teardown();
Ok(())
}
#[cfg(all(
feature = "build",
feature = "rustc",
all(
feature = "git",
any(feature = "gitcl", feature = "git2", feature = "gix")
),
feature = "cargo",
feature = "si"
))]
#[test]
#[serial_test::serial]
fn all_features_no_output() -> Result<()> {
use crate::utils::testutils::{setup, teardown};
setup();
let mut stdout_buf = vec![];
_ = EmitBuilder::builder().emit_to(&mut stdout_buf)?;
assert!(stdout_buf.is_empty());
teardown();
Ok(())
}
}