Debian Codegraph @

src/lib.rs

raw
1 // MIT License
2 //
3 // Copyright (c) Lukas Lueg <[email protected]>
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in all
13 // copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 // SOFTWARE.
22 //
23
24 #![allow(clippy::needless_doctest_main)]
25
26 //! Provides a crate with information from the time it was built.
27 //!
28 //! `built` is used as a build-time dependency to collect various information
29 //! about the build-environment, serialize this information into Rust-code and
30 //! provide that to the crate. The information collected by `built` include:
31 //!
32 //! * Various metadata like version, authors, homepage etc. as set by `Cargo.toml`
33 //! * The tag or commit id if the crate was being compiled from within a Git repository.
34 //! * The values of `CARGO_CFG_*` build script environment variables, like `CARGO_CFG_TARGET_OS` and `CARGO_CFG_TARGET_ARCH`.
35 //! * The features the crate was compiled with.
36 //! * The various dependencies, dependencies of dependencies and their versions Cargo ultimately chose to compile.
37 //! * The presence of a CI-platform like `Github Actions`, `Travis CI` and `AppVeyor`.
38 //! * The compiler and it's version; the documentation-generator and it's version.
39 //!
40 //! `built` does not add any further runtime-dependencies to a crate; all information
41 //! is serialized as types from `stdlib`. One can include `built` as a
42 //! runtime-dependency and use it's convenience functions.
43 //!
44 //! To add `built` to a crate, add it as a build-time dependency, use a build-script
45 //! to collect and serialize the build-time information, and `include!` the generated code.
46 //!
47 //! Add this to `Cargo.toml`:
48 //!
49 //! ```toml
50 //! [package]
51 //! build = "build.rs"
52 //!
53 //! [build-dependencies]
54 //! built = "0.8"
55 //! ```
56 //!
57 //! Add or modify a build-script. In `build.rs`:
58 //!
59 //! ```rust,no_run
60 //! fn main() {
61 //! built::write_built_file().expect("Failed to acquire build-time information");
62 //! }
63 //! ```
64 //!
65 //! The build-script will by default write a file named `built.rs` into Cargo's output
66 //! directory. It can be picked up in `main.rs` (or anywhere else) like this:
67 //!
68 //! ```rust,ignore
69 //! // Use of a mod or pub mod is not actually necessary.
70 //! pub mod built_info {
71 //! // The file has been placed there by the build script.
72 //! include!(concat!(env!("OUT_DIR"), "/built.rs"));
73 //! }
74 //! ```
75 //!
76 //! ...and then used somewhere in the crate's code:
77 //!
78 //! ```rust
79 //! # mod built_info {
80 //! # pub static PKG_VERSION_PRE: &str = "";
81 //! # pub static CI_PLATFORM: Option<&str> = None;
82 //! # pub static GIT_VERSION: Option<&str> = None;
83 //! # pub static DEPENDENCIES: [(&str, &str); 0] = [];
84 //! # pub static BUILT_TIME_UTC: &str = "Tue, 14 Feb 2017 05:21:41 GMT";
85 //! # }
86 //! #
87 //! # enum LogLevel { TRACE, ERROR };
88 //! /// Determine if current version is a pre-release or was built from a git-repo
89 //! fn release_is_unstable() -> bool {
90 //! return !built_info::PKG_VERSION_PRE.is_empty() || built_info::GIT_VERSION.is_some()
91 //! }
92 //!
93 //! /// Default log-level, enhanced on CI
94 //! fn default_log_level() -> LogLevel {
95 //! if built_info::CI_PLATFORM.is_some() {
96 //! LogLevel::TRACE
97 //! } else {
98 //! LogLevel::ERROR
99 //! }
100 //! }
101 //!
102 //! /// The time this crate was built
103 //! #[cfg(feature = "chrono")]
104 //! fn built_time() -> built::chrono::DateTime<built::chrono::Local> {
105 //! built::util::strptime(built_info::BUILT_TIME_UTC)
106 //! .with_timezone(&built::chrono::offset::Local)
107 //! }
108 //!
109 //! /// If another crate pulls in a dependency we don't like, print a warning
110 //! #[cfg(feature = "semver")]
111 //! fn check_sane_dependencies() {
112 //! if built::util::parse_versions(&built_info::DEPENDENCIES)
113 //! .any(|(name, ver)| name == "DeleteAllMyFiles"
114 //! && ver < built::semver::Version::parse("1.1.4").unwrap()) {
115 //! eprintln!("DeleteAllMyFiles < 1.1.4 may not delete all your files. Beware!");
116 //! }
117 //! }
118 //! ```
119 //!
120 //!
121 //! ## Overrides
122 //!
123 //! Most values otherwise detected by `built` can be manually set using environment variables. The
124 //! primary use-case for this is to allow automated build-systems and package-managers to enforce
125 //! certain values, e.g. to hide the presence of a CI-platform and/or allow for reproducible
126 //! builds.
127 //!
128 //! The values set via the environment take precedence over what `built` would otherwise detect.
129 //! There is no mechanism to ensure that values derived from override-variables are sensible,
130 //! besides enforcing the correct type.
131 //!
132 //! Override-variables are prefixed by `BUILT_OVERRIDE_{PKG_NAME}_`, where `{PKG_NAME}` is the name
133 //! of the package as reported by `cargo`. For example, if the package is named "mypkg", and the value
134 //! to be overridden is named "CI_PLATFORM", then the override-variable is named
135 //! "BUILT_OVERRIDE_mypkg_CI_PLATFORM". Remember that more than one package in a dependency-graph
136 //! might use `built` internally, so you might have to override multiple instances of the same
137 //! value. If the original `{PKG_NAME}` contain hyphens `-`, they will be substituted by underscores `_`.
138 //! For example, if the package name is `great-pkg`, the corresponding override-variable is named
139 //! "BUILT_OVERRIDE_great_pkg_...".
140 //! Unused override-variables result in a warning at compile time, albeit cargo only reports those
141 //! for path-specific (e.g. local) packages.
142 //!
143 //! An override-variable's text-presentation must parse to the value's respective type:
144 //! * Strings are used as-is.
145 //! * Integers and `bool` must parse via their `std::str::FromStr`-implementation.
146 //! * `std::option::Option<T>` parses the string `BUILT_OVERRIDE_NONE` as `Option::None`; every other value
147 //! must parse as `T`. For example, `BUILT_OVERRIDE_mypkg_CI_PLATFORM=BUILT_OVERRIDE_NONE` forces
148 //! `CI_PLATFORM.is_none()`.
149 //! * List-like values are parsed as comma-separated values.
150 //!
151 //! If an override-variable can't be parsed, the build-process will abort with a `panic!()`.
152 //!
153 //! Notice that values that were overridden are recorded in `OVERRIDE_VARIABLES_USED`.
154 //!
155 //! Please refer to the respective item's documentation for more information on overrides.
156 //!
157 //! ## Feature flags
158 //! The information that `built` collects and makes available in `built.rs` depends
159 //! on the features that were enabled on the build-time dependency.
160 //!
161 //! Crates using `built` should avoid enabling unnecessary features on `built`: These features
162 //! pull in other dependencies, which slows down the compilation-process; in the worst case,
163 //! one of `built`'s dependencies may fail to build on the target-platform, causing a build-
164 //! failure for the entire dependency-tree; there is nothing dependent crates can do to fix
165 //! the build in these situations.
166 //! If your crate separates into multiple sub-crates, `built` should generally be used most close
167 //! to the top-most crate (e.g. in the CLI crate).
168 //!
169 //! ### _Always available_
170 //! The following information is available regardless of feature-flags.
171 //!
172 //! ```
173 //! /// The Continuous Integration platform detected during compilation.
174 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CI_PLATFORM`.
175 //! pub static CI_PLATFORM: Option<&str> = None;
176 //!
177 //! /// The full version.
178 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_VERSION`.
179 //! pub static PKG_VERSION: &str = "0.1.0";
180 //! /// The major version.
181 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_MAJOR`.
182 //! pub static PKG_VERSION_MAJOR: &str = "0";
183 //! /// The minor version.
184 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_MINOR`.
185 //! pub static PKG_VERSION_MINOR: &str = "1";
186 //! /// "The patch version.
187 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_PATCH`.
188 //! pub static PKG_VERSION_PATCH: &str = "0";
189 //! /// "The pre-release version.
190 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_PRE`.
191 //! pub static PKG_VERSION_PRE: &str = "";
192 //!
193 //! /// "A colon-separated list of authors.
194 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_AUTHORS`.
195 //! pub static PKG_AUTHORS: &str = "Lukas Lueg <[email protected]>";
196 //!
197 //! /// The name of the package.
198 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_NAME`.
199 //! pub static PKG_NAME: &str = "example_project";
200 //! /// "The description.
201 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_DESCRIPTION`.
202 //! pub static PKG_DESCRIPTION: &str = "";
203 //! /// "The homepage.
204 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_HOMEPAGE`.
205 //! pub static PKG_HOMEPAGE: &str = "";
206 //! /// "The license.
207 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_LICENSE`.
208 //! pub static PKG_LICENSE: &str = "MIT";
209 //! /// The source repository as advertised in Cargo.toml.
210 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PKG_REPOSITORY`.
211 //! pub static PKG_REPOSITORY: &str = "";
212 //!
213 //! /// The target triple that was being compiled for.
214 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_TARGET`.
215 //! pub static TARGET: &str = "x86_64-unknown-linux-gnu";
216 //! /// The host triple of the rust compiler.
217 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_HOST`.
218 //! pub static HOST: &str = "x86_64-unknown-linux-gnu";
219 //! /// `release` for release builds, `debug` for other builds.
220 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_PROFILE`.
221 //! pub static PROFILE: &str = "debug";
222 //!
223 //! /// The compiler that cargo resolved to use.
224 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_RUSTC`; notice that
225 //! /// if `RUSTC` is overridden, `RUSTC_VERSION` *must* also be overridden.
226 //! pub static RUSTC: &str = "rustc";
227 //! /// The documentation-generator that cargo resolved to use.
228 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_RUSTDOC`; notice that if `RUSTDOC`
229 //! /// is overridden, `RUSTDOC_VERSION` *must* also be overridden.
230 //! pub static RUSTDOC: &str = "rustdoc";
231 //! /// The output of `rustc -V`
232 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_RUSTC_VERSION`.
233 //! pub static RUSTC_VERSION: &str = "rustc 1.43.1 (8d69840ab 2020-05-04)";
234 //! /// The output of `rustdoc -V`
235 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_RUSTDOC_VERSION`.
236 //! pub static RUSTDOC_VERSION: &str = "rustdoc 1.43.1 (8d69840ab 2020-05-04)";
237 //!
238 //! /// Value of `OPT_LEVEL` for the profile used during compilation.
239 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_OPT_LEVEL`.
240 //! pub static OPT_LEVEL: &str = "0";
241 //! /// The parallelism that was specified during compilation.
242 //! /// If `SOURCE_DATE_EPOCH` is set, `NUM_JOBS` is forced to `1`.
243 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_NUM_JOBS`.
244 //! pub static NUM_JOBS: u32 = 8;
245 //! /// "Value of DEBUG for the profile used during compilation.
246 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_NUM_DEBUG`.
247 //! pub static DEBUG: bool = true;
248 //!
249 //! /// The features that were enabled during compilation.
250 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_FEATURES`.
251 //! pub static FEATURES: [&str; 0] = [];
252 //! /// The features as a comma-separated string.
253 //! pub static FEATURES_STR: &str = "";
254 //! /// The features as above, as lowercase strings.
255 //! pub static FEATURES_LOWERCASE: [&str; 0] = [];
256 //! /// The feature-string as above, from lowercase strings.
257 //! pub static FEATURES_LOWERCASE_STR: &str = "";
258 //!
259 //! /// The target architecture, given by `CARGO_CFG_TARGET_ARCH`.
260 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CFG_TARGET_ARCH`.
261 //! pub static CFG_TARGET_ARCH: &str = "x86_64";
262 //! /// The endianness, given by `CARGO_CFG_TARGET_ENDIAN`.
263 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CFG_ENDIAN`.
264 //! pub static CFG_ENDIAN: &str = "little";
265 //! /// The toolchain-environment, given by `CARGO_CFG_TARGET_ENV`.
266 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CFG_ENV`.
267 //! pub static CFG_ENV: &str = "gnu";
268 //! /// The OS-family, given by `CARGO_CFG_TARGET_FAMILY`.
269 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CFG_FAMILY`.
270 //! pub static CFG_FAMILY: &str = "unix";
271 //! /// The operating system, given by `CARGO_CFG_TARGET_OS`.
272 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CFG_OS`.
273 //! pub static CFG_OS: &str = "linux";
274 //! /// The pointer width, given by `CARGO_CFG_TARGET_POINTER_WIDTH`.
275 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_CFG_POINTER_WIDTH`.
276 //! pub static CFG_POINTER_WIDTH: &str = "64";
277 //!
278 //! /// The override-variables that were used during compilation.
279 //! pub static OVERRIDE_VARIABLES_USED: [&str; 0] = [];
280 //! ```
281 //!
282 //! ### `cargo-lock`
283 //! Parses `Cargo.lock` and generates representations of dependencies and their versions.
284 //!
285 //! For this to work, `Cargo.lock` needs to actually be there; this is (usually)
286 //! only true for executables and not for libraries. Cargo will only create a
287 //! `Cargo.lock` for the top-level crate in a dependency-tree. In case
288 //! of a library, the top-level crate will decide which crate/version
289 //! combination to compile and there will be no `Cargo.lock` while the library
290 //! gets compiled as a dependency.
291 //!
292 //! Parsing `Cargo.lock` instead of `Cargo.toml` allows to serialize the
293 //! precise versions Cargo chose to compile. One can't, however, distinguish
294 //! `build-dependencies`, `dev-dependencies` and `dependencies`. Furthermore,
295 //! some dependencies never show up if Cargo had not been forced to
296 //! actually use them (e.g. `dev-dependencies` with `cargo test` never
297 //! having been executed).
298 //!
299 //! Note that if the `dependency-tree`-feature is not active, the list of dependencies
300 //! contains the root-package(s) as well.
301 //!
302 //! ```
303 //! /// An array of effective dependencies as documented by `Cargo.lock`.
304 //! pub static DEPENDENCIES: [(&str, &str); 37] = [("autocfg", "1.0.0"), ("bitflags", "1.2.1"), ("built", "0.4.1"), ("cargo-lock", "4.0.1"), ("cc", "1.0.54"), ("cfg-if", "0.1.10"), ("chrono", "0.4.11"), ("example_project", "0.1.0"), ("git2", "0.13.6"), ("idna", "0.2.0"), ("jobserver", "0.1.21"), ("libc", "0.2.71"), ("libgit2-sys", "0.12.6+1.0.0"), ("libz-sys", "1.0.25"), ("log", "0.4.8"), ("matches", "0.1.8"), ("num-integer", "0.1.42"), ("num-traits", "0.2.11"), ("percent-encoding", "2.1.0"), ("pkg-config", "0.3.17"), ("proc-macro2", "1.0.17"), ("quote", "1.0.6"), ("semver", "1.0.0"), ("serde", "1.0.110"), ("serde_derive", "1.0.110"), ("smallvec", "1.4.0"), ("syn", "1.0.25"), ("time", "0.1.43"), ("toml", "0.5.6"), ("unicode-bidi", "0.3.4"), ("unicode-normalization", "0.1.12"), ("unicode-xid", "0.2.0"), ("url", "2.1.1"), ("vcpkg", "0.2.8"), ("winapi", "0.3.8"), ("winapi-i686-pc-windows-gnu", "0.4.0"), ("winapi-x86_64-pc-windows-gnu", "0.4.0")];
305 //! /// The effective dependencies as a comma-separated string.
306 //! pub static DEPENDENCIES_STR: &str = "autocfg 1.0.0, bitflags 1.2.1, built 0.4.1, cargo-lock 4.0.1, cc 1.0.54, cfg-if 0.1.10, chrono 0.4.11, example_project 0.1.0, git2 0.13.6, idna 0.2.0, jobserver 0.1.21, libc 0.2.71, libgit2-sys 0.12.6+1.0.0, libz-sys 1.0.25, log 0.4.8, matches 0.1.8, num-integer 0.1.42, num-traits 0.2.11, percent-encoding 2.1.0, pkg-config 0.3.17, proc-macro2 1.0.17, quote 1.0.6, semver 1.0.0, serde 1.0.110, serde_derive 1.0.110, smallvec 1.4.0, syn 1.0.25, time 0.1.43, toml 0.5.6, unicode-bidi 0.3.4, unicode-normalization 0.1.12, unicode-xid 0.2.0, url 2.1.1, vcpkg 0.2.8, winapi 0.3.8, winapi-i686-pc-windows-gnu 0.4.0, winapi-x86_64-pc-windows-gnu 0.4.0";
307 //! ```
308 //!
309 //! ### `dependency-tree` (implies `cargo-lock`)
310 //! Solve the dependency-graph in `Cargo.lock` to discern direct and indirect
311 //! dependencies.
312 //!
313 //! "Direct" dependencies are those which the root-package(s) depends on.
314 //! "Indirect" dependencies are those which are not direct dependencies.
315 //!
316 //! ```
317 //! /// An array of direct dependencies as documented by `Cargo.lock`.
318 //! pub static DIRECT_DEPENDENCIES: [(&str, &str); 1] = [("built", "0.6.1")];
319 //! /// The direct dependencies as a comma-separated string.
320 //! pub static DIRECT_DEPENDENCIES_STR: &str = r"built 0.6.1";
321 //!
322 //! /// An array of indirect dependencies as documented by `Cargo.lock`.
323 //! pub static INDIRECT_DEPENDENCIES: [(&str, &str); 64] = [("android-tzdata", "0.1.1"), ("android_system_properties", "0.1.5"), ("autocfg", "1.1.0"), ("bitflags", "2.4.0"), ("bumpalo", "3.13.0"), ("cargo-lock", "9.0.0"), ("cc", "1.0.83"), ("cfg-if", "1.0.0"), ("chrono", "0.4.29"), ("core-foundation-sys", "0.8.4"), ("equivalent", "1.0.1"), ("example_project", "0.1.0"), ("fixedbitset", "0.4.2"), ("form_urlencoded", "1.2.0"), ("git2", "0.18.0"), ("hashbrown", "0.14.0"), ("iana-time-zone", "0.1.57"), ("iana-time-zone-haiku", "0.1.2"), ("idna", "0.4.0"), ("indexmap", "2.0.0"), ("jobserver", "0.1.26"), ("js-sys", "0.3.64"), ("libc", "0.2.147"), ("libgit2-sys", "0.16.1+1.7.1"), ("libz-sys", "1.1.12"), ("log", "0.4.20"), ("memchr", "2.6.3"), ("num-traits", "0.2.16"), ("once_cell", "1.18.0"), ("percent-encoding", "2.3.0"), ("petgraph", "0.6.4"), ("pkg-config", "0.3.27"), ("proc-macro2", "1.0.66"), ("quote", "1.0.33"), ("semver", "1.0.18"), ("serde", "1.0.188"), ("serde_derive", "1.0.188"), ("serde_spanned", "0.6.3"), ("syn", "2.0.31"), ("tinyvec", "1.6.0"), ("tinyvec_macros", "0.1.1"), ("toml", "0.7.6"), ("toml_datetime", "0.6.3"), ("toml_edit", "0.19.14"), ("unicode-bidi", "0.3.13"), ("unicode-ident", "1.0.11"), ("unicode-normalization", "0.1.22"), ("url", "2.4.1"), ("vcpkg", "0.2.15"), ("wasm-bindgen", "0.2.87"), ("wasm-bindgen-backend", "0.2.87"), ("wasm-bindgen-macro", "0.2.87"), ("wasm-bindgen-macro-support", "0.2.87"), ("wasm-bindgen-shared", "0.2.87"), ("windows", "0.48.0"), ("windows-targets", "0.48.5"), ("windows_aarch64_gnullvm", "0.48.5"), ("windows_aarch64_msvc", "0.48.5"), ("windows_i686_gnu", "0.48.5"), ("windows_i686_msvc", "0.48.5"), ("windows_x86_64_gnu", "0.48.5"), ("windows_x86_64_gnullvm", "0.48.5"), ("windows_x86_64_msvc", "0.48.5"), ("winnow", "0.5.15")];
324 //! /// The indirect dependencies as a comma-separated string.
325 //! pub static INDIRECT_DEPENDENCIES_STR: &str = r"android-tzdata 0.1.1, android_system_properties 0.1.5, autocfg 1.1.0, bitflags 2.4.0, bumpalo 3.13.0, cargo-lock 9.0.0, cc 1.0.83, cfg-if 1.0.0, chrono 0.4.29, core-foundation-sys 0.8.4, equivalent 1.0.1, example_project 0.1.0, fixedbitset 0.4.2, form_urlencoded 1.2.0, git2 0.18.0, hashbrown 0.14.0, iana-time-zone 0.1.57, iana-time-zone-haiku 0.1.2, idna 0.4.0, indexmap 2.0.0, jobserver 0.1.26, js-sys 0.3.64, libc 0.2.147, libgit2-sys 0.16.1+1.7.1, libz-sys 1.1.12, log 0.4.20, memchr 2.6.3, num-traits 0.2.16, once_cell 1.18.0, percent-encoding 2.3.0, petgraph 0.6.4, pkg-config 0.3.27, proc-macro2 1.0.66, quote 1.0.33, semver 1.0.18, serde 1.0.188, serde_derive 1.0.188, serde_spanned 0.6.3, syn 2.0.31, tinyvec 1.6.0, tinyvec_macros 0.1.1, toml 0.7.6, toml_datetime 0.6.3, toml_edit 0.19.14, unicode-bidi 0.3.13, unicode-ident 1.0.11, unicode-normalization 0.1.22, url 2.4.1, vcpkg 0.2.15, wasm-bindgen 0.2.87, wasm-bindgen-backend 0.2.87, wasm-bindgen-macro 0.2.87, wasm-bindgen-macro-support 0.2.87, wasm-bindgen-shared 0.2.87, windows 0.48.0, windows-targets 0.48.5, windows_aarch64_gnullvm 0.48.5, windows_aarch64_msvc 0.48.5, windows_i686_gnu 0.48.5, windows_i686_msvc 0.48.5, windows_x86_64_gnu 0.48.5, windows_x86_64_gnullvm 0.48.5, windows_x86_64_msvc 0.48.5, winnow 0.5.15";
326 //! ```
327 //!
328 //! ### `git2`
329 //! Try to open the git-repository at `manifest_location` and retrieve `HEAD`
330 //! tag or commit id.
331 //!
332 //! Notice that `GIT_HEAD_REF` is `None` if `HEAD` is detached or not valid UTF-8.
333 //!
334 //! Continuous Integration platforms like `Travis` and `AppVeyor` will
335 //! do shallow clones, causing `libgit2` to be unable to get a meaningful
336 //! result. `GIT_VERSION` and `GIT_DIRTY` will therefore always be `None` if
337 //! a CI-platform is detected.
338 //! ```
339 //! /// If the crate was compiled from within a git-repository,
340 //! /// `GIT_VERSION` contains HEAD's tag. The short commit id is used
341 //! /// if HEAD is not tagged.
342 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_GIT_VERSION`.
343 //! pub static GIT_VERSION: Option<&str> = Some("0.4.1-10-gca2af4f");
344 //!
345 //! /// If the repository had dirty/staged files.
346 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_GIT_DIRTY`.
347 //! pub static GIT_DIRTY: Option<bool> = Some(true);
348 //!
349 //! /// If the crate was compiled from within a git-repository,
350 //! /// `GIT_HEAD_REF` contains full name to the reference pointed to by
351 //! /// HEAD (e.g.: `refs/heads/master`). If HEAD is detached or the branch
352 //! /// name is not valid UTF-8 `None` will be stored.
353 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_GIT_HEAD_REF`.
354 //! pub static GIT_HEAD_REF: Option<&str> = Some("refs/heads/master");
355 //!
356 //! /// If the crate was compiled from within a git-repository,
357 //! /// `GIT_COMMIT_HASH` contains HEAD's full commit SHA-1 hash.
358 //! /// Can be overridden with `BUILT_OVERRIDE_{pkg_name}_GIT_COMMIT_HASH`.
359 //! pub static GIT_COMMIT_HASH: Option<&str> = Some("ca2af4f11bb8f4f6421c4cccf428bf4862573daf");
360 //!
361 //! /// If the crate was compiled from within a git-repository,
362 //! /// `GIT_COMMIT_HASH_SHORT` contains HEAD's short commit SHA-1 hash.
363 //! /// Can be overridden using `BUILT_OVERRIDE_{pkg_name}_GIT_COMMIT_HASH_SHORT`.
364 //! pub static GIT_COMMIT_HASH_SHORT: Option<&str> = Some("ca2af4f");
365 //! ```
366 //!
367 //! ### `gix`
368 //! An alternative to `git2` that uses the `gix` (gitoxide) crate for git operations.
369 //! This feature provides the same git information as `git2` but uses a pure Rust
370 //! implementation with potentially faster build times.
371 //!
372 //! **Note**: When both `git2` and `gix` features are enabled, `git2` takes precedence.
373 //!
374 //! ### `chrono`
375 //!
376 //! The build-time is recorded as `BUILT_TIME_UTC`. If `built` is included as a runtime-dependency,
377 //! it can parse the string-representation into a `time:Tm` with the help of
378 //! `built::util::strptime()`.
379 //!
380 //! `built` honors the environment variable `SOURCE_DATE_EPOCH`. If the variable is defined and
381 //! parses to a valid UTC timestamp, that build-time is used instead of the current local time.
382 //! The variable is silently ignored if defined but but does not parse to a valid UTC timestamp.
383 //!
384 //! ```
385 //! /// The built-time in RFC2822, UTC
386 //! /// Can be overridden with`BUILT_OVERRIDE_BUILT_TIME_UTC`; the override takes precedence
387 //! /// over `SOURCE_DATE_EPOCH`; it *must* parse via `chrono::DateTime::parse_from_rfc2822()`.
388 //! pub static BUILT_TIME_UTC: &str = "Wed, 27 May 2020 18:12:39 +0000";
389 //! ```
390
391 #[cfg(feature = "cargo-lock")]
392 mod dependencies;
393 mod environment;
394 #[cfg(feature = "git2")]
395 mod git_impl;
396 #[cfg(any(feature = "git2", feature = "gix"))]
397 mod git_shared;
398 #[cfg(all(feature = "gix", any(test, not(feature = "git2"))))]
399 mod gix_impl;
400 #[cfg(feature = "chrono")]
401 mod krono;
402 pub mod util;
403
404 use std::{env, fmt, fs, io, io::Write, path};
405
406 #[cfg(feature = "semver")]
407 pub use semver;
408
409 #[cfg(feature = "chrono")]
410 pub use chrono;
411
412 #[cfg(feature = "gix")]
413 pub use gix;
414
415 pub use environment::CIPlatform;
416
417 #[doc = include_str!("../README.md")]
418 #[allow(dead_code)]
419 type _READMETEST = ();
420
421 /// If `SOURCE_DATE_EPOCH` is defined, its value is used instead of
422 /// `chrono::..::now()` as `BUILT_TIME_UTC`.
423 /// The presence of `SOURCE_DATE_EPOCH` also soft-indicates that a
424 /// reproducible build is desired, which we may or may not be able
425 /// to honor.
426 const SOURCE_DATE_EPOCH: &str = "SOURCE_DATE_EPOCH";
427
428 macro_rules! write_variable {
429 ($writer:expr, $name:expr, $datatype:expr, $value:expr, $doc:expr) => {
430 writeln!(
431 $writer,
432 "#[allow(clippy::needless_raw_string_hashes)]\n#[doc=r#\"{}\"#]\n#[allow(dead_code)]\npub static {}: {} = {};",
433 $doc, $name, $datatype, $value
434 )?;
435 };
436 }
437 pub(crate) use write_variable;
438
439 macro_rules! write_str_variable {
440 ($writer:expr, $name:expr, $value:expr, $doc:expr) => {
441 write_variable!(
442 $writer,
443 $name,
444 "&str",
445 format_args!("\"{}\"", $value.escape_default()),
446 $doc
447 );
448 };
449 }
450 pub(crate) use write_str_variable;
451
452 pub(crate) fn fmt_option_str<S: fmt::Display>(o: Option<S>) -> String {
453 match o {
454 Some(s) => format!("Some(\"{s}\")"),
455 None => "None".to_owned(),
456 }
457 }
458
459 /// Writes rust-code describing the crate at `manifest_location` to a new file named `dst`.
460 ///
461 /// # Errors
462 /// The function returns an error if the file at `dst` already exists or can't
463 /// be written to. This should not be a concern if the filename points to
464 /// `OUR_DIR`.
465 pub fn write_built_file_with_opts(
466 #[cfg(any(feature = "cargo-lock", feature = "git2", feature = "gix"))]
467 manifest_location: Option<&path::Path>,
468 dst: &path::Path,
469 ) -> io::Result<()> {
470 let mut built_file = fs::File::create(dst)?;
471 built_file.write_all(
472 r#"//
473 // EVERYTHING BELOW THIS POINT WAS AUTO-GENERATED DURING COMPILATION. DO NOT MODIFY.
474 //
475 "#
476 .as_ref(),
477 )?;
478
479 let envmap = environment::EnvironmentMap::new();
480 envmap.write_ci(&built_file)?;
481 envmap.write_env(&built_file)?;
482 envmap.write_features(&built_file)?;
483 envmap.write_compiler_version(&built_file)?;
484 envmap.write_cfg(&built_file)?;
485
486 #[cfg(any(feature = "git2", feature = "gix"))]
487 {
488 if let Some(manifest_location) = manifest_location {
489 git_shared::write_git_version(manifest_location, &envmap, &built_file)?;
490 }
491 }
492
493 #[cfg(feature = "cargo-lock")]
494 if let Some(manifest_location) = manifest_location {
495 dependencies::write_dependencies(manifest_location, &built_file)?;
496 }
497
498 #[cfg(feature = "chrono")]
499 krono::write_time(&built_file, &envmap)?;
500
501 let mut used_override_vars = envmap.used_override_vars().collect::<Vec<_>>();
502 used_override_vars.sort_unstable();
503 write_variable!(
504 built_file,
505 "OVERRIDE_VARIABLES_USED",
506 format_args!("[&str; {}]", used_override_vars.len()),
507 util::ArrayDisplay(&used_override_vars, |t, f| write!(
508 f,
509 "\"{}\"",
510 t.escape_default()
511 )),
512 "The override-variables that were used during compilation."
513 );
514
515 built_file.write_all(
516 r#"//
517 // EVERYTHING ABOVE THIS POINT WAS AUTO-GENERATED DURING COMPILATION. DO NOT MODIFY.
518 //
519 "#
520 .as_ref(),
521 )?;
522
523 let unused_override_vars = envmap.unused_override_vars().collect::<Vec<_>>().join(", ");
524 if !unused_override_vars.is_empty() {
525 println!(
526 "cargo::warning=At least one environment variable looks like an override-variable but was ignored by built: `{unused_override_vars}`. Typo?"
527 );
528 }
529
530 Ok(())
531 }
532
533 /// A shorthand for calling `write_built_file_with_opts()` with `CARGO_MANIFEST_DIR` and
534 /// `[OUT_DIR]/built.rs`.
535 ///
536 /// # Errors
537 /// Same as `write_built_file_with_opts()`.
538 ///
539 /// # Panics
540 /// If `CARGO_MANIFEST_DIR` or `OUT_DIR` are not set.
541 pub fn write_built_file() -> io::Result<()> {
542 let dst = path::Path::new(&env::var("OUT_DIR").expect("OUT_DIR not set")).join("built.rs");
543 write_built_file_with_opts(
544 #[cfg(any(feature = "cargo-lock", feature = "git2", feature = "gix"))]
545 Some(
546 env::var("CARGO_MANIFEST_DIR")
547 .expect("CARGO_MANIFEST_DIR")
548 .as_ref(),
549 ),
550 &dst,
551 )?;
552 Ok(())
553 }