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::{ResultExt, message};
10 use gix_transport::client::Capabilities;
11 use gix_utils::progress::Progress;
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 ) -> gix_error::Result<Vec<Ref>> {
114 let _span = gix_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(|| 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(|| 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() -> gix_testtools::TestResult {
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 for (kind, retryable) in [
221 (ErrorKind::BrokenPipe, true),
222 (ErrorKind::ConnectionReset, true),
223 (ErrorKind::PermissionDenied, false),
224 ] {
225 let transport = gix_transport::client::git::blocking_io::Connection::new(
226 &[][..],
227 FailingWriter(kind),
228 gix_transport::Protocol::V2,
229 "repo.git",
230 None::<(&str, _)>,
231 gix_transport::client::git::ConnectMode::Process,
232 false,
233 );
234 let err = super::LsRefsCommand::new(None, &capabilities, ("agent", Some("test".into())))
235 .invoke_blocking(transport, &mut gix_utils::progress::Discard, false)
236 .expect_err("the transport write fails");
237 error_snapshots.push(gix_testtools::redact_debug_snapshot(&(err), &[]));
238 assert_eq!(err.can_retry_lenient(), retryable, "preserve retry policy for {kind:?}");
239 assert!(
240 !err.is_retryable(),
241 "I/O failures are classified without extra retry markers"
242 );
243 assert_eq!(
244 err.downcast_any_ref::<io::Error>()
245 .expect("retain the I/O cause")
246 .kind(),
247 kind,
248 "the original transport failure remains available"
249 );
250 }
251 insta::assert_debug_snapshot!(error_snapshots, "invoke preserves transport retryability", @"
252 [
253 Could not invoke ls-refs
254
255 Caused by:
256 0: An IO error occurred when talking to the server
257 1: broken pipe,
258 Could not invoke ls-refs
259
260 Caused by:
261 0: An IO error occurred when talking to the server
262 1: connection reset,
263 Could not invoke ls-refs
264
265 Caused by:
266 0: An IO error occurred when talking to the server
267 1: permission denied,
268 ]
269 ");
270 Ok(())
271 }
272
273 #[test]
274 fn extend_preserves_first_seen_order_and_deduplicates_prefixes() {
275 let mut prefixes = RefPrefixes::new();
276 prefixes.extend(
277 [
278 "refs/tags",
279 "HEAD",
280 "main",
281 "refs/heads/main",
282 "refs/tags",
283 "HEAD",
284 "refs/heads/feature",
285 "refs/heads/main",
286 ]
287 .into_iter()
288 .map(|prefix| prefix.as_bytes().as_bstr().to_owned()),
289 );
290
291 assert_eq!(
292 prefixes.into_args().collect::<Vec<_>>(),
293 [
294 "ref-prefix refs/tags",
295 "ref-prefix HEAD",
296 "ref-prefix main",
297 "ref-prefix refs/heads/main",
298 "ref-prefix refs/heads/feature"
299 ]
300 .into_iter()
301 .map(BString::from)
302 .collect::<Vec<_>>()
303 );
304 }
305
306 #[test]
307 fn from_refspecs_keeps_exact_refs_and_dwim_expansions() -> gix_testtools::TestResult {
308 let specs = [
309 gix_refspec::parse("HEAD".into(), gix_refspec::parse::Operation::Fetch)?.to_owned(),
310 gix_refspec::parse("dwim".into(), gix_refspec::parse::Operation::Fetch)?.to_owned(),
311 gix_refspec::parse(
312 "refs/tags/prefix*:refs/tags/prefix*".into(),
313 gix_refspec::parse::Operation::Fetch,
314 )?
315 .to_owned(),
316 gix_refspec::parse("refs/heads/main".into(), gix_refspec::parse::Operation::Fetch)?.to_owned(),
317 ];
318
319 let prefixes = RefPrefixes::from_refspecs(&specs);
320
321 assert_eq!(
322 prefixes.into_args().collect::<Vec<_>>(),
323 [
324 "ref-prefix HEAD",
325 "ref-prefix dwim",
326 "ref-prefix refs/dwim",
327 "ref-prefix refs/tags/dwim",
328 "ref-prefix refs/heads/dwim",
329 "ref-prefix refs/remotes/dwim",
330 "ref-prefix refs/remotes/dwim/HEAD",
331 "ref-prefix refs/tags/prefix",
332 "ref-prefix refs/heads/main",
333 ]
334 .into_iter()
335 .map(BString::from)
336 .collect::<Vec<_>>()
337 );
338 Ok(())
339 }
340 }
341}