girt 0.13.0

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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
use std::fs;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use super::{BranchSelection, CloneHead, ClonePlan, ClonePlanError, config, plan};
use crate::fetch::{
    Advertisement, FetchError, FetchFinishError, FetchLimits, FetchPlanError, FetchReady,
    FetchReport, FetchRequest, FetchUpdateLimits, ReceivedFetch,
};
use crate::refs::{Expected, RefEdit, RefEditOutcome, RefName, Reflog, Target};
use crate::transport::TransportControl;
use crate::{InitKind, ObjectKind, Repository};

/// Destination and explicit policy for a full clone, without checkout.
///
/// The destination must not exist, even as an empty directory or dangling symlink; its parent
/// must exist. Preparation checks this without reserving the path. Finish exclusively reserves
/// it again. Callers must exclude path replacement, other writers, checkout and GC during finish.
/// Parent symlinks follow filesystem resolution; this is not an untrusted-path security boundary.
///
/// The stored URL is caller-selected metadata, separate from the actual transport endpoint and
/// credentials. Supply a credential-free URL usable by future callers; relative local paths are
/// interpreted relative to the new repository by Git, so prefer an absolute path. No endpoint
/// discovery, credential persistence/discovery, retry, pruning, implicit force, or runtime is
/// provided. `origin` is the fixed remote name. All branch/tag refspecs are unforced; subsequent
/// fetch callers supply any force intent and authorization explicitly.
///
/// Direct refs use the supplied reflog policy; symbolic HEAD uses `Reflog::Preserve` because
/// stored symbolic replacements cannot append logs. No `origin/HEAD` alias is created. No index,
/// checkout, shallow/filter, alternates, hardlinks, mirror or submodule behavior is supported.
/// Finish requires the existing reference backend. Native local clone reads girt storage directly
/// and needs no Git executable. The optional SSH adapter requires macOS/Linux; HTTP is
/// feature-gated and uses the caller's runtime. See the [module
/// example](crate::clone#example-cloning-a-local-repository) for a runnable local clone.
///
/// # Examples
///
/// Clone a local repository, choosing the initial local branch by name. Like every clone, this
/// writes no working files; see [`crate::Repository::checkout_tree`] for that step:
///
/// ```
/// use std::ops::ControlFlow;
/// use std::sync::atomic::AtomicBool;
///
/// use girt::InitKind;
/// use girt::clone::{BranchSelection, CloneRequest};
/// use girt::fetch::{FetchLimits, FetchUpdateLimits};
/// use girt::refs::{RefName, Reflog, Target};
/// use girt::transport::TransportControl;
/// # let (directory, upstream, _, main, _) = include!("../doctest/remote.rs");
///
/// let main_ref = RefName::new("refs/heads/main")?;
/// let request = CloneRequest::prepare_tracking(
///     directory.path().join("clone"),
///     InitKind::Worktree,
///     b"../upstream.git",
///     BranchSelection::Branch(main_ref.clone()),
///     Reflog::Preserve,
/// )?;
/// let cancel = AtomicBool::new(false);
/// let ready = request.receive_local(
///     upstream.git_dir(),
///     FetchLimits::default(),
///     TransportControl::new(&cancel),
///     |_| ControlFlow::Continue(()),
/// )?;
/// let report = ready.finish(FetchUpdateLimits::default(), &cancel)?;
/// let clone = report.repository.expect("finish succeeded");
/// assert_eq!(
///     clone.references()?.read(&main_ref)?,
///     Some(Target::Direct(main))
/// );
/// // The recorded origin URL is the one passed to `prepare_tracking`.
/// assert_eq!(
///     girt::remote::Remote::find(clone.config(), b"origin")?
///         .and_then(|origin| origin.fetch_url().map(<[u8]>::to_vec)),
///     Some(b"../upstream.git".to_vec()),
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct CloneRequest {
    pub(super) destination: PathBuf,
    pub(super) kind: InitKind,
    url: Vec<u8>,
    pub(super) selection: BranchSelection,
    reflog: Reflog,
}

