girt-cli 0.2.11

Command-line tool for inspecting and benchmarking Git repositories with girt
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
//! `girt clone`, `girt fetch` and `girt push`: move objects and refs between repositories.
//!
//! Terminal progress goes to stderr; `--quiet` and `--git` suppress it. Transfer result records
//! on stdout retain girt's format.

use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;

use clap_complete::ArgValueCandidates;
use color_eyre::eyre::{Result, WrapErr as _, bail, eyre};
use girt::clone::CloneHead;
use girt::push::{ForcePolicy, PushCommand, RejectionOrigin, Status};
use girt::refs::RefName;
use girt::remote::RefSource;
use girt::revision::Resolver;
use girt::serve::{Protocol, ReceivePack, UploadLimits, UploadPack};
use girt::workflow::{self, Environment, FetchOptions, PushOptions};
use girt::{InitKind, ObjectId, Repository};

use crate::common::{display_bytes, resolve, resolve_ref, stdout};
use crate::config::find_remote;
use crate::{Context, complete};

/// Copy a repository into a new directory and check out its `HEAD`.
///
/// Supports local paths, `file://`, configured HTTP(S) credentials, and SSH on macOS/Linux.
/// SSH accepts `ssh://` and `[user@]host:path`, normal OpenSSH config and configured commands.
/// Use an agent or askpass for authentication; terminal prompts are unavailable.
/// `--git` suppresses progress but retains girt's result format.
#[derive(Debug, clap::Args)]
pub struct CloneArgs {
    /// Repository to clone.
    url: String,
    /// Destination directory (default: the URL's last component, without `.git`).
    #[arg(value_name = "DIRECTORY")]
    destination: Option<PathBuf>,
    /// Create a bare repository.
    #[arg(long)]
    bare: bool,
    /// Leave the working tree and index empty (`girt checkout HEAD` fills them later).
    #[arg(short, long)]
    no_checkout: bool,
    #[command(flatten)]
    filter: FilterArgs,
}

/// `--filter` and `--no-filter`, shared by clone and fetch.
///
/// As in Git, repeated `--filter` values combine into one `combine:` filter, and `--no-filter`
/// discards the values before it.
#[derive(Debug, Default)]
struct FilterArgs {
    /// Filters given after the last `--no-filter`, in order.
    filters: Vec<girt::fetch::ObjectFilter>,
    /// `--no-filter` appeared after every `--filter`.
    no_filter: bool,
}

impl FilterArgs {
    /// The combined filter, or `None` without one.
    fn filter(&self) -> Option<girt::fetch::ObjectFilter> {
        use girt::fetch::ObjectFilter;
        match self.filters.as_slice() {
            [] => None,
            [one] => Some(one.clone()),
            many => Some(ObjectFilter::Combine(
                many.iter()
                    .flat_map(|filter| match filter {
                        ObjectFilter::Combine(parts) => parts.clone(),
                        other => vec![other.clone()],
                    })
                    .collect(),
            )),
        }
    }
}

impl clap::FromArgMatches for FilterArgs {
    fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
        let mut args = Self::default();
        args.update_from_arg_matches(matches)?;
        Ok(args)
    }

    fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
        // A count flag has a default value; only command-line occurrences clear filters.
        let cleared = (matches.value_source("no_filter")
            == Some(clap::parser::ValueSource::CommandLine))
        .then(|| matches.indices_of("no_filter").and_then(Iterator::max))
        .flatten();
        let values = matches
            .get_many::<girt::fetch::ObjectFilter>("filter")
            .into_iter()
            .flatten();
        let indices = matches.indices_of("filter").into_iter().flatten();
        self.filters = values
            .zip(indices)
            .filter(|(_, index)| cleared.is_none_or(|cleared| *index > cleared))
            .map(|(filter, _)| filter.clone())
            .collect();
        self.no_filter = cleared.is_some() && self.filters.is_empty();
        Ok(())
    }
}

