1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
56// 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.
1718use std::{
19 env, fs,
20 fs::File,
21 io,
22 io::Read,
23 path::{Path, PathBuf},
24};
2526/// Make sure the calling `build.rs` script is rerun when `.git/HEAD` or the ref of `.git/HEAD`
27/// changed.
28///
29/// The file is searched from the `CARGO_MANIFEST_DIR` upwards. If the file can not be found,
30/// a warning is generated.
31pub fn rerun_if_git_head_changed() {
32let mut manifest_dir = PathBuf::from(
33 env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is always set by cargo."),
34 );
35let manifest_dir_copy = manifest_dir.clone();
3637while manifest_dir.parent().is_some() {
38match get_git_paths(&manifest_dir) {
39Err(err) => {
40eprintln!("cargo:warning=Unable to read the Git repository: {}", err);
4142return
43},
44Ok(None) => {},
45Ok(Some(paths)) => {
46for p in paths {
47println!("cargo:rerun-if-changed={}", p.display());
48 }
4950return
51},
52 }
5354 manifest_dir.pop();
55 }
5657println!(
58"cargo:warning=Could not find `.git/HEAD` searching from `{}` upwards!",
59 manifest_dir_copy.display(),
60 );
61}
6263// Code taken from https://github.com/rustyhorde/vergen/blob/8d522db8c8e16e26c0fc9ea8e6b0247cbf5cca84/src/output/envvar.rs
64fn get_git_paths(path: &Path) -> Result<Option<Vec<PathBuf>>, io::Error> {
65let git_dir_or_file = path.join(".git");
6667if let Ok(metadata) = fs::metadata(&git_dir_or_file) {
68if metadata.is_dir() {
69// Echo the HEAD path
70let git_head_path = git_dir_or_file.join("HEAD");
7172// Determine where HEAD points and echo that path also.
73let mut f = File::open(&git_head_path)?;
74let mut git_head_contents = String::new();
75 f.read_to_string(&mut git_head_contents)?;
76let ref_vec: Vec<&str> = git_head_contents.split(": ").collect();
7778if ref_vec.len() == 2 {
79let current_head_file = ref_vec[1];
80let git_refs_path = git_dir_or_file.join(current_head_file);
8182Ok(Some(vec![git_head_path, git_refs_path]))
83 } else {
84Err(io::Error::new(
85 io::ErrorKind::Other,
86"You are most likely in a detached HEAD state",
87 ))
88 }
89 } else if metadata.is_file() {
90// We are in a worktree, so find out where the actual worktrees/<name>/HEAD file is.
91let mut git_file = File::open(&git_dir_or_file)?;
92let mut git_contents = String::new();
93 git_file.read_to_string(&mut git_contents)?;
94let dir_vec: Vec<&str> = git_contents.split(": ").collect();
95let git_path = dir_vec[1].trim();
9697// Echo the HEAD psth
98let git_head_path = PathBuf::from(git_path).join("HEAD");
99100// Find out what the full path to the .git dir is.
101let mut actual_git_dir = PathBuf::from(git_path);
102 actual_git_dir.pop();
103 actual_git_dir.pop();
104105// Determine where HEAD points and echo that path also.
106let mut f = File::open(&git_head_path)?;
107let mut git_head_contents = String::new();
108 f.read_to_string(&mut git_head_contents)?;
109let ref_vec: Vec<&str> = git_head_contents.split(": ").collect();
110111if ref_vec.len() == 2 {
112let current_head_file = ref_vec[1];
113let git_refs_path = actual_git_dir.join(current_head_file);
114115Ok(Some(vec![git_head_path, git_refs_path]))
116 } else {
117Err(io::Error::new(
118 io::ErrorKind::Other,
119"You are most likely in a detached HEAD state",
120 ))
121 }
122 } else {
123Err(io::Error::new(
124 io::ErrorKind::Other,
125"Invalid .git format (Not a directory or a file)",
126 ))
127 }
128 } else {
129Ok(None)
130 }
131}