impl std::fmt::Debug for CloneRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CloneRequest")
            .field("destination", &self.destination)
            .field("kind", &self.kind)
            .field("selection", &self.selection)
            .finish_non_exhaustive()
    }
}

impl CloneRequest {
    /// Prepares a clone with all branches in `refs/remotes/origin/*`, all tags, and at most one
    /// local branch. Checks destination absence without creating files or connecting.
    ///
    /// `kind` selects metadata placement only. In particular, `InitKind::Bare` uses this tracking
    /// layout too: enumerating or serving `refs/heads/*` exposes only the selected local branch
    /// (none for detached or unborn HEAD). Conventional bare copies with every remote branch under
    /// `refs/heads/*` are unsupported. Subsequent fetch can update the configured tracking refs
    /// without allowing branch destinations or weakening worktree safeguards.
    ///
    /// `url` preserves bytes through quoted Git configuration. Empty values, NUL and carriage
    /// returns are rejected. The library does not infer whether supplied bytes contain secrets.
    ///
    /// # Errors
    ///
    /// Returns invalid branch/URL policy or filesystem/destination errors without mutation.
    pub fn prepare_tracking(
        destination: impl AsRef<Path>,
        kind: InitKind,
        url: &[u8],
        selection: BranchSelection,
        reflog: Reflog,
    ) -> Result<Self, CloneFailure> {
        if url.is_empty() || url.contains(&0) || url.contains(&b'\r') {
            return Err(CloneFailure::Url);
        }
        if let BranchSelection::Branch(name) = &selection {
            plan::branch(name)?;
        }
        let destination = destination.as_ref().to_path_buf();
        absent(&destination)?;
        Ok(Self {
            destination,
            kind,
            url: url.to_vec(),
            selection,
            reflog,
        })
    }

    /// Previews HEAD and mappings without I/O. Receive always replans from its own advertisement.
    ///
    /// # Errors
    ///
    /// Rejects invalid/missing selection, conflicting mappings or inconsistent symbolic HEAD.
    pub fn plan(&self, advertisement: &Advertisement) -> Result<ClonePlan, ClonePlanError> {
        plan::plan(&self.selection, advertisement)
    }

    /// Downloads and validates a full local upload-pack transfer without creating the destination.
    ///
    /// No local known history is offered. Selection uses this session's advertisement; later
    /// remote ref movement never substitutes another ID. Server refusal/lost objects fail transfer.
    /// See [`crate::fetch::receive_local`] for process, deadline and progress policy.
    ///
    /// # Errors
    ///
    /// Returns planning/transfer errors with no destination effects. Dropping the result likewise
    /// leaves no destination; completion requires [`CloneReady::finish`].
    pub fn receive_local(
        self,
        source: impl AsRef<Path>,
        limits: FetchLimits,
        control: TransportControl<'_>,
        mut progress: impl FnMut(&[u8]) -> ControlFlow<()>,
    ) -> Result<CloneReady, CloneTransferError> {
        self.receive_local_with_progress(
            source,
            limits,
            control,
            crate::fetch::LocalFetchObserver::default().with_messages(&mut progress),
        )
    }

    /// Receives a local clone with optional construction and validation observers.
    ///
    /// Uses [`Self::receive_local`]'s selection, cancellation and publication contracts.
    /// Notifications follow [`crate::fetch::LocalFetchObserver`]; completion precedes installation.
    ///
    /// # Errors
    ///
    /// Returns the same planning and transfer errors as [`Self::receive_local`].
    pub fn receive_local_with_progress(
        self,
        source: impl AsRef<Path>,
        limits: FetchLimits,
        control: TransportControl<'_>,
        observer: crate::fetch::LocalFetchObserver<'_>,
    ) -> Result<CloneReady, CloneTransferError> {
        let mut saved = None;
        let received = crate::fetch::receive_local(
            source,
            |ad| plan::select(self.plan(ad), &mut saved),
            crate::fetch::LocalFetchRequest::new(limits),
            control,
            observer,
        );
        let (plan, received) = selected(saved, received)?;
        Ok(CloneReady {
            request: self,
            head: plan.head,
            received,
        })
    }
}

