girt-cli 0.1.0

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
//! `girt config` and `girt remote`: read and edit configuration, manage and query remotes.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::atomic::AtomicBool;

use color_eyre::eyre::{Result, WrapErr as _, bail, eyre};
use girt::Repository;
use girt::config::{ConfigInputs, Origin};
use girt::fetch::{AdvertisementKind, FetchLimits, RemoteDiscovery};
use girt::remote::{Remote, RemoteConfig};
use girt::transport::TransportControl;

use crate::Context;
use crate::common::{display_bytes, stdout, write_line};

/// Installation config files probed in order; the first that exists is the system layer.
const SYSTEM_CONFIG: &[&str] = &[
    "/opt/homebrew/etc/gitconfig",
    "/usr/local/etc/gitconfig",
    "/etc/gitconfig",
];

/// Largest local config file `set`/`unset` will edit.
const MAX_CONFIG_BYTES: usize = 16 << 20;

#[derive(Debug, clap::Subcommand)]
pub enum Command {
    /// Print the effective (last) value of a key (≈ `git config --get`).
    ///
    /// Exits with status 1 when the key is not set.
    Get {
        /// Key as `section.name` or `section.subsection.name`.
        key: String,
    },
    /// List every effective entry as `key=value`, lowest precedence first (≈ `git config --list`).
    ///
    /// Section and variable names are lowercased; subsections keep their case. A valueless
    /// (implicit true) entry prints the key alone.
    List {
        /// Prefix each entry with its origin (`file:<path>` or `command line:`) and a tab.
        #[arg(long)]
        show_origin: bool,
    },
    /// Set a key in the repository's local config file, replacing its last local occurrence.
    Set {
        /// Key as `section.name` or `section.subsection.name`.
        key: String,
        /// New value.
        value: String,
    },
    /// Remove every occurrence of a key from the repository's local config file.
    Unset {
        /// Key as `section.name` or `section.subsection.name`.
        key: String,
    },
}

#[derive(Debug, clap::Subcommand)]
pub enum RemoteCommand {
    /// List configured remotes, one name per line (≈ `git remote [-v]`; `--urls` is `-v`).
    List {
        /// Also print fetch and push URLs (`<name>\t<url> (fetch|push)`).
        #[arg(short, long)]
        urls: bool,
    },
    /// Add a remote that fetches every branch into `refs/remotes/<name>/`.
    Add {
        /// Remote name.
        name: String,
        /// Fetch (and push) URL.
        url: String,
    },
    /// Show a remote's URLs and refspecs.
    Show {
        /// Remote name.
        name: String,
    },
    /// List the references a remote advertises as `<id>\t<ref>` (≈ `git ls-remote`).
    ///
    /// Accepts a configured remote name, a local path, a `file://` URL or an `http(s)://` URL
    /// (anonymous access only). SSH is not supported yet. Peeled annotated tags print as
    /// `<ref>^{}` lines after their tag.
    Heads {
        /// Remote name or URL.
        remote: String,
    },
}

pub fn run(command: Command, context: &Context) -> Result<ExitCode> {
    match command {
        Command::Get { key } => get(&key, context),
        Command::List { show_origin } => list(show_origin, context),
        Command::Set { key, value } => set(&key, &value, context),
        Command::Unset { key } => unset(&key, context),
    }
}

pub fn remote(command: RemoteCommand, context: &Context) -> Result<ExitCode> {
    match command {
        RemoteCommand::List { urls } => remote_list(urls, context),
        RemoteCommand::Add { name, url } => remote_add(&name, &url, context),
        RemoteCommand::Show { name } => remote_show(&name, context),
        RemoteCommand::Heads { remote } => remote_heads(&remote, context),
    }
}

/// Discovers the repository and reopens it with system, global and environment config layers, as
/// Git resolves them.
pub fn configured_repository(context: &Context) -> Result<Repository> {
    let discovered = context.repository()?;
    let system = SYSTEM_CONFIG
        .iter()
        .map(PathBuf::from)
        .find(|path| path.exists());
    let inputs = ConfigInputs::from_environment(system, |name| std::env::var_os(name), 1024)
        .wrap_err("reading config environment")?;
    let path = discovered.worktree().unwrap_or(discovered.git_dir());
    Repository::open_with_config(path, &inputs).wrap_err("opening repository with config")
}

/// Splits `section[.subsection].name` the way Git does: subsection is everything between the
/// first and last dots.
fn split_key(key: &str) -> Result<(&str, Option<&str>, &str)> {
    let (section, rest) = key
        .split_once('.')
        .ok_or_else(|| eyre!("key `{key}` does not contain a section"))?;
    let (subsection, name) = match rest.rsplit_once('.') {
        Some((subsection, name)) => (Some(subsection), name),
        None => (None, rest),
    };
    if section.is_empty() || name.is_empty() {
        bail!("invalid key `{key}`");
    }
    Ok((section, subsection, name))
}

