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
use std::io;
use bstr::{BStr, BString, ByteSlice};
use quick_error::quick_error;
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
use crate::client;
use crate::Protocol;
quick_error! {
#[derive(Debug)]
#[allow(missing_docs)]
pub enum Error {
MissingDelimitingNullByte {
display("Capabilities were missing entirely as there was no 0 byte")
}
NoCapabilities {
display("there was not a single capability behind the delimiter")
}
MissingVersionLine {
display("a version line was expected, but none was retrieved")
}
MalformattedVersionLine(actual: String) {
display("expected 'version X', got '{}'", actual)
}
UnsupportedVersion(wanted: Protocol, got: String) {
display("Got unsupported version '{}', expected '{}'", got, *wanted as usize)
}
Io(err: io::Error) {
display("An IO error occurred while reading V2 lines")
from()
source(err)
}
}
}
#[derive(Debug, Clone)]
pub struct Capabilities {
data: BString,
value_sep: u8,
}
pub struct Capability<'a>(&'a BStr);
impl<'a> Capability<'a> {
pub fn name(&self) -> &BStr {
self.0
.splitn(2, |b| *b == b'=')
.next()
.expect("there is always a single item")
.as_bstr()
}
pub fn value(&self) -> Option<&BStr> {
self.0.splitn(2, |b| *b == b'=').nth(1).map(|s| s.as_bstr())
}
pub fn values(&self) -> Option<impl Iterator<Item = &BStr>> {
self.value().map(|v| v.split(|b| *b == b' ').map(|s| s.as_bstr()))
}
pub fn supports(&self, want: impl Into<&'a BStr>) -> Option<bool> {
let want = want.into();
self.values().map(|mut iter| iter.any(|v| v == want))
}
}
impl Capabilities {
pub fn from_bytes(bytes: &[u8]) -> Result<(Capabilities, usize), Error> {
let delimiter_pos = bytes.find_byte(0).ok_or(Error::MissingDelimitingNullByte)?;
if delimiter_pos + 1 == bytes.len() {
return Err(Error::NoCapabilities);
}
let capabilities = &bytes[delimiter_pos + 1..];
Ok((
Capabilities {
data: capabilities.as_bstr().to_owned(),
value_sep: b' ',
},
delimiter_pos,
))
}
pub fn from_lines(
first_line: Option<impl Into<std::io::Result<String>>>,
remaining_lines: impl Into<String>,
) -> Result<Capabilities, Error> {
let version_line = first_line.map(Into::into).ok_or(Error::MissingVersionLine)??;
let (name, value) = version_line.split_at(
version_line
.find(' ')
.ok_or_else(|| Error::MalformattedVersionLine(version_line.clone()))?,
);
if name != "version" {
return Err(Error::MalformattedVersionLine(version_line));
}
if value != " 2" {
return Err(Error::UnsupportedVersion(Protocol::V2, value.to_owned()));
}
Ok(Capabilities {
value_sep: b'\n',
data: remaining_lines.into().into(),
})
}
pub fn contains(&self, feature: &str) -> bool {
self.capability(feature).is_some()
}
pub fn capability(&self, name: &str) -> Option<Capability<'_>> {
self.iter().find(|c| c.name() == name.as_bytes().as_bstr())
}
pub fn iter(&self) -> impl Iterator<Item = Capability<'_>> {
self.data
.split(move |b| *b == self.value_sep)
.map(|c| Capability(c.as_bstr()))
}
}
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
impl Capabilities {
fn extract_protocol<'a>(
capabilities_or_version: &'a git_packetline::PacketLineRef<'_>,
) -> Result<(git_packetline::TextRef<'a>, Protocol), client::Error> {
let first_line = capabilities_or_version
.as_text()
.ok_or(client::Error::ExpectedLine("text"))?;
let line = first_line.as_bstr();
let version = if line.starts_with_str("version ") {
if line.len() != "version X".len() {
return Err(client::Error::UnsupportedProtocolVersion(line.as_bstr().into()));
}
match line {
line if line.ends_with_str("1") => Protocol::V1,
line if line.ends_with_str("2") => Protocol::V2,
_ => return Err(client::Error::UnsupportedProtocolVersion(line.as_bstr().into())),
}
} else {
Protocol::V1
};
Ok((first_line, version))
}
}
#[cfg(feature = "blocking-client")]
pub mod recv {
use std::{io, io::BufRead};
use crate::{client, client::Capabilities, Protocol};
pub struct Outcome<'a> {
pub capabilities: Capabilities,
pub refs: Option<Box<dyn io::BufRead + 'a>>,
pub protocol: Protocol,
}
impl Capabilities {
pub fn from_lines_with_version_detection<T: io::Read>(
rd: &mut git_packetline::StreamingPeekableIter<T>,
) -> Result<Outcome<'_>, client::Error> {
rd.fail_on_err_lines(true);
let capabilities_or_version = rd
.peek_line()
.ok_or(client::Error::ExpectedLine("capabilities or version"))???;
let (first_line, version) = Capabilities::extract_protocol(&capabilities_or_version)?;
match version {
Protocol::V1 => {
let (capabilities, delimiter_position) = Capabilities::from_bytes(first_line.0)?;
rd.peek_buffer_replace_and_truncate(delimiter_position, b'\n');
Ok(Outcome {
capabilities,
refs: Some(Box::new(rd.as_read())),
protocol: Protocol::V1,
})
}
Protocol::V2 => Ok(Outcome {
capabilities: {
let rd = rd.as_read();
let mut lines = rd.lines();
Capabilities::from_lines(lines.next(), lines.collect::<Result<Vec<_>, _>>()?.join("\n"))?
},
refs: None,
protocol: Protocol::V2,
}),
}
}
}
}
#[cfg(feature = "async-client")]
#[allow(missing_docs)]
pub mod recv {
use futures_io::{AsyncBufRead, AsyncRead};
use futures_lite::{AsyncBufReadExt, StreamExt};
use crate::{client, client::Capabilities, Protocol};
pub struct Outcome<'a> {
pub capabilities: Capabilities,
pub refs: Option<Box<dyn AsyncBufRead + Unpin + 'a>>,
pub protocol: Protocol,
}
impl Capabilities {
pub async fn from_lines_with_version_detection<T: AsyncRead + Unpin>(
rd: &mut git_packetline::StreamingPeekableIter<T>,
) -> Result<Outcome<'_>, client::Error> {
rd.fail_on_err_lines(true);
let capabilities_or_version = rd
.peek_line()
.await
.ok_or(client::Error::ExpectedLine("capabilities or version"))???;
let (first_line, version) = Capabilities::extract_protocol(&capabilities_or_version)?;
match version {
Protocol::V1 => {
let (capabilities, delimiter_position) = Capabilities::from_bytes(first_line.0)?;
rd.peek_buffer_replace_and_truncate(delimiter_position, b'\n');
Ok(Outcome {
capabilities,
refs: Some(Box::new(rd.as_read())),
protocol: Protocol::V1,
})
}
Protocol::V2 => Ok(Outcome {
capabilities: {
let rd = rd.as_read();
let mut lines_with_err = rd.lines();
let mut lines = Vec::new();
while let Some(line) = lines_with_err.next().await {
lines.push(line?);
}
let mut lines = lines.into_iter();
Capabilities::from_lines(lines.next().map(Ok), lines.collect::<Vec<_>>().join("\n"))?
},
refs: None,
protocol: Protocol::V2,
}),
}
}
}
}