pub(super) fn selected<T>(
    saved: Option<Result<ClonePlan, ClonePlanError>>,
    transfer: Result<T, FetchError>,
) -> Result<(ClonePlan, T), CloneTransferError> {
    let plan = saved.transpose()?;
    let transfer = transfer?;
    let plan = plan.ok_or(FetchError::Protocol("selection callback was not invoked"))?;
    Ok((plan, transfer))
}

/// A validated full transfer and private advertisement-derived HEAD, ready for synchronous finish.
///
/// This workflow has not created the destination. Move to a caller-managed worker if needed;
/// dropping it only releases
/// memory. The destination/selection/transfer cannot be replaced through this value.
///
/// # Examples
///
/// Check what the clone will check out before creating anything:
///
/// ```
/// use std::ops::ControlFlow;
/// use std::sync::atomic::AtomicBool;
///
/// use girt::InitKind;
/// use girt::clone::{BranchSelection, CloneHead, CloneRequest};
/// use girt::fetch::{FetchLimits, FetchUpdateLimits};
/// use girt::refs::{RefName, Reflog};
/// use girt::transport::TransportControl;
/// # let (directory, upstream, _, main, _) = include!("../doctest/remote.rs");
///
/// let destination = directory.path().join("clone.git");
/// let request = CloneRequest::prepare_tracking(
///     &destination,
///     InitKind::Bare,
///     b"../upstream.git",
///     BranchSelection::Default,
///     Reflog::Preserve,
/// )?;
/// let cancel = AtomicBool::new(false);
/// let ready = request.receive_local(
///     upstream.git_dir(),
///     FetchLimits::default(),
///     TransportControl::new(&cancel),
///     |_| ControlFlow::Continue(()),
/// )?;
/// assert_eq!(
///     ready.head(),
///     &CloneHead::Branch {
///         name: RefName::new("refs/heads/main")?,
///         id: main
///     }
/// );
///
/// let report = ready.finish(FetchUpdateLimits::default(), &cancel)?;
/// let clone = report.repository.expect("finish succeeded");
/// // Every remote branch is tracked; only the selected one becomes local.
/// assert!(
///     clone
///         .references()?
///         .read(&RefName::new("refs/remotes/origin/main")?)?
///         .is_some()
/// );
/// assert!(
///     clone
///         .references()?
///         .read(&RefName::new("refs/heads/main")?)?
///         .is_some()
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct CloneReady {
    pub(super) request: CloneRequest,
    pub(super) head: CloneHead,
    pub(super) received: ReceivedFetch,
}

impl CloneReady {
    /// Advertised initial HEAD; commit-kind checks happen after installation during finish.
    pub fn head(&self) -> &CloneHead {
        &self.head
    }

