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
use bstr::{BStr, BString, ByteSlice};
use crate::{
Instruction, RefSpec, RefSpecRef,
instruction::{Fetch, Push},
parse::Operation,
types::Mode,
};
/// Conversion. Use the [`RefSpecRef`][RefSpec::to_ref()] type for more usage options.
impl RefSpec {
/// Return ourselves as reference type.
pub fn to_ref(&self) -> RefSpecRef<'_> {
RefSpecRef {
mode: self.mode,
op: self.op,
src: self.src.as_ref().map(AsRef::as_ref),
dst: self.dst.as_ref().map(AsRef::as_ref),
}
}
/// Return true if the spec starts with a `+` and thus forces setting the reference.
pub fn allow_non_fast_forward(&self) -> bool {
matches!(self.mode, Mode::Force)
}
}
mod impls {
use std::{
cmp::Ordering,
hash::{Hash, Hasher},
};
use crate::{RefSpec, RefSpecRef};
impl From<RefSpecRef<'_>> for RefSpec {
fn from(v: RefSpecRef<'_>) -> Self {
v.to_owned()
}
}
impl Hash for RefSpec {
fn hash<H: Hasher>(&self, state: &mut H) {
self.to_ref().hash(state);
}
}
impl Hash for RefSpecRef<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.instruction().hash(state);
}
}
impl PartialEq for RefSpec {
fn eq(&self, other: &Self) -> bool {
self.to_ref().eq(&other.to_ref())
}
}
impl PartialEq for RefSpecRef<'_> {
fn eq(&self, other: &Self) -> bool {
self.instruction().eq(&other.instruction())
}
}
impl PartialOrd for RefSpecRef<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd for RefSpec {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for RefSpecRef<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.instruction().cmp(&other.instruction())
}
}
impl Ord for RefSpec {
fn cmp(&self, other: &Self) -> Ordering {
self.to_ref().cmp(&other.to_ref())
}
}
}
/// Access
impl<'a> RefSpecRef<'a> {
/// Return the left-hand side of the spec, typically the source.
/// It takes many different forms so don't rely on this being a ref name.
///
/// It's not present in case of deletions.
pub fn source(&self) -> Option<&BStr> {
self.src
}
/// Return the right-hand side of the spec, typically the destination ref name or ref pattern.
///
/// It's not present in case of source-only specs.
pub fn destination(&self) -> Option<&BStr> {
self.dst
}
/// Return the explicitly stored remote side, whose position depends on how the refspec was parsed.
///
/// A one-sided push refspec has no explicit remote side and returns `None` here, even though its source
/// is later also used as its destination.
pub fn remote(&self) -> Option<&BStr> {
match self.op {
Operation::Push => self.dst,
Operation::Fetch => self.src,
}
}
/// Return the explicitly stored local side, whose position depends on how the refspec was parsed.
pub fn local(&self) -> Option<&BStr> {
match self.op {
Operation::Push => self.src,
Operation::Fetch => self.dst,
}
}
/// Derive the prefix from the [`source`][Self::source()] side of this spec if this is a fetch spec,
/// or the [`destination`][Self::destination()] side if it is a push spec, if it is possible to do so without ambiguity.
///
/// Exact refs starting with `refs/` are returned unchanged, like `refs/heads/main`
/// or `refs/namespaces/foo/refs/heads/main`. Git-style ref patterns return the fixed portion before
/// their single `*` when it is more specific than `refs/`: both `refs/heads/*` and
/// `refs/heads/*/suffix` yield `refs/heads/`.
/// Negative refspecs and one-sided push refspecs return `None`.
pub fn prefix(&self) -> Option<&BStr> {
if self.mode == Mode::Negative {
return None;
}
let source = match self.op {
Operation::Fetch => self.source(),
Operation::Push => self.destination(),
}?;
if source == "HEAD" {
return source.into();
}
let sans_refs_prefix = source.strip_prefix(b"refs/")?;
if let Some(star_pos) = sans_refs_prefix.find_byte(b'*') {
if star_pos == 0
|| sans_refs_prefix[star_pos + 1..].contains(&b'*')
|| sans_refs_prefix.find_byteset(b"?[]\\").is_some()
{
return None;
}
let prefix = &source[.."refs/".len() + star_pos];
return (!prefix.is_empty()).then_some(prefix.as_bstr());
}
Some(source)
}
/// Append the remote-ref prefixes represented by this refspec to `out`, suitable for limiting the refs
/// requested from a remote. Unlike [`prefix()`][Self::prefix], partial names without an unambiguous prefix
/// are expanded to all of their Git-style ref-name candidates. For example, `main` expands to `main`,
/// `refs/main`, `refs/tags/main`, `refs/heads/main`, `refs/remotes/main`, and `refs/remotes/main/HEAD`.
///
/// Fetch refspecs use their source; push refspecs use their explicit destination. Negative refspecs produce
/// no prefixes because they only exclude refs selected by positive refspecs; they do not request remote refs.
pub fn expand_prefixes(&self, out: &mut Vec<BString>) {
if self.mode == Mode::Negative {
return;
}
match self.prefix() {
Some(prefix) => out.push(prefix.into()),
None => {
let source = match match self.op {
Operation::Fetch => self.source(),
Operation::Push => self.destination(),
} {
Some(source) => source,
None => return,
};
if let Some(rest) = source.strip_prefix(b"refs/") {
if !rest.contains(&b'/') {
out.push(source.into());
}
return;
} else if gix_hash::ObjectId::from_hex(source).is_ok() {
return;
}
expand_partial_name(source, |expanded| {
out.push(expanded.into());
None::<()>
});
}
}
}
/// Transform the state of the refspec into an instruction making clear what to do with it.
pub fn instruction(&self) -> Instruction<'a> {
match self.op {
Operation::Fetch => match (self.mode, self.src, self.dst) {
(Mode::Normal | Mode::Force, Some(src), None) => Instruction::Fetch(Fetch::Only { src }),
(Mode::Normal | Mode::Force, Some(src), Some(dst)) => Instruction::Fetch(Fetch::AndUpdate {
src,
dst,
allow_non_fast_forward: matches!(self.mode, Mode::Force),
}),
(Mode::Negative, Some(src), None) => Instruction::Fetch(Fetch::Exclude { src }),
(mode, src, dest) => {
unreachable!(
"BUG: fetch instructions with {:?} {:?} {:?} are not possible",
mode, src, dest
)
}
},
Operation::Push => match (self.mode, self.src, self.dst) {
(Mode::Normal | Mode::Force, Some(src), None) => Instruction::Push(Push::Matching {
src,
dst: src,
allow_non_fast_forward: matches!(self.mode, Mode::Force),
}),
(Mode::Normal | Mode::Force, None, Some(dst)) => {
Instruction::Push(Push::Delete { ref_or_pattern: dst })
}
(Mode::Normal | Mode::Force, None, None) => Instruction::Push(Push::AllMatchingBranches {
allow_non_fast_forward: matches!(self.mode, Mode::Force),
}),
(Mode::Normal | Mode::Force, Some(src), Some(dst)) => Instruction::Push(Push::Matching {
src,
dst,
allow_non_fast_forward: matches!(self.mode, Mode::Force),
}),
(Mode::Negative, Some(src), None) => Instruction::Push(Push::Exclude { src }),
(mode, src, dest) => {
unreachable!(
"BUG: push instructions with {:?} {:?} {:?} are not possible",
mode, src, dest
)
}
},
}
}
}
/// Conversion
impl RefSpecRef<'_> {
/// Convert this ref into a standalone, owned copy.
pub fn to_owned(&self) -> RefSpec {
RefSpec {
mode: self.mode,
op: self.op,
src: self.src.map(ToOwned::to_owned),
dst: self.dst.map(ToOwned::to_owned),
}
}
}
pub(crate) fn expand_partial_name<T>(name: &BStr, mut cb: impl FnMut(&BStr) -> Option<T>) -> Option<T> {
use bstr::ByteVec;
let mut buf = BString::from(Vec::with_capacity(128));
for (base, append_head) in [
("", false),
("refs/", false),
("refs/tags/", false),
("refs/heads/", false),
("refs/remotes/", false),
("refs/remotes/", true),
] {
buf.clear();
buf.push_str(base);
buf.push_str(name);
if append_head {
buf.push_str("/HEAD");
}
if let Some(res) = cb(buf.as_ref()) {
return Some(res);
}
}
None
}