-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlilgitd.rs
246 lines (233 loc) · 6.49 KB
/
lilgitd.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
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
/*
* lilgitd serves as a ~daemon component paired with a shell profile/prompt
* plugin. The shell plugin prints $PWD to lilgitd's stdin once per prompt
* and waits for it to print a response on stdout. lilgitd will read-loop on
* stdin, treat each line as a path, and attempt to print 3 values on stdout
* as a response:
* - whether the path is a repo
* - whether the repo is dirty
* - a description of the repo's checkout/worktree
*/
use std::{io, path::Path, process::Command, str};
use git2::{ErrorCode::UnbornBranch, Reference, Repository};
use tokio::signal::unix::{signal, SignalKind};
struct Report {
is_repo: bool,
is_dirty: bool,
description: String,
}
impl Report {
pub fn new(start_path: &Path) -> Self {
let repo = match Repository::discover(start_path) {
Ok(val) => val,
Err(_e) => {
return Report {
is_repo: false,
is_dirty: false,
description: "".to_string(),
}
}
};
let head = match repo.head() {
Ok(head) => head,
Err(e) => {
// probably a new repo
match e.code() {
UnbornBranch => {
let msg = e.message();
// e.message: "reference \'refs/heads/spangles\' not found"
if msg.starts_with("reference \'refs/heads/") {
return Report {
is_repo: true,
is_dirty: false,
description: branch_from_unborn_error(msg),
};
} else {
eprintln!("good question, wtf?");
return Report {
is_repo: false,
is_dirty: false,
description: "error :(".to_string(),
};
}
}
_ => {
eprintln!("good question, wtf?");
return Report {
is_repo: false,
is_dirty: false,
description: "error :(".to_string(),
};
}
}
}
};
let detached = match repo.head_detached() {
Ok(detached) => detached,
Err(_e) => false,
};
let name = if detached {
head
.target()
.expect("if we've got a head, we've got a target")
.to_string()
} else {
head
.shorthand()
.expect("if we've got a head, it's got a shorthand")
.to_string()
};
return Self {
is_repo: true,
is_dirty: dirty(start_path, &repo, detached, &head, &name),
description: description(detached, &name),
};
}
}
// extract name from "reference \'refs/heads/spangles\' not found"
fn branch_from_unborn_error(msg: &str) -> String {
return match msg.strip_prefix("reference \'refs/heads/") {
Some(val) => match val.strip_suffix("\' not found") {
Some(val) => val.to_string(),
None => "".to_string(),
},
None => "".to_string(),
};
}
fn description(detached: bool, name: &str) -> String {
if detached {
return format!("detached @ {:.11}", name);
} else {
return name.to_string();
}
}
fn dirty(
repo_path: &Path,
repo: &Repository,
detached: bool,
head: &Reference,
name: &str,
) -> bool {
if !detached {
let branch = repo
.find_branch(&name, git2::BranchType::Local)
.expect("should always have a branch (we know repo is true, and that we aren't detached)");
// check for upstream (and record whether we do)
let mut upstream = None;
match branch.upstream() {
Ok(val) => {
upstream = Some(true);
if head.target() != val.get().target() {
// return true early if head.target == upstream.target
return true;
}
}
Err(_err) => {
upstream = Some(false);
}
}
/*
I've tried a few git2 approaches to this and TL;DR:
Answering this with any sort of diff through libgit2
is painfully slow on big repos.
Also stumbled on someone corroborating this observation:
https://github.com/Kurt-Bonatz/pursue/commit/a8c10a20d91ad19c8a0e799f2a7de3f41ef0a8b3
*/
let code = if upstream == Some(true) {
// use upstream
Command::new("git")
.arg("-C")
.arg(repo_path)
.arg("diff")
.arg("--quiet")
.arg("@{u}")
.status()
} else {
// just use HEAD
Command::new("git")
.arg("-C")
.arg(repo_path)
.arg("diff")
.arg("--quiet")
.arg("HEAD")
.status()
};
match code {
Ok(val) => return !val.success(),
Err(_e) => return false,
}
}
return false;
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let input = io::stdin();
/*
very minimal arg handling
- normal use: call w/o args, write paths to stdin
- debug use: each arg treated as a path to check
*/
let mut args = std::env::args();
match args.len() {
// golden path, only arg is $0
1 => {
let mut io_stream = signal(SignalKind::io())?;
// get SIGINT, but do nothing with it (keep ctrl-c from killing us)
let mut _int_stream = signal(SignalKind::interrupt())?;
loop {
// TODO: maybe worth declaring once and clearing
// i.e. from_shell.clear();
let mut from_shell = String::new();
match input.read_line(&mut from_shell) {
Ok(n) => {
if n > 3 {
let arg = from_shell.trim().to_string();
let out = Report::new(&Path::new(&arg));
println!(
"{} {} {}",
out.is_repo.to_string(),
out.is_dirty.to_string(),
out.description
);
} else if n == 0 {
io_stream.recv().await;
}
}
Err(_err) => {
io_stream.recv().await;
}
}
}
}
// a single arg
2 => {
let arg = std::env::args().nth(1).expect("repo path");
let out = Report::new(&Path::new(&arg));
println!(
"{} {} {}",
out.is_repo.to_string(),
out.is_dirty.to_string(),
out.description
);
Ok(())
}
// more than 1 arg
// Note: only handled separate from 1-arg to print path w/ check
_ => {
// skip arg $0
&args.next();
// treat all remaining args as paths
for arg in args {
let out = Report::new(&Path::new(&arg));
println!(
"{} {} {} {}",
arg, // also print the path alongside each
out.is_repo.to_string(),
out.is_dirty.to_string(),
out.description
);
}
Ok(())
}
}
}