    /// Creates the destination, installs/publishes tracking refs and tags, writes remote/branch
    /// config, packs the published refs, then conditionally publishes the local branch and HEAD
    /// (HEAD last). As with `git clone`, tracking refs and tags end up in `packed-refs`, while the
    /// local branch and symbolic refs stay loose.
    ///
    /// Both layouts contain all tracking branches/tags and at most one local branch. No index or
    /// worktree files are written. The returned repository has freshly reopened configuration.
    /// Branch/HEAD tips must be commits (not tags that peel to commits). Fetch validation rereads
    /// installed graphs before publication; all direct branch tips are checked before final HEAD.
    ///
    /// Cancellation is cooperative between phases, not inside config replacement or a reference
    /// transaction. Once publication starts, a completed operation may win cancellation. Join
    /// workers before releasing their resources. Limits retain [`FetchUpdateLimits`]' phase bounds;
    /// metadata transactions are not a hard memory/deadline bound.
    ///
    /// # Errors
    ///
    /// [`CloneError::report`] records destination reservation, initialization, fetch, config and
    /// final refs separately. Initialization failure can leave partial metadata. Fetch failure can
    /// leave an unindexed pack or partial refs/logs; inspect its nested report. Later failure keeps
    /// installed objects, tracking refs/tags and possibly config/local refs. No automatic cleanup,
    /// retry, rollback, whole-operation atomic visibility or crash durability is promised.
    pub fn finish(
        self,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
    ) -> Result<CloneReport, CloneError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "clone.finish",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            let mut report = CloneReport {
                destination: self.request.destination.clone(),
                reserved: false,
                initialized: false,
                fetch: None,
                configured: false,
                packed_refs: None,
                references: Vec::new(),
                repository: None,
                head: self.head.clone(),
            };
            let result = self.create_finish(limits, cancel, &mut report);
            match result {
                Ok(()) => Ok(report),
                Err(source) => Err(CloneError {
                    report: Box::new(report),
                    source,
                }),
            }
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| {
            crate::trace::clone_finish(error, &span)
        });

        result
    }

    fn create_finish(
        self,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
        report: &mut CloneReport,
    ) -> Result<(), CloneFailure> {
        cancelled(cancel)?;
        absent(&self.request.destination)?;
        fs::create_dir(&self.request.destination)?;
        report.reserved = true;
        let repo = Repository::init_reserved_clone(
            &self.request.destination,
            self.request.kind,
            self.received.object_format(),
        )?;
        report.initialized = true;
        self.finish_in(repo, limits, cancel, report)
    }

    fn finish_in(
        self,
        repo: Repository,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
        report: &mut CloneReport,
    ) -> Result<(), CloneFailure> {
        let has_head = self.received.advertisement().refs.iter().any(|r| {
            r.kind == crate::fetch::AdvertisementKind::Tip && r.name.as_bytes() == b"HEAD"
        });
        let request = FetchRequest::prepare(
            repo,
            plan::specs(has_head),
            Default::default(),
            self.request.reflog.clone(),
        )?;
        let ready = FetchReady::for_clone(request, self.received)?;
        report.fetch = Some(ready.finish(limits, cancel)?);
        let repo = Repository::open(&self.request.destination)?;
        verify_branches(
            &repo,
            report.fetch.as_ref().unwrap(),
            &self.head,
            limits,
            cancel,
        )?;
        cancelled(cancel)?;
        let bytes = config::contents(
            self.request.kind,
            repo.object_format(),
            &self.request.url,
            &self.head,
        );
        config::publish(&repo, self.request.kind, &bytes).map_err(CloneFailure::Configuration)?;
        report.configured = true;
        cancelled(cancel)?;
        // Like Git's clone, publish fetched refs packed; the local branch and HEAD stay loose.
        if repo.reference_backend() == crate::refs::Backend::Files {
            let objects = repo.objects_with(limits.snapshot)?;
            report.packed_refs = Some(
                repo.references()?
                    .pack(&objects, crate::refs::PackRefsOptions::ALL)?,
            );
        }
        cancelled(cancel)?;
        report.references = repo
            .references()?
            .transaction(&head_edits(&self.head, &self.request.reflog))?;
        report.repository = Some(Repository::open(&self.request.destination)?);
        Ok(())
    }
}

fn verify_branches(
    repo: &Repository,
    fetch: &FetchReport,
    head: &CloneHead,
    limits: FetchUpdateLimits,
    cancel: &AtomicBool,
) -> Result<(), CloneFailure> {
    let objects = repo
        .objects_with(limits.snapshot)
        .map_err(FetchError::Destination)?;
    let detached = match head {
        CloneHead::Detached(id) => Some(*id),
        _ => None,
    };
    let branches = fetch
        .updates
        .iter()
        .filter_map(|u| u.mapping.source.as_ref())
        .filter(|s| s.name.as_bytes().starts_with(b"refs/heads/"))
        .map(|s| s.id);
    for id in branches.chain(detached) {
        cancelled(cancel)?;
        let object = objects
            .read_with(id, limits.verification.known_read)
            .map_err(FetchError::from)?
            .ok_or(FetchError::Missing(id))?;
        if object.kind() != ObjectKind::Commit {
            return Err(FetchError::Kind(id).into());
        }
    }
    Ok(())
}

