grit-lib 0.5.29

Core library for the grit Git implementation
Documentation
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
//! `reference-transaction` hook around ref store prepare/commit.

use std::sync::Arc;

use crate::hooks::{RefHookContext, ReferenceTransactionPhase};
use crate::objects::ObjectId;

use super::{PreparedRefTransaction, RawRef, RefStore, RefStoreError, RefTransaction, RefUpdate};

type StoreResult<T> = std::result::Result<T, RefStoreError>;

/// One `<old-hex> <new-hex> <ref>` line for the hook stdin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ReferenceTransactionLine {
    pub old_oid: ObjectId,
    pub new_oid: ObjectId,
    pub refname: String,
}

impl ReferenceTransactionLine {
    fn format_line(&self) -> String {
        format!(
            "{} {} {}\n",
            self.old_oid.to_hex(),
            self.new_oid.to_hex(),
            self.refname
        )
    }
}

/// Build sorted hook stdin lines for `updates` against current `store` state.
pub(crate) fn reference_transaction_lines(
    store: &dyn RefStore,
    updates: &[RefUpdate],
    null_oid: ObjectId,
) -> StoreResult<Vec<ReferenceTransactionLine>> {
    let mut lines = Vec::new();
    for update in updates {
        if let Some(line) = line_for_update(store, update, null_oid)? {
            lines.push(line);
        }
    }
    lines.sort_by(|a, b| a.refname.cmp(&b.refname));
    Ok(lines)
}

fn line_for_update(
    store: &dyn RefStore,
    update: &RefUpdate,
    null_oid: ObjectId,
) -> StoreResult<Option<ReferenceTransactionLine>> {
    if update.flags.log_only {
        let Some(RawRef::Direct(new_oid)) = &update.new_value else {
            return Ok(None);
        };
        let old_oid = current_log_only_old_oid(store, &update.name, null_oid)?;
        return Ok(Some(ReferenceTransactionLine {
            old_oid,
            new_oid: *new_oid,
            refname: update.name.clone(),
        }));
    }
    match &update.new_value {
        None => {
            let old_oid = current_direct_oid(store, &update.name, null_oid)?;
            Ok(Some(ReferenceTransactionLine {
                old_oid,
                new_oid: null_oid,
                refname: update.name.clone(),
            }))
        }
        Some(RawRef::Direct(new_oid)) => {
            let old_oid = current_direct_oid(store, &update.name, null_oid)?;
            Ok(Some(ReferenceTransactionLine {
                old_oid,
                new_oid: *new_oid,
                refname: update.name.clone(),
            }))
        }
        Some(RawRef::Symbolic(_)) => Ok(None),
    }
}

fn current_direct_oid(
    store: &dyn RefStore,
    name: &str,
    null_oid: ObjectId,
) -> StoreResult<ObjectId> {
    let Some(raw) = store
        .read_raw(name)
        .map_err(|e| RefStoreError::Corrupt(e.to_string()))?
    else {
        return Ok(null_oid);
    };
    match raw {
        RawRef::Direct(oid) => Ok(oid),
        RawRef::Symbolic(_) => Ok(null_oid),
    }
}

/// Old oid for log-only direct updates (e.g. `HEAD` reflog while `HEAD` stays symbolic).
fn current_log_only_old_oid(
    store: &dyn RefStore,
    name: &str,
    null_oid: ObjectId,
) -> StoreResult<ObjectId> {
    let Some(raw) = store
        .read_raw(name)
        .map_err(|e| RefStoreError::Corrupt(e.to_string()))?
    else {
        return Ok(null_oid);
    };
    match raw {
        RawRef::Direct(oid) => Ok(oid),
        RawRef::Symbolic(_) => match store.resolve(name) {
            Ok(oid) => Ok(oid),
            Err(crate::error::Error::RefStore(RefStoreError::NotFound { .. })) => Ok(null_oid),
            Err(e) => Err(match e {
                crate::error::Error::RefStore(err) => err,
                other => RefStoreError::Corrupt(other.to_string()),
            }),
        },
    }
}

pub(crate) fn stdin_from_lines(lines: &[ReferenceTransactionLine]) -> Vec<u8> {
    lines
        .iter()
        .flat_map(|l| l.format_line().into_bytes())
        .collect()
}

