girt 0.1.1

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
//! Native local pack installation followed by conditional reference publication.

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, NativeContents, ReceivedFetch,
};
use crate::refs::{
    Expected, RefEdit, RefName, RefOutcome, ReferenceError, Reflog, Target, TransactionError,
};
use crate::transport::TransportControl;
use crate::{Repository, Signature};

pub(super) fn send(
    destination: &Path,
    prepared: &PreparedPush,
    control: TransportControl<'_>,
    identity: Option<&Signature>,
    config_inputs: &ConfigInputs,
) -> 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() != prepared.format {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "destination object format",
        )));
    }
    if prepared.has_options {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "native local push options",
        )));
    }
    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)?;
    for (section, key) in [
        ("receive", "procreceiverefs"),
        ("receive", "maxinputsize"),
        ("receive", "fsckobjects"),
        ("transfer", "fsckobjects"),
    ] {
        if repository.config().value(section, None, key).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 mut report = PushReport::pending(&prepared.commands);
    for reference in &mut report.refs {
        reference.rewrite_complete = true;
    }
    if prepared.commands.is_empty() {
        return Ok(report);
    }
    if repository
        .config()
        .value("core", None, "hookspath")
        .is_some()
    {
        return Err(PushError::NotSent(PushFailure::Unsupported(
            "configured receive hooks",
        )));
    }
    for hook in [
        "pre-receive",
        "update",
        "post-receive",
        "proc-receive",
        "reference-transaction",
        "push-to-checkout",
    ] {
        let path = repository.common_dir().join("hooks").join(hook);
        match fs::symlink_metadata(path) {
            Ok(_) => {
                return Err(PushError::NotSent(PushFailure::Unsupported(
                    "receive hooks",
                )));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(PushError::NotSent(error.into())),
        }
    }
    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() {
        let store = repository.objects(Default::default()).map_err(|error| {
            PushError::NotSent(PushFailure::install(FetchError::Destination(error)))
        })?;
        KnownHistory::new_local(
            &store,
            &prepared.receiver_roots,
            FetchLimits {
                max_known_objects: prepared.limits.pack.max_objects as usize,
                max_known_bytes: prepared
                    .limits
                    .pack
                    .max_input_bytes
                    .try_into()
                    .unwrap_or(usize::MAX),
                max_known_edges: prepared.limits.max_edges,
                known_read: prepared.limits.read,
                ..FetchLimits::default()
            },
            control.cancel,
        )
        .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
    }
    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,
        ..FetchLimits::default()
    };
    if !prepared.pack.is_empty() {
        let received = ReceivedFetch::native(
            Advertisement {
                refs: Vec::new(),
                capabilities: Vec::new(),
            },
            prepared
                .commands
                .iter()
                .filter(|command| !command.deletes())
                .map(|command| command.new)
                .collect(),
            NativeContents {
                format: prepared.format,
                pack: Vec::new(),
                index: Vec::new(),
                checksum: prepared.checksum,
                objects: prepared.object_count() as usize,
                dependencies: Vec::new(),
                limits,
            },
        );
        received
            .install_bytes(
                &repository,
                Default::default(),
                control.cancel,
                &prepared.pack,
                &prepared.index,
                false,
            )
            .map_err(|error| PushError::NotSent(PushFailure::install(error)))?;
    }
    report.unpack = Some(Status::Ok);
    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 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),
                });
            }
        }
    }
    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(),
    })
}