1#[cfg(any(feature = "blocking-client", feature = "async-client"))]
2pub use self::function::RefPrefixes;
3
4#[cfg(any(feature = "blocking-client", feature = "async-client"))]
5pub(crate) mod function {
6 use std::collections::HashSet;
7
8 use bstr::{BString, ByteVec};
9 use gix_error::{ExnResult, ResultExt, message};
10 use gix_features::progress::Progress;
11 use gix_transport::client::Capabilities;
12
13 #[cfg(feature = "async-client")]
14 use crate::transport::client::async_io::TransportV2Ext as _;
15 #[cfg(feature = "blocking-client")]
16 use crate::transport::client::blocking_io::TransportV2Ext as _;
17 use crate::{Command, handshake::Ref};
18
19 pub struct RefPrefixes {
34 prefixes: Vec<BString>,
35 }
36
37 impl Default for RefPrefixes {
38 fn default() -> Self {
39 Self::new()
40 }
41 }
42
43 impl RefPrefixes {
44 pub fn new() -> RefPrefixes {
46 RefPrefixes { prefixes: Vec::new() }
47 }
48
49 pub fn from_refspecs<'a>(refspecs: impl IntoIterator<Item = &'a gix_refspec::RefSpec>) -> Self {
61 let mut seen = HashSet::new();
62 let mut prefixes = Self::new();
63 for spec in refspecs.into_iter() {
64 let spec = spec.to_ref();
65 if seen.insert(spec.instruction()) {
66 let mut out = Vec::with_capacity(1);
67 spec.expand_prefixes(&mut out);
68 prefixes.extend(out);
69 }
70 }
71 prefixes
72 }
73
74 fn into_args(self) -> impl Iterator<Item = BString> {
75 self.prefixes.into_iter().map(|mut prefix| {
76 prefix.insert_str(0, "ref-prefix ");
77 prefix
78 })
79 }
80 }
81
82 impl Extend<BString> for RefPrefixes {
83 fn extend<T: IntoIterator<Item = BString>>(&mut self, iter: T) {
84 for prefix in iter {
85 if !self.prefixes.iter().any(|existing| existing == &prefix) {
86 self.prefixes.push(prefix);
87 }
88 }
89 }
90 }
91
92 pub struct LsRefsCommand<'a> {
96 pub(crate) capabilities: &'a Capabilities,
97 features: Vec<crate::command::Feature>,
98 arguments: Vec<BString>,
99 }
100
101 macro_rules! invoke {
102 ($name:ident, $bisync:path, $transport:path, $from_v2_refs:path, $mode:literal) => {
103 #[$bisync]
108 pub async fn $name(
109 self,
110 mut transport: impl $transport,
111 progress: &mut impl Progress,
112 trace: bool,
113 ) -> ExnResult<Vec<Ref>> {
114 let _span = gix_features::trace::detail!("gix_protocol::LsRefsCommand::invoke()", mode = $mode);
115 Command::LsRefs
116 .validate_argument_prefixes(
117 gix_transport::Protocol::V2,
118 self.capabilities,
119 &self.arguments,
120 &self.features,
121 )
122 .or_raise_erased(|| message("Invalid ls-refs arguments or capabilities"))?;
123
124 progress.step();
125 progress.set_name("list refs".into());
126 let mut remote_refs = transport
127 .invoke(
128 Command::LsRefs.as_str(),
129 self.features.into_iter(),
130 if self.arguments.is_empty() {
131 None
132 } else {
133 Some(self.arguments.into_iter())
134 },
135 trace,
136 )
137 .await
138 .or_raise_erased(|| message("Could not invoke ls-refs"))?;
139 $from_v2_refs(&mut remote_refs).await
140 }
141 };
142 }
143
144 impl<'a> LsRefsCommand<'a> {
145 pub fn new(
151 ref_prefixes: Option<RefPrefixes>,
152 capabilities: &'a Capabilities,
153 agent: crate::command::Feature,
154 ) -> Self {
155 let ls_refs = Command::LsRefs;
156 let mut features = ls_refs.default_features(gix_transport::Protocol::V2, capabilities);
157 features.push(agent);
158 let mut arguments = ls_refs.initial_v2_arguments(&features);
159 if capabilities
160 .capability("ls-refs")
161 .and_then(|cap| cap.supports("unborn"))
162 .unwrap_or_default()
163 {
164 arguments.push("unborn".into());
165 }
166
167 if let Some(prefixes) = ref_prefixes {
168 arguments.extend(prefixes.into_args());
169 }
170
171 Self {
172 capabilities,
173 features,
174 arguments,
175 }
176 }
177
178 #[cfg(feature = "async-client")]
179 invoke!(
180 invoke_async,
181 ::gix_macros::keep,
182 crate::transport::client::async_io::Transport,
183 crate::handshake::refs::async_io::from_v2_refs,
184 "async"
185 );
186
187 #[cfg(feature = "blocking-client")]
188 invoke!(
189 invoke_blocking,
190 ::gix_macros::sync,
191 crate::transport::client::blocking_io::Transport,
192 crate::handshake::refs::blocking_io::from_v2_refs,
193 "blocking"
194 );
195 }
196
197 #[cfg(test)]
198 mod tests {
199 use bstr::{BString, ByteSlice};
200
201 use super::RefPrefixes;
202
203 #[cfg(feature = "blocking-client")]
204 #[test]
205 fn invoke_preserves_transport_retryability() {
206 let mut error_snapshots = Vec::new();
207 use std::io::{self, ErrorKind};
208
209 struct FailingWriter(ErrorKind);
210 impl io::Write for FailingWriter {
211 fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
212 Err(self.0.into())
213 }
214 fn flush(&mut self) -> io::Result<()> {
215 Ok(())
216 }
217 }
218
219 let capabilities = super::Capabilities::from_lines("version 2\nls-refs\nagent=test\n".into())
220 .expect("valid V2 capabilities");
221 for (kind, retryable) in [
222 (ErrorKind::BrokenPipe, true),
223 (ErrorKind::ConnectionReset, true),
224 (ErrorKind::PermissionDenied, false),
225 ] {
226 let transport = gix_transport::client::git::blocking_io::Connection::new(
227 &[][..],
228 FailingWriter(kind),
229 gix_transport::Protocol::V2,
230 "repo.git",
231 None::<(&str, _)>,
232 gix_transport::client::git::ConnectMode::Process,
233 false,
234 );
235 let err = super::LsRefsCommand::new(None, &capabilities, ("agent", Some("test".into())))
236 .invoke_blocking(transport, &mut gix_features::progress::Discard, false)
237 .expect_err("the transport write fails")
238 .into_error();
239 error_snapshots.push(gix_testtools::redact_debug_snapshot(&(err), &[]));
240 assert_eq!(err.can_retry_lenient(), retryable, "preserve retry policy for {kind:?}");
241 assert!(
242 !err.is_retryable(),
243 "I/O failures are classified without extra retry markers"
244 );
245 assert_eq!(
246 err.downcast_any_ref::<io::Error>()
247 .expect("retain the I/O cause")
248 .kind(),
249 kind,
250 "the original transport failure remains available"
251 );
252 }
253 insta::assert_debug_snapshot!(error_snapshots, "invoke preserves transport retryability", @"
254 [
255 Could not invoke ls-refs
256 |
257 └─ An IO error occurred when talking to the server
258 |
259 └─ broken pipe,
260 Could not invoke ls-refs
261 |
262 └─ An IO error occurred when talking to the server
263 |
264 └─ connection reset,
265 Could not invoke ls-refs
266 |
267 └─ An IO error occurred when talking to the server
268 |
269 └─ permission denied,
270 ]
271 ");
272 }
273
274 #[test]
275 fn extend_preserves_first_seen_order_and_deduplicates_prefixes() {
276 let mut prefixes = RefPrefixes::new();
277 prefixes.extend(
278 [
279 "refs/tags",
280 "HEAD",
281 "main",
282 "refs/heads/main",
283 "refs/tags",
284 "HEAD",
285 "refs/heads/feature",
286 "refs/heads/main",
287 ]
288 .into_iter()
289 .map(|prefix| prefix.as_bytes().as_bstr().to_owned()),
290 );
291
292 assert_eq!(
293 prefixes.into_args().collect::<Vec<_>>(),
294 [
295 "ref-prefix refs/tags",
296 "ref-prefix HEAD",
297 "ref-prefix main",
298 "ref-prefix refs/heads/main",
299 "ref-prefix refs/heads/feature"
300 ]
301 .into_iter()
302 .map(BString::from)
303 .collect::<Vec<_>>()
304 );
305 }
306
307 #[test]
308 fn from_refspecs_keeps_exact_refs_and_dwim_expansions() {
309 let specs = [
310 gix_refspec::parse("HEAD".into(), gix_refspec::parse::Operation::Fetch)
311 .expect("valid")
312 .to_owned(),
313 gix_refspec::parse("dwim".into(), gix_refspec::parse::Operation::Fetch)
314 .expect("valid")
315 .to_owned(),
316 gix_refspec::parse(
317 "refs/tags/prefix*:refs/tags/prefix*".into(),
318 gix_refspec::parse::Operation::Fetch,
319 )
320 .expect("valid")
321 .to_owned(),
322 gix_refspec::parse("refs/heads/main".into(), gix_refspec::parse::Operation::Fetch)
323 .expect("valid")
324 .to_owned(),
325 ];
326
327 let prefixes = RefPrefixes::from_refspecs(&specs);
328
329 assert_eq!(
330 prefixes.into_args().collect::<Vec<_>>(),
331 [
332 "ref-prefix HEAD",
333 "ref-prefix dwim",
334 "ref-prefix refs/dwim",
335 "ref-prefix refs/tags/dwim",
336 "ref-prefix refs/heads/dwim",
337 "ref-prefix refs/remotes/dwim",
338 "ref-prefix refs/remotes/dwim/HEAD",
339 "ref-prefix refs/tags/prefix",
340 "ref-prefix refs/heads/main",
341 ]
342 .into_iter()
343 .map(BString::from)
344 .collect::<Vec<_>>()
345 );
346 }
347 }
348}