-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.rs
215 lines (187 loc) · 5.75 KB
/
build.rs
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
210
211
212
213
214
215
use fs::File;
use io::{BufRead, Read, Write};
use path::{Path, PathBuf};
use std::{env, fmt, fs, io, path};
enum Error {
GitDirNotFound,
Io(io::Error),
OutDir(env::VarError),
InvalidUserHooksDir(PathBuf),
EmptyUserHook(PathBuf),
}
type Result<T> = std::result::Result<T, Error>;
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
impl From<env::VarError> for Error {
fn from(error: env::VarError) -> Error {
Error::OutDir(error)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = match self {
Error::GitDirNotFound => format!(
".git directory was not found in '{}' or its parent directories",
env::var("OUT_DIR").unwrap_or_else(|_| "".to_string()),
),
Error::Io(inner) => format!("IO error: {}", inner),
Error::OutDir(env::VarError::NotPresent) => unreachable!(),
Error::OutDir(env::VarError::NotUnicode(msg)) => msg.to_string_lossy().to_string(),
Error::InvalidUserHooksDir(path) => {
format!("User hooks directory is not found or no executable file is found in '{:?}'. Did you forget to make a hook script executable?", path)
}
Error::EmptyUserHook(path) => format!("User hook script is empty: {:?}", path),
};
write!(f, "{}", msg)
}
}
fn resolve_gitdir() -> Result<PathBuf> {
let dir = env::var("OUT_DIR")?;
let mut dir = PathBuf::from(dir);
if !dir.has_root() {
dir = fs::canonicalize(dir)?;
}
loop {
let gitdir = dir.join(".git");
if gitdir.is_dir() {
return Ok(gitdir);
}
if gitdir.is_file() {
let mut buf = String::new();
File::open(gitdir)?.read_to_string(&mut buf)?;
let newlines: &[_] = &['\n', '\r'];
let gitdir = PathBuf::from(buf.trim_end_matches(newlines));
if !gitdir.is_dir() {
return Err(Error::GitDirNotFound);
}
return Ok(gitdir);
}
if !dir.pop() {
return Err(Error::GitDirNotFound);
}
}
}
// This function returns true when
// - the hook was generated by the same version of cargo-husky
// - someone else had already put another hook script
// For safety, cargo-husky does nothing on case2 also.
fn hook_already_exists(hook: &Path) -> bool {
let f = match File::open(hook) {
Ok(f) => f,
Err(..) => return false,
};
let ver_line = match io::BufReader::new(f).lines().nth(2) {
None => return true, // Less than 2 lines. The hook script seemed to be generated by someone else
Some(Err(..)) => return false, // Failed to read entry. Re-generate anyway
Some(Ok(line)) => line,
};
ver_line.contains(&format!(
"# This hook was set for {} v{}: {}",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
env!("CARGO_PKG_HOMEPAGE")
))
}
fn create_executable_file(path: &Path) -> io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o755)
.open(path)
}
fn install_hook(src: &Path, dst: &Path) -> Result<()> {
if hook_already_exists(dst) {
return Ok(());
}
let mut lines = {
let mut vec = vec![];
for line in io::BufReader::new(File::open(src)?).lines() {
vec.push(line?);
}
vec
};
if lines.is_empty() {
return Err(Error::EmptyUserHook(src.to_owned()));
}
// Insert project package version information as comment
if !lines[0].starts_with("#!") {
lines.insert(0, "#".to_string());
}
lines.insert(1, "#".to_string());
lines.insert(
2,
format!(
"# This hook was set for {} v{}: {}",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
env!("CARGO_PKG_HOMEPAGE")
),
);
let dst_file_path = dst.join(src.file_name().unwrap());
let mut f = io::BufWriter::new(create_executable_file(&dst_file_path)?);
for line in lines {
writeln!(f, "{}", line)?;
}
Ok(())
}
fn is_executable_file(entry: &fs::DirEntry) -> bool {
use std::os::unix::fs::PermissionsExt;
let ft = match entry.file_type() {
Ok(ft) => ft,
Err(..) => return false,
};
if !ft.is_file() {
return false;
}
let md = match entry.metadata() {
Ok(md) => md,
Err(..) => return false,
};
let mode = md.permissions().mode();
mode & 0o555 == 0o555 // Check file is read and executable mode
}
fn install_hooks() -> Result<()> {
let git_dir = resolve_gitdir()?;
let user_hooks_dir = {
let mut p = git_dir.clone();
p.pop();
p.push(".project");
p.push("hooks");
p
};
if !user_hooks_dir.is_dir() {
return Err(Error::InvalidUserHooksDir(user_hooks_dir));
}
let hook_paths = fs::read_dir(&user_hooks_dir)?
.filter_map(|e| e.ok().filter(is_executable_file).map(|e| e.path()))
.collect::<Vec<_>>();
if hook_paths.is_empty() {
return Err(Error::InvalidUserHooksDir(user_hooks_dir));
}
let hooks_dir = git_dir.join("hooks");
if !hooks_dir.exists() {
fs::create_dir(hooks_dir.as_path())?;
}
for path in hook_paths {
install_hook(&path, &hooks_dir)?;
}
Ok(())
}
fn install() -> Result<()> {
install_hooks()
}
fn main() -> Result<()> {
match install() {
Err(e @ Error::GitDirNotFound) => {
// #2
eprintln!("Warning: {:?}", e);
Ok(())
}
otherwise => otherwise,
}
}