girt 0.4.2

An incremental, idiomatic Rust implementation of Git
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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Native local pack installation followed by conditional reference publication.

use std::borrow::Borrow;
use std::fs;
use std::path::Path;

use super::{PreparedPush, PushError, PushFailure, PushReport, RejectionOrigin, Status};
use crate::config::ConfigInputs;
use crate::fetch::{Advertisement, FetchError, FetchLimits, KnownHistory, ReceivedFetch};
use crate::refs::{
    Expected, RefEdit, RefName, RefOutcome, ReferenceError, References, Reflog, Target,
    TransactionError,
};
use crate::transport::TransportControl;
use crate::{Repository, Signature};

/// The destination's references as `git receive-pack` would advertise them, read on request.
pub(crate) struct LocalAdvertisement<'a> {
    refs: &'a References<'a>,
    hide: &'a HideRules,
}

impl LocalAdvertisement<'_> {
    /// Targets of the visible direct references, sorted and deduplicated. Like receive-pack, refs
    /// hidden by `receive.hideRefs` or `transfer.hideRefs` are not offered.
    pub(crate) fn receiver_roots(&self) -> Result<Vec<crate::ObjectId>, PushFailure> {
        let mut roots: Vec<_> = self
            .refs
            .list()
            .map_err(PushFailure::reference)?
            .into_iter()
            .filter(|reference| !self.hide.matches(&reference.name))
            .filter_map(|reference| match reference.target {
                Target::Direct(id) => Some(id),
                Target::Symbolic(_) => None,
            })
            .collect();
        roots.sort_unstable();
        roots.dedup();
        Ok(roots)
    }
}