impl clap::Args for FilterArgs {
    fn augment_args(command: clap::Command) -> clap::Command {
        command
            .arg(
                clap::Arg::new("filter")
                    .long("filter")
                    .value_name("SPEC")
                    .action(clap::ArgAction::Append)
                    .value_parser(clap::value_parser!(girt::fetch::ObjectFilter))
                    .help(
                        "Leave out objects the filter matches, such as `blob:none`, and record \
                         the remote as a promisor. Repeated filters combine. Only girt's object \
                         commands fetch the missing objects later; local paths and `file://` \
                         URLs are read directly and ignore the filter",
                    ),
            )
            .arg(
                clap::Arg::new("no_filter")
                    .long("no-filter")
                    .action(clap::ArgAction::Count)
                    .help(
                        "Fetch every object, discarding earlier `--filter` values and the \
                         remote's `partialclonefilter`",
                    ),
            )
    }

    fn augment_args_for_update(command: clap::Command) -> clap::Command {
        Self::augment_args(command)
    }
}

/// Fetch a remote's configured refspecs, printing each updated ref as `<old>..<new> <ref>`.
///
/// New refs print the null ID as `<old>`, pruned refs the null ID as `<new>`. Tags are not
/// followed automatically. Local, HTTP(S) credential helpers and system OpenSSH remotes are
/// supported. Interactive credential and SSH terminal prompts are unavailable. `--git` suppresses
/// progress but retains girt's result format.
#[derive(Debug, clap::Args)]
pub struct FetchArgs {
    /// Configured remote name.
    #[arg(default_value = "origin", add = ArgValueCandidates::new(complete::remotes))]
    remote: String,
    #[command(flatten)]
    filter: FilterArgs,
}

/// Receive pushes into a repository.
#[derive(Debug, clap::Args)]
pub struct ReceivePackArgs {
    /// Repository to receive into.
    directory: PathBuf,
}

/// Serve one receive-pack session on stdin and stdout.
pub fn receive_pack(args: ReceivePackArgs, context: &Context) -> Result<ExitCode> {
    // The receiving repository is trusted; the client's commands and pack are bounded.
    let defaults = girt::push::PushLimits::default();
    let mut limits = girt::push::PushLimits::trusted()
        .with_max_commands(defaults.max_commands)
        .with_max_command_bytes(defaults.max_command_bytes);
    limits.pack = defaults.pack;
    let mut receive =
        ReceivePack::new(&args.directory, context.config_inputs()?).with_limits(limits);
    // Like Git, reflog entries record the receiving process's committer, when it has one.
    let repository = Repository::open_with_config(&args.directory, &context.config_inputs()?)
        .wrap_err_with(|| format!("opening {}", args.directory.display()))?;
    if let Ok(identity) = girt::Signature::committer(repository.config(), &context.environment) {
        receive = receive.with_identity(identity);
    }
    let cancel = std::sync::atomic::AtomicBool::new(false);
    receive
        .serve(
            &mut std::io::stdin().lock(),
            &mut std::io::BufWriter::new(std::io::stdout().lock()),
            &cancel,
        )
        .wrap_err("serving receive-pack")?;
    Ok(ExitCode::SUCCESS)
}

/// Serve fetches from a repository.
#[derive(Debug, clap::Args)]
pub struct UploadPackArgs {
    /// Repository to serve.
    directory: PathBuf,
}

/// Serve one upload-pack session on stdin and stdout.
pub fn upload_pack(args: UploadPackArgs, context: &Context) -> Result<ExitCode> {
    let repository = Repository::open_with_config(&args.directory, &context.config_inputs()?)
        .wrap_err_with(|| format!("opening {}", args.directory.display()))?;
    let protocol = context
        .environment
        .get("GIT_PROTOCOL")
        .map_or(Protocol::V0, |value| {
            Protocol::from_parameters(value.as_encoded_bytes())
        });
    // The served repository is trusted; the client's request isn't.
    let request = UploadLimits::default();
    let limits = UploadLimits::trusted()
        .with_max_request_bytes(request.max_request_bytes)
        .with_max_wants(request.max_wants)
        .with_max_haves(request.max_haves);
    let upload = UploadPack::new(&repository)?.with_limits(limits);
    let cancel = std::sync::atomic::AtomicBool::new(false);
    upload
        .serve(
            protocol,
            &mut std::io::stdin().lock(),
            &mut std::io::BufWriter::new(std::io::stdout().lock()),
            &cancel,
        )
        .wrap_err("serving upload-pack")?;
    Ok(ExitCode::SUCCESS)
}

