mkit_cli/commands/
show_ref.rs1use std::io::Write;
6
7use clap::Parser;
8use mkit_core::refs;
9
10use crate::clap_shim;
11use crate::exit;
12use crate::format;
13
14#[derive(Debug, Parser)]
15#[command(name = "mkit show-ref", about = "List refs and their object ids.")]
16struct ShowRefOpts {
17 #[arg(long)]
19 heads: bool,
20 #[arg(long)]
22 tags: bool,
23}
24
25#[must_use]
26pub fn run(args: &[String]) -> u8 {
27 let opts = match clap_shim::parse::<ShowRefOpts>("mkit show-ref", args) {
28 Ok(o) => o,
29 Err(code) => return code,
30 };
31 let cwd = match std::env::current_dir() {
32 Ok(p) => p,
33 Err(e) => return emit_err(&format!("cwd: {e}"), exit::NOINPUT),
34 };
35 let layout = match super::resolve_layout(&cwd) {
36 Ok(layout) => layout,
37 Err(code) => return code,
38 };
39
40 let want_heads = opts.heads || !opts.tags;
43 let want_tags = opts.tags || !opts.heads;
44
45 let mut lines: Vec<(String, String)> = Vec::new(); if want_heads {
47 match refs::list_refs(&layout) {
48 Ok(rs) => collect(&mut lines, &rs, "refs/heads/"),
49 Err(e) => return emit_err(&format!("list refs: {e}"), exit::GENERAL_ERROR),
50 }
51 }
52 if want_tags {
53 match refs::list_tags(&layout) {
54 Ok(rs) => collect(&mut lines, &rs, "refs/tags/"),
55 Err(e) => return emit_err(&format!("list tags: {e}"), exit::GENERAL_ERROR),
56 }
57 }
58 if !opts.heads && !opts.tags {
61 match refs::list_remote_names(&layout) {
62 Ok(remotes) => {
63 for remote in remotes {
64 match refs::list_remote_refs(&layout, &remote) {
65 Ok(rs) => {
66 collect(&mut lines, &rs, &format!("refs/remotes/{remote}/"));
67 }
68 Err(e) => {
69 return emit_err(
70 &format!("list remote refs: {e}"),
71 exit::GENERAL_ERROR,
72 );
73 }
74 }
75 }
76 }
77 Err(e) => return emit_err(&format!("list remotes: {e}"), exit::GENERAL_ERROR),
78 }
79 }
80 lines.sort_by(|a, b| a.0.cmp(&b.0));
81
82 let mut stdout = std::io::stdout().lock();
83 for (name, hash) in &lines {
84 let _ = writeln!(stdout, "{hash} {name}");
85 }
86 if lines.is_empty() {
89 exit::GENERAL_ERROR
90 } else {
91 exit::OK
92 }
93}
94
95fn collect(out: &mut Vec<(String, String)>, rs: &[refs::Ref], prefix: &str) {
97 for r in rs {
98 if let Some(h) = &r.hash {
99 out.push((format!("{prefix}{}", r.name), format::hex_hash(h)));
100 }
101 }
102}
103
104use super::error as emit_err;