Skip to main content

sley_remote/
clone.rs

1//! Callable clone orchestration for HTTP(S) and local (`file://`/path) remotes.
2//!
3//! [`clone`] performs the transport-shaped core of `git clone` for the common
4//! branch-tracking case: it initializes the destination repository, fetches from
5//! the resolved remote (reusing the Stage E [`crate::fetch`] machinery), creates
6//! the local branch at the fetched remote tip, points `refs/remotes/<origin>/HEAD`
7//! at the remote default branch, and checks out the worktree (via
8//! [`sley_worktree`]). Everything is taken as explicit parameters — the
9//! destination, the [`ObjectFormat`], the resolved [`CloneSource`], a
10//! [`CloneOptions`], two caller callbacks, and the seam objects
11//! ([`CredentialProvider`], [`ProgressSink`]) — so it never reads process-global
12//! state, mutates the process CWD, parses arguments, or prints.
13//!
14//! Crucially, [`clone`] takes the destination `git_dir` implicitly (from the
15//! init it performs) and drives the fetch against it directly, so there is no
16//! `set_current_dir` dance: the CLI's old clone path chdir'd into the new repo so
17//! its `discover_git_dir`/`ls_remote_resolved_url` helpers would resolve the
18//! freshly-created repository, then restored the CWD. Here the repository and
19//! remote are already resolved by the caller and passed in, so the process CWD is
20//! never touched.
21//!
22//! The CLI keeps everything that is policy or presentation: argument parsing, the
23//! "Cloning into…"/"done." lines and `--depth`/`--filter` warnings, the
24//! unsupported-option gating (bare/mirror, `--revision`, `--shared`/`--reference`,
25//! `--bundle-uri`, SHA-256 over HTTP), and the post-checkout steps
26//! (`--no-checkout` worktree removal, `--sparse`, `--separate-git-dir`). The two
27//! `configure` callbacks let the CLI run its own config-writing helpers (template
28//! application, `remote.<origin>.*`, `-c` overrides, `submodule.active`, branch
29//! upstream) at the right points in the flow while returning the [`GitConfig`]
30//! the next step needs, keeping that CLI-coupled config I/O out of the library.
31//!
32//! SSH clone uses the same [`crate::fetch`] SSH dispatch as fetch; only the
33//! caller-side URL resolution and post-clone presentation stay in the CLI.
34
35use std::path::{Path, PathBuf};
36
37use sley_config::GitConfig;
38use sley_core::{GitError, ObjectFormat, ObjectId, Result};
39use sley_formats::{InitOptions, RefStorageFormat, RepositoryBootstrap};
40use sley_object::{Commit, ObjectType, Tree};
41use sley_odb::{FileObjectDatabase, ObjectReader};
42use sley_refs::{FileRefStore, RefTarget, RefUpdate};
43use sley_transport::RemoteUrl;
44
45use crate::fetch::{FetchOptions, FetchSource, fetch};
46use crate::{CredentialProvider, ProgressSink};
47
48/// The unborn placeholder branch the destination is initialized on, replaced by
49/// the real checked-out branch; mirrors the CLI's previous clone init.
50const CLONE_UNBORN_BRANCH: &str = "__git_rs_clone_unborn__";
51
52/// How [`clone`] reaches the remote it is cloning from.
53///
54/// The caller resolves the remote (URL rewriting, repository discovery — all
55/// process-state dependent) and hands `clone` a concrete transport.
56pub enum CloneSource {
57    /// A smart-HTTP(S) remote at the given already-resolved URL.
58    Http(RemoteUrl),
59    /// An SSH remote at the given already-resolved URL. Fetched by spawning `ssh`
60    /// (the credential seam is unused — the `ssh` program owns authentication).
61    Ssh(RemoteUrl),
62    /// A native anonymous `git://` remote at the given already-resolved URL.
63    Git {
64        remote: RemoteUrl,
65        protocol_v2: bool,
66    },
67    /// A local repository served in-process from `git_dir`.
68    Local {
69        /// The remote repository's `$GIT_DIR`.
70        git_dir: PathBuf,
71        /// The remote repository's common `$GIT_DIR` (object format source).
72        common_git_dir: PathBuf,
73    },
74}
75
76/// The clone inputs the library needs for the branch-tracking flow, all resolved
77/// by the caller. The remaining `git clone` knobs (bare/mirror, `--revision`,
78/// templates, config overrides, sparse, separate-git-dir, etc.) stay in the CLI:
79/// the unsupported ones are gated before `clone` is called, and the config-writing
80/// ones run inside the `configure`/`configure_branch` callbacks.
81pub struct CloneOptions<'a> {
82    /// The remote name to configure and track (`--origin`, default `origin`).
83    pub origin: &'a str,
84    /// The branch to create locally and check out (the requested `--branch` or
85    /// the remote's default branch).
86    pub checkout_branch: &'a str,
87    /// The remote's default branch, used to decide whether to point
88    /// `refs/remotes/<origin>/HEAD` at it.
89    pub remote_head_branch: &'a str,
90    /// Whether only `checkout_branch` was fetched (`--single-branch`); when set,
91    /// `refs/remotes/<origin>/HEAD` is only written if the checked-out branch is
92    /// the remote default.
93    pub single_branch: bool,
94    /// Shallow clone depth (`--depth N`): truncate history to `N` commits per tip,
95    /// writing `$GIT_DIR/shallow`. `None` is a full clone. Honored by the HTTP
96    /// and SSH transports and by the in-process local server (`git clone
97    /// --no-local --depth N <path>`); a depth on a plain local clone is
98    /// warned-and-ignored upstream of `clone` by the caller, matching git's
99    /// `is_local` behavior.
100    pub depth: Option<u32>,
101    /// `--shallow-since=<date>` (parsed to an epoch): deepen to commits newer
102    /// than the date. Local in-process transport only.
103    pub deepen_since: Option<i64>,
104    /// `--shallow-exclude=<ref>` values, resolved against the remote.
105    pub deepen_not: Vec<String>,
106    /// The committer identity for the branch-creation and checkout reflog entries.
107    pub committer: Vec<u8>,
108    /// The remote `HEAD` is detached at this commit (no default branch). After
109    /// the fetch the destination checks out this commit detached instead of
110    /// creating `checkout_branch`; `refs/remotes/<origin>/HEAD` is not written.
111    pub detached_head: Option<ObjectId>,
112    /// Whether clone should populate the worktree. `--no-checkout` still writes
113    /// refs/config but must not hydrate filtered blobs solely for checkout.
114    pub checkout: bool,
115    /// Partial-clone object filter (`--filter=blob:none`) to apply to the
116    /// clone fetch. Only honored by the in-process local server.
117    pub filter: Option<sley_odb::PackObjectFilter>,
118    /// Whether `checkout_branch` came from an explicit `--branch`. When set, a
119    /// missing remote tip for that branch is a hard error ("Remote branch … not
120    /// found"); when unset, a missing tip is an empty/unborn-repository clone.
121    pub branch_explicit: bool,
122    /// Destination repository ref storage format.
123    pub ref_storage: RefStorageFormat,
124    /// SSH command-line shape for the clone's internal fetch, used for
125    /// clone-only flags like `-4`/`-6`.
126    pub ssh_options: Option<crate::ssh::SshTransportOptions>,
127}
128
129/// The structured result of a [`clone`].
130#[derive(Debug, Clone)]
131pub struct CloneOutcome {
132    /// The destination repository's `$GIT_DIR` (the `.git` directory created by
133    /// the init step). The caller uses it for its post-checkout steps.
134    pub git_dir: PathBuf,
135    /// The object id the local branch was created at (the fetched remote tip),
136    /// or `None` when the remote was empty/unborn (no branch was created and
137    /// `HEAD` was left as an unborn symref to `checkout_branch`).
138    pub branch_oid: Option<ObjectId>,
139    /// True when the remote advertised no refs for `checkout_branch` and no
140    /// `--branch`/`--revision` was requested: an empty/unborn-repository clone.
141    /// The caller prints git's "You appear to have cloned an empty repository."
142    /// warning and skips the worktree checkout.
143    pub empty: bool,
144}
145
146/// Fully resolved inputs for a [`clone`] run.
147pub struct CloneRequest<'a> {
148    /// Destination worktree/repository path.
149    pub destination: &'a Path,
150    /// Explicit destination git directory, used by `GIT_WORK_TREE git clone`
151    /// where the command-line directory is the repository admin dir and the
152    /// worktree lives elsewhere.
153    pub git_dir_override: Option<&'a Path>,
154    /// Value to write as `core.worktree` when `git_dir_override` separates the
155    /// admin dir from the checkout root.
156    pub core_worktree: Option<&'a str>,
157    /// Destination repository object format.
158    pub format: ObjectFormat,
159    /// Already-resolved clone source.
160    pub source: &'a CloneSource,
161    /// Clone behavior and branch-tracking options.
162    pub options: &'a CloneOptions<'a>,
163}
164
165/// Mutable seams used while cloning.
166pub struct CloneServices<'a> {
167    /// Callback that writes initial repository config and returns the resulting
168    /// config snapshot used for the fetch.
169    pub configure: &'a mut dyn FnMut(&Path) -> Result<GitConfig>,
170    /// Callback that writes local branch upstream config and returns the config
171    /// snapshot used for checkout filtering.
172    pub configure_branch: &'a mut dyn FnMut(&Path, &str) -> Result<GitConfig>,
173    /// Credential source for authenticated transports.
174    pub credentials: &'a mut dyn CredentialProvider,
175    /// Progress sink for fetch progress/prune notices.
176    pub progress: &'a mut dyn ProgressSink,
177}
178
179/// Clone the resolved `source` into a fresh repository at `destination`.
180///
181/// Performs the transport-shaped core the CLI's `clone_http_repository` and the
182/// inline local clone path shared: initializes the repository, invokes
183/// `configure` to let the caller write the new repo's config (returning the
184/// [`GitConfig`] to fetch against), fetches the configured refs (reusing
185/// [`crate::fetch::fetch`] with clone's fixed options), creates the local
186/// `checkout_branch` at its fetched remote tip, invokes `configure_branch` to let
187/// the caller write the branch's upstream config (returning the [`GitConfig`] to
188/// check out against), points `refs/remotes/<origin>/HEAD` at the remote default
189/// branch when appropriate, and checks out the worktree.
190///
191/// `configure` runs right after init (before the fetch) and must return the
192/// repository config; `configure_branch` runs right after the local branch is
193/// created (before the worktree checkout) and must return the config used for
194/// checkout. Splitting the config writes into these callbacks keeps the CLI's
195/// config I/O helpers (which depend on CLI-specific config serialization and
196/// templates) out of the library while preserving their ordering in the flow.
197///
198/// Emits any library-side progress through `progress` and returns the structured
199/// [`CloneOutcome`]; never prints, mutates the process CWD, or returns
200/// `GitError::Exit`. A missing `refs/remotes/<origin>/<checkout_branch>` after the
201/// fetch is reported as [`GitError::NotFound`] for the caller to map (the CLI
202/// turns an explicit `--branch` miss into its own message).
203pub fn clone(request: CloneRequest<'_>, services: CloneServices<'_>) -> Result<CloneOutcome> {
204    let layout = RepositoryBootstrap::init(InitOptions {
205        git_dir_override: request.git_dir_override.map(Path::to_path_buf),
206        core_worktree: request.core_worktree.map(str::to_string),
207        worktree: request.destination.to_path_buf(),
208        object_format: request.format,
209        object_format_explicit: false,
210        bare: false,
211        initial_branch: CLONE_UNBORN_BRANCH.into(),
212        template_dir: None,
213        copy_template_config: false,
214        separate_git_dir: None,
215        shared_repository: None,
216        ref_storage: request.options.ref_storage,
217        ref_storage_explicit: request.options.ref_storage != RefStorageFormat::Files,
218    })?;
219    let git_dir = layout.git_dir;
220
221    let config = (services.configure)(&git_dir)?;
222    crate::protocol::check_transport_allowed(
223        scheme_for_clone_source(request.source),
224        Some(&config),
225        None,
226    )
227    .map_err(crate::protocol::transport_policy_git_error)?;
228    let fetch_source = match request.source {
229        #[cfg(feature = "http")]
230        CloneSource::Http(remote) => FetchSource::Http(remote.clone()),
231        #[cfg(not(feature = "http"))]
232        CloneSource::Http(_) => {
233            return Err(GitError::Unsupported(
234                "HTTP transport is not enabled in this build".into(),
235            ));
236        }
237        CloneSource::Ssh(remote) => FetchSource::Ssh(remote.clone()),
238        CloneSource::Git {
239            remote,
240            protocol_v2,
241        } => FetchSource::Git {
242            remote: remote.clone(),
243            protocol_v2: *protocol_v2,
244        },
245        CloneSource::Local {
246            git_dir: remote_git_dir,
247            common_git_dir: remote_common_git_dir,
248        } => FetchSource::Local {
249            git_dir: remote_git_dir.clone(),
250            common_git_dir: remote_common_git_dir.clone(),
251        },
252    };
253    let fetch_options = clone_fetch_options(
254        request.options.depth,
255        request.options.deepen_since,
256        request.options.deepen_not.clone(),
257        request.options.filter.clone(),
258        !request.options.checkout,
259        request.options.ssh_options,
260    );
261    fetch(
262        crate::fetch::FetchRequest {
263            git_dir: &git_dir,
264            format: request.format,
265            config: &config,
266            remote_name: request.options.origin,
267            source: &fetch_source,
268            refspecs: &[],
269            options: &fetch_options,
270        },
271        crate::fetch::FetchServices {
272            credentials: services.credentials,
273            progress: services.progress,
274        },
275    )?;
276
277    let store = FileRefStore::new(&git_dir, request.format);
278    if let Some(detached) = &request.options.detached_head {
279        if request.options.checkout {
280            sley_worktree::checkout_detached_filtered(
281                request.destination,
282                &git_dir,
283                request.format,
284                detached,
285                request.options.committer.clone(),
286                b"clone: checkout".to_vec(),
287                &config,
288            )?;
289        } else {
290            let mut tx = store.transaction();
291            tx.update(RefUpdate {
292                name: "HEAD".to_string(),
293                expected: None,
294                new: RefTarget::Direct(*detached),
295                reflog: None,
296            });
297            tx.commit()?;
298        }
299        return Ok(CloneOutcome {
300            git_dir,
301            branch_oid: Some(*detached),
302            empty: false,
303        });
304    }
305    let remote_branch_ref = format!(
306        "refs/remotes/{}/{}",
307        request.options.origin, request.options.checkout_branch
308    );
309    let branch_oid = match store.read_ref(&remote_branch_ref)? {
310        Some(RefTarget::Direct(oid)) => oid,
311        Some(RefTarget::Symbolic(_)) => {
312            return Err(GitError::Unsupported(
313                "clone remote-tracking branch must be direct".into(),
314            ));
315        }
316        None => {
317            // The remote advertised no tip for the branch we are tracking. When
318            // the caller did not request an explicit branch this is an
319            // empty/unborn-repository clone: upstream `builtin/clone.c` warns,
320            // skips the checkout, and leaves `HEAD` as an unborn symref pointing
321            // at the remote's (or local default) branch — `update_head`'s
322            // `unborn` arm. We mirror that by setting `HEAD` and returning a
323            // marker for the CLI to print the warning. An explicit-branch miss
324            // is still a hard error (the CLI maps it to git's "Remote branch …
325            // not found" message).
326            if request.options.branch_explicit {
327                return Err(GitError::reference_not_found(format!(
328                    "remote ref {remote_branch_ref}"
329                )));
330            }
331            let unborn = format!("refs/heads/{}", request.options.checkout_branch);
332            let mut tx = store.transaction();
333            tx.update(RefUpdate {
334                name: "HEAD".to_string(),
335                expected: None,
336                new: RefTarget::Symbolic(unborn),
337                reflog: None,
338            });
339            tx.commit()?;
340            // Install branch upstream config for the unborn branch, matching
341            // git's `install_branch_config` in the unborn path.
342            (services.configure_branch)(&git_dir, request.options.checkout_branch)?;
343            return Ok(CloneOutcome {
344                git_dir,
345                branch_oid: None,
346                empty: true,
347            });
348        }
349    };
350    store.create_branch(
351        request.options.checkout_branch,
352        branch_oid.clone(),
353        request.options.committer.clone(),
354        format!(
355            "branch: Created from {}/{}",
356            request.options.origin, request.options.checkout_branch
357        )
358        .into_bytes(),
359    )?;
360    // The branch upstream config is written here and the resulting config is used
361    // for the checkout below, matching the CLI's previous order: configure the
362    // branch, point the remote `HEAD`, then read the (now final) config for the
363    // smudge-side checkout filters. Pointing `HEAD` only updates refs, so it does
364    // not change the config `configure_branch` returns.
365    let checkout_config = (services.configure_branch)(&git_dir, request.options.checkout_branch)?;
366    if request.options.checkout {
367        fetch_local_partial_clone_checkout_blobs(&request, &git_dir, branch_oid)?;
368    } else {
369        let mut tx = store.transaction();
370        tx.update(RefUpdate {
371            name: "HEAD".to_string(),
372            expected: None,
373            new: RefTarget::Symbolic(format!("refs/heads/{}", request.options.checkout_branch)),
374            reflog: None,
375        });
376        tx.commit()?;
377    }
378    if !request.options.remote_head_branch.is_empty()
379        && (!request.options.single_branch
380        || request.options.checkout_branch == request.options.remote_head_branch
381    ) {
382        let mut tx = store.transaction();
383        tx.update(RefUpdate {
384            name: format!("refs/remotes/{}/HEAD", request.options.origin),
385            expected: None,
386            new: RefTarget::Symbolic(format!(
387                "refs/remotes/{}/{}",
388                request.options.origin, request.options.remote_head_branch
389            )),
390            reflog: None,
391        });
392        tx.commit()?;
393    }
394
395    if request.options.checkout {
396        sley_worktree::checkout_branch_filtered(
397            request.destination,
398            &git_dir,
399            request.format,
400            request.options.checkout_branch,
401            request.options.committer.clone(),
402            &checkout_config,
403        )?;
404    }
405
406    Ok(CloneOutcome {
407        git_dir,
408        branch_oid: Some(branch_oid),
409        empty: false,
410    })
411}
412
413fn scheme_for_clone_source(source: &CloneSource) -> &'static str {
414    match source {
415        CloneSource::Http(remote) => crate::protocol::transport_scheme_for_remote(remote),
416        CloneSource::Ssh(remote) => crate::protocol::transport_scheme_for_remote(remote),
417        CloneSource::Git { remote, .. } => crate::protocol::transport_scheme_for_remote(remote),
418        CloneSource::Local { .. } => "file",
419    }
420}
421
422fn fetch_local_partial_clone_checkout_blobs(
423    request: &CloneRequest<'_>,
424    git_dir: &Path,
425    commit_oid: ObjectId,
426) -> Result<()> {
427    if request.options.filter.is_none() {
428        return Ok(());
429    }
430    let CloneSource::Local {
431        git_dir: remote_git_dir,
432        common_git_dir: remote_common_git_dir,
433    } = request.source
434    else {
435        return Ok(());
436    };
437
438    let remote_db = FileObjectDatabase::from_git_dir(remote_common_git_dir, request.format);
439    let mut wants = Vec::new();
440    collect_checkout_blob_wants(&remote_db, request.format, commit_oid, &mut wants)?;
441    crate::local::install_fetch_pack_via_local_upload_pack(
442        git_dir,
443        remote_git_dir,
444        request.format,
445        wants,
446        None,
447        true,
448        false,
449        Some(sley_odb::PackObjectFilter::BlobNone),
450        false,
451        None,
452    )?;
453    Ok(())
454}
455
456fn collect_checkout_blob_wants(
457    db: &FileObjectDatabase,
458    format: ObjectFormat,
459    commit_oid: ObjectId,
460    wants: &mut Vec<ObjectId>,
461) -> Result<()> {
462    let commit_object = db.read_object(&commit_oid)?;
463    if commit_object.object_type != ObjectType::Commit {
464        return Err(GitError::InvalidObject(format!(
465            "expected commit {commit_oid}, found {}",
466            commit_object.object_type.as_str()
467        )));
468    }
469    let commit = Commit::parse_ref(format, &commit_object.body)?;
470    collect_tree_blob_wants(db, format, commit.tree, wants)
471}
472
473fn collect_tree_blob_wants(
474    db: &FileObjectDatabase,
475    format: ObjectFormat,
476    tree_oid: ObjectId,
477    wants: &mut Vec<ObjectId>,
478) -> Result<()> {
479    let tree_object = db.read_object(&tree_oid)?;
480    if tree_object.object_type != ObjectType::Tree {
481        return Err(GitError::InvalidObject(format!(
482            "expected tree {tree_oid}, found {}",
483            tree_object.object_type.as_str()
484        )));
485    }
486    for entry in Tree::parse(format, &tree_object.body)?.entries {
487        if entry.is_tree() {
488            collect_tree_blob_wants(db, format, entry.oid, wants)?;
489        } else if !entry.is_gitlink() {
490            wants.push(entry.oid);
491        }
492    }
493    Ok(())
494}
495
496/// The fixed [`FetchOptions`] a clone fetch uses: quiet, auto-follow tags, write
497/// `FETCH_HEAD`, the requested shallow `depth`, and otherwise neutral (no prune, no
498/// `--tags`, not a dry run, not appending). Mirrors the options the CLI's clone
499/// paths passed.
500fn clone_fetch_options(
501    depth: Option<u32>,
502    deepen_since: Option<i64>,
503    deepen_not: Vec<String>,
504    filter: Option<sley_odb::PackObjectFilter>,
505    record_promisor_refs: bool,
506    ssh_options: Option<crate::ssh::SshTransportOptions>,
507) -> FetchOptions {
508    FetchOptions {
509        quiet: true,
510        auto_follow_tags: true,
511        fetch_all_tags: false,
512        prune: false,
513        prune_tags: false,
514        dry_run: false,
515        append: false,
516        write_fetch_head: true,
517        tag_option_explicit: false,
518        prune_option_explicit: false,
519        prune_tags_option_explicit: false,
520        refmap: None,
521        depth,
522        merge_srcs: Vec::new(),
523        filter,
524        refetch: false,
525        cloning: true,
526        record_promisor_refs,
527        update_shallow: false,
528        deepen_relative: false,
529        update_head_ok: false,
530        deepen_since,
531        deepen_not,
532        ssh_options,
533    }
534}