grit-lib 0.5.24

Core library for the grit Git implementation
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! [`RefTransaction`] builder and validation.

use std::collections::HashSet;

use super::error::RefStoreError;
use super::types::{Expected, RawRef, RefCaseOnlyRename, RefReflogRename, RefUpdate};
use super::validation::{validate_reflog_update, validate_storable_refname};

/// Batch of ref updates prepared for [`super::RefStore::prepare`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RefTransaction {
    updates: Vec<RefUpdate>,
    reflog_renames: Vec<RefReflogRename>,
    case_only_renames: Vec<RefCaseOnlyRename>,
    initial: bool,
}

impl RefTransaction {
    /// Start an empty transaction.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Start a transaction holding `updates`, checking for duplicate names in one pass.
    ///
    /// # Errors
    ///
    /// Returns [`RefStoreError::DuplicateUpdate`] for the first name queued twice.
    pub(crate) fn from_updates(updates: Vec<RefUpdate>) -> Result<Self, RefStoreError> {
        Self::validate_no_duplicates(&updates)?;
        Ok(Self {
            updates,
            ..Self::default()
        })
    }

    /// Append an update, rejecting duplicate ref names in the same batch.
    ///
    /// # Errors
    ///
    /// Returns [`RefStoreError::DuplicateUpdate`] when `update.name` was already queued.
    pub fn update(mut self, update: RefUpdate) -> Result<Self, RefStoreError> {
        self.push_update(update)?;
        Ok(self)
    }

    /// Append an update in place.
    ///
    /// # Errors
    ///
    /// Returns [`RefStoreError::DuplicateUpdate`] when `update.name` was already queued.
    pub fn push_update(&mut self, update: RefUpdate) -> Result<(), RefStoreError> {
        if self
            .updates
            .iter()
            .any(|existing| existing.name == update.name)
        {
            return Err(RefStoreError::DuplicateUpdate {
                name: update.name.clone(),
            });
        }
        self.updates.push(update);
        Ok(())
    }

    /// Borrow the queued updates.
    #[must_use]
    pub fn updates(&self) -> &[RefUpdate] {
        &self.updates
    }

    /// Consume the transaction and return the update list.
    #[must_use]
    pub fn into_updates(self) -> Vec<RefUpdate> {
        self.updates
    }

    /// Reflog rename operations bundled with this transaction.
    #[must_use]
    pub fn reflog_renames(&self) -> &[RefReflogRename] {
        &self.reflog_renames
    }

    /// Case-only ref renames bundled with this transaction.
    #[must_use]
    pub fn case_only_renames(&self) -> &[RefCaseOnlyRename] {
        &self.case_only_renames
    }

    /// Append a branch reflog rename to this transaction.
    #[must_use]
    pub fn with_reflog_rename(mut self, rename: RefReflogRename) -> Self {
        self.reflog_renames.push(rename);
        self
    }

    /// Append a case-only branch ref rename (files backend).
    #[must_use]
    pub fn with_case_only_rename(mut self, rename: RefCaseOnlyRename) -> Self {
        self.case_only_renames.push(rename);
        self
    }

    /// Mark this as the first ref transaction of a new repository, such as the remote refs a
    /// clone imports (Git's initial ref transaction).
    ///
    /// The files backend then writes the batch as one `packed-refs` rewrite, without a loose
    /// file or lock per ref, when every update creates a direct ref (no reflog, expectation
    /// [`Expected::Any`] or [`Expected::Missing`]) that does not exist yet in the common
    /// directory. Any other batch, and every other backend, commits as usual, so the flag
    /// never changes which refs end up stored, only how they are laid out.
    ///
    /// The packed write takes only `packed-refs.lock`: callers promise no other writer is
    /// creating the same refs, which holds for a repository nobody else knows about yet.
    #[must_use]
    pub fn initial(mut self) -> Self {
        self.initial = true;
        self
    }

    /// Whether [`Self::initial`] marked this transaction.
    #[must_use]
    pub fn is_initial(&self) -> bool {
        self.initial
    }

    /// Split into ref updates, reflog renames, and case-only ref renames.
    #[must_use]
    pub fn into_parts(self) -> (Vec<RefUpdate>, Vec<RefReflogRename>, Vec<RefCaseOnlyRename>) {
        (self.updates, self.reflog_renames, self.case_only_renames)
    }

    /// The ref a lock failure on this transaction is reported under: the first update, else
    /// the source of the first reflog or case-only rename, else `refs`.
    pub(crate) fn lock_name(&self) -> String {
        self.updates
            .first()
            .map(|u| &u.name)
            .or_else(|| self.reflog_renames.first().map(|r| &r.from))
            .or_else(|| self.case_only_renames.first().map(|r| &r.from))
            .map_or_else(|| "refs".to_owned(), Clone::clone)
    }

