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
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
mod error {
use crate::handshake::refs::parse;
/// The error returned by invoking a [`super::function::LsRefsCommand`].
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Transport(#[from] gix_transport::client::Error),
#[error(transparent)]
Parse(#[from] parse::Error),
#[error(transparent)]
ArgumentValidation(#[from] crate::command::validate_argument_prefixes::Error),
}
impl gix_transport::IsSpuriousError for Error {
fn is_spurious(&self) -> bool {
match self {
Error::Io(err) => err.is_spurious(),
Error::Transport(err) => err.is_spurious(),
_ => false,
}
}
}
}
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
pub use error::Error;
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
pub use self::function::RefPrefixes;
#[cfg(any(feature = "blocking-client", feature = "async-client"))]
pub(crate) mod function {
use std::{borrow::Cow, collections::HashSet};
use bstr::{BString, ByteVec};
use gix_features::progress::Progress;
use gix_transport::client::Capabilities;
use super::Error;
#[cfg(feature = "async-client")]
use crate::transport::client::async_io::{self, TransportV2Ext as _};
#[cfg(feature = "blocking-client")]
use crate::transport::client::blocking_io::{self, TransportV2Ext as _};
use crate::{
handshake::{refs::from_v2_refs, Ref},
Command,
};
/// [`RefPrefixes`] are the set of prefixes that are sent to the server for
/// filtering purposes.
///
/// These are communicated by sending zero or more `ref-prefix` values, and
/// are documented in [gitprotocol-v2.adoc#ls-refs].
///
/// These prefixes can be constructed from a set of [`RefSpec`]'s using
/// [`RefPrefixes::from_refspecs`].
///
/// Alternatively, they can be constructed using [`RefPrefixes::new`] and
/// using [`RefPrefixes::extend`] to add new prefixes.
///
/// [`RefSpec`]: gix_refspec::RefSpec
/// [gitprotocol-v2.adoc#ls-refs]: https://github.com/git/git/blob/master/Documentation/gitprotocol-v2.adoc#ls-refs
pub struct RefPrefixes {
prefixes: Vec<BString>,
}
impl Default for RefPrefixes {
fn default() -> Self {
Self::new()
}
}
impl RefPrefixes {
/// Create an empty set of [`RefPrefixes`].
pub fn new() -> RefPrefixes {
RefPrefixes { prefixes: Vec::new() }
}
/// Convert a series of [`RefSpec`]'s into a set of [`RefPrefixes`].
///
/// It attempts to expand each [`RefSpec`] into prefix references, e.g.
/// `refs/heads/`, `refs/remotes/`, `refs/namespaces/foo/`, etc.
///
/// Inputs that aren't fully qualified refs, like `HEAD` or `main`, are
/// expanded in the same DWIM-style way that Git uses for `ref-prefix`
/// generation, yielding prefixes like `HEAD`, `refs/heads/main`, and
/// other rev-parse candidates.
///
/// [`RefSpec`]: gix_refspec::RefSpec
pub fn from_refspecs<'a>(refspecs: impl IntoIterator<Item = &'a gix_refspec::RefSpec>) -> Self {
let mut seen = HashSet::new();
let mut prefixes = Self::new();
for spec in refspecs.into_iter() {
let spec = spec.to_ref();
if seen.insert(spec.instruction()) {
let mut out = Vec::with_capacity(1);
spec.expand_prefixes(&mut out);
prefixes.extend(out);
}
}
prefixes
}
fn into_args(self) -> impl Iterator<Item = BString> {
self.prefixes.into_iter().map(|mut prefix| {
prefix.insert_str(0, "ref-prefix ");
prefix
})
}
}
impl Extend<BString> for RefPrefixes {
fn extend<T: IntoIterator<Item = BString>>(&mut self, iter: T) {
for prefix in iter {
if !self.prefixes.iter().any(|existing| existing == &prefix) {
self.prefixes.push(prefix);
}
}
}
}
/// A command to list references from a remote Git repository.
///
/// It acts as a utility to separate the invocation into the shared blocking portion,
/// and the one that performs IO either blocking or `async`.
pub struct LsRefsCommand<'a> {
pub(crate) capabilities: &'a Capabilities,
features: Vec<(&'static str, Option<Cow<'static, str>>)>,
arguments: Vec<BString>,
}
impl<'a> LsRefsCommand<'a> {
/// Build a command to list refs from the given server `capabilities`,
/// using `agent` information to identify ourselves.
///
/// Use [`crate::ls_refs::RefPrefixes::from_refspecs()`] to construct `ref_prefixes`
/// from refspecs, or [`crate::ls_refs::RefPrefixes::new()`] to build them manually.
pub fn new(
ref_prefixes: Option<RefPrefixes>,
capabilities: &'a Capabilities,
agent: (&'static str, Option<Cow<'static, str>>),
) -> Self {
let ls_refs = Command::LsRefs;
let mut features = ls_refs.default_features(gix_transport::Protocol::V2, capabilities);
features.push(agent);
let mut arguments = ls_refs.initial_v2_arguments(&features);
if capabilities
.capability("ls-refs")
.and_then(|cap| cap.supports("unborn"))
.unwrap_or_default()
{
arguments.push("unborn".into());
}
if let Some(prefixes) = ref_prefixes {
arguments.extend(prefixes.into_args());
}
Self {
capabilities,
features,
arguments,
}
}
/// Invoke a ls-refs V2 command on `transport`.
///
/// `progress` is used to provide feedback.
/// If `trace` is `true`, all packetlines received or sent will be passed to the facilities of the `gix-trace` crate.
#[cfg(feature = "async-client")]
pub async fn invoke_async(
self,
mut transport: impl async_io::Transport,
progress: &mut impl Progress,
trace: bool,
) -> Result<Vec<Ref>, Error> {
let _span = gix_features::trace::detail!("gix_protocol::LsRefsCommand::invoke_async()");
Command::LsRefs.validate_argument_prefixes(
gix_transport::Protocol::V2,
self.capabilities,
&self.arguments,
&self.features,
)?;
progress.step();
progress.set_name("list refs".into());
let mut remote_refs = transport
.invoke(
Command::LsRefs.as_str(),
self.features.into_iter(),
if self.arguments.is_empty() {
None
} else {
Some(self.arguments.into_iter())
},
trace,
)
.await?;
Ok(from_v2_refs(&mut remote_refs).await?)
}
/// Invoke a ls-refs V2 command on `transport`.
///
/// `progress` is used to provide feedback.
/// If `trace` is `true`, all packetlines received or sent will be passed to the facilities of the `gix-trace` crate.
#[cfg(feature = "blocking-client")]
pub fn invoke_blocking(
self,
mut transport: impl blocking_io::Transport,
progress: &mut impl Progress,
trace: bool,
) -> Result<Vec<Ref>, Error> {
let _span = gix_features::trace::detail!("gix_protocol::LsRefsCommand::invoke_blocking()");
Command::LsRefs.validate_argument_prefixes(
gix_transport::Protocol::V2,
self.capabilities,
&self.arguments,
&self.features,
)?;
progress.step();
progress.set_name("list refs".into());
let mut remote_refs = transport.invoke(
Command::LsRefs.as_str(),
self.features.into_iter(),
if self.arguments.is_empty() {
None
} else {
Some(self.arguments.into_iter())
},
trace,
)?;
Ok(from_v2_refs(&mut remote_refs)?)
}
}
#[cfg(test)]
mod ref_prefixes {
use bstr::{BString, ByteSlice};
use super::RefPrefixes;
#[test]
fn extend_preserves_first_seen_order_and_deduplicates_prefixes() {
let mut prefixes = RefPrefixes::new();
prefixes.extend(
[
"refs/tags",
"HEAD",
"main",
"refs/heads/main",
"refs/tags",
"HEAD",
"refs/heads/feature",
"refs/heads/main",
]
.into_iter()
.map(|prefix| prefix.as_bytes().as_bstr().to_owned()),
);
assert_eq!(
prefixes.into_args().collect::<Vec<_>>(),
[
"ref-prefix refs/tags",
"ref-prefix HEAD",
"ref-prefix main",
"ref-prefix refs/heads/main",
"ref-prefix refs/heads/feature"
]
.into_iter()
.map(BString::from)
.collect::<Vec<_>>()
);
}
#[test]
fn from_refspecs_keeps_exact_refs_and_dwim_expansions() {
let specs = [
gix_refspec::parse("HEAD".into(), gix_refspec::parse::Operation::Fetch)
.expect("valid")
.to_owned(),
gix_refspec::parse("dwim".into(), gix_refspec::parse::Operation::Fetch)
.expect("valid")
.to_owned(),
gix_refspec::parse(
"refs/tags/prefix*:refs/tags/prefix*".into(),
gix_refspec::parse::Operation::Fetch,
)
.expect("valid")
.to_owned(),
gix_refspec::parse("refs/heads/main".into(), gix_refspec::parse::Operation::Fetch)
.expect("valid")
.to_owned(),
];
let prefixes = RefPrefixes::from_refspecs(&specs);
assert_eq!(
prefixes.into_args().collect::<Vec<_>>(),
[
"ref-prefix HEAD",
"ref-prefix dwim",
"ref-prefix refs/dwim",
"ref-prefix refs/tags/dwim",
"ref-prefix refs/heads/dwim",
"ref-prefix refs/remotes/dwim",
"ref-prefix refs/remotes/dwim/HEAD",
"ref-prefix refs/tags/prefix",
"ref-prefix refs/heads/main",
]
.into_iter()
.map(BString::from)
.collect::<Vec<_>>()
);
}
}
}