/// Push refs to a remote, printing `<status>\t<ref>[\t<reason>]` per ref.
///
/// Each refspec is `[+]<src>[:<dst>]`; an empty `<src>` deletes `<dst>`. The remote must still have
/// the value recorded by the matching remote-tracking ref (or not have the ref at all if there is
/// none), like `git push --force-with-lease`; fetch first if the push is rejected as stale. `+`
/// permits non-fast-forward updates. Local, HTTP(S) credential helpers and system OpenSSH remotes
/// are supported. Interactive credential and SSH terminal prompts are unavailable. `--git`
/// suppresses progress but retains girt's result format.
#[derive(Debug, clap::Args)]
pub struct PushArgs {
    /// Configured remote name.
    #[arg(add = ArgValueCandidates::new(complete::remotes))]
    remote: String,
    /// Refspecs to push.
    #[arg(required = true)]
    refspecs: Vec<String>,
}

pub fn clone(args: CloneArgs, context: &Context) -> Result<ExitCode> {
    let directory = match args.destination {
        Some(directory) => directory,
        None => default_directory(&args.url, args.bare)?,
    };
    let destination = std::fs::canonicalize(context.directory())
        .wrap_err_with(|| format!("reading {}", context.directory().display()))?
        .join(directory);
    let filter = args.filter.filter();
    if filter.is_some() && is_plain_path(&args.url) {
        eprintln!("warning: --filter is ignored in local clones; use file:// instead.");
    }
    let mut options = workflow::CloneOptions::default()
        .with_kind(if args.bare {
            InitKind::Bare
        } else {
            InitKind::Worktree
        })
        .with_checkout(!args.no_checkout)
        .with_fetch_limits(girt::fetch::FetchLimits::trusted())
        .with_update_limits(girt::fetch::FetchUpdateLimits::trusted());
    if let Some(filter) = filter.clone() {
        options = options.with_filter(filter);
    }
    let mut progress = crate::progress::Progress::new(context.progress);
    let outcome = workflow::clone_with(
        &args.url,
        &destination,
        &options,
        &context.config_inputs()?,
        &environment(context)?,
        &mut progress,
    )
    .map_err(|error| match &error {
        workflow::CloneError::Checkout { .. }
        | workflow::CloneError::Read { .. }
        | workflow::CloneError::FetchPromised { .. } =>
            eyre!(error).wrap_err(format!(
                "clone completed at {}; inspect files and index before recovery with `girt -C {} checkout HEAD`",
                destination.display(), destination.display(),
            )),
        workflow::CloneError::Finish(_) => eyre!(error).wrap_err(format!(
            "clone installation failed; inspect {} for partial effects", destination.display()
        )),
        _ => eyre!(error).wrap_err("cloning"),
    })?;
    progress.finish();
    if filter.is_some() && !outcome.filter_applied && !is_local(&args.url) {
        eprintln!("warning: filtering not recognized by server, ignoring");
    }
    let report = outcome.clone;
    let mut out = stdout();
    writeln!(out, "cloned into {}", destination.display())?;
    match &report.head {
        CloneHead::Branch { name, id } => {
            writeln!(out, "HEAD -> {} {id}", display_bytes(name.as_bytes()))?;
        }
        CloneHead::Detached(id) => writeln!(out, "HEAD {id} (detached)")?,
        CloneHead::Unborn(name) => {
            writeln!(out, "HEAD -> {} (unborn)", display_bytes(name.as_bytes()))?;
        }
        other => writeln!(out, "HEAD {other:?}")?,
    }
    out.flush()?;
    Ok(ExitCode::SUCCESS)
}