    /// Backend-independent checks every [`super::RefStore::prepare`] runs before taking locks.
    ///
    /// Duplicate names cannot reach here because [`Self::push_update`] rejects them.
    pub(crate) fn validate(&self) -> Result<(), RefStoreError> {
        for update in &self.updates {
            validate_storable_refname(&update.name)?;
            if !update.flags.log_only
                && matches!(&update.new_value, Some(RawRef::Direct(oid)) if oid.is_zero())
            {
                return Err(RefStoreError::NullOid {
                    name: update.name.clone(),
                });
            }
            if let Some(ref log) = update.reflog {
                validate_reflog_update(log)?;
            }
        }
        for rename in &self.reflog_renames {
            validate_reflog_update(&rename.append)?;
        }
        let renames = self
            .reflog_renames
            .iter()
            .map(|r| (&r.from, &r.to))
            .chain(self.case_only_renames.iter().map(|r| (&r.from, &r.to)));
        for (from, to) in renames {
            validate_storable_refname(from)?;
            validate_storable_refname(to)?;
        }
        Ok(())
    }

    fn validate_no_duplicates(updates: &[RefUpdate]) -> Result<(), RefStoreError> {
        let mut seen = HashSet::with_capacity(updates.len());
        for update in updates {
            if !seen.insert(&update.name) {
                return Err(RefStoreError::DuplicateUpdate {
                    name: update.name.clone(),
                });
            }
        }
        Ok(())
    }
}

/// Whether `actual` satisfies `expected`.
#[must_use]
pub fn expected_matches(actual: Option<&RawRef>, expected: &Expected) -> bool {
    match expected {
        Expected::Any => true,
        Expected::Missing => actual.is_none(),
        Expected::Exists => actual.is_some(),
        Expected::Oid(want) => matches!(actual, Some(RawRef::Direct(got)) if got == want),
        Expected::Symref(want) => matches!(actual, Some(RawRef::Symbolic(got)) if got == want),
    }
}

#[cfg(test)]
mod tests {
    use crate::objects::ObjectId;

    use super::*;

    fn oid(byte: u8) -> ObjectId {
        let mut bytes = [0u8; 20];
        bytes[19] = byte;
        ObjectId::from_bytes(&bytes).expect("valid oid")
    }

    #[test]
    fn duplicate_names_rejected() {
        let txn = RefTransaction::new().update(RefUpdate {
            name: "refs/heads/a".to_owned(),
            new_value: Some(RawRef::Direct(oid(1))),
            expected: Expected::Any,
            reflog: None,
            flags: Default::default(),
        });
        assert!(txn.is_ok());
        let err = txn
            .unwrap()
            .update(RefUpdate {
                name: "refs/heads/a".to_owned(),
                new_value: Some(RawRef::Direct(oid(2))),
                expected: Expected::Any,
                reflog: None,
                flags: Default::default(),
            })
            .unwrap_err();
        assert!(matches!(
            err,
            RefStoreError::DuplicateUpdate { name } if name == "refs/heads/a"
        ));
    }

    fn direct(name: &str, value: ObjectId) -> RefUpdate {
        RefUpdate {
            name: name.to_owned(),
            new_value: Some(RawRef::Direct(value)),
            expected: Expected::Any,
            reflog: None,
            flags: Default::default(),
        }
    }

    fn sample_log() -> super::super::ReflogUpdate {
        super::super::ReflogUpdate {
            identity: "A <a@example.com>".to_owned(),
            message: "rename".to_owned(),
            time: time::OffsetDateTime::UNIX_EPOCH,
            old_oid: None,
            new_oid: None,
        }
    }

    #[test]
    fn validate_rejects_unsafe_update_names() {
        for name in [
            "",
            "heads/x",
            "refs/heads/../x",
            "refs/heads/a b",
            "refs/heads/x/",
        ] {
            let err = RefTransaction::new()
                .update(direct(name, oid(1)))
                .unwrap()
                .validate()
                .unwrap_err();
            assert_eq!(
                err,
                RefStoreError::InvalidRefName {
                    name: name.to_owned()
                }
            );
        }
    }

    #[test]
    fn validate_rejects_unsafe_rename_sides() {
        let reflog = RefTransaction::new().with_reflog_rename(RefReflogRename {
            from: "refs/heads/ok".to_owned(),
            to: "refs/heads/x.lock".to_owned(),
            append: sample_log(),
        });
        assert_eq!(
            reflog.validate().unwrap_err(),
            RefStoreError::InvalidRefName {
                name: "refs/heads/x.lock".to_owned()
            }
        );
        let case_only = RefTransaction::new().with_case_only_rename(RefCaseOnlyRename {
            from: "refs/heads//x".to_owned(),
            to: "refs/heads/X".to_owned(),
        });
        assert_eq!(
            case_only.validate().unwrap_err(),
            RefStoreError::InvalidRefName {
                name: "refs/heads//x".to_owned()
            }
        );
    }