pub(crate) fn run_reference_transaction_phase(
    ctx: &RefHookContext,
    phase: ReferenceTransactionPhase,
    lines: &[ReferenceTransactionLine],
) -> StoreResult<()> {
    if lines.is_empty() {
        return Ok(());
    }
    let stdin = stdin_from_lines(lines);
    ctx.run_reference_transaction(phase, &stdin)
        .map_err(|e| RefStoreError::Hook(e.into()))
}

/// Prepared batch with optional hook phases after the backend locks.
pub(crate) struct HookWrappedPrepared<'a> {
    inner: Option<Box<dyn PreparedRefTransaction + Send + 'a>>,
    hooks: Arc<RefHookContext>,
    lines: Vec<ReferenceTransactionLine>,
    hook_armed: bool,
}

impl<'a> HookWrappedPrepared<'a> {
    pub fn new(
        inner: Box<dyn PreparedRefTransaction + Send + 'a>,
        hooks: Arc<RefHookContext>,
        lines: Vec<ReferenceTransactionLine>,
    ) -> Self {
        Self {
            inner: Some(inner),
            hooks,
            lines,
            hook_armed: true,
        }
    }
}

impl Drop for HookWrappedPrepared<'_> {
    fn drop(&mut self) {
        if let Some(inner) = self.inner.take() {
            let _ = inner.abort();
        }
        if self.hook_armed {
            let _ = run_reference_transaction_phase(
                self.hooks.as_ref(),
                ReferenceTransactionPhase::Aborted,
                &self.lines,
            );
        }
    }
}

impl PreparedRefTransaction for HookWrappedPrepared<'_> {
    fn rejected_updates(&self) -> &[(String, RefStoreError)] {
        match self.inner.as_ref() {
            Some(inner) => inner.rejected_updates(),
            None => &[],
        }
    }

    fn commit(mut self: Box<Self>) -> StoreResult<()> {
        self.hook_armed = false;
        let inner = self
            .inner
            .take()
            .ok_or_else(|| RefStoreError::Corrupt("ref transaction already finished".into()))?;
        inner.commit()?;
        let _ = run_reference_transaction_phase(
            self.hooks.as_ref(),
            ReferenceTransactionPhase::Committed,
            &self.lines,
        );
        Ok(())
    }

    fn abort(mut self: Box<Self>) -> StoreResult<()> {
        self.hook_armed = false;
        let inner = self.inner.take();
        let result = inner.map_or(Ok(()), |inner| inner.abort());
        let _ = run_reference_transaction_phase(
            self.hooks.as_ref(),
            ReferenceTransactionPhase::Aborted,
            &self.lines,
        );
        result
    }
}

/// Run prepare on `inner`, then `prepared` / `committed` / `aborted` hooks when `hooks` is set.
pub(crate) fn prepare_with_reference_transaction_hooks<'a>(
    store: &'a dyn RefStore,
    inner: &'a dyn RefStore,
    hooks: Option<&'a Arc<RefHookContext>>,
    null_oid: ObjectId,
    txn: RefTransaction,
    wait: crate::lockfile::LockWait,
) -> StoreResult<Box<dyn PreparedRefTransaction + Send + 'a>> {
    let updates: Vec<RefUpdate> = txn.updates().to_vec();
    let inner_prepared = inner.prepare_for(txn, wait)?;
    let Some(hooks) = hooks else {
        return Ok(inner_prepared);
    };
    let lines = reference_transaction_lines(store, &updates, null_oid)?;
    if let Err(err) =
        run_reference_transaction_phase(hooks.as_ref(), ReferenceTransactionPhase::Prepared, &lines)
    {
        let _ = inner_prepared.abort();
        let _ = run_reference_transaction_phase(
            hooks.as_ref(),
            ReferenceTransactionPhase::Aborted,
            &lines,
        );
        return Err(err);
    }
    Ok(Box::new(HookWrappedPrepared::new(
        inner_prepared,
        Arc::clone(hooks),
        lines,
    )))
}