/// A clone source Git treats as a local path rather than a URL, where it ignores `--filter`.
fn is_plain_path(url: &str) -> bool {
    !url.contains("://") && !is_scp_like(url)
}

/// A source girt reads directly: a plain path or a `file://` URL.
fn is_local(url: &str) -> bool {
    url.starts_with("file://") || is_plain_path(url)
}

/// `[user@]host:path`, Git's SSH shorthand: a colon before any slash.
fn is_scp_like(url: &str) -> bool {
    url.find(':')
        .is_some_and(|colon| !url[..colon].contains('/') && colon > 1)
}

/// Git's default clone directory: the last path component, without `.git` unless bare.
fn default_directory(url: &str, bare: bool) -> Result<PathBuf> {
    let trimmed = url.trim_end_matches('/');
    let trimmed = trimmed.strip_suffix("/.git").unwrap_or(trimmed);
    let last = trimmed
        .rsplit(['/', ':'])
        .next()
        .filter(|name| !name.is_empty())
        .ok_or_else(|| eyre!("cannot derive a directory name from `{url}`"))?;
    let stem = last.strip_suffix(".git").unwrap_or(last);
    Ok(PathBuf::from(if bare {
        format!("{stem}.git")
    } else {
        stem.to_owned()
    }))
}

/// Environment for workflow transfers, resolving relative remote paths against `-C`.
fn environment(context: &Context) -> Result<Environment> {
    let directory = std::fs::canonicalize(context.directory())
        .wrap_err_with(|| format!("reading {}", context.directory().display()))?;
    Ok(Environment::from_process().with_current_dir(directory))
}

pub fn fetch(args: FetchArgs, context: &Context) -> Result<ExitCode> {
    let repository = context.repository()?;
    let remote = find_remote(&repository, &args.remote)?;
    let refspecs: Vec<Vec<u8>> = remote
        .fetch_refspecs()
        .specs()
        .iter()
        .map(|spec| spec.as_bytes().to_vec())
        .collect();
    if refspecs.is_empty() {
        bail!("remote {} has no fetch refspecs", args.remote);
    }
    let mut options = FetchOptions::new(refspecs);
    if args.filter.no_filter {
        options = options.without_filter();
    } else if let Some(filter) = args.filter.filter() {
        options = options.with_filter(filter);
    }
    let filtered = !args.filter.no_filter
        && (!args.filter.filters.is_empty()
            || repository
                .config()
                .string("remote", Some(args.remote.as_bytes()), "partialclonefilter")
                .is_some_and(|spec| !spec.is_empty()));
    let mut progress = crate::progress::Progress::new(context.progress);
    let outcome = workflow::fetch(
        &repository,
        &args.remote,
        &options,
        &environment(context)?,
        &mut progress,
    )
    .wrap_err_with(|| format!("fetching {}", args.remote))?;
    progress.finish();
    if filtered && !outcome.filter_applied && !is_local(&remote_url(&remote)) {
        eprintln!("warning: filtering not recognized by server, ignoring");
    }
    let null = ObjectId::null(repository.object_format());
    let mut out = stdout();
    for change in &outcome.updated {
        let old = change.old.unwrap_or(null);
        let new = change.new.unwrap_or(null);
        write!(out, "{old}..{new} ")?;
        out.write_all(change.name.as_bytes())?;
        out.write_all(b"\n")?;
    }
    out.flush()?;
    for source in &outcome.missing_sources {
        eprintln!("warning: remote has no {}", display_bytes(source));
    }
    Ok(ExitCode::SUCCESS)
}

/// The remote's fetch URL as text, or empty when it has none.
fn remote_url(remote: &girt::remote::Remote) -> String {
    remote
        .fetch_url()
        .map(|url| display_bytes(url).into_owned())
        .unwrap_or_default()
}

