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::RepositoryLayout;
40use sley_refs::{FileRefStore, RefTarget, RefUpdate};
41use sley_transport::RemoteUrl;
42
43use crate::fetch::{FetchOptions, FetchSource, fetch};
44use crate::{CredentialProvider, ProgressSink};
45
46/// The unborn placeholder branch the destination is initialized on, replaced by
47/// the real checked-out branch; mirrors the CLI's previous clone init.
48const CLONE_UNBORN_BRANCH: &str = "__git_rs_clone_unborn__";
49
50/// How [`clone`] reaches the remote it is cloning from.
51///
52/// The caller resolves the remote (URL rewriting, repository discovery — all
53/// process-state dependent) and hands `clone` a concrete transport.
54pub enum CloneSource {
55    /// A smart-HTTP(S) remote at the given already-resolved URL.
56    Http(RemoteUrl),
57    /// An SSH remote at the given already-resolved URL. Fetched by spawning `ssh`
58    /// (the credential seam is unused — the `ssh` program owns authentication).
59    Ssh(RemoteUrl),
60    /// A native anonymous `git://` remote at the given already-resolved URL.
61    Git(RemoteUrl),
62    /// A local repository served in-process from `git_dir`.
63    Local {
64        /// The remote repository's `$GIT_DIR`.
65        git_dir: PathBuf,
66        /// The remote repository's common `$GIT_DIR` (object format source).
67        common_git_dir: PathBuf,
68    },
69}
70
71/// The clone inputs the library needs for the branch-tracking flow, all resolved
72/// by the caller. The remaining `git clone` knobs (bare/mirror, `--revision`,
73/// templates, config overrides, sparse, separate-git-dir, etc.) stay in the CLI:
74/// the unsupported ones are gated before `clone` is called, and the config-writing
75/// ones run inside the `configure`/`configure_branch` callbacks.
76pub struct CloneOptions<'a> {
77    /// The remote name to configure and track (`--origin`, default `origin`).
78    pub origin: &'a str,
79    /// The branch to create locally and check out (the requested `--branch` or
80    /// the remote's default branch).
81    pub checkout_branch: &'a str,
82    /// The remote's default branch, used to decide whether to point
83    /// `refs/remotes/<origin>/HEAD` at it.
84    pub remote_head_branch: &'a str,
85    /// Whether only `checkout_branch` was fetched (`--single-branch`); when set,
86    /// `refs/remotes/<origin>/HEAD` is only written if the checked-out branch is
87    /// the remote default.
88    pub single_branch: bool,
89    /// Shallow clone depth (`--depth N`): truncate history to `N` commits per tip,
90    /// writing `$GIT_DIR/shallow`. `None` is a full clone. Honored by the HTTP
91    /// and SSH transports and by the in-process local server (`git clone
92    /// --no-local --depth N <path>`); a depth on a plain local clone is
93    /// warned-and-ignored upstream of `clone` by the caller, matching git's
94    /// `is_local` behavior.
95    pub depth: Option<u32>,
96    /// `--shallow-since=<date>` (parsed to an epoch): deepen to commits newer
97    /// than the date. Local in-process transport only.
98    pub deepen_since: Option<i64>,
99    /// `--shallow-exclude=<ref>` values, resolved against the remote.
100    pub deepen_not: Vec<String>,
101    /// The committer identity for the branch-creation and checkout reflog entries.
102    pub committer: Vec<u8>,
103    /// The remote `HEAD` is detached at this commit (no default branch). After
104    /// the fetch the destination checks out this commit detached instead of
105    /// creating `checkout_branch`; `refs/remotes/<origin>/HEAD` is not written.
106    pub detached_head: Option<ObjectId>,
107    /// Partial-clone object filter (`--filter=blob:none`) to apply to the
108    /// clone fetch. Only honored by the in-process local server.
109    pub filter: Option<sley_odb::PackObjectFilter>,
110}
111
112/// The structured result of a [`clone`].
113#[derive(Debug, Clone)]
114pub struct CloneOutcome {
115    /// The destination repository's `$GIT_DIR` (the `.git` directory created by
116    /// the init step). The caller uses it for its post-checkout steps.
117    pub git_dir: PathBuf,
118    /// The object id the local branch was created at (the fetched remote tip).
119    pub branch_oid: ObjectId,
120}
121
122/// Fully resolved inputs for a [`clone`] run.
123pub struct CloneRequest<'a> {
124    /// Destination worktree/repository path.
125    pub destination: &'a Path,
126    /// Destination repository object format.
127    pub format: ObjectFormat,
128    /// Already-resolved clone source.
129    pub source: &'a CloneSource,
130    /// Clone behavior and branch-tracking options.
131    pub options: &'a CloneOptions<'a>,
132}
133
134/// Mutable seams used while cloning.
135pub struct CloneServices<'a> {
136    /// Callback that writes initial repository config and returns the resulting
137    /// config snapshot used for the fetch.
138    pub configure: &'a mut dyn FnMut(&Path) -> Result<GitConfig>,
139    /// Callback that writes local branch upstream config and returns the config
140    /// snapshot used for checkout filtering.
141    pub configure_branch: &'a mut dyn FnMut(&Path, &str) -> Result<GitConfig>,
142    /// Credential source for authenticated transports.
143    pub credentials: &'a mut dyn CredentialProvider,
144    /// Progress sink for fetch progress/prune notices.
145    pub progress: &'a mut dyn ProgressSink,
146}
147
148/// Clone the resolved `source` into a fresh repository at `destination`.
149///
150/// Performs the transport-shaped core the CLI's `clone_http_repository` and the
151/// inline local clone path shared: initializes the repository, invokes
152/// `configure` to let the caller write the new repo's config (returning the
153/// [`GitConfig`] to fetch against), fetches the configured refs (reusing
154/// [`crate::fetch::fetch`] with clone's fixed options), creates the local
155/// `checkout_branch` at its fetched remote tip, invokes `configure_branch` to let
156/// the caller write the branch's upstream config (returning the [`GitConfig`] to
157/// check out against), points `refs/remotes/<origin>/HEAD` at the remote default
158/// branch when appropriate, and checks out the worktree.
159///
160/// `configure` runs right after init (before the fetch) and must return the
161/// repository config; `configure_branch` runs right after the local branch is
162/// created (before the worktree checkout) and must return the config used for
163/// checkout. Splitting the config writes into these callbacks keeps the CLI's
164/// config I/O helpers (which depend on CLI-specific config serialization and
165/// templates) out of the library while preserving their ordering in the flow.
166///
167/// Emits any library-side progress through `progress` and returns the structured
168/// [`CloneOutcome`]; never prints, mutates the process CWD, or returns
169/// `GitError::Exit`. A missing `refs/remotes/<origin>/<checkout_branch>` after the
170/// fetch is reported as [`GitError::NotFound`] for the caller to map (the CLI
171/// turns an explicit `--branch` miss into its own message).
172pub fn clone(request: CloneRequest<'_>, services: CloneServices<'_>) -> Result<CloneOutcome> {
173    let layout = RepositoryLayout::init_at_with_initial_branch(
174        request.destination,
175        request.format,
176        false,
177        CLONE_UNBORN_BRANCH,
178    )?;
179    let git_dir = layout.git_dir;
180
181    let config = (services.configure)(&git_dir)?;
182    let fetch_source = match request.source {
183        #[cfg(feature = "http")]
184        CloneSource::Http(remote) => FetchSource::Http(remote.clone()),
185        #[cfg(not(feature = "http"))]
186        CloneSource::Http(_) => {
187            return Err(GitError::Unsupported(
188                "HTTP transport is not enabled in this build".into(),
189            ));
190        }
191        CloneSource::Ssh(remote) => FetchSource::Ssh(remote.clone()),
192        CloneSource::Git(remote) => FetchSource::Git(remote.clone()),
193        CloneSource::Local {
194            git_dir: remote_git_dir,
195            common_git_dir: remote_common_git_dir,
196        } => FetchSource::Local {
197            git_dir: remote_git_dir.clone(),
198            common_git_dir: remote_common_git_dir.clone(),
199        },
200    };
201    let fetch_options = clone_fetch_options(
202        request.options.depth,
203        request.options.deepen_since,
204        request.options.deepen_not.clone(),
205        request.options.filter,
206    );
207    fetch(
208        crate::fetch::FetchRequest {
209            git_dir: &git_dir,
210            format: request.format,
211            config: &config,
212            remote_name: request.options.origin,
213            source: &fetch_source,
214            refspecs: &[],
215            options: &fetch_options,
216        },
217        crate::fetch::FetchServices {
218            credentials: services.credentials,
219            progress: services.progress,
220        },
221    )?;
222
223    let store = FileRefStore::new(&git_dir, request.format);
224    if let Some(detached) = &request.options.detached_head {
225        sley_worktree::checkout_detached_filtered(
226            request.destination,
227            &git_dir,
228            request.format,
229            detached,
230            request.options.committer.clone(),
231            b"clone: checkout".to_vec(),
232            &config,
233        )?;
234        return Ok(CloneOutcome {
235            git_dir,
236            branch_oid: *detached,
237        });
238    }
239    let remote_branch_ref = format!(
240        "refs/remotes/{}/{}",
241        request.options.origin, request.options.checkout_branch
242    );
243    let branch_oid = match store.read_ref(&remote_branch_ref)? {
244        Some(RefTarget::Direct(oid)) => oid,
245        Some(RefTarget::Symbolic(_)) => {
246            return Err(GitError::Unsupported(
247                "clone remote-tracking branch must be direct".into(),
248            ));
249        }
250        None => {
251            return Err(GitError::reference_not_found(format!(
252                "remote ref {remote_branch_ref}"
253            )));
254        }
255    };
256    store.create_branch(
257        request.options.checkout_branch,
258        branch_oid.clone(),
259        request.options.committer.clone(),
260        format!(
261            "branch: Created from {}/{}",
262            request.options.origin, request.options.checkout_branch
263        )
264        .into_bytes(),
265    )?;
266    // The branch upstream config is written here and the resulting config is used
267    // for the checkout below, matching the CLI's previous order: configure the
268    // branch, point the remote `HEAD`, then read the (now final) config for the
269    // smudge-side checkout filters. Pointing `HEAD` only updates refs, so it does
270    // not change the config `configure_branch` returns.
271    let checkout_config = (services.configure_branch)(&git_dir, request.options.checkout_branch)?;
272    if !request.options.single_branch
273        || request.options.checkout_branch == request.options.remote_head_branch
274    {
275        let mut tx = store.transaction();
276        tx.update(RefUpdate {
277            name: format!("refs/remotes/{}/HEAD", request.options.origin),
278            expected: None,
279            new: RefTarget::Symbolic(format!(
280                "refs/remotes/{}/{}",
281                request.options.origin, request.options.remote_head_branch
282            )),
283            reflog: None,
284        });
285        tx.commit()?;
286    }
287
288    sley_worktree::checkout_branch_filtered(
289        request.destination,
290        &git_dir,
291        request.format,
292        request.options.checkout_branch,
293        request.options.committer.clone(),
294        &checkout_config,
295    )?;
296
297    Ok(CloneOutcome {
298        git_dir,
299        branch_oid,
300    })
301}
302
303/// The fixed [`FetchOptions`] a clone fetch uses: quiet, auto-follow tags, write
304/// `FETCH_HEAD`, the requested shallow `depth`, and otherwise neutral (no prune, no
305/// `--tags`, not a dry run, not appending). Mirrors the options the CLI's clone
306/// paths passed.
307fn clone_fetch_options(
308    depth: Option<u32>,
309    deepen_since: Option<i64>,
310    deepen_not: Vec<String>,
311    filter: Option<sley_odb::PackObjectFilter>,
312) -> FetchOptions {
313    FetchOptions {
314        quiet: true,
315        auto_follow_tags: true,
316        fetch_all_tags: false,
317        prune: false,
318        dry_run: false,
319        append: false,
320        write_fetch_head: true,
321        tag_option_explicit: false,
322        prune_option_explicit: false,
323        depth,
324        merge_src: None,
325        filter,
326        cloning: true,
327        update_shallow: false,
328        deepen_relative: false,
329        deepen_since,
330        deepen_not,
331    }
332}