fn get(key: &str, context: &Context) -> Result<ExitCode> {
    let (section, subsection, name) = split_key(key)?;
    let repository = configured_repository(context)?;
    let value = repository
        .config()
        .value(section, subsection.map(str::as_bytes), name);
    let Some(value) = value else {
        return Ok(ExitCode::from(1));
    };
    let mut out = stdout();
    // Git prints an implicit boolean as `true` under `--get`.
    write_line(&mut out, value.unwrap_or(b"true"))?;
    out.flush()?;
    Ok(ExitCode::SUCCESS)
}

fn list(show_origin: bool, context: &Context) -> Result<ExitCode> {
    let repository = configured_repository(context)?;
    let base = repository.worktree().unwrap_or(repository.git_dir());
    let mut out = stdout();
    for entry in repository.config().entries() {
        if show_origin {
            write_origin(&mut out, entry.origin.as_ref(), base)?;
            out.write_all(b"\t")?;
        }
        out.write_all(&entry.section.to_ascii_lowercase())?;
        if let Some(subsection) = &entry.subsection {
            out.write_all(b".")?;
            out.write_all(subsection)?;
        }
        out.write_all(b".")?;
        out.write_all(&entry.name.to_ascii_lowercase())?;
        if let Some(value) = &entry.value {
            out.write_all(b"=")?;
            out.write_all(value)?;
        }
        out.write_all(b"\n")?;
    }
    out.flush()?;
    Ok(ExitCode::SUCCESS)
}

/// Writes Git's `--show-origin` label; files inside the repository are shown relative to it.
fn write_origin(out: &mut impl Write, origin: Option<&Origin>, base: &Path) -> Result<()> {
    let Some(origin) = origin else {
        return Ok(out.write_all(b"command line:")?);
    };
    match &origin.location.path {
        Some(path) => {
            let shown = path.strip_prefix(base).unwrap_or(path);
            write!(out, "file:{}", shown.display())?;
        }
        None => out.write_all(b"command line:")?,
    }
    Ok(())
}

fn set(key: &str, value: &str, context: &Context) -> Result<ExitCode> {
    let (section, subsection, name) = split_key(key)?;
    let subsection = subsection.map(str::as_bytes);
    let repository = context.repository()?;
    let mut edit = repository
        .edit_config(MAX_CONFIG_BYTES)
        .wrap_err("opening local config")?;
    let document = edit.document_mut();
    let last = last_occurrence(document.config(), section, subsection, name);
    match last {
        Some(index) => document.set_value(index, value.as_bytes()),
        None => document.append(section, subsection, name, value.as_bytes()),
    }
    .wrap_err_with(|| format!("setting {key}"))?;
    edit.commit().wrap_err("writing local config")?;
    Ok(ExitCode::SUCCESS)
}

fn unset(key: &str, context: &Context) -> Result<ExitCode> {
    let (section, subsection, name) = split_key(key)?;
    let subsection = subsection.map(str::as_bytes);
    let repository = context.repository()?;
    let mut edit = repository
        .edit_config(MAX_CONFIG_BYTES)
        .wrap_err("opening local config")?;
    let document = edit.document_mut();
    let mut removed = false;
    // Remove from the end so earlier occurrence indexes stay valid.
    while let Some(index) = last_occurrence(document.config(), section, subsection, name) {
        document
            .remove(index)
            .wrap_err_with(|| format!("unsetting {key}"))?;
        removed = true;
    }
    if !removed {
        edit.abort().wrap_err("releasing local config")?;
        // Git exits 5 when there is nothing to unset.
        return Ok(ExitCode::from(5));
    }
    edit.commit().wrap_err("writing local config")?;
    Ok(ExitCode::SUCCESS)
}

/// Index of the last entry matching a key (section and name compared case-insensitively).
fn last_occurrence(
    config: &girt::Config,
    section: &str,
    subsection: Option<&[u8]>,
    name: &str,
) -> Option<usize> {
    config.entries().iter().rposition(|entry| {
        entry.section.eq_ignore_ascii_case(section.as_bytes())
            && entry.subsection.as_deref() == subsection
            && entry.name.eq_ignore_ascii_case(name.as_bytes())
    })
}

/// Finds a configured remote by name.
pub fn find_remote(repository: &Repository, name: &str) -> Result<Remote> {
    Remote::find(repository.config(), name.as_bytes())
        .wrap_err_with(|| format!("reading remote {name}"))?
        .ok_or_else(|| eyre!("no such remote `{name}`"))
}

/// Push URLs as Git reports them: explicit `pushurl`s, else the fetch URLs.
fn push_urls(remote: &Remote) -> &[Vec<u8>] {
    match remote.configured_push_urls() {
        [] => remote.urls(),
        urls => urls,
    }
}

fn remote_list(urls: bool, context: &Context) -> Result<ExitCode> {
    let repository = configured_repository(context)?;
    let mut out = stdout();
    let mut names = Remote::names(repository.config());
    names.sort_unstable();
    for name in names {
        if !urls {
            write_line(&mut out, name)?;
            continue;
        }
        let remote = Remote::find(repository.config(), name)?
            .ok_or_else(|| eyre!("remote {} vanished", display_bytes(name)))?;
        for url in remote.fetch_url().into_iter() {
            write_url(&mut out, name, url, "fetch")?;
        }
        for url in push_urls(&remote) {
            write_url(&mut out, name, url, "push")?;
        }
    }
    out.flush()?;
    Ok(ExitCode::SUCCESS)
}

