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
//! Build-time version injection using gitversion-rs **as a library**.
//!
//! This mirrors what you would put in a real project's `build.rs`: compute the
//! version from Git history with gitversion-rs and forward it to the compiler via
//! `cargo:rustc-env=` so the crate can read it at compile time with `env!(...)`.
//!
//! Run it from the repository root to see the lines a `build.rs` would emit:
//!
//! cargo run --example build_inject
//!
//! ## Using it in your own project
//!
//! Add gitversion-rs as a **build-dependency** and put the logic in `build.rs`:
//!
//! ```toml
//! # Cargo.toml
//! [build-dependencies]
//! gitversion-rs = "0.1"
//! ```
//!
//! ```rust,ignore
//! // build.rs
//! use std::path::Path;
//! use gitversion_rs::{config, git, version};
//!
//! fn main() -> anyhow::Result<()> {
//! let work_dir = Path::new(".").canonicalize()?;
//! let repo = git::GitRepo::discover(&work_dir)?;
//! let repo_root = repo.workdir().map(Path::to_path_buf);
//! let cfg = config::loader::load(None, &work_dir, repo_root.as_deref())?;
//! let vars = version::calculation::calculate(&repo, &cfg, None)?;
//!
//! // Overwrite Cargo's CARGO_PKG_VERSION* with the GitVersion-computed values.
//! println!("cargo:rustc-env=CARGO_PKG_VERSION={}", vars.sem_ver);
//! println!("cargo:rustc-env=GITVERSION_FULL_SEMVER={}", vars.full_sem_ver);
//! // Recompute whenever HEAD moves.
//! println!("cargo:rerun-if-changed=.git/HEAD");
//! Ok(())
//! }
//! ```
//!
//! Then read the injected values anywhere in your crate:
//!
//! ```rust,ignore
//! const VERSION: &str = env!("CARGO_PKG_VERSION"); // overwritten by build.rs
//! const FULL_SEMVER: &str = env!("GITVERSION_FULL_SEMVER");
//! ```
//!
//! Unlike the exec-hook approach (see `examples/exec-config-inject/`), this can
//! override the crate's own `CARGO_PKG_VERSION` because `cargo:rustc-env` is applied
//! by Cargo itself, after it reads `Cargo.toml`.
use Path;
use ;