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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::FromStr;
use anyhow::Context;
use fn_error_context::context;
use log::warn;
use crate::config::get_main_branch_name;
pub fn wrap_git_error(error: git2::Error) -> anyhow::Error {
anyhow::anyhow!("Git error {:?}: {}", error.code(), error.message())
}
#[context("Getting HEAD OID for repository")]
pub fn get_head_oid(repo: &git2::Repository) -> anyhow::Result<Option<git2::Oid>> {
let head_ref = match repo.head() {
Ok(head_ref) => Ok(head_ref),
Err(err)
if err.code() == git2::ErrorCode::NotFound
|| err.code() == git2::ErrorCode::UnbornBranch =>
{
return Ok(None)
}
Err(err) => Err(err),
}?;
let head_commit = head_ref.peel_to_commit()?;
Ok(Some(head_commit.id()))
}
#[context("Getting main branch OID for repository")]
pub fn get_main_branch_oid(repo: &git2::Repository) -> anyhow::Result<git2::Oid> {
let main_branch_name = get_main_branch_name(&repo)?;
let branch = repo
.find_branch(&main_branch_name, git2::BranchType::Local)
.or_else(|_| repo.find_branch(&main_branch_name, git2::BranchType::Remote))?;
let commit = branch.get().peel_to_commit()?;
Ok(commit.id())
}
#[context("Getting branch-OID-to-names map for repository")]
pub fn get_branch_oid_to_names(
repo: &git2::Repository,
) -> anyhow::Result<HashMap<git2::Oid, HashSet<String>>> {
let branches = repo
.branches(Some(git2::BranchType::Local))
.with_context(|| "Reading branches")?;
let mut result = HashMap::new();
for branch_info in branches {
let branch_info = branch_info.with_context(|| "Iterating over branches")?;
match branch_info {
(branch, git2::BranchType::Remote) => anyhow::bail!(
"Unexpectedly got a remote branch in local branch iterator: {:?}",
branch.name()
),
(branch, git2::BranchType::Local) => {
let reference = branch.into_reference();
match reference.name() {
None => warn!(
"Could not decode branch name, skipping: {:?}",
reference.name_bytes()
),
Some(reference_name) => {
let reference_name = match reference_name.strip_prefix("refs/heads/") {
Some(reference_name) => reference_name,
None => reference_name,
};
let commit = reference.peel_to_commit().with_context(|| {
format!("Peeling branch into commit: {}", reference_name)
})?;
let branch_oid = commit.id();
result
.entry(branch_oid)
.or_insert_with(HashSet::new)
.insert(reference_name.to_owned());
}
}
}
}
}
let main_branch_name = get_main_branch_name(repo)?;
let main_branch_oid = get_main_branch_oid(repo)?;
result
.entry(main_branch_oid)
.or_insert_with(HashSet::new)
.insert(main_branch_name);
Ok(result)
}
#[context("Getting `git2::Repository` for repo")]
pub fn get_repo() -> anyhow::Result<git2::Repository> {
let path = std::env::current_dir().with_context(|| "Getting working directory")?;
let repository = git2::Repository::discover(path).map_err(wrap_git_error)?;
Ok(repository)
}
#[context("Getting connection to SQLite database for repo")]
pub fn get_db_conn(repo: &git2::Repository) -> anyhow::Result<rusqlite::Connection> {
let dir = repo.path().join("branchless");
std::fs::create_dir_all(&dir).with_context(|| "Creating .git/branchless dir")?;
let path = dir.join("db.sqlite3");
let conn = rusqlite::Connection::open(&path)
.with_context(|| format!("Opening database connection at {:?}", &path))?;
Ok(conn)
}
#[derive(Debug)]
pub struct GitExecutable<'path>(pub &'path Path);
#[context("Running Git ({:?}) with args: {:?}", git_executable, args)]
#[must_use]
pub fn run_git<S: AsRef<str> + std::fmt::Debug>(
out: &mut impl Write,
err: &mut impl Write,
git_executable: &GitExecutable,
args: &[S],
) -> anyhow::Result<isize> {
let GitExecutable(git_executable) = git_executable;
writeln!(
out,
"branchless: {} {}",
git_executable.to_string_lossy(),
args.iter()
.map(|arg| arg.as_ref())
.collect::<Vec<_>>()
.join(" ")
)?;
out.flush()?;
err.flush()?;
let result = Command::new(git_executable)
.args(args.iter().map(|arg| arg.as_ref()))
.output()
.with_context(|| {
format!(
"Waiting for Git subprocess to complete: {:?} {:?}",
git_executable, args
)
})?;
out.write_all(&result.stdout)?;
err.write_all(&result.stderr)?;
let exit_code = result.status.code().unwrap_or(1);
let exit_code = exit_code
.try_into()
.with_context(|| format!("Converting exit code {} from i32 to isize", exit_code))?;
Ok(exit_code)
}
pub fn run_git_silent<S: AsRef<str> + std::fmt::Debug>(
repo: &git2::Repository,
git_executable: &GitExecutable,
args: &[S],
) -> anyhow::Result<String> {
let GitExecutable(git_executable) = git_executable;
let repo_path = repo.path();
let repo_path = repo_path.to_str().ok_or_else(|| {
anyhow::anyhow!(
"Path to Git repo could not be converted to UTF-8 string: {:?}",
repo_path
)
})?;
let args = {
let mut result = vec!["-C", repo_path];
result.extend(args.iter().map(|arg| arg.as_ref()));
result
};
let result = Command::new(git_executable)
.args(&args)
.output()
.with_context(|| format!("Spawning Git subprocess: {:?} {:?}", git_executable, args))?;
let result = String::from_utf8(result.stdout).with_context(|| {
format!(
"Decoding stdout from Git subprocess: {:?} {:?}",
git_executable, args
)
})?;
Ok(result)
}
#[derive(Debug, PartialEq, PartialOrd, Eq)]
pub struct GitVersion(pub isize, pub isize, pub isize);
impl FromStr for GitVersion {
type Err = anyhow::Error;
#[context("Parsing Git version from string: {:?}", output)]
fn from_str(output: &str) -> anyhow::Result<GitVersion> {
let output = output.trim();
let words = output.split(' ').collect::<Vec<&str>>();
let version_str = match &words.as_slice() {
[_git, _version, version_str, ..] => version_str,
_ => anyhow::bail!("Could not parse Git version output: {:?}", output),
};
match version_str.split('.').collect::<Vec<&str>>().as_slice() {
[major, minor, patch, ..] => {
let major = major.parse()?;
let minor = minor.parse()?;
let patch = patch.parse()?;
Ok(GitVersion(major, minor, patch))
}
_ => anyhow::bail!("Could not parse Git version string: {}", version_str),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_git_version_output() {
assert_eq!(
"git version 12.34.56".parse::<GitVersion>().unwrap(),
GitVersion(12, 34, 56)
);
assert_eq!(
"git version 12.34.56\n".parse::<GitVersion>().unwrap(),
GitVersion(12, 34, 56)
);
assert_eq!(
"git version 12.34.56.78.abcdef"
.parse::<GitVersion>()
.unwrap(),
GitVersion(12, 34, 56)
);
}
}