vergen_git2/
lib.rs

1// Copyright (c) 2022 vergen developers
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9//! # vergen-git2 - Emit cargo instructions from a build script
10//! `vergen-git2` uses the [`git2`](https://docs.rs/git2) library to generate the git instructions.
11//!
12//! `vergen-git2`, when used in conjunction with cargo [build scripts] can emit the following:
13//!
14//! - Will emit [`cargo:rustc-env=VAR=VALUE`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-envvarvalue)
15//!   for each feature you have enabled.  These can be referenced with the [`env`!](std::env!) or [`option_env`!](std::option_env!) macro in your code.
16//! - Can emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) outputs if the
17//!   [`fail_on_error`](Emitter::fail_on_error) feature is not enabled and the requested variable is defaulted through error or
18//!   the [`idempotent`](Emitter::idempotent) flag.
19//! - Will emit [`cargo:rerun-if-changed=.git/HEAD`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed)
20//!   if git instructions are emitted.  This is done to ensure any git instructions are regenerated when commits are made.
21//! - Will emit [`cargo:rerun-if-changed=.git/<path_to_ref>`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed)
22//!   if git instructions are emitted.  This is done to ensure any git instructions are regenerated when commits are made.
23//! - Will emit [`cargo:rerun-if-changed=build.rs`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed)
24//!   to rerun instruction emission if the `build.rs` file changed.
25//! - Will emit [`cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed)
26//!   to rerun instruction emission if the `VERGEN_IDEMPOTENT` environment variable has changed.
27//! - Will emit [`cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed)
28//!   to rerun instruction emission if the `SOURCE_DATE_EPOCH` environment variable has changed.
29//!
30//! ## Usage
31//!
32//! 1. Ensure you have build scripts enabled via the `build` configuration in your `Cargo.toml`
33//!
34//! ```toml
35//! [package]
36//! #..
37//! build = "build.rs"
38//! ```
39//!
40//! 2. Add `vergen-git2` as a build dependency in `Cargo.toml`, specifying the features you wish to enable.
41//!
42//! ```toml
43//! [dependencies]
44//! #..
45//!
46//! [build-dependencies]
47//! # All features enabled
48//! vergen-git2 = { version = "1.0.0", features = ["build", "cargo", "rustc", "si"] }
49//! # or
50//! vergen-git2 = { version = "1.0.0", features = ["build"] }
51//! # if you wish to disable certain features
52//! ```
53//!
54//! 3. Create a `build.rs` file that uses `vergen-git2` to emit cargo instructions.  Configuration
55//!    starts with [`Emitter`].  Eventually you will call [`emit`](Emitter::emit) to output the
56//!    cargo instructions. See the [`emit`](Emitter::emit) documentation for more robust examples.
57//!
58//! #### Generate all output
59//!
60//! ```
61//! # use anyhow::Result;
62//! # use vergen_git2::{Emitter, Git2};
63#![cfg_attr(feature = "build", doc = r"# use vergen_git2::Build;")]
64#![cfg_attr(feature = "cargo", doc = r"# use vergen_git2::Cargo;")]
65#![cfg_attr(feature = "rustc", doc = r"# use vergen_git2::Rustc;")]
66#![cfg_attr(feature = "si", doc = r"# use vergen_git2::Sysinfo;")]
67#![cfg_attr(feature = "cargo", doc = r"# use test_util::with_cargo_vars;")]
68//! #
69//! # pub fn main() -> Result<()> {
70#![cfg_attr(feature = "cargo", doc = r"# let result = with_cargo_vars(|| {")]
71//! // NOTE: This will output everything, and requires all features enabled.
72//! // NOTE: See the specific builder documentation for configuration options.
73#![cfg_attr(feature = "build", doc = r"let build = Build::all_build();")]
74#![cfg_attr(feature = "cargo", doc = r"let cargo = Cargo::all_cargo();")]
75//! let git2 = Git2::all_git();
76#![cfg_attr(feature = "rustc", doc = r"let rustc = Rustc::all_rustc();")]
77#![cfg_attr(feature = "si", doc = r"let si = Sysinfo::all_sysinfo();")]
78//!
79//! Emitter::default()
80#![cfg_attr(feature = "build", doc = r"    .add_instructions(&build)?")]
81#![cfg_attr(feature = "cargo", doc = r"    .add_instructions(&cargo)?")]
82//!     .add_instructions(&git2)?
83#![cfg_attr(feature = "rustc", doc = r"    .add_instructions(&rustc)?")]
84#![cfg_attr(feature = "si", doc = r"    .add_instructions(&si)?")]
85//!     .emit()?;
86#![cfg_attr(
87    feature = "cargo",
88    doc = r"
89# Ok(())
90# });
91# assert!(result.is_ok());"
92)]
93//! #    Ok(())
94//! # }
95//! ```
96//! #### Sample Output
97//! ```text
98//! cargo:rustc-env=VERGEN_BUILD_DATE=2024-01-31
99//! cargo:rustc-env=VERGEN_BUILD_TIMESTAMP=2024-01-31T03:26:34.065893658Z
100//! cargo:rustc-env=VERGEN_CARGO_DEBUG=true
101//! cargo:rustc-env=VERGEN_CARGO_FEATURES=
102//! cargo:rustc-env=VERGEN_CARGO_OPT_LEVEL=0
103//! cargo:rustc-env=VERGEN_CARGO_TARGET_TRIPLE=x86_64-unknown-linux-gnu
104//! cargo:rustc-env=VERGEN_CARGO_DEPENDENCIES=anyhow 1.0.79,vergen-pretty 0.3.2
105//! cargo:rustc-env=VERGEN_GIT_BRANCH=master
106//! cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_EMAIL=emitter@vergen.com
107//! cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_NAME=Jason Ozias
108//! cargo:rustc-env=VERGEN_GIT_COMMIT_COUNT=44
109//! cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=2024-01-30
110//! cargo:rustc-env=VERGEN_GIT_COMMIT_MESSAGE=depsup
111//! cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2024-01-30T21:43:43.000000000Z
112//! cargo:rustc-env=VERGEN_GIT_DESCRIBE=0.1.0-beta.1-15-g728e25c
113//! cargo:rustc-env=VERGEN_GIT_SHA=728e25ca5bb7edbbc505f12b28c66b2b27883cf1
114//! cargo:rustc-env=VERGEN_RUSTC_CHANNEL=nightly
115//! cargo:rustc-env=VERGEN_RUSTC_COMMIT_DATE=2024-01-29
116//! cargo:rustc-env=VERGEN_RUSTC_COMMIT_HASH=5518eaa946291f00471af8b254b2a1715f234882
117//! cargo:rustc-env=VERGEN_RUSTC_HOST_TRIPLE=x86_64-unknown-linux-gnu
118//! cargo:rustc-env=VERGEN_RUSTC_LLVM_VERSION=17.0
119//! cargo:rustc-env=VERGEN_RUSTC_SEMVER=1.77.0-nightly
120//! cargo:rustc-env=VERGEN_SYSINFO_NAME=Arch Linux
121//! cargo:rustc-env=VERGEN_SYSINFO_OS_VERSION=Linux  Arch Linux
122//! cargo:rustc-env=VERGEN_SYSINFO_USER=jozias
123//! cargo:rustc-env=VERGEN_SYSINFO_TOTAL_MEMORY=31 GiB
124//! cargo:rustc-env=VERGEN_SYSINFO_CPU_VENDOR=AuthenticAMD
125//! cargo:rustc-env=VERGEN_SYSINFO_CPU_CORE_COUNT=8
126//! cargo:rustc-env=VERGEN_SYSINFO_CPU_NAME=cpu0,cpu1,cpu2,cpu3,cpu4,cpu5,cpu6,cpu7
127//! cargo:rustc-env=VERGEN_SYSINFO_CPU_BRAND=AMD Ryzen Threadripper 1900X 8-Core Processor
128//! cargo:rustc-env=VERGEN_SYSINFO_CPU_FREQUENCY=3792
129//! cargo:rerun-if-changed=/home/jozias/projects/rust-lang/vergen-cl/.git/HEAD
130//! cargo:rerun-if-changed=/home/jozias/projects/rust-lang/vergen-cl/.git/refs/heads/master
131//! cargo:rerun-if-changed=build.rs
132//! cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT
133//! cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH
134//! ```
135//!
136//! #### Generate specific output
137//!
138//! ```
139//! # use anyhow::Result;
140//! # use vergen_git2::{Emitter, Git2};
141#![cfg_attr(feature = "build", doc = r"# use vergen_git2::Build;")]
142#![cfg_attr(feature = "cargo", doc = r"# use vergen_git2::Cargo;")]
143#![cfg_attr(feature = "rustc", doc = r"# use vergen_git2::Rustc;")]
144#![cfg_attr(feature = "si", doc = r"# use vergen_git2::Sysinfo;")]
145#![cfg_attr(feature = "cargo", doc = r"# use test_util::with_cargo_vars;")]
146//! #
147//! # pub fn main() -> Result<()> {
148#![cfg_attr(feature = "cargo", doc = r"# let result = with_cargo_vars(|| {")]
149#![cfg_attr(
150    feature = "build",
151    doc = r"// NOTE: This will output only the instructions specified.
152// NOTE: See the specific builder documentation for configuration options. 
153let build = Build::builder().build_timestamp(true).build();"
154)]
155#![cfg_attr(
156    feature = "cargo",
157    doc = r"let cargo = Cargo::builder().opt_level(true).build();"
158)]
159//! let git2 = Git2::builder().commit_timestamp(true).build();
160#![cfg_attr(
161    feature = "rustc",
162    doc = r"let rustc = Rustc::builder().semver(true).build();"
163)]
164#![cfg_attr(
165    feature = "si",
166    doc = r"let si = Sysinfo::builder().cpu_core_count(true).build();"
167)]
168//!
169//! Emitter::default()
170#![cfg_attr(feature = "build", doc = r"    .add_instructions(&build)?")]
171#![cfg_attr(feature = "cargo", doc = r"    .add_instructions(&cargo)?")]
172//!     .add_instructions(&git2)?
173#![cfg_attr(feature = "rustc", doc = r"    .add_instructions(&rustc)?")]
174#![cfg_attr(feature = "si", doc = r"    .add_instructions(&si)?")]
175//!     .emit()?;
176#![cfg_attr(
177    feature = "cargo",
178    doc = r"
179#   Ok(())
180# });
181# assert!(result.is_ok());"
182)]
183//! #     Ok(())
184//! # }
185//! ```
186//! #### Sample Output
187//! ```text
188//! cargo:rustc-env=VERGEN_BUILD_TIMESTAMP=2024-01-31T03:26:34.065893658Z
189//! cargo:rustc-env=VERGEN_CARGO_OPT_LEVEL=0
190//! cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2024-01-30T21:43:43.000000000Z
191//! cargo:rustc-env=VERGEN_RUSTC_SEMVER=1.77.0-nightly
192//! cargo:rustc-env=VERGEN_SYSINFO_CPU_CORE_COUNT=8
193//! cargo:rerun-if-changed=/home/jozias/projects/rust-lang/vergen-cl/.git/HEAD
194//! cargo:rerun-if-changed=/home/jozias/projects/rust-lang/vergen-cl/.git/refs/heads/master
195//! cargo:rerun-if-changed=build.rs
196//! cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT
197//! cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH
198//! ```
199//!
200//! 4. Use the [`env!`](std::env!) or [`option_env!`](std::option_env!) macro in your code to read the environment variables.
201//!
202//! ```
203//! if let Some(timestamp) = option_env!("VERGEN_BUILD_TIMESTAMP") {
204//!     println!("Build Timestamp: {timestamp}");
205//! }
206//! if let Some(describe) = option_env!("VERGEN_GIT_DESCRIBE") {
207//!     println!("git describe: {describe}");
208//! }
209//! ```
210//!
211//! ## Features
212//! `vergen-git2` has four main feature toggles allowing you to customize your output. No features are enabled by default.
213//! You **must** specifically enable the features you wish to use.
214//!
215//! | Feature | Enables |
216//! | ------- | ------- |
217//! |  build  | `VERGEN_BUILD_*` instructions |
218//! |  cargo  | `VERGEN_CARGO_*` instructions |
219//! |  rustc  | `VERGEN_RUSTC_*` instructions |
220//! |   si    | `VERGEN_SYSINFO_*` instructions |
221//!
222//! ## Environment Variables
223//! `vergen-git2` currently recognizes the following environment variables. The full list of the environment variable names can be
224//! found as [constants here](https://docs.rs/vergen-lib/latest/vergen_lib/constants/features/index.html)
225//!
226//! | Variable | Functionality |
227//! | -------- | ------------- |
228//! | `VERGEN_IDEMPOTENT` | If this environment variable is set `vergen` will use the idempotent output feature regardless of the configuration set in `build.rs`.  This exists mainly to allow package maintainers to force idempotent output to generate deterministic binary output. |
229//! | `SOURCE_DATE_EPOCH` | If this environment variable is set `vergen` will use the value (unix time since epoch) as the basis for a time based instructions.  This can help emit deterministic instructions. |
230//! | `VERGEN_BUILD_*` | If this environment variable is set `vergen` will use the value you specify for the output rather than generating it. |
231//! | `VERGEN_CARGO_*` | If this environment variable is set `vergen` will use the value you specify for the output rather than generating it. |
232//! | `VERGEN_GIT_*` | If this environment variable is set `vergen` will use the value you specify for the output rather than generating it. |
233//! | `VERGEN_RUSTC_*` | If this environment variable is set `vergen` will use the value you specify for the output rather than generating it. |
234//! | `VERGEN_SYSINFO_*` | If this environment variable is set `vergen` will use the value you specify for the output rather than generating it. |
235//!
236//! [build scripts]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script
237//! [cargo:rustc-env]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-env
238//! [cargo:rerun-if-changed]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed
239//!
240
241// rustc lints
242#![cfg_attr(
243    all(feature = "unstable", nightly),
244    feature(
245        multiple_supertrait_upcastable,
246        must_not_suspend,
247        non_exhaustive_omitted_patterns_lint,
248        rustdoc_missing_doc_code_examples,
249        strict_provenance_lints,
250        supertrait_item_shadowing,
251        unqualified_local_imports,
252    )
253)]
254#![cfg_attr(nightly, allow(single_use_lifetimes, unexpected_cfgs))]
255#![cfg_attr(
256    nightly,
257    deny(
258        absolute_paths_not_starting_with_crate,
259        ambiguous_glob_imports,
260        ambiguous_glob_reexports,
261        ambiguous_negative_literals,
262        ambiguous_wide_pointer_comparisons,
263        anonymous_parameters,
264        array_into_iter,
265        asm_sub_register,
266        async_fn_in_trait,
267        bad_asm_style,
268        bare_trait_objects,
269        boxed_slice_into_iter,
270        break_with_label_and_loop,
271        clashing_extern_declarations,
272        closure_returning_async_block,
273        coherence_leak_check,
274        confusable_idents,
275        const_evaluatable_unchecked,
276        const_item_mutation,
277        dangling_pointers_from_temporaries,
278        dead_code,
279        dependency_on_unit_never_type_fallback,
280        deprecated,
281        deprecated_in_future,
282        deprecated_safe_2024,
283        deprecated_where_clause_location,
284        deref_into_dyn_supertrait,
285        deref_nullptr,
286        double_negations,
287        drop_bounds,
288        dropping_copy_types,
289        dropping_references,
290        duplicate_macro_attributes,
291        dyn_drop,
292        edition_2024_expr_fragment_specifier,
293        elided_lifetimes_in_paths,
294        ellipsis_inclusive_range_patterns,
295        explicit_outlives_requirements,
296        exported_private_dependencies,
297        ffi_unwind_calls,
298        forbidden_lint_groups,
299        forgetting_copy_types,
300        forgetting_references,
301        for_loops_over_fallibles,
302        function_item_references,
303        hidden_glob_reexports,
304        if_let_rescope,
305        impl_trait_overcaptures,
306        impl_trait_redundant_captures,
307        improper_ctypes,
308        improper_ctypes_definitions,
309        inline_no_sanitize,
310        internal_features,
311        invalid_from_utf8,
312        invalid_macro_export_arguments,
313        invalid_nan_comparisons,
314        invalid_value,
315        irrefutable_let_patterns,
316        keyword_idents_2018,
317        keyword_idents_2024,
318        large_assignments,
319        late_bound_lifetime_arguments,
320        legacy_derive_helpers,
321        let_underscore_drop,
322        macro_use_extern_crate,
323        map_unit_fn,
324        meta_variable_misuse,
325        mismatched_lifetime_syntaxes,
326        missing_abi,
327        missing_copy_implementations,
328        missing_debug_implementations,
329        missing_docs,
330        missing_unsafe_on_extern,
331        mixed_script_confusables,
332        named_arguments_used_positionally,
333        never_type_fallback_flowing_into_unsafe,
334        no_mangle_generic_items,
335        non_ascii_idents,
336        non_camel_case_types,
337        non_contiguous_range_endpoints,
338        non_fmt_panics,
339        non_local_definitions,
340        non_shorthand_field_patterns,
341        non_snake_case,
342        non_upper_case_globals,
343        noop_method_call,
344        opaque_hidden_inferred_bound,
345        out_of_scope_macro_calls,
346        overlapping_range_endpoints,
347        path_statements,
348        private_bounds,
349        private_interfaces,
350        ptr_to_integer_transmute_in_consts,
351        redundant_imports,
352        redundant_lifetimes,
353        redundant_semicolons,
354        refining_impl_trait_internal,
355        refining_impl_trait_reachable,
356        renamed_and_removed_lints,
357        repr_transparent_external_private_fields,
358        rust_2021_incompatible_closure_captures,
359        rust_2021_incompatible_or_patterns,
360        rust_2021_prefixes_incompatible_syntax,
361        rust_2021_prelude_collisions,
362        rust_2024_guarded_string_incompatible_syntax,
363        rust_2024_incompatible_pat,
364        rust_2024_prelude_collisions,
365        self_constructor_from_outer_item,
366        semicolon_in_expressions_from_macros,
367        single_use_lifetimes,
368        special_module_name,
369        stable_features,
370        static_mut_refs,
371        suspicious_double_ref_op,
372        tail_expr_drop_order,
373        trivial_bounds,
374        trivial_casts,
375        trivial_numeric_casts,
376        type_alias_bounds,
377        tyvar_behind_raw_pointer,
378        uncommon_codepoints,
379        unconditional_recursion,
380        uncovered_param_in_projection,
381        unfulfilled_lint_expectations,
382        ungated_async_fn_track_caller,
383        uninhabited_static,
384        unit_bindings,
385        unknown_lints,
386        unknown_or_malformed_diagnostic_attributes,
387        unnameable_test_items,
388        unnameable_types,
389        unpredictable_function_pointer_comparisons,
390        unreachable_code,
391        unreachable_patterns,
392        unreachable_pub,
393        unsafe_attr_outside_unsafe,
394        unsafe_code,
395        unsafe_op_in_unsafe_fn,
396        unstable_name_collisions,
397        unstable_syntax_pre_expansion,
398        unused_allocation,
399        unused_assignments,
400        unused_associated_type_bounds,
401        unused_attributes,
402        unused_braces,
403        unused_comparisons,
404        unused_crate_dependencies,
405        unused_doc_comments,
406        unused_extern_crates,
407        unused_features,
408        unused_import_braces,
409        unused_imports,
410        unused_labels,
411        unused_lifetimes,
412        unused_macro_rules,
413        unused_macros,
414        unused_must_use,
415        unused_mut,
416        unused_parens,
417        unused_qualifications,
418        unused_results,
419        unused_unsafe,
420        unused_variables,
421        useless_ptr_null_checks,
422        uses_power_alignment,
423        variant_size_differences,
424        while_true,
425    )
426)]
427// If nightly and unstable, allow `incomplete_features` and `unstable_features`
428#![cfg_attr(
429    all(feature = "unstable", nightly),
430    allow(incomplete_features, unstable_features)
431)]
432// If nightly and not unstable, deny `incomplete_features` and `unstable_features`
433#![cfg_attr(
434    all(not(feature = "unstable"), nightly),
435    deny(incomplete_features, unstable_features)
436)]
437// The unstable lints
438#![cfg_attr(
439    all(feature = "unstable", nightly),
440    deny(
441        fuzzy_provenance_casts,
442        lossy_provenance_casts,
443        multiple_supertrait_upcastable,
444        must_not_suspend,
445        non_exhaustive_omitted_patterns,
446        supertrait_item_shadowing_definition,
447        supertrait_item_shadowing_usage,
448        unqualified_local_imports,
449    )
450)]
451// clippy lints
452#![cfg_attr(nightly, deny(clippy::all, clippy::pedantic))]
453// rustdoc lints
454#![cfg_attr(
455    nightly,
456    deny(
457        rustdoc::bare_urls,
458        rustdoc::broken_intra_doc_links,
459        rustdoc::invalid_codeblock_attributes,
460        rustdoc::invalid_html_tags,
461        rustdoc::missing_crate_level_docs,
462        rustdoc::private_doc_tests,
463        rustdoc::private_intra_doc_links,
464    )
465)]
466#![cfg_attr(
467    all(nightly, feature = "unstable"),
468    deny(rustdoc::missing_doc_code_examples)
469)]
470#![cfg_attr(all(docsrs, nightly), feature(doc_cfg))]
471#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
472
473mod git2;
474
475#[cfg(test)]
476use {regex as _, temp_env as _};
477// This is here to appease the `unused_crate_dependencies` lint
478#[cfg(not(any(
479    feature = "build",
480    feature = "cargo",
481    feature = "rustc",
482    feature = "si"
483)))]
484use vergen as _;
485
486pub use self::git2::Git2;
487#[cfg(feature = "build")]
488pub use vergen::Build;
489#[cfg(feature = "cargo")]
490pub use vergen::Cargo;
491#[cfg(feature = "si")]
492pub use vergen::CpuRefreshKind;
493#[cfg(feature = "cargo_metadata")]
494pub use vergen::DependencyKind;
495#[cfg(feature = "si")]
496pub use vergen::MemoryRefreshKind;
497#[cfg(feature = "si")]
498pub use vergen::ProcessRefreshKind;
499#[cfg(feature = "si")]
500pub use vergen::RefreshKind;
501#[cfg(feature = "rustc")]
502pub use vergen::Rustc;
503#[cfg(feature = "si")]
504pub use vergen::Sysinfo;
505pub use vergen_lib::AddCustomEntries;
506pub use vergen_lib::CargoRerunIfChanged;
507pub use vergen_lib::CargoWarning;
508pub use vergen_lib::DefaultConfig;
509pub use vergen_lib::Emitter;