fn head_edits(head: &CloneHead, reflog: &Reflog) -> Vec<RefEdit> {
    let mut edits = Vec::new();
    let target = match head {
        CloneHead::Branch { name, id } => {
            edits.push(RefEdit {
                name: name.clone(),
                dereference: crate::refs::Dereference::Stored,
                target: Some(Target::Direct(*id)),
                expected: Expected::Absent,
                reflog: reflog.clone(),
            });
            Target::Symbolic(name.clone())
        }
        CloneHead::Detached(id) => Target::Direct(*id),
        CloneHead::Unborn(name) => Target::Symbolic(name.clone()),
    };
    let head_reflog = if matches!(target, Target::Direct(_)) {
        reflog.clone()
    } else {
        Reflog::Preserve
    };
    edits.push(RefEdit {
        name: RefName::HEAD,
        dereference: crate::refs::Dereference::Stored,
        target: Some(target),
        expected: Expected::Value(Target::Symbolic(crate::repository::initial_branch())),
        reflog: head_reflog,
    });
    edits
}

fn absent(path: &Path) -> Result<(), CloneFailure> {
    match fs::symlink_metadata(path) {
        Ok(_) => Err(CloneFailure::Exists(path.into())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e.into()),
    }
}
fn cancelled(cancel: &AtomicBool) -> Result<(), CloneFailure> {
    if cancel.load(Ordering::Relaxed) {
        return Err(FetchError::Cancelled.into());
    }
    Ok(())
}

/// Completed phases, including on failure. No field implies rollback or crash durability.
///
/// On success every phase is complete and [`repository`](Self::repository) holds the new
/// repository. After a failure, inspect the fields in order: whether the destination was
/// reserved, initialized, fetched into, configured, and given its local branch and `HEAD`.
///
/// # Examples
///
/// ```
/// use std::ops::ControlFlow;
/// use std::sync::atomic::AtomicBool;
///
/// use girt::InitKind;
/// use girt::clone::{BranchSelection, CloneRequest};
/// use girt::fetch::{FetchLimits, FetchUpdateLimits};
/// use girt::refs::Reflog;
/// use girt::transport::TransportControl;
/// # let (directory, upstream, _, _, _) = include!("../doctest/remote.rs");
///
/// let request = CloneRequest::prepare_tracking(
///     directory.path().join("clone"),
///     InitKind::Bare,
///     b"../upstream.git",
///     BranchSelection::Default,
///     Reflog::Preserve,
/// )?;
/// let cancel = AtomicBool::new(false);
/// let ready = request.receive_local(
///     upstream.git_dir(),
///     FetchLimits::default(),
///     TransportControl::new(&cancel),
///     |_| ControlFlow::Continue(()),
/// )?;
/// let report = ready.finish(FetchUpdateLimits::default(), &cancel)?;
/// assert!(report.reserved && report.initialized && report.configured);
/// assert!(
///     report
///         .fetch
///         .as_ref()
///         .is_some_and(|fetch| fetch.installed.is_some())
/// );
/// assert!(report.repository.is_some());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct CloneReport {
    /// Requested path; inspect here for residual files after failure.
    pub destination: PathBuf,
    /// Whether this operation reserved the root; false does not authorize cleanup of any path.
    pub reserved: bool,
    /// Minimal initialization completed; otherwise partial metadata can remain if reserved.
    pub initialized: bool,
    /// Successful fetch installation/publication. On fetch failure consult the nested error.
    pub fetch: Option<FetchReport>,
    /// Complete remote/branch config replaced initialization config.
    pub configured: bool,
    /// Fetched refs written to `packed-refs`; `None` for reftable or an earlier failure. Loose
    /// copies stay on non-Unix hosts; see [`crate::refs::References::pack`].
    pub packed_refs: Option<crate::refs::PackRefsReport>,
    /// Successful local branch/HEAD transaction. On error inspect the nested transaction outcomes.
    pub references: Vec<RefEditOutcome>,
    /// Reopened repository with persisted config, present only on complete success.
    pub repository: Option<Repository>,
    /// Planned HEAD, not evidence of its publication.
    pub head: CloneHead,
}

