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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use std::io;
use bstr::BString;
use quick_error::quick_error;
quick_error! {
#[derive(Debug)]
#[allow(missing_docs)]
pub enum Error {
Io(err: io::Error) {
display("An IO error occurred while reading refs from the server")
from()
source(err)
}
Id(err: git_hash::decode::Error) {
display("Failed to hex-decode object hash")
from()
source(err)
}
MalformedSymref(symref: BString) {
display("'{}' could not be parsed. A symref is expected to look like <NAME>:<target>.", symref)
}
MalformedV1RefLine(line: String) {
display("'{}' could not be parsed. A V1 ref line should be '<hex-hash> <path>'.", line)
}
MalformedV2RefLine(line: String) {
display("'{}' could not be parsed. A V2 ref line should be '<hex-hash> <path>[ (peeled|symref-target):<value>'.", line)
}
UnkownAttribute(attribute: String, line: String) {
display("The ref attribute '{}' is unknown. Found in line '{}'", attribute, line)
}
InvariantViolation(message: &'static str) {
display("{}", message)
}
}
}
#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub enum Ref {
Peeled {
path: BString,
tag: git_hash::ObjectId,
object: git_hash::ObjectId,
},
Direct {
path: BString,
object: git_hash::ObjectId,
},
Symbolic {
path: BString,
target: BString,
object: git_hash::ObjectId,
},
}
impl Ref {
pub fn unpack(&self) -> (&BString, &git_hash::ObjectId) {
match self {
Ref::Direct { path, object, .. }
| Ref::Peeled { path, tag: object, .. }
| Ref::Symbolic { path, object, .. } => (path, object),
}
}
}
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
pub(crate) mod shared {
use bstr::{BString, ByteSlice};
use crate::fetch::{refs, Ref};
impl From<InternalRef> for Ref {
fn from(v: InternalRef) -> Self {
match v {
InternalRef::Symbolic { path, target, object } => Ref::Symbolic { path, target, object },
InternalRef::Peeled { path, tag, object } => Ref::Peeled { path, tag, object },
InternalRef::Direct { path, object } => Ref::Direct { path, object },
InternalRef::SymbolicForLookup { .. } => {
unreachable!("this case should have been removed during processing")
}
}
}
}
#[cfg_attr(test, derive(PartialEq, Eq, Debug, Clone))]
pub(crate) enum InternalRef {
Peeled {
path: BString,
tag: git_hash::ObjectId,
object: git_hash::ObjectId,
},
Direct { path: BString, object: git_hash::ObjectId },
Symbolic {
path: BString,
target: BString,
object: git_hash::ObjectId,
},
SymbolicForLookup { path: BString, target: BString },
}
impl InternalRef {
fn unpack_direct(self) -> Option<(BString, git_hash::ObjectId)> {
match self {
InternalRef::Direct { path, object } => Some((path, object)),
_ => None,
}
}
fn lookup_symbol_has_path(&self, predicate_path: &str) -> bool {
matches!(self, InternalRef::SymbolicForLookup { path, .. } if path == predicate_path)
}
}
pub(crate) fn from_capabilities<'a>(
capabilities: impl Iterator<Item = git_transport::client::capabilities::Capability<'a>>,
) -> Result<Vec<InternalRef>, refs::Error> {
let mut out_refs = Vec::new();
let symref_values = capabilities.filter_map(|c| {
if c.name() == b"symref".as_bstr() {
c.value().map(ToOwned::to_owned)
} else {
None
}
});
for symref in symref_values {
let (left, right) = symref.split_at(
symref
.find_byte(b':')
.ok_or_else(|| refs::Error::MalformedSymref(symref.to_owned()))?,
);
if left.is_empty() || right.is_empty() {
return Err(refs::Error::MalformedSymref(symref.to_owned()));
}
out_refs.push(InternalRef::SymbolicForLookup {
path: left.into(),
target: right[1..].into(),
})
}
Ok(out_refs)
}
pub(in crate::fetch::refs) fn parse_v1(
num_initial_out_refs: usize,
out_refs: &mut Vec<InternalRef>,
line: &str,
) -> Result<(), refs::Error> {
let trimmed = line.trim_end();
let (hex_hash, path) = trimmed.split_at(
trimmed
.find(' ')
.ok_or_else(|| refs::Error::MalformedV1RefLine(trimmed.to_owned()))?,
);
let path = &path[1..];
if path.is_empty() {
return Err(refs::Error::MalformedV1RefLine(trimmed.to_owned()));
}
match path.strip_suffix("^{}") {
Some(stripped) => {
let (previous_path, tag) =
out_refs
.pop()
.and_then(InternalRef::unpack_direct)
.ok_or(refs::Error::InvariantViolation(
"Expecting peeled refs to be preceded by direct refs",
))?;
if previous_path != stripped {
return Err(refs::Error::InvariantViolation(
"Expecting peeled refs to have the same base path as the previous, unpeeled one",
));
}
out_refs.push(InternalRef::Peeled {
path: previous_path,
tag,
object: git_hash::ObjectId::from_hex(hex_hash.as_bytes())?,
});
}
None => {
let object = git_hash::ObjectId::from_hex(hex_hash.as_bytes())?;
match out_refs
.iter()
.take(num_initial_out_refs)
.position(|r| r.lookup_symbol_has_path(path))
{
Some(position) => match out_refs.swap_remove(position) {
InternalRef::SymbolicForLookup { path: _, target } => out_refs.push(InternalRef::Symbolic {
path: path.into(),
object,
target,
}),
_ => unreachable!("Bug in lookup_symbol_has_path - must return lookup symbols"),
},
None => out_refs.push(InternalRef::Direct {
object,
path: path.into(),
}),
};
}
}
Ok(())
}
pub(in crate::fetch::refs) fn parse_v2(line: &str) -> Result<Ref, refs::Error> {
let trimmed = line.trim_end();
let mut tokens = trimmed.splitn(3, ' ');
match (tokens.next(), tokens.next()) {
(Some(hex_hash), Some(path)) => {
let id = git_hash::ObjectId::from_hex(hex_hash.as_bytes())?;
if path.is_empty() {
return Err(refs::Error::MalformedV2RefLine(trimmed.to_owned()));
}
Ok(if let Some(attribute) = tokens.next() {
let mut tokens = attribute.splitn(2, ':');
match (tokens.next(), tokens.next()) {
(Some(attribute), Some(value)) => {
if value.is_empty() {
return Err(refs::Error::MalformedV2RefLine(trimmed.to_owned()));
}
match attribute {
"peeled" => Ref::Peeled {
path: path.into(),
object: git_hash::ObjectId::from_hex(value.as_bytes())?,
tag: id,
},
"symref-target" => Ref::Symbolic {
path: path.into(),
object: id,
target: value.into(),
},
_ => {
return Err(refs::Error::UnkownAttribute(attribute.to_owned(), trimmed.to_owned()))
}
}
}
_ => return Err(refs::Error::MalformedV2RefLine(trimmed.to_owned())),
}
} else {
Ref::Direct {
object: id,
path: path.into(),
}
})
}
_ => Err(refs::Error::MalformedV2RefLine(trimmed.to_owned())),
}
}
}
#[cfg(feature = "async-client")]
mod async_io {
use futures_io::AsyncBufRead;
use futures_lite::AsyncBufReadExt;
use crate::fetch::{refs, Ref};
pub async fn from_v2_refs(in_refs: &mut (dyn AsyncBufRead + Unpin)) -> Result<Vec<Ref>, refs::Error> {
let mut out_refs = Vec::new();
let mut line = String::new();
loop {
line.clear();
let bytes_read = in_refs.read_line(&mut line).await?;
if bytes_read == 0 {
break;
}
out_refs.push(refs::shared::parse_v2(&line)?);
}
Ok(out_refs)
}
pub async fn from_v1_refs_received_as_part_of_handshake_and_capabilities<'a>(
in_refs: &mut (dyn AsyncBufRead + Unpin),
capabilities: impl Iterator<Item = git_transport::client::capabilities::Capability<'a>>,
) -> Result<Vec<Ref>, refs::Error> {
let mut out_refs = refs::shared::from_capabilities(capabilities)?;
let number_of_possible_symbolic_refs_for_lookup = out_refs.len();
let mut line = String::new();
loop {
line.clear();
let bytes_read = in_refs.read_line(&mut line).await?;
if bytes_read == 0 {
break;
}
refs::shared::parse_v1(number_of_possible_symbolic_refs_for_lookup, &mut out_refs, &line)?;
}
Ok(out_refs.into_iter().map(Into::into).collect())
}
}
#[cfg(feature = "async-client")]
pub use async_io::{from_v1_refs_received_as_part_of_handshake_and_capabilities, from_v2_refs};
#[cfg(feature = "blocking-client")]
mod blocking_io {
use std::io;
use crate::fetch::{refs, Ref};
pub fn from_v2_refs(in_refs: &mut dyn io::BufRead) -> Result<Vec<Ref>, refs::Error> {
let mut out_refs = Vec::new();
let mut line = String::new();
loop {
line.clear();
let bytes_read = in_refs.read_line(&mut line)?;
if bytes_read == 0 {
break;
}
out_refs.push(refs::shared::parse_v2(&line)?);
}
Ok(out_refs)
}
pub fn from_v1_refs_received_as_part_of_handshake_and_capabilities<'a>(
in_refs: &mut dyn io::BufRead,
capabilities: impl Iterator<Item = git_transport::client::capabilities::Capability<'a>>,
) -> Result<Vec<Ref>, refs::Error> {
let mut out_refs = refs::shared::from_capabilities(capabilities)?;
let number_of_possible_symbolic_refs_for_lookup = out_refs.len();
let mut line = String::new();
loop {
line.clear();
let bytes_read = in_refs.read_line(&mut line)?;
if bytes_read == 0 {
break;
}
refs::shared::parse_v1(number_of_possible_symbolic_refs_for_lookup, &mut out_refs, &line)?;
}
Ok(out_refs.into_iter().map(Into::into).collect())
}
}
#[cfg(feature = "blocking-client")]
pub use blocking_io::{from_v1_refs_received_as_part_of_handshake_and_capabilities, from_v2_refs};