gix_refspec/
spec.rs

1use bstr::{BStr, BString, ByteSlice};
2
3use crate::{
4    instruction::{Fetch, Push},
5    parse::Operation,
6    types::Mode,
7    Instruction, RefSpec, RefSpecRef,
8};
9
10/// Conversion. Use the [`RefSpecRef`][RefSpec::to_ref()] type for more usage options.
11impl RefSpec {
12    /// Return ourselves as reference type.
13    pub fn to_ref(&self) -> RefSpecRef<'_> {
14        RefSpecRef {
15            mode: self.mode,
16            op: self.op,
17            src: self.src.as_ref().map(AsRef::as_ref),
18            dst: self.dst.as_ref().map(AsRef::as_ref),
19        }
20    }
21
22    /// Return true if the spec stats with a `+` and thus forces setting the reference.
23    pub fn allow_non_fast_forward(&self) -> bool {
24        matches!(self.mode, Mode::Force)
25    }
26}
27
28mod impls {
29    use std::{
30        cmp::Ordering,
31        hash::{Hash, Hasher},
32    };
33
34    use crate::{RefSpec, RefSpecRef};
35
36    impl From<RefSpecRef<'_>> for RefSpec {
37        fn from(v: RefSpecRef<'_>) -> Self {
38            v.to_owned()
39        }
40    }
41
42    impl Hash for RefSpec {
43        fn hash<H: Hasher>(&self, state: &mut H) {
44            self.to_ref().hash(state);
45        }
46    }
47
48    impl Hash for RefSpecRef<'_> {
49        fn hash<H: Hasher>(&self, state: &mut H) {
50            self.instruction().hash(state);
51        }
52    }
53
54    impl PartialEq for RefSpec {
55        fn eq(&self, other: &Self) -> bool {
56            self.to_ref().eq(&other.to_ref())
57        }
58    }
59
60    impl PartialEq for RefSpecRef<'_> {
61        fn eq(&self, other: &Self) -> bool {
62            self.instruction().eq(&other.instruction())
63        }
64    }
65
66    impl PartialOrd for RefSpecRef<'_> {
67        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
68            Some(self.cmp(other))
69        }
70    }
71
72    #[allow(clippy::non_canonical_partial_ord_impl)]
73    impl PartialOrd for RefSpec {
74        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
75            Some(self.to_ref().cmp(&other.to_ref()))
76        }
77    }
78
79    impl Ord for RefSpecRef<'_> {
80        fn cmp(&self, other: &Self) -> Ordering {
81            self.instruction().cmp(&other.instruction())
82        }
83    }
84
85    impl Ord for RefSpec {
86        fn cmp(&self, other: &Self) -> Ordering {
87            self.to_ref().cmp(&other.to_ref())
88        }
89    }
90}
91
92/// Access
93impl<'a> RefSpecRef<'a> {
94    /// Return the left-hand side of the spec, typically the source.
95    /// It takes many different forms so don't rely on this being a ref name.
96    ///
97    /// It's not present in case of deletions.
98    pub fn source(&self) -> Option<&BStr> {
99        self.src
100    }
101
102    /// Return the right-hand side of the spec, typically the destination.
103    /// It takes many different forms so don't rely on this being a ref name.
104    ///
105    /// It's not present in case of source-only specs.
106    pub fn destination(&self) -> Option<&BStr> {
107        self.dst
108    }
109
110    /// Always returns the remote side, whose actual side in the refspec depends on how it was parsed.
111    pub fn remote(&self) -> Option<&BStr> {
112        match self.op {
113            Operation::Push => self.dst,
114            Operation::Fetch => self.src,
115        }
116    }
117
118    /// Always returns the local side, whose actual side in the refspec depends on how it was parsed.
119    pub fn local(&self) -> Option<&BStr> {
120        match self.op {
121            Operation::Push => self.src,
122            Operation::Fetch => self.dst,
123        }
124    }
125
126    /// Derive the prefix from the [`source`][Self::source()] side of this spec if this is a fetch spec,
127    /// or the [`destination`][Self::destination()] side if it is a push spec, if it is possible to do so without ambiguity.
128    ///
129    /// This means it starts with `refs/`. Note that it won't contain more than two components, like `refs/heads/`
130    pub fn prefix(&self) -> Option<&BStr> {
131        if self.mode == Mode::Negative {
132            return None;
133        }
134        let source = match self.op {
135            Operation::Fetch => self.source(),
136            Operation::Push => self.destination(),
137        }?;
138        if source == "HEAD" {
139            return source.into();
140        }
141        let suffix = source.strip_prefix(b"refs/")?;
142        let slash_pos = suffix.find_byte(b'/')?;
143        let prefix = source[..="refs/".len() + slash_pos].as_bstr();
144        (!prefix.contains(&b'*')).then_some(prefix)
145    }
146
147    /// As opposed to [`prefix()`][Self::prefix], if the latter is `None` it will expand to all possible prefixes and place them in `out`.
148    ///
149    /// Note that only the `source` side is considered.
150    pub fn expand_prefixes(&self, out: &mut Vec<BString>) {
151        match self.prefix() {
152            Some(prefix) => out.push(prefix.into()),
153            None => {
154                let source = match match self.op {
155                    Operation::Fetch => self.source(),
156                    Operation::Push => self.destination(),
157                } {
158                    Some(source) => source,
159                    None => return,
160                };
161                if let Some(rest) = source.strip_prefix(b"refs/") {
162                    if !rest.contains(&b'/') {
163                        out.push(source.into());
164                    }
165                    return;
166                } else if gix_hash::ObjectId::from_hex(source).is_ok() {
167                    return;
168                }
169                expand_partial_name(source, |expanded| {
170                    out.push(expanded.into());
171                    None::<()>
172                });
173            }
174        }
175    }
176
177    /// Transform the state of the refspec into an instruction making clear what to do with it.
178    pub fn instruction(&self) -> Instruction<'a> {
179        match self.op {
180            Operation::Fetch => match (self.mode, self.src, self.dst) {
181                (Mode::Normal | Mode::Force, Some(src), None) => Instruction::Fetch(Fetch::Only { src }),
182                (Mode::Normal | Mode::Force, Some(src), Some(dst)) => Instruction::Fetch(Fetch::AndUpdate {
183                    src,
184                    dst,
185                    allow_non_fast_forward: matches!(self.mode, Mode::Force),
186                }),
187                (Mode::Negative, Some(src), None) => Instruction::Fetch(Fetch::Exclude { src }),
188                (mode, src, dest) => {
189                    unreachable!(
190                        "BUG: fetch instructions with {:?} {:?} {:?} are not possible",
191                        mode, src, dest
192                    )
193                }
194            },
195            Operation::Push => match (self.mode, self.src, self.dst) {
196                (Mode::Normal | Mode::Force, Some(src), None) => Instruction::Push(Push::Matching {
197                    src,
198                    dst: src,
199                    allow_non_fast_forward: matches!(self.mode, Mode::Force),
200                }),
201                (Mode::Normal | Mode::Force, None, Some(dst)) => {
202                    Instruction::Push(Push::Delete { ref_or_pattern: dst })
203                }
204                (Mode::Normal | Mode::Force, None, None) => Instruction::Push(Push::AllMatchingBranches {
205                    allow_non_fast_forward: matches!(self.mode, Mode::Force),
206                }),
207                (Mode::Normal | Mode::Force, Some(src), Some(dst)) => Instruction::Push(Push::Matching {
208                    src,
209                    dst,
210                    allow_non_fast_forward: matches!(self.mode, Mode::Force),
211                }),
212                (mode, src, dest) => {
213                    unreachable!(
214                        "BUG: push instructions with {:?} {:?} {:?} are not possible",
215                        mode, src, dest
216                    )
217                }
218            },
219        }
220    }
221}
222
223/// Conversion
224impl RefSpecRef<'_> {
225    /// Convert this ref into a standalone, owned copy.
226    pub fn to_owned(&self) -> RefSpec {
227        RefSpec {
228            mode: self.mode,
229            op: self.op,
230            src: self.src.map(ToOwned::to_owned),
231            dst: self.dst.map(ToOwned::to_owned),
232        }
233    }
234}
235
236pub(crate) fn expand_partial_name<T>(name: &BStr, mut cb: impl FnMut(&BStr) -> Option<T>) -> Option<T> {
237    use bstr::ByteVec;
238    let mut buf = BString::from(Vec::with_capacity(128));
239    for (base, append_head) in [
240        ("", false),
241        ("refs/", false),
242        ("refs/tags/", false),
243        ("refs/heads/", false),
244        ("refs/remotes/", false),
245        ("refs/remotes/", true),
246    ] {
247        buf.clear();
248        buf.push_str(base);
249        buf.push_str(name);
250        if append_head {
251            buf.push_str("/HEAD");
252        }
253        if let Some(res) = cb(buf.as_ref()) {
254            return Some(res);
255        }
256    }
257    None
258}