fn write_url(out: &mut impl Write, name: &[u8], url: &[u8], kind: &str) -> Result<()> {
    out.write_all(name)?;
    out.write_all(b"\t")?;
    out.write_all(url)?;
    writeln!(out, " ({kind})")?;
    Ok(())
}

fn remote_add(name: &str, url: &str, context: &Context) -> Result<ExitCode> {
    let repository = context.repository()?;
    let mut edit = repository
        .edit_config(MAX_CONFIG_BYTES)
        .wrap_err("opening local config")?;
    let fetch = format!("+refs/heads/*:refs/remotes/{name}/*");
    RemoteConfig::new(edit.document_mut())
        .add(name.as_bytes(), url.as_bytes(), &[fetch.as_bytes()])
        .wrap_err_with(|| format!("adding remote {name}"))?;
    edit.commit().wrap_err("writing local config")?;
    Ok(ExitCode::SUCCESS)
}

fn remote_show(name: &str, context: &Context) -> Result<ExitCode> {
    if context.git {
        bail!("--git is not supported for `remote show` (git contacts the remote)");
    }
    let repository = configured_repository(context)?;
    let remote = find_remote(&repository, name)?;
    let mut out = stdout();
    writeln!(out, "name\t{name}")?;
    for url in remote.urls() {
        writeln!(out, "url\t{}", display_bytes(url))?;
    }
    for url in push_urls(&remote) {
        writeln!(out, "pushurl\t{}", display_bytes(url))?;
    }
    for spec in remote.fetch_refspecs().specs() {
        writeln!(out, "fetch\t{}", display_bytes(spec.as_bytes()))?;
    }
    for spec in remote.push_refspecs().specs() {
        writeln!(out, "push\t{}", display_bytes(spec.as_bytes()))?;
    }
    out.flush()?;
    Ok(ExitCode::SUCCESS)
}

fn remote_heads(target: &str, context: &Context) -> Result<ExitCode> {
    // A configured remote name wins; otherwise the argument is a URL or path.
    let url = context
        .repository()
        .ok()
        .and_then(|_| configured_repository(context).ok())
        .and_then(|repository| {
            Remote::find(repository.config(), target.as_bytes())
                .ok()
                .flatten()
                .and_then(|remote| remote.fetch_url().map(<[u8]>::to_vec))
        })
        .map(|url| String::from_utf8_lossy(&url).into_owned())
        .unwrap_or_else(|| target.to_owned());
    let discovery = discover(&url, context.directory())?;
    let mut out = stdout();
    for reference in &discovery.advertisement.refs {
        write!(out, "{}\t", reference.id)?;
        out.write_all(reference.name.as_bytes())?;
        if reference.kind == AdvertisementKind::PeeledHint {
            out.write_all(b"^{}")?;
        }
        out.write_all(b"\n")?;
    }
    out.flush()?;
    Ok(ExitCode::SUCCESS)
}

/// The transport a URL selects.
pub enum Endpoint {
    /// A local repository path.
    Local(PathBuf),
    /// An `http://` or `https://` URL.
    Http(String),
}

/// Classifies a URL or path; local paths are resolved against `base`.
pub fn endpoint(url: &str, base: &Path) -> Result<Endpoint> {
    if url.starts_with("http://") || url.starts_with("https://") {
        return Ok(Endpoint::Http(url.to_owned()));
    }
    if let Some(path) = url.strip_prefix("file://") {
        return Ok(Endpoint::Local(PathBuf::from(path)));
    }
    let scp_like = url
        .split_once(':')
        .is_some_and(|(host, _)| !host.contains('/'));
    if url.contains("://") || scp_like {
        bail!("girt CLI does not support this transport yet (only local paths and HTTP(S))");
    }
    Ok(Endpoint::Local(base.join(url)))
}

/// Builds an anonymous HTTP endpoint.
pub fn http_remote(url: &str) -> Result<girt::transport::http::HttpRemote> {
    girt::transport::http::HttpRemote::new(url, &[], &[]).wrap_err("configuring HTTP remote")
}

/// Runs a future to completion on a fresh multi-threaded runtime.
pub fn block_on<F: Future>(future: F) -> Result<F::Output> {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .wrap_err("starting async runtime")?;
    Ok(runtime.block_on(future))
}

fn discover(url: &str, base: &Path) -> Result<RemoteDiscovery> {
    let cancel = AtomicBool::new(false);
    let control = TransportControl::new(&cancel);
    let limits = FetchLimits::trusted();
    match endpoint(url, base)? {
        Endpoint::Local(path) => girt::fetch::discover_local(&path, limits, control)
            .wrap_err_with(|| format!("listing {}", path.display())),
        Endpoint::Http(url) => {
            let remote = http_remote(&url)?;
            block_on(girt::fetch::discover_http(&remote, limits, control))?
                .wrap_err_with(|| format!("listing {url}"))
        }
    }
}