bin_version/lib.rs
1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5/// Hidden reexports for the bin_version macro
6pub mod _hidden {
7 pub use const_str::concat;
8 pub use git_version::git_version;
9}
10
11/// Define constants that hold the git revision and package versions.
12///
13/// Defines two global `const`s:
14/// `GIT_REVISION`: The git revision as specified by the `GIT_REVISION` env
15/// variable provided at compile time, or the current git revision as discovered
16/// by running `git describe`.
17///
18/// `VERSION`: The value of the `CARGO_PKG_VERSION` environment variable
19/// concatenated with the value of `GIT_REVISION` if it is not empty.
20///
21/// Note: This macro must only be used from a binary, if used inside a library
22/// this will fail to compile.
23#[macro_export]
24macro_rules! bin_version {
25 () => {
26 $crate::git_revision!();
27
28 const VERSION: &str = {
29 const _VERSION_BASE: &str = if GIT_REVISION.is_empty() {
30 env!("CARGO_PKG_VERSION")
31 } else {
32 $crate::_hidden::concat!(env!("CARGO_PKG_VERSION"), "-", GIT_REVISION)
33 };
34 if cfg!(debug_assertions) {
35 $crate::_hidden::concat!(_VERSION_BASE, "-debug")
36 } else {
37 _VERSION_BASE
38 }
39 };
40 };
41}
42
43/// Defines constant that holds the git revision at build time.
44///
45/// `GIT_REVISION`: The git revision as specified by the `GIT_REVISION` env
46/// variable provided at compile time, or the current git revision as discovered
47/// by running `git describe`.
48///
49/// Note: This macro must only be used from a binary, if used inside a library
50/// this will fail to compile.
51#[macro_export]
52macro_rules! git_revision {
53 () => {
54 const _ASSERT_IS_BINARY: () = {
55 env!(
56 "CARGO_BIN_NAME",
57 "`bin_version!()` must be used from a binary"
58 );
59 };
60
61 const GIT_REVISION: &str = {
62 if let Some(revision) = option_env!("GIT_REVISION") {
63 revision
64 } else {
65 let version = $crate::_hidden::git_version!(
66 args = ["--always", "--abbrev=12", "--dirty", "--exclude", "*"],
67 fallback = ""
68 );
69
70 if version.is_empty() {
71 panic!("unable to query git revision");
72 }
73 version
74 }
75 };
76 };
77}