/// Opens and checks the destination's receive policy, prepares the push from its advertisement,
/// then installs and publishes it.
///
/// Policy refusals happen before `prepare` runs. Receiver roots the preparation relied on are
/// checked against the references read after preparation; a change is
/// [`PushFailure::KnowledgeChanged`].
pub(super) fn send_preparing<P: Borrow<PreparedPush>>(
    destination: &Path,
    format: crate::ObjectFormat,
    control: TransportControl<'_>,
    identity: Option<&Signature>,
    config_inputs: &ConfigInputs,
    prepare: impl FnOnce(&LocalAdvertisement<'_>) -> Result<P, PushFailure>,
) -> Result<PushReport, PushError> {
    control
        .check()
        .map_err(|error| PushError::NotSent(error.into()))?;
    let repository = Repository::open_with_config(destination, config_inputs)
        .map_err(|error| PushError::NotSent(PushFailure::destination(error)))?;
    if repository.object_format() != format {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "destination object format",
        )));
    }
    let advertises_push_options =
        configured_boolean(&repository, "receive", "advertisepushoptions")?.unwrap_or(false);
    if identity.is_some_and(|person| person.validate().is_err() || person.seconds < 0) {
        return Err(PushError::NotSent(PushFailure::Identity));
    }
    let current_policy = current_policy(&repository)?;
    let deny_delete_current = delete_current_policy(&repository)?;
    let deny_deletes = configured_boolean(&repository, "receive", "denydeletes")?.unwrap_or(false);
    let deny_non_fast_forwards =
        configured_boolean(&repository, "receive", "denynonfastforwards")?.unwrap_or(false);
    let log_policy = log_policy(&repository)?;
    let hide = HideRules::parse(&repository)?;
    // Objects are always validated, which satisfies `receive.fsckObjects`.
    if repository
        .config()
        .value("receive", None, "procreceiverefs")
        .is_some()
    {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "configured receive policy",
        )));
    }
    if !repository.shallow_roots().is_empty() {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "shallow destination",
        )));
    }
    let refs = repository
        .references()
        .map_err(|error| PushError::NotSent(PushFailure::reference(error)))?;
    let prepared = prepare(&LocalAdvertisement {
        refs: &refs,
        hide: &hide,
    })
    .map_err(PushError::NotSent)?;
    let prepared: &PreparedPush = prepared.borrow();
    if prepared.format != format {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "destination object format",
        )));
    }
    if prepared.has_options && !advertises_push_options {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "the receiving end does not support push options",
        )));
    }
    control
        .check()
        .map_err(|error| PushError::NotSent(error.into()))?;
    let mut report = PushReport::pending(&prepared.commands);
    for reference in &mut report.refs {
        reference.rewrite_complete = true;
    }
    if prepared.commands.is_empty() {
        return Ok(report);
    }
    let hooks = super::hooks::ReceiveHooks::new(&repository, prepared.options.clone());
    for hook in ["proc-receive", "reference-transaction", "push-to-checkout"] {
        if hooks.has(hook) {
            return Err(PushError::NotSent(PushFailure::Unsupported(
                "proc-receive, reference-transaction or push-to-checkout hook",
            )));
        }
    }
    let current = refs
        .list()
        .map_err(|error| PushError::NotSent(PushFailure::reference(error)))?;
    for command in &prepared.commands {
        if matches!(
            refs.read(&command.name)
                .map_err(|error| PushError::NotSent(PushFailure::reference(error)))?,
            Some(Target::Symbolic(_))
        ) {
            return Err(PushError::NotSent(PushFailure::Unsupported(
                "symbolic push destination",
            )));
        }
        let checked_out = is_checked_out(&repository, &command.name, config_inputs)
            .map_err(PushError::NotSent)?;
        let rejected_current = checked_out
            && (command.deletes() && deny_delete_current
                || !command.deletes() && current_policy == CurrentPolicy::Refuse);
        if !rejected_current && !hide.matches(&command.name) {
            reflog_policy(&refs, command, log_policy, identity).map_err(PushError::NotSent)?;
        }
    }
    for root in &prepared.receiver_roots {
        if !current
            .iter()
            .any(|reference| reference.target == Target::Direct(*root))
        {
            return Err(PushError::NotSent(PushFailure::KnowledgeChanged(*root)));
        }
    }
    if !prepared.receiver_roots.is_empty() {
        // Like Git, the destination's existing objects are trusted to have complete history, so
        // the pack may omit anything reachable from these roots.
        let store = repository.objects(Default::default()).map_err(|error| {
            PushError::NotSent(PushFailure::install(FetchError::Destination(error)))
        })?;
        for &root in &prepared.receiver_roots {
            let present = store
                .read(root, prepared.limits.read)
                .map_err(|error| {
                    PushError::NotSent(PushFailure::install(FetchError::Destination(error)))
                })?
                .is_some();
            if !present {
                return Err(PushError::NotSent(PushFailure::KnowledgeChanged(root)));
            }
        }
    }
    let limits = FetchLimits {
        max_pack_bytes: prepared
            .limits
            .pack
            .max_pack_bytes
            .try_into()
            .unwrap_or(usize::MAX),
        max_objects: prepared.limits.pack.max_objects as usize,
        max_object_bytes: prepared
            .limits
            .pack
            .max_object_bytes
            .try_into()
            .unwrap_or(usize::MAX),
        max_decode_bytes: prepared
            .limits
            .pack
            .max_input_bytes
            .try_into()
            .unwrap_or(usize::MAX),
        max_delta_depth: prepared.limits.read.max_delta_depth,
        max_delta_bytes: prepared.limits.read.max_delta_bytes,
        ..FetchLimits::trusted()
    };
    if !prepared.pack.is_empty() {
        let store = repository.objects(Default::default()).map_err(|error| {
            PushError::NotSent(PushFailure::install(FetchError::Destination(error)))
        })?;
        let roots: Vec<_> = current
            .iter()
            .filter_map(|reference| match reference.target {
                Target::Direct(id) => Some(id),
                Target::Symbolic(_) => None,
            })
            .collect();
        let mut known = KnownHistory::from_store_roots(store, &roots, control.cancel)
            .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
        // Git treats the canonical empty tree as present in every repository, so the sender omits
        // it when the receiver's history reaches it, even if the receiver doesn't store it.
        let unstored_empty_tree = known.assume_empty_tree();
        let mut pack = crate::fetch::Bytes::temporary()
            .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
        // Keep the prepared artifact reusable; import owns this independent temporary copy.
        let mut reader = prepared
            .pack
            .reader()
            .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
        let mut buffer = [0; 64 * 1024];
        loop {
            control
                .check()
                .map_err(|error| PushError::NotSent(error.into()))?;
            let count = std::io::Read::read(&mut reader, &mut buffer)
                .map_err(|e| PushError::NotSent(e.into()))?;
            if count == 0 {
                break;
            }
            pack.append(&buffer[..count])
                .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
        }
        let received = ReceivedFetch::validate_known(
            Advertisement {
                refs: Vec::new(),
                capabilities: vec![format!("object-format={}", prepared.format).into_bytes()],
            },
            prepared
                .commands
                .iter()
                .filter(|command| !command.deletes())
                .map(|command| command.new)
                .collect(),
            pack,
            &known,
            vec![],
            crate::fetch::FetchOptions {
                limits,
                depth: None,
            },
            &mut crate::fetch::ValidationObserver::new(control.cancel, &mut |_| {}),
        )
        .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
        if let Some(id) = unstored_empty_tree
            && received.dependencies().contains(&id)
        {
            repository
                .loose_objects()
                .write_object(prepared.format, crate::ObjectKind::Tree, b"")
                .map_err(|error| {
                    PushError::NotSent(PushFailure::Io(std::io::Error::other(error)))
                })?;
        }
        received
            .install(&repository, Default::default(), control.cancel)
            .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
    }
    report.unpack = Some(Status::Ok);
    // Like Git, a reference that already has the requested (non-deletion) value is up to date,
    // whatever the expected value, and isn't part of the update.
    let null = crate::ObjectId::null(prepared.format);
    let mut current_values = Vec::with_capacity(prepared.commands.len());
    for command in &prepared.commands {
        let current = refs
            .read(&command.name)
            .map_err(|error| PushError::Uncertain {
                cause: PushFailure::reference(error),
                report: Box::new(report.clone()),
            })?;
        current_values.push(match current {
            Some(Target::Direct(id)) => Some(id),
            _ => None,
        });
    }
    let up_to_date: Vec<bool> = prepared
        .commands
        .iter()
        .zip(&current_values)
        // Deletions are never up to date: deleting an absent reference still checks its
        // expected value, as with `git push --force-with-lease`.
        .map(|(command, current)| !command.deletes() && *current == Some(command.new))
        .collect();
    let hook_updates = |selected: &dyn Fn(usize) -> bool| {
        prepared
            .commands
            .iter()
            .enumerate()
            .filter(|&(index, _)| selected(index))
            .map(|(index, command)| super::hooks::HookUpdate {
                old: current_values[index].unwrap_or(null),
                new: command.new,
                name: &command.name,
            })
            .collect::<Vec<_>>()
    };
    let hook_error = |error: std::io::Error, report: &PushReport| PushError::Uncertain {
        cause: error.into(),
        report: Box::new(report.clone()),
    };
    let (accepted, messages) = hooks
        .run(
            "pre-receive",
            &[],
            &hook_updates(&|index| !up_to_date[index]),
        )
        .map_err(|error| hook_error(error, &report))?;
    report
        .progress
        .extend((!messages.is_empty()).then_some(messages));
    if !accepted {
        for (index, reference) in report.refs.iter_mut().enumerate() {
            if !up_to_date[index] {
                reference.status = Some(Status::Rejected(b"pre-receive hook declined".to_vec()));
                reference.rejection_origin = Some(RejectionOrigin::Receiver);
            } else {
                reference.status = Some(Status::Ok);
            }
        }
        return Ok(report);
    }
    for (index, command) in prepared.commands.iter().enumerate() {
        if let Err(error) = control.check() {
            return Err(PushError::Uncertain {
                cause: error.into(),
                report: Box::new(report),
            });
        }
        report.refs[index].attempted = true;
        if up_to_date[index] {
            report.refs[index].status = Some(Status::Ok);
            continue;
        }
        let old = current_values[index].unwrap_or(null).to_string();
        let new = command.new.to_string();
        let (accepted, messages) = hooks
            .run(
                "update",
                &[command.name.as_bytes(), old.as_bytes(), new.as_bytes()],
                &[],
            )
            .map_err(|error| hook_error(error, &report))?;
        report
            .progress
            .extend((!messages.is_empty()).then_some(messages));
        if !accepted {
            // As `git-receive-pack` reports it.
            let mut message = b"error: hook declined to update ".to_vec();
            message.extend_from_slice(command.name.as_bytes());
            message.push(b'\n');
            report.progress.push(message);
            report.refs[index].status = Some(Status::Rejected(b"hook declined".to_vec()));
            report.refs[index].rejection_origin = Some(RejectionOrigin::Receiver);
            continue;
        }
        if hide.matches(&command.name) {
            report.refs[index].status = Some(Status::Rejected(b"hidden reference".to_vec()));
            report.refs[index].rejection_origin = Some(RejectionOrigin::Receiver);
            continue;
        }
        let checked_out =
            is_checked_out(&repository, &command.name, config_inputs).map_err(|error| {
                PushError::Uncertain {
                    cause: error,
                    report: Box::new(report.clone()),
                }
            })?;
        if checked_out {
            if command.deletes() && deny_delete_current {
                report.refs[index].status = Some(Status::Rejected(
                    b"deletion of current branch denied".to_vec(),
                ));
                report.refs[index].rejection_origin = Some(RejectionOrigin::Receiver);
                continue;
            }
            if !command.deletes() && current_policy == CurrentPolicy::Refuse {
                report.refs[index].status = Some(Status::Rejected(
                    b"branch is currently checked out".to_vec(),
                ));
                report.refs[index].rejection_origin = Some(RejectionOrigin::Receiver);
                continue;
            }
            if !command.deletes() && current_policy == CurrentPolicy::Warn {
                report
                    .warnings
                    .push(b"updating currently checked out branch".to_vec());
            }
        }
        if command.deletes() && deny_deletes {
            report.refs[index].status = Some(Status::Rejected(b"deletion denied".to_vec()));
            report.refs[index].rejection_origin = Some(RejectionOrigin::Receiver);
            continue;
        }
        if command.force == super::ForcePolicy::Allow
            && command.name.as_bytes().starts_with(b"refs/heads/")
            && let Some(old) = command.expected
            && !command.deletes()
            && deny_non_fast_forwards
        {
            let objects =
                repository
                    .objects(Default::default())
                    .map_err(|error| PushError::Uncertain {
                        cause: PushFailure::install(FetchError::Destination(error)),
                        report: Box::new(report.clone()),
                    })?;
            let fast_forward = objects
                .is_ancestor(old, command.new, crate::HistoryLimits::default())
                .unwrap_or(false);
            if !fast_forward {
                report.refs[index].status = Some(Status::Rejected(b"non-fast-forward".to_vec()));
                report.refs[index].rejection_origin = Some(RejectionOrigin::Receiver);
                continue;
            }
        }
        let edit = RefEdit {
            name: command.name.clone(),
            dereference: false,
            target: (!command.deletes()).then_some(Target::Direct(command.new)),
            expected: command
                .expected
                .map_or(Expected::Absent, |id| Expected::Value(Target::Direct(id))),
            reflog: reflog_policy(&refs, command, log_policy, identity).map_err(|cause| {
                PushError::Uncertain {
                    cause,
                    report: Box::new(report.clone()),
                }
            })?,
        };
        match refs.transaction(&[edit]) {
            Ok(outcomes) => {
                report.refs[index].status = Some(Status::Ok);
                report.refs[index].effects = outcomes.into_iter().next();
            }
            Err(TransactionError::Prepare { source, .. }) => {
                let (reason, origin) = if matches!(source, ReferenceError::Mismatch { .. }) {
                    (b"stale old value".to_vec(), RejectionOrigin::ExpectedValue)
                } else {
                    (
                        b"reference storage rejected".to_vec(),
                        RejectionOrigin::Receiver,
                    )
                };
                report.refs[index].status = Some(Status::Rejected(reason));
                report.refs[index].rejection_origin = Some(origin);
            }
            Err(TransactionError::Publish { source, outcomes }) => {
                if let Some(effect) = outcomes.into_iter().next() {
                    if effect.reference == RefOutcome::Published {
                        report.refs[index].status = Some(Status::Ok);
                    }
                    report.refs[index].effects = Some(effect);
                }
                return Err(PushError::Uncertain {
                    cause: PushFailure::reference(source),
                    report: Box::new(report),
                });
            }
        }
    }
    let updated =
        |index: usize| !up_to_date[index] && report.refs[index].status == Some(Status::Ok);
    let post_updates = hook_updates(&updated);
    if !post_updates.is_empty() {
        let (_, messages) = hooks
            .run("post-receive", &[], &post_updates)
            .map_err(|error| hook_error(error, &report))?;
        let names: Vec<&[u8]> = post_updates
            .iter()
            .map(|update| update.name.as_bytes())
            .collect();
        let (_, update_messages) = hooks
            .run("post-update", &names, &[])
            .map_err(|error| hook_error(error, &report))?;
        report
            .progress
            .extend((!messages.is_empty()).then_some(messages));
        report
            .progress
            .extend((!update_messages.is_empty()).then_some(update_messages));
    }
    Ok(report)
}

