gix_protocol/remote_progress.rs
1use bstr::ByteSlice;
2
3/// The information usually found in remote progress messages as sent by a git server during
4/// fetch, clone and push operations.
5#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7pub struct RemoteProgress<'a> {
8 #[cfg_attr(feature = "serde", serde(borrow))]
9 /// The name of the action, like "clone".
10 pub action: &'a bstr::BStr,
11 /// The percentage to indicate progress, between 0 and 100.
12 pub percent: Option<u32>,
13 /// The amount of items already processed.
14 pub step: Option<usize>,
15 /// The maximum expected amount of items. `step` / `max` * 100 = `percent`.
16 pub max: Option<usize>,
17}
18
19impl RemoteProgress<'_> {
20 /// Parse the progress from a typical git progress `line` as sent by the remote.
21 pub fn from_bytes(mut line: &[u8]) -> Option<RemoteProgress<'_>> {
22 parse_progress(&mut line)
23 .ok()
24 .filter(|&r| !(r.percent.is_none() && r.step.is_none() && r.max.is_none()))
25 }
26
27 /// Parse `text`, which is interpreted as error if `is_error` is true, as [`RemoteProgress`] and call the respective
28 /// methods on the given `progress` instance.
29 pub fn translate_to_progress(is_error: bool, text: &[u8], progress: &mut impl gix_features::progress::Progress) {
30 fn progress_name(current: Option<String>, action: &[u8]) -> String {
31 match current {
32 Some(current) => format!(
33 "{}: {}",
34 current.split_once(':').map_or(&*current, |x| x.0),
35 action.as_bstr()
36 ),
37 None => action.as_bstr().to_string(),
38 }
39 }
40 if is_error {
41 // ignore keep-alive packages sent with 'sideband-all'
42 if !text.is_empty() {
43 progress.fail(progress_name(None, text));
44 }
45 } else {
46 match RemoteProgress::from_bytes(text) {
47 Some(RemoteProgress {
48 action,
49 percent: _,
50 step,
51 max,
52 }) => {
53 progress.set_name(progress_name(progress.name(), action));
54 progress.init(max, gix_features::progress::count("objects"));
55 if let Some(step) = step {
56 progress.set(step);
57 }
58 }
59 None => progress.set_name(progress_name(progress.name(), text)),
60 }
61 }
62 }
63}
64
65/// Parse a non-empty prefix of ASCII decimal digits as an unsigned number.
66///
67/// On success, `i` is advanced past the parsed digits and the parsed value is
68/// returned. If there are no digits at the current position, `None` is
69/// returned. If the digit prefix cannot be represented as `usize`, `i` is
70/// advanced anyway to avoid retrying the same input and `None` is returned.
71fn parse_number(i: &mut &[u8]) -> Option<usize> {
72 let len = i.iter().take_while(|b| b.is_ascii_digit()).count();
73 if len == 0 {
74 return None;
75 }
76 let (number, rest) = i.split_at(len);
77 *i = rest;
78 gix_utils::btoi::to_signed(number).ok()
79}
80
81/// Advance `i` to the first ASCII digit in the remaining input.
82///
83/// If no digit is present, `i` is advanced to the end of the input.
84/// If `i` already starts with a digit, it is left unchanged.
85fn skip_until_digit_or_to_end(i: &mut &[u8]) {
86 let pos = i.iter().position(u8::is_ascii_digit).unwrap_or(i.len());
87 *i = &i[pos..];
88}
89
90/// Find and parse the next ASCII decimal number only if it is followed by `%`.
91///
92/// For example, `b" 42% (21/50)"` yields `Some(42)` and advances `i` to
93/// `b" (21/50)"`, while `b" (21/50)"` yields `None` because the next number is
94/// not a percentage. `b" done"` yields `None` with `i` fully consumed, as there
95/// are no digits left to parse.
96///
97/// If the digit prefix cannot be represented as `u32`, it is treated as
98/// absent and `None` is returned with `i` advanced past all consumed bytes.
99fn next_optional_percentage(i: &mut &[u8]) -> Option<u32> {
100 let before = *i;
101 skip_until_digit_or_to_end(i);
102 let number = parse_number(i)?;
103 if let Some(rest) = i.strip_prefix(b"%") {
104 *i = rest;
105 u32::try_from(number).ok()
106 } else {
107 *i = before;
108 None
109 }
110}
111
112/// Find and parse the next ASCII decimal number, if one is present.
113///
114/// For example, `b" (21/50)"` yields `Some(21)` and advances `i` to `b"/50)"`.
115/// Calling it again on that remainder yields `Some(50)` and advances `i` to
116/// `b")"`. If no digit is present, it yields `None` and advances `i` to the
117/// empty suffix.
118///
119/// If the next digit prefix cannot be represented as `usize`, it is treated as
120/// absent and `None` is returned. In that case, `i` is advanced past the digit
121/// prefix because [`parse_number`] consumes it before conversion.
122fn next_optional_number(i: &mut &[u8]) -> Option<usize> {
123 skip_until_digit_or_to_end(i);
124 parse_number(i)
125}
126
127/// Parse a remote progress line with a non-empty action followed by `:`.
128///
129/// The remainder is scanned leniently for the common progress fields emitted by
130/// git servers: an optional percentage, then up to two optional numbers for the
131/// current step and maximum. For example, inputs like
132/// `b"Receiving objects: 42% (21/50)"` and `b"Resolving deltas: 21/50"` can
133/// produce an action plus `percent`, `step`, and `max` values.
134///
135/// `line` is advanced as the fields are found. If parsing succeeds, it points at
136/// the unconsumed suffix after the parsed progress fields. Inputs without a
137/// colon, or with an empty action before the colon, return an error.
138fn parse_progress<'i>(line: &mut &'i [u8]) -> Result<RemoteProgress<'i>, ()> {
139 let action_end = line.iter().position(|b| *b == b':').ok_or(())?;
140 if action_end == 0 {
141 return Err(());
142 }
143 let action = &line[..action_end];
144 *line = &line[action_end..];
145 let percent = next_optional_percentage(line);
146 let step = next_optional_number(line);
147 let max = next_optional_number(line);
148 Ok(RemoteProgress {
149 action: action.into(),
150 percent,
151 step,
152 max,
153 })
154}