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
use gitv_core::git_capped;
use super::{DIFF_LIMIT, Repo};
use crate::cache::cached;
use crate::html::{icon, plural, subject_or_placeholder};
use crate::urls::{Q, lossy, param};
use crate::{View, templates};
pub(crate) struct Change {
pub(crate) status: &'static str,
pub(crate) path: Vec<u8>,
}
pub(crate) fn parse_changes(out: &[u8]) -> Vec<Change> {
let mut fields = out.split(|b| *b == 0).filter(|f| !f.is_empty());
let mut changes = Vec::new();
while let Some(code) = fields.next() {
let (status, paths) = match code.first() {
Some(b'A') => ("Added", 1),
Some(b'D') => ("Deleted", 1),
Some(b'R') => ("Renamed", 2),
Some(b'C') => ("Copied", 2),
_ => ("", 1),
};
let mut path = None;
for _ in 0..paths {
path = fields.next();
}
let Some(path) = path else { break };
changes.push(Change { status, path: path.to_vec() });
}
changes
}
pub(crate) struct DiffLine {
pub(crate) class: &'static str,
pub(crate) old: String,
pub(crate) new: String,
pub(crate) text: String,
}
impl DiffLine {
fn new(class: &'static str, old: String, new: String, text: &str) -> DiffLine {
DiffLine { class, old, new, text: text.to_string() }
}
pub(crate) fn sign(&self) -> &'static str {
match self.class {
"add" => "+",
"del" => "-",
_ => " ",
}
}
}
pub(crate) struct FileDiff {
pub(crate) rows: Vec<DiffLine>,
pub(crate) added: usize,
pub(crate) removed: usize,
pub(crate) binary: bool,
}
pub(crate) fn parse_diff(text: &str) -> Vec<FileDiff> {
let mut files: Vec<FileDiff> = Vec::new();
let (mut old, mut new) = (0usize, 0usize);
for line in text.lines() {
if line.starts_with("diff --git ") {
files.push(FileDiff { rows: Vec::new(), added: 0, removed: 0, binary: false });
continue;
}
let Some(file) = files.last_mut() else { continue };
let in_hunk = !file.rows.is_empty();
if !in_hunk && line.starts_with("Binary files ") {
file.binary = true;
} else if line.starts_with("@@") {
let nums: Vec<usize> = line
.split_whitespace()
.skip(1)
.take(2)
.map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0))
.collect();
(old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0));
file.rows.push(DiffLine::new("hunk", String::new(), String::new(), line));
} else if !in_hunk {
continue;
} else if let Some(t) = line.strip_prefix('+') {
file.rows.push(DiffLine::new("add", String::new(), new.to_string(), t));
new += 1;
file.added += 1;
} else if let Some(t) = line.strip_prefix('-') {
file.rows.push(DiffLine::new("del", old.to_string(), String::new(), t));
old += 1;
file.removed += 1;
} else if let Some(t) = line.strip_prefix(' ') {
file.rows.push(DiffLine::new("ctx", old.to_string(), new.to_string(), t));
old += 1;
new += 1;
}
}
files
}
pub(crate) fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
let id = param(q, "id")?;
if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let commit = repo.reader.commit_object(&id)?;
let meta = repo.reader.git(&[
"show",
"-s",
"--date=format:%-d %b %Y, %H:%M",
"--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b",
&commit,
])?;
let f: Vec<&str> = meta.splitn(7, '\0').collect();
let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?;
let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" ");
let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents))
.unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into());
Some(View::Html(
templates::Commit {
title: subject_or_placeholder(subject),
signed_in: repo.signed_in,
masthead: repo.masthead("log", &repo.reader.default_ref(), None),
browse: repo.url("tree", &[("ref", oid)]),
message: message.trim(),
author,
email,
date,
short_id: oid.get(..12)?,
parent_links,
diff: &diff,
}
.to_string(),
))
}
pub(crate) fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> {
let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"];
let names = [&["show", "-z", "--name-status"][..], &options, &[oid]].concat();
let patch = [&["show", "--patch"][..], &options, &[oid]].concat();
let parent = parents.split_whitespace().next().unwrap_or(oid);
render_changes(repo, &names, &patch, parent, oid, "This commit’s changes")
}
pub(crate) fn render_diff_between(repo: &Repo, old: &str, new: &str) -> Option<String> {
let options = ["--no-color", "-M", old, new, "--"];
let names = [&["diff", "-z", "--name-status"][..], &options].concat();
let patch = [&["diff", "--patch"][..], &options].concat();
render_changes(repo, &names, &patch, old, new, "These changes")
}
fn render_changes(
repo: &Repo,
names: &[&str],
patch: &[&str],
old: &str,
new: &str,
what: &'static str,
) -> Option<String> {
let names = repo.reader.git_bytes(names)?;
let changes = parse_changes(&names);
let (patch, too_big) = git_capped(&repo.reader.dir, patch, DIFF_LIMIT).ok()?;
let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) };
let paired = files.len() == changes.len();
let panels: Vec<templates::DiffFile> = changes
.iter()
.enumerate()
.map(|(i, change)| {
let at = if change.status == "Deleted" { old } else { new };
templates::DiffFile {
href: repo.url_at("blob", at.as_bytes(), &change.path, ""),
path: lossy(&change.path),
status: change.status,
diff: files.get(i).filter(|_| paired),
}
})
.collect();
let totals = paired.then(|| files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed)));
let diff = templates::Diff {
file_count: plural(changes.len(), "file", "files"),
totals,
too_big,
what,
file_icon: icon("file"),
files: panels,
};
Some(diff.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_status_parsing() {
let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0";
let changes = parse_changes(out);
let got: Vec<(&str, &[u8])> = changes.iter().map(|c| (c.status, c.path.as_slice())).collect();
assert_eq!(
got,
[("", &b"src/a b.rs"[..]), ("Renamed", b"new\tname"), ("Deleted", b"gone"), ("Added", b"\xffbin")]
);
}
}