struct HideRules(Vec<(Vec<u8>, bool)>);

impl HideRules {
    fn parse(repository: &Repository) -> Result<Self, PushError> {
        let mut rules = Vec::new();
        for entry in repository.config().entries() {
            if entry.subsection.is_some()
                || !entry.name.eq_ignore_ascii_case(b"hiderefs")
                || !(entry.section.eq_ignore_ascii_case(b"transfer")
                    || entry.section.eq_ignore_ascii_case(b"receive"))
            {
                continue;
            }
            let value =
                entry
                    .value
                    .as_deref()
                    .ok_or(PushError::NotSent(PushFailure::Unsupported(
                        "implicit hideRefs pattern",
                    )))?;
            let (visible, pattern) = if let Some(pattern) = value.strip_prefix(b"!") {
                (true, pattern)
            } else {
                (false, value)
            };
            // Namespace rewriting is not active in the native adapter, so ^ matches the same
            // spelling as an ordinary pattern. Reject an empty pattern rather than hiding all refs.
            let pattern = pattern.strip_prefix(b"^").unwrap_or(pattern);
            if pattern.is_empty() {
                return Err(PushError::NotSent(PushFailure::Unsupported(
                    "empty hideRefs pattern",
                )));
            }
            rules.push((pattern.to_vec(), visible));
        }
        Ok(Self(rules))
    }