pub fn push(args: PushArgs, context: &Context) -> Result<ExitCode> {
    let repository = context.repository()?;
    let remote = find_remote(&repository, &args.remote)?;
    let mut commands = Vec::new();
    for refspec in &args.refspecs {
        commands.push(
            push_command(&repository, &remote, refspec)
                .wrap_err_with(|| format!("planning {refspec}"))?,
        );
    }
    let mut progress = crate::progress::Progress::new(context.progress);
    let report = workflow::push(
        &repository,
        &args.remote,
        commands,
        &PushOptions::default(),
        &environment(context)?,
        &mut progress,
    )
    .wrap_err_with(|| format!("pushing to {}", args.remote))?;
    progress.finish();
    let mut out = stdout();
    for reference in &report.refs {
        let name = display_bytes(reference.command.name.as_bytes());
        match &reference.status {
            Some(Status::Ok) => writeln!(out, "ok\t{name}")?,
            Some(Status::Rejected(reason)) => {
                let stale = reference.rejection_origin == Some(RejectionOrigin::ExpectedValue);
                let hint = if stale { " (stale; fetch first)" } else { "" };
                writeln!(out, "rejected\t{name}\t{}{hint}", display_bytes(reason))?;
            }
            Some(other) => writeln!(out, "{other:?}\t{name}")?,
            None => writeln!(out, "not-attempted\t{name}")?,
        }
    }
    out.flush()?;
    Ok(if report.all_succeeded() {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

/// Builds one push command from `[+]<src>[:<dst>]`, leasing on the remote-tracking ref.
fn push_command(
    repository: &Repository,
    remote: &girt::remote::Remote,
    refspec: &str,
) -> Result<PushCommand> {
    let (force, spec) = match refspec.strip_prefix('+') {
        Some(spec) => (ForcePolicy::Allow, spec),
        None => (ForcePolicy::FastForwardOnly, refspec),
    };
    let (source, destination) = match spec.split_once(':') {
        Some((source, destination)) => (source, Some(destination)),
        None => (spec, None),
    };
    let objects = repository.objects()?;
    let source_ref = if source.is_empty() {
        None
    } else {
        Resolver::new(repository, &objects)?
            .expand_ref(source)?
            .map(|(name, _)| name)
    };
    let new = if source.is_empty() {
        ObjectId::null(repository.object_format())
    } else {
        resolve(repository, source)?
    };
    let destination = match (destination, &source_ref) {
        (Some(name), _) if name.starts_with("refs/") => name.to_owned(),
        (Some(name), _) => format!("refs/heads/{name}"),
        (None, Some(name)) if name.as_bytes() != b"HEAD" => {
            display_bytes(name.as_bytes()).into_owned()
        }
        _ => bail!("cannot infer a destination for `{refspec}`; use <src>:<dst>"),
    };
    let name = RefName::new(&destination).wrap_err_with(|| format!("invalid ref {destination}"))?;
    let expected = tracking_value(repository, remote, &name)?;
    Ok(PushCommand::new(name, expected, new).with_force(force))
}

/// The local remote-tracking value for a remote ref, found through the fetch refspecs.
fn tracking_value(
    repository: &Repository,
    remote: &girt::remote::Remote,
    name: &RefName,
) -> Result<Option<ObjectId>> {
    // Mapping needs a nonzero ID; only the destination names matter here.
    let probe = [RefSource {
        name: name.clone(),
        id: ObjectId::for_blob(repository.object_format(), b""),
    }];
    let mappings = remote
        .fetch_refspecs()
        .map(&probe)
        .wrap_err("mapping fetch refspecs")?;
    let references = repository.references().wrap_err("opening references")?;
    for tracking in mappings
        .iter()
        .filter_map(|mapping| mapping.destination.as_ref())
    {
        if let Some(id) = resolve_ref(&references, tracking)? {
            return Ok(Some(id));
        }
    }
    Ok(None)
}