/// Hook lines for a files-backend branch commit (matches Git's `HEAD` + branch pair).
pub(crate) fn branch_commit_reference_transaction_lines(
    branch_ref: &str,
    old_oid: ObjectId,
    new_oid: ObjectId,
) -> Vec<ReferenceTransactionLine> {
    let mut lines = vec![
        ReferenceTransactionLine {
            old_oid,
            new_oid,
            refname: "HEAD".to_owned(),
        },
        ReferenceTransactionLine {
            old_oid,
            new_oid,
            refname: branch_ref.to_owned(),
        },
    ];
    lines.sort_by(|a, b| a.refname.cmp(&b.refname));
    lines
}

/// Hook lines for detached `HEAD` commit on the files backend.
pub(crate) fn detached_head_commit_reference_transaction_lines(
    old_oid: ObjectId,
    new_oid: ObjectId,
) -> Vec<ReferenceTransactionLine> {
    vec![ReferenceTransactionLine {
        old_oid,
        new_oid,
        refname: "HEAD".to_owned(),
    }]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::zero_oid;
    use crate::refs::store::{MemoryRefStore, RefUpdateFlags};

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

    #[test]
    fn skips_symbolic_only_update() {
        let store = MemoryRefStore::new();
        store
            .set_ref("HEAD", RawRef::Symbolic("refs/heads/main".into()))
            .expect("head");
        let null = zero_oid();
        let lines = reference_transaction_lines(
            &store,
            &[RefUpdate {
                name: "HEAD".into(),
                new_value: Some(RawRef::Symbolic("refs/heads/other".into())),
                expected: crate::refs::store::Expected::Any,
                reflog: None,
                flags: RefUpdateFlags::default(),
            }],
            null,
        )
        .expect("lines");
        assert!(lines.is_empty());
    }

    #[test]
    fn log_only_direct_includes_head() {
        let store = MemoryRefStore::new();
        let old = oid(1);
        let new = oid(2);
        store.set_ref("HEAD", RawRef::Direct(old)).expect("head");
        let null = zero_oid();
        let lines = reference_transaction_lines(
            &store,
            &[RefUpdate {
                name: "HEAD".into(),
                new_value: Some(RawRef::Direct(new)),
                expected: crate::refs::store::Expected::Any,
                reflog: None,
                flags: RefUpdateFlags {
                    log_only: true,
                    no_deref: true,
                    ..Default::default()
                },
            }],
            null,
        )
        .expect("lines");
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].old_oid, old);
        assert_eq!(lines[0].new_oid, new);
    }

    #[test]
    fn log_only_resolves_symbolic_head_old_oid() {
        let store = MemoryRefStore::new();
        let tip = oid(3);
        let new = oid(4);
        store
            .set_ref("refs/heads/main", RawRef::Direct(tip))
            .expect("branch");
        store
            .set_ref("HEAD", RawRef::Symbolic("refs/heads/main".into()))
            .expect("head");
        let null = zero_oid();
        let lines = reference_transaction_lines(
            &store,
            &[RefUpdate {
                name: "HEAD".into(),
                new_value: Some(RawRef::Direct(new)),
                expected: crate::refs::store::Expected::Any,
                reflog: None,
                flags: RefUpdateFlags {
                    log_only: true,
                    no_deref: true,
                    ..Default::default()
                },
            }],
            null,
        )
        .expect("lines");
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].old_oid, tip);
        assert_eq!(lines[0].new_oid, new);
    }

    #[test]
    fn log_only_unborn_symbolic_head_uses_null_old_oid() {
        let store = MemoryRefStore::new();
        let new = oid(1);
        store
            .set_ref("HEAD", RawRef::Symbolic("refs/heads/main".into()))
            .expect("head");
        let null = zero_oid();
        let lines = reference_transaction_lines(
            &store,
            &[RefUpdate {
                name: "HEAD".into(),
                new_value: Some(RawRef::Direct(new)),
                expected: crate::refs::store::Expected::Any,
                reflog: None,
                flags: RefUpdateFlags {
                    log_only: true,
                    no_deref: true,
                    ..Default::default()
                },
            }],
            null,
        )
        .expect("lines");
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].old_oid, null);
        assert_eq!(lines[0].new_oid, new);
    }
}