substrate_build_script_utils/
version.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use std::{borrow::Cow, process::Command};
19
20/// Generate the `cargo:` key output
21pub fn generate_cargo_keys() {
22	let commit = if let Ok(hash) = std::env::var("SUBSTRATE_CLI_GIT_COMMIT_HASH") {
23		Cow::from(hash.trim().to_owned())
24	} else {
25		// We deliberately set the length here to `11` to ensure that
26		// the emitted hash is always of the same length; otherwise
27		// it can (and will!) vary between different build environments.
28		match Command::new("git").args(["rev-parse", "--short=11", "HEAD"]).output() {
29			Ok(o) if o.status.success() => {
30				let sha = String::from_utf8_lossy(&o.stdout).trim().to_owned();
31				Cow::from(sha)
32			},
33			Ok(o) => {
34				let stderr = String::from_utf8_lossy(&o.stderr).trim().to_owned();
35				println!(
36					"cargo:warning=Git command failed with status '{}' with message: '{}'",
37					o.status, stderr,
38				);
39				Cow::from("unknown")
40			},
41			Err(err) => {
42				println!("cargo:warning=Failed to execute git command: {}", err);
43				Cow::from("unknown")
44			},
45		}
46	};
47
48	println!("cargo:rustc-env=SUBSTRATE_CLI_COMMIT_HASH={commit}");
49	println!("cargo:rustc-env=SUBSTRATE_CLI_IMPL_VERSION={}", get_version(&commit))
50}
51
52fn get_version(impl_commit: &str) -> String {
53	let commit_dash = if impl_commit.is_empty() { "" } else { "-" };
54
55	format!(
56		"{}{}{}",
57		std::env::var("CARGO_PKG_VERSION").unwrap_or_default(),
58		commit_dash,
59		impl_commit
60	)
61}