-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
209 lines (194 loc) · 7.24 KB
/
Copy pathlib.rs
File metadata and controls
209 lines (194 loc) · 7.24 KB
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
//! Embed git information into the build.
//!
//! This crate is meant to be used in cargo build scripts. It exports the
//! following macros:
//!
//! - [`buidlref::rev!`]: The full commit hash of HEAD.
//! - [`buidlref::shortrev!`]: The first few characters of the commit hash of HEAD.
//! - [`buidlref::time!`]: The RFC 3339 time of the commit of HEAD, in UTC.
//!
//! These are set by
//!
//! - The git repository when using [`from_git_repo`].
//! - The `gitver_{REV,SHORTREV,TIME}_OVERRIDE` environment variables when using [`from_env_override`].
//!
//! ## Example
//!
//! First, set up your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! gitver = { version = "*" }
//!
//! [build-dependencies]
//! gitver = { version = "*", features = ["build"] }
//! ```
//!
//! In your `build.rs`:
//!
//! ```ignore
//! pub fn main() {
//! gitver::from_env_override()
//! .unwrap_or_else(|_| {
//! gitver::from_git_repo(std::env!("CARGO_MANIFEST_DIR"))
//! .inspect_err(|e| println!("cargo::error={e}"))
//! .unwrap()
//! })
//! .print_cargo_directives();
//! }
//! ```
//!
//! Then, in your library:
//!
//! ```ignore
//! println!("version={}", gitver::rev!());
//! println!("built={}", gitver::time!());
//! ```
//!
//! For workspaces, it's common to have a shared "proxy" crate for storing the
//! gitver information. So you'd make a `version-proxy` crate in your workspace
//! with a `build.rs` file like above.
//!
//! ## Rationale
//!
//! There are many other crates that do this, but why make our own?
//!
//! - `git-version`: Uses `include_bytes!` on files in `.git` to trigger recompilation
//! rather than build scripts with `rerun-if-changed`. Ends up recompiling more than
//! necessary.
//!
//! - `git2version`: Better, but no environment variable override in the case we're not
//! in a git repo, and has a very weird api.
//!
//! - `vergen`: Wildly complex, has some bizarrely behaving edge cases around
//! `VERGEN_IDEMOPOTENT=1`, and doesn't support environment variables.
//!
//! In contrast, the main logic of this crate is roughly 50 lines of code and does
//! everything we need. The logic for picking which files to `rerun-if-changed` on
//! is kept minimal so recompilations are minimized.
// NOTE: `env!` can't have consts, so make sure string literals below are in sync.
/// Returns the full commit hash of HEAD.
///
/// See crate-level documentation for more information.
#[macro_export]
macro_rules! rev {
() => {
::core::env!("__GITVER_REV")
};
}
/// Returns the commit hash of HEAD shortened to the first few characters.
///
/// See crate-level documentation for more information.
#[macro_export]
macro_rules! shortrev {
() => {
::core::env!("__GITVER_SHORTREV")
};
}
/// Returns the RFC 3339 time of the commit of HEAD, in UTC.
///
/// See crate-level documentation for more information.
#[macro_export]
macro_rules! time {
() => {
::core::env!("__GITVER_TIME")
};
}
#[cfg(feature = "build")]
pub mod build {
use snafu::prelude::*;
// NOTE: `env!` can't have consts, so make sure string literals above are in sync.
const ENV_REV_NAME: &str = "GITVER_REV";
const ENV_SHORTREV_NAME: &str = "GITVER_SHORTREV";
const ENV_TIME_NAME: &str = "GITVER_TIME";
#[derive(Debug, snafu::Snafu)]
#[snafu(whatever)]
pub struct GitError {
message: String,
#[snafu(source(from(Box<dyn std::error::Error + Send + Sync>, Some)))]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
pub struct Info {
sha: String,
short_sha: String,
date: String,
git_dir: Option<std::path::PathBuf>,
git_common_dir: Option<std::path::PathBuf>,
/// Only Some if HEAD is not detached. Takes the form of `refs/heads/branch-name`.
ref_name: Option<String>,
}
impl Info {
/// Print cargo directives to rerun the build if the git repo changes.
pub fn print_cargo_directives(self) {
if let Some(git_dir) = self.git_dir {
let head = git_dir.join("HEAD");
assert!(std::fs::exists(&head).unwrap());
println!("cargo::rerun-if-changed={}", head.display());
}
// see `man 5 gitrepository-layout`.
println!("cargo::rerun-if-env-changed=GIT_COMMON_DIR");
if let Some(git_common_dir) = self.git_common_dir {
let packed_path = git_common_dir.join("packed-refs");
println!("cargo::rerun-if-changed={}", packed_path.display());
// HEAD can be one of two things:
//
// - detached: HEAD contains only the commit hash
// - attached: HEAD contains "ref: refs/heads/branch-name"
//
// when detached, we only need to rerun if HEAD changes.
// when attached, we additionally rerun if the sha in the file
// pointed to by the ref changes.
//
// note: this file may not exist if the ref is packed.
if let Some(ref_name) = self.ref_name {
let ref_path = git_common_dir.join(ref_name);
println!("cargo::rerun-if-changed={}", ref_path.display());
}
}
println!("cargo::rerun-if-env-changed={}_OVERRIDE", ENV_REV_NAME);
println!("cargo::rerun-if-env-changed={}_OVERRIDE", ENV_SHORTREV_NAME);
println!("cargo::rerun-if-env-changed={}_OVERRIDE", ENV_TIME_NAME);
println!("cargo::rustc-env=__{}={}", ENV_REV_NAME, self.sha);
println!(
"cargo::rustc-env=__{}={}",
ENV_SHORTREV_NAME, self.short_sha
);
println!("cargo::rustc-env=__{}={}", ENV_TIME_NAME, self.date);
}
}
pub fn from_env_override() -> Result<Info, std::env::VarError> {
Ok(Info {
sha: std::env::var(format!("{}_OVERRIDE", ENV_REV_NAME))?,
short_sha: std::env::var(format!("{}_OVERRIDE", ENV_SHORTREV_NAME))?,
date: std::env::var(format!("{}_OVERRIDE", ENV_TIME_NAME))?,
git_dir: None,
git_common_dir: None,
ref_name: None,
})
}
pub fn from_git_repo(
cargo_manifest_dir: impl AsRef<std::path::Path>,
) -> Result<Info, GitError> {
let repo = git2::Repository::discover(cargo_manifest_dir)
.whatever_context("failed to find git repository; are you in a git repo?")?;
let ref_ = repo
.head()
.whatever_context("could not find repository HEAD")?;
let commit = ref_
.peel_to_commit()
.whatever_context("commit for HEAD not found")?;
let sha = commit.id().to_string();
let short_sha = sha[..8].to_string();
let epoch = commit.time().seconds();
let time = time::OffsetDateTime::from_unix_timestamp(epoch).unwrap();
let fmt = time::format_description::well_known::Rfc3339;
Ok(Info {
sha,
short_sha,
date: time.format(&fmt).unwrap(),
git_dir: Some(repo.path().to_owned()),
git_common_dir: Some(repo.commondir().to_owned()),
ref_name: ref_.name().map(|s| s.to_string()),
})
}
}