    fn matches(&self, name: &RefName) -> bool {
        let mut hidden = false;
        for (pattern, visible) in &self.0 {
            let pattern = pattern.strip_suffix(b"/").unwrap_or(pattern);
            let rest = name.as_bytes().strip_prefix(pattern);
            if rest.is_some_and(|rest| rest.is_empty() || rest.starts_with(b"/")) {
                hidden = !visible;
            }
        }
        hidden
    }
}

fn is_checked_out(
    repository: &Repository,
    name: &RefName,
    config_inputs: &ConfigInputs,
) -> Result<bool, PushFailure> {
    if !name.as_bytes().starts_with(b"refs/heads/") {
        return Ok(false);
    }
    let main = Repository::open_with_config(repository.common_dir(), config_inputs)
        .map_err(PushFailure::destination)?;
    if head_names(&main, name)? {
        return Ok(true);
    }
    let entries = match fs::read_dir(repository.common_dir().join("worktrees")) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error.into()),
    };
    for entry in entries {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            return Err(PushFailure::Unsupported("worktree registration"));
        }
        let worktree = Repository::open_with_config(entry.path(), config_inputs)
            .map_err(PushFailure::destination)?;
        if head_names(&worktree, name)? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn head_names(repository: &Repository, name: &RefName) -> Result<bool, PushFailure> {
    if repository.is_bare() {
        return Ok(false);
    }
    let head = RefName::new(b"HEAD").expect("valid HEAD");
    let refs = repository.references().map_err(PushFailure::reference)?;
    if !matches!(
        refs.read(&head).map_err(PushFailure::reference)?,
        Some(Target::Symbolic(_))
    ) {
        return Ok(false);
    }
    Ok(refs
        .resolve(&head, 32)
        .map_err(PushFailure::reference)?
        .name
        == *name)
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum CurrentPolicy {
    Refuse,
    Allow,
    Warn,
}

fn current_policy(repository: &Repository) -> Result<CurrentPolicy, PushError> {
    let value = repository
        .config()
        .value("receive", None, "denycurrentbranch");
    match value {
        None | Some(None) => Ok(CurrentPolicy::Refuse),
        Some(Some(value)) if value.eq_ignore_ascii_case(b"refuse") => Ok(CurrentPolicy::Refuse),
        Some(Some(value)) if value.eq_ignore_ascii_case(b"ignore") => Ok(CurrentPolicy::Allow),
        Some(Some(value)) if value.eq_ignore_ascii_case(b"warn") => Ok(CurrentPolicy::Warn),
        Some(Some(value)) if value.eq_ignore_ascii_case(b"updateInstead") => {
            Err(PushError::NotSent(PushFailure::Unsupported(
                "receive.denyCurrentBranch=updateInstead",
            )))
        }
        Some(Some(value)) if crate::config::boolean(Some(value)) == Some(true) => {
            Ok(CurrentPolicy::Refuse)
        }
        Some(Some(value)) if crate::config::boolean(Some(value)) == Some(false) => {
            Ok(CurrentPolicy::Allow)
        }
        _ => Err(PushError::NotSent(PushFailure::Unsupported(
            "receive.denyCurrentBranch value",
        ))),
    }
}

fn configured_boolean(
    repository: &Repository,
    section: &str,
    name: &str,
) -> Result<Option<bool>, PushError> {
    let value = repository.config().value(section, None, name);
    match value {
        None => Ok(None),
        Some(None) => Ok(Some(true)),
        Some(Some(value)) => {
            crate::config::boolean(Some(value))
                .map(Some)
                .ok_or(PushError::NotSent(PushFailure::Unsupported(
                    "receive boolean policy",
                )))
        }
    }
}

fn delete_current_policy(repository: &Repository) -> Result<bool, PushError> {
    let value = repository
        .config()
        .value("receive", None, "denydeletecurrent");
    match value {
        None | Some(None) => Ok(true),
        Some(Some(value)) if value.eq_ignore_ascii_case(b"refuse") => Ok(true),
        Some(Some(value)) if value.eq_ignore_ascii_case(b"ignore") => Ok(false),
        Some(Some(value)) => crate::config::boolean(Some(value)).ok_or(PushError::NotSent(
            PushFailure::Unsupported("receive.denyDeleteCurrent value"),
        )),
    }
}

#[derive(Clone, Copy)]
enum LogPolicy {
    Existing,
    Standard,
    Always,
}

fn log_policy(repository: &Repository) -> Result<LogPolicy, PushError> {
    let value = repository.config().value("core", None, "logallrefupdates");
    match value {
        Some(Some(value)) if value.eq_ignore_ascii_case(b"always") => Ok(LogPolicy::Always),
        None if repository.is_bare() => Ok(LogPolicy::Existing),
        None => Ok(LogPolicy::Standard),
        _ => match configured_boolean(repository, "core", "logallrefupdates")? {
            Some(true) => Ok(LogPolicy::Standard),
            Some(false) => Ok(LogPolicy::Existing),
            None => unreachable!(),
        },
    }
}

fn reflog_policy(
    refs: &crate::refs::References<'_>,
    command: &super::PushCommand,
    policy: LogPolicy,
    identity: Option<&Signature>,
) -> Result<Reflog, PushFailure> {
    if command.deletes() {
        return Ok(Reflog::Delete);
    }
    let name = command.name.as_bytes();
    let standard = name.starts_with(b"refs/heads/")
        || name.starts_with(b"refs/remotes/")
        || name.starts_with(b"refs/notes/");
    let create =
        matches!(policy, LogPolicy::Always) || matches!(policy, LogPolicy::Standard) && standard;
    let exists = refs
        .has_reflog(&command.name)
        .map_err(PushFailure::reference)?;
    if !create && !exists {
        return Ok(Reflog::Preserve);
    }
    let identity = identity.ok_or(PushFailure::Identity)?;
    Ok(Reflog::Append {
        committer: identity.clone(),
        message: b"push".to_vec(),
    })
}