    #[test]
    fn validate_rejects_null_oid_unless_log_only() {
        let err = RefTransaction::new()
            .update(direct("refs/heads/z", ObjectId::zero()))
            .unwrap()
            .validate()
            .unwrap_err();
        assert_eq!(
            err,
            RefStoreError::NullOid {
                name: "refs/heads/z".to_owned()
            }
        );

        let mut log_only = direct("HEAD", ObjectId::zero());
        log_only.flags.log_only = true;
        assert!(RefTransaction::new()
            .update(log_only)
            .unwrap()
            .validate()
            .is_ok());
    }

    #[test]
    fn validate_rejects_forged_reflog_identity_and_message() {
        let mut update = direct("HEAD", oid(1));
        update.flags.log_only = true;
        update.reflog = Some(super::super::ReflogUpdate {
            identity: "Evil <a@b>\nforged".to_owned(),
            message: "ok".to_owned(),
            time: time::OffsetDateTime::UNIX_EPOCH,
            old_oid: None,
            new_oid: None,
        });
        assert!(matches!(
            RefTransaction::new()
                .update(update)
                .unwrap()
                .validate()
                .unwrap_err(),
            RefStoreError::InvalidReflog(_)
        ));

        let mut update = direct("HEAD", oid(1));
        update.flags.log_only = true;
        update.reflog = Some(super::super::ReflogUpdate {
            identity: "A <a@example.com>".to_owned(),
            message: "bad\nline".to_owned(),
            time: time::OffsetDateTime::UNIX_EPOCH,
            old_oid: None,
            new_oid: None,
        });
        assert!(matches!(
            RefTransaction::new()
                .update(update)
                .unwrap()
                .validate()
                .unwrap_err(),
            RefStoreError::InvalidReflog(_)
        ));

        let txn = RefTransaction::new().with_reflog_rename(RefReflogRename {
            from: "refs/heads/a".to_owned(),
            to: "refs/heads/b".to_owned(),
            append: super::super::ReflogUpdate {
                identity: "Evil <a@b>\nforged".to_owned(),
                message: "rename".to_owned(),
                time: time::OffsetDateTime::UNIX_EPOCH,
                old_oid: None,
                new_oid: None,
            },
        });
        assert!(matches!(
            txn.validate().unwrap_err(),
            RefStoreError::InvalidReflog(_)
        ));
    }

    #[test]
    fn validate_accepts_pseudorefs_symrefs_and_deletes() {
        let txn = RefTransaction::new()
            .update(direct("ORIG_HEAD", oid(1)))
            .unwrap()
            .update(RefUpdate {
                name: "HEAD".to_owned(),
                new_value: Some(RawRef::Symbolic("refs/heads/main".to_owned())),
                expected: Expected::Any,
                reflog: None,
                flags: Default::default(),
            })
            .unwrap()
            .update(RefUpdate {
                name: "refs/heads/gone".to_owned(),
                new_value: None,
                expected: Expected::Any,
                reflog: None,
                flags: Default::default(),
            })
            .unwrap();
        assert!(txn.validate().is_ok());
    }

    #[test]
    fn from_updates_rejects_a_name_queued_twice() {
        let update = |name: &str| RefUpdate {
            name: name.to_owned(),
            new_value: None,
            expected: Expected::Any,
            reflog: None,
            flags: Default::default(),
        };
        let txn =
            RefTransaction::from_updates(vec![update("refs/heads/a"), update("refs/heads/b")])
                .expect("distinct names");
        assert_eq!(txn.updates().len(), 2);
        let err = RefTransaction::from_updates(vec![
            update("refs/heads/a"),
            update("refs/heads/b"),
            update("refs/heads/a"),
        ])
        .unwrap_err();
        assert!(matches!(
            err,
            RefStoreError::DuplicateUpdate { name } if name == "refs/heads/a"
        ));
    }

    #[test]
    fn expected_oid_requires_direct_match() {
        let direct = RawRef::Direct(oid(1));
        assert!(expected_matches(Some(&direct), &Expected::Oid(oid(1))));
        assert!(!expected_matches(Some(&direct), &Expected::Oid(oid(2))));
        assert!(!expected_matches(None, &Expected::Exists));
        assert!(expected_matches(None, &Expected::Missing));
    }
}