/// Transfer or planning failure with no destination effects.
///
/// The destination was not created. [`Plan`](Self::Plan) means the branch choice doesn't fit the
/// remote; see [`ClonePlanError`]. [`Transfer`](Self::Transfer) covers the connection, limits,
/// cancellation and invalid data; see [`FetchError`] for what each cause means.
///
/// # Examples
///
/// ```
/// use std::ops::ControlFlow;
/// use std::sync::atomic::AtomicBool;
///
/// use girt::InitKind;
/// use girt::clone::{BranchSelection, CloneRequest, CloneTransferError};
/// use girt::fetch::{FetchError, FetchLimits};
/// use girt::refs::Reflog;
/// use girt::transport::TransportControl;
/// # let (directory, upstream, _, _, _) = include!("../doctest/remote.rs");
///
/// let destination = directory.path().join("clone");
/// let request = CloneRequest::prepare_tracking(
///     &destination,
///     InitKind::Worktree,
///     b"../upstream.git",
///     BranchSelection::Default,
///     Reflog::Preserve,
/// )?;
/// // A tight limit stops the transfer; the destination is never created.
/// let cancel = AtomicBool::new(false);
/// let result = request.receive_local(
///     upstream.git_dir(),
///     FetchLimits::default().with_max_objects(1),
///     TransportControl::new(&cancel),
///     |_| ControlFlow::Continue(()),
/// );
/// assert!(matches!(
///     result,
///     Err(CloneTransferError::Transfer(FetchError::Limit(_)))
/// ));
/// assert!(!destination.exists());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CloneTransferError {
    /// Advertisement/default branch could not be selected.
    #[error(transparent)]
    Plan(#[from] ClonePlanError),
    /// Protocol, transport, validation, cancellation or resource limit failure.
    #[error(transparent)]
    Transfer(#[from] FetchError),
}

/// Finish failure preserving completed phases and precise nested publication effects.
///
/// girt never deletes a destination it did not finish. `report.reserved` says whether this
/// operation created the destination directory, and the other report fields say which phases
/// completed, so the caller can decide whether to remove it or leave it for inspection. Fetching
/// into it does not finish it: the configuration, local branch and `HEAD` are published last, and
/// a partially initialized repository needs repair first.
///
/// # Examples
///
/// Cancelling before `finish` creates the destination leaves nothing to clean up:
///
/// ```
/// use std::ops::ControlFlow;
/// use std::sync::atomic::{AtomicBool, Ordering};
///
/// use girt::InitKind;
/// use girt::clone::{BranchSelection, CloneFailure, CloneRequest};
/// use girt::fetch::{FetchError, FetchLimits, FetchUpdateLimits};
/// use girt::refs::Reflog;
/// use girt::transport::TransportControl;
/// # let (directory, upstream, _, _, _) = include!("../doctest/remote.rs");
///
/// let destination = directory.path().join("clone");
/// let request = CloneRequest::prepare_tracking(
///     &destination,
///     InitKind::Worktree,
///     b"../upstream.git",
///     BranchSelection::Default,
///     Reflog::Preserve,
/// )?;
/// let cancel = AtomicBool::new(false);
/// let ready = request.receive_local(
///     upstream.git_dir(),
///     FetchLimits::default(),
///     TransportControl::new(&cancel),
///     |_| ControlFlow::Continue(()),
/// )?;
///
/// cancel.store(true, Ordering::Relaxed);
/// let error = ready
///     .finish(FetchUpdateLimits::default(), &cancel)
///     .unwrap_err();
/// assert!(matches!(
///     error.source,
///     CloneFailure::Verification(FetchError::Cancelled)
/// ));
/// // Decide on cleanup from the report, not by guessing.
/// assert!(!error.report.reserved && !error.report.initialized);
/// assert!(!destination.exists());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[error("clone failed")]
#[non_exhaustive]
pub struct CloneError {
    /// Completed phases; residual state is never automatically removed.
    pub report: Box<CloneReport>,
    /// Failed operation.
    #[source]
    pub source: CloneFailure,
}

/// Preparation or finish phase failure; URL contents are omitted from diagnostics.
///
/// [`CloneRequest::prepare_tracking`] returns these directly; [`CloneReady::finish`] wraps them in
/// a [`CloneError`] with a report of the completed phases.
///
/// - **Before anything is created:** [`Exists`](Self::Exists) (choose another path, or remove the
///   existing one only after confirming it is disposable), [`Url`](Self::Url) (the stored URL is
///   empty or contains NUL or a carriage return) and [`Plan`](Self::Plan) (the branch choice
///   doesn't fit the remote).
/// - **While creating the repository:** [`Io`](Self::Io) and
///   [`Initialization`](Self::Initialization). Partial metadata may remain if the report says the
///   destination was reserved.
/// - **While fetching into it:** [`FetchPlan`](Self::FetchPlan) and [`Fetch`](Self::Fetch) (with
///   its own [`FetchFinishError`] report).
/// - **In more than one phase:** [`Open`](Self::Open) reopening the repository, which happens after
///   the fetch and again at the very end, so the clone may be fully published.
///   [`Verification`](Self::Verification) covers cancellation, which is checked before creation and
///   between later phases, failures reading the installed objects, and a fetched branch whose tip
///   is not a commit. For these, the [`CloneReport`] says what completed.
/// - **While finishing:** [`Configuration`](Self::Configuration), [`Reference`](Self::Reference),
///   [`PackRefs`](Self::PackRefs), [`Objects`](Self::Objects) and
///   [`Publication`](Self::Publication). The objects and remote-tracking references are in place;
///   the origin configuration, local branch or `HEAD` may be missing.
///
/// # Examples
///
/// An existing destination is refused before anything is written:
///
/// ```
/// use girt::InitKind;
/// use girt::clone::{BranchSelection, CloneFailure, CloneRequest};
/// use girt::refs::Reflog;
///
/// let directory = tempfile::tempdir()?;
/// let result = CloneRequest::prepare_tracking(
///     directory.path(),
///     InitKind::Worktree,
///     b"https://example.com/project.git",
///     BranchSelection::Default,
///     Reflog::Preserve,
/// );
/// assert!(matches!(result, Err(CloneFailure::Exists(_))));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CloneFailure {
    /// Existing files/directories/symlinks are not accepted.
    #[error("clone destination already exists: {0}")]
    Exists(PathBuf),
    /// Stored URL must be nonempty without NUL or carriage return.
    #[error("invalid stored clone URL")]
    Url,
    /// Branch/advertisement policy failed.
    #[error(transparent)]
    Plan(#[from] ClonePlanError),
    /// Destination reservation I/O failed.
    #[error("clone destination")]
    Io(#[from] std::io::Error),
    /// Minimal initialization failed; partial metadata may remain.
    #[error(transparent)]
    Initialization(#[from] crate::InitError),
    /// Repository reopening failed.
    #[error(transparent)]
    Open(#[from] crate::OpenError),
    /// Fetch preparation failed after initialization.
    #[error(transparent)]
    FetchPlan(#[from] FetchPlanError),
    /// Fetch install/publication failed; includes its own partial-state report.
    #[error(transparent)]
    Fetch(#[from] FetchFinishError),
    /// Cancellation or installed branch-kind verification failed.
    #[error(transparent)]
    Verification(#[from] FetchError),
    /// Config lock, precondition, write or replacement failed; clone did not replace the config.
    #[error("clone configuration")]
    Configuration(#[source] std::io::Error),
    /// Reference store could not be opened.
    #[error(transparent)]
    Reference(#[from] crate::refs::ReferenceError),
    /// Packing fetched refs failed; every fetched ref keeps its value.
    #[error(transparent)]
    PackRefs(#[from] crate::refs::PackRefsError),
    /// Object storage could not be opened to record peeled tags.
    #[error(transparent)]
    Objects(#[from] crate::ObjectReadError),
    /// Final branch/HEAD transaction failed, retaining per-ref/log partial effects.
    #[error(transparent)]
    Publication(#[from] crate::refs::TransactionError),
}

#[cfg(test)]
#[path = "workflow_tests.rs"]
mod tests;