mkit-cli 0.4.1

The mkit command-line tool: a content-addressed VCS with native attestation support
Documentation
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
//! `mkit tag` — list / create / delete tags.
//!
//! Three creation modes:
//!
//! * **Lightweight** (`mkit tag <name> [<commit>]`): writes a tag ref
//!   pointing straight at the target commit hash. No tag object.
//! * **Annotated** (`mkit tag -a <name> [-m <msg>] [<commit>]`): builds
//!   a [`Tag`] object (target, tagger identity, message, timestamp) and
//!   points the tag ref at the tag-object hash. Unsigned (zero
//!   signature).
//! * **Signed** (`mkit tag -s <name> [-m <msg>] [<commit>]`): an
//!   annotated tag whose 64-byte field is an Ed25519 signature over the
//!   canonical tag signing bytes under the distinct `mkit.tag\0` domain
//!   (SPEC-SIGNING §4a). Verify with `mkit verify <name>`.

use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};

use clap::{Parser, ValueEnum};
use mkit_core::layout::RepoLayout;
use mkit_core::object::{Object, ObjectType, Tag};
use mkit_core::refs;
use mkit_core::serialize;
use mkit_core::store::ObjectStore;

use crate::clap_shim;
use crate::editor::spawn_editor;
use crate::exit;
use crate::format::{self, JsonObject};

const TAG_EDITMSG_TEMPLATE: &str =
    "\n# Write a message for tag.\n# Lines starting with '#' are ignored.\n";

#[derive(Debug, Clone, Copy, ValueEnum)]
enum TagFormat {
    Default,
    Json,
}

#[derive(Debug, Parser)]
#[command(name = "mkit tag", about = "List, create, or delete tags.")]
#[allow(clippy::struct_excessive_bools)] // clap option flags, not a state machine
struct TagOpts {
    /// Delete the named tag instead of creating one.
    #[arg(short = 'd', long)]
    delete: bool,
    /// List tags, optionally filtered by a shell glob pattern
    /// (`mkit tag -l 'v*'`).
    #[arg(short = 'l', long = "list")]
    list: bool,
    /// Create an unsigned annotated tag object.
    #[arg(short = 'a', long)]
    annotate: bool,
    /// Create a signed annotated tag object (implies -a).
    #[arg(short = 's', long)]
    sign: bool,
    /// Tag message. With -a/-s and no -m, `$EDITOR` is launched.
    #[arg(short = 'm', long)]
    message: Option<String>,
    /// Override the tagger Identity for this tag.
    #[arg(long = "author", value_name = "SPEC")]
    author_spec: Option<String>,
    /// Output format. On the list form, JSONL with keys `name`, `hash`,
    /// `annotated`, `signed`; on create/delete, one outcome object.
    #[arg(long, value_enum, default_value = "default")]
    format: TagFormat,
    /// Tag name. Omit to list all tags.
    name: Option<String>,
    /// Commit-ish to tag. Defaults to HEAD.
    target: Option<String>,
}

/// `error(msg, code)` plus, when `json` is set, a `{"ok":false,...}`
/// line on stdout.
fn emit_err_json(msg: &str, code: u8, json: bool) -> u8 {
    if json {
        let mut obj = JsonObject::new();
        obj.field_bool("ok", false).field_str("error", msg);
        let mut stdout = std::io::stdout().lock();
        let _ = writeln!(stdout, "{}", obj.finish());
    }
    emit_err(msg, code)
}

#[must_use]
pub fn run(args: &[String]) -> u8 {
    let opts = match clap_shim::parse::<TagOpts>("mkit tag", args) {
        Ok(o) => o,
        Err(code) => return code,
    };
    let json = matches!(opts.format, TagFormat::Json);
    let cwd = match std::env::current_dir() {
        Ok(p) => p,
        Err(e) => return emit_err(&format!("cwd: {e}"), exit::NOINPUT),
    };
    let layout = match super::resolve_layout(&cwd) {
        Ok(layout) => layout,
        Err(code) => return code,
    };

    // -s implies -a (a signed tag is an annotated tag with a signature).
    let annotated = opts.annotate || opts.sign;

    // `-l`/`--list` forces list mode, with the positional treated as a
    // glob filter (like `git tag -l '<pattern>'`). `-l` with `-d` is an
    // error, like git (the modes are mutually exclusive).
    if opts.list {
        if opts.delete {
            return super::usage_error("mkit tag: -l and -d are mutually exclusive");
        }
        return list(&layout, opts.name.as_deref(), json);
    }

    match (opts.delete, opts.name.as_deref()) {
        (true, Some(name)) => {
            let was = refs::read_tag(&layout, name).ok().flatten();
            match refs::delete_tag(&layout, name) {
                Ok(()) => {
                    let mut stderr = std::io::stderr().lock();
                    match was {
                        Some(h) => {
                            let _ = writeln!(
                                stderr,
                                "Deleted tag '{name}' (was {})",
                                format::short_hash(&h, format::SUMMARY_ABBREV)
                            );
                        }
                        None => {
                            let _ = writeln!(stderr, "Deleted tag '{name}'");
                        }
                    }
                    drop(stderr);
                    if json {
                        let mut obj = JsonObject::new();
                        obj.field_bool("ok", true)
                            .field_str("kind", "deleted")
                            .field_str("name", name)
                            .field_opt_hash("hash", was.as_ref());
                        let mut stdout = std::io::stdout().lock();
                        let _ = writeln!(stdout, "{}", obj.finish());
                    }
                    exit::OK
                }
                Err(e) => emit_err_json(
                    &format!("delete tag {name}: {e}"),
                    exit::GENERAL_ERROR,
                    json,
                ),
            }
        }
        (true, None) => super::usage_error("usage: mkit tag -d <name>"),
        (false, None) => {
            if annotated || opts.message.is_some() {
                return super::usage_error("usage: mkit tag -a|-s <name> [-m <msg>] [<commit>]");
            }
            list(&layout, None, json)
        }
        (false, Some(name)) => {
            if annotated {
                create_annotated(&layout, &opts, name, json)
            } else {
                if opts.message.is_some() {
                    return super::usage_error(
                        "the -m flag requires -a or -s (annotated/signed tag)",
                    );
                }
                create_lightweight(&layout, name, opts.target.as_deref(), json)
            }
        }
    }
}

fn list(layout: &RepoLayout, pattern: Option<&str>, json: bool) -> u8 {
    let mut tags = match refs::list_tags(layout) {
        Ok(t) => t,
        Err(e) => return emit_err_json(&format!("list tags: {e}"), exit::GENERAL_ERROR, json),
    };
    if let Some(pat) = pattern {
        tags.retain(|t| super::branch::glob_match(pat, &t.name));
    }
    // Open the store so we can peek at annotated-tag objects. Listing
    // still works if this fails.
    let store = ObjectStore::open(layout).ok();
    let mut stdout = std::io::stdout().lock();
    for t in tags {
        let annotation = t.hash.and_then(|h| {
            let store = store.as_ref()?;
            match store.read_object(&h) {
                Ok(Object::Tag(tag)) => Some(tag.signature != [0u8; 64]),
                _ => None,
            }
        });
        if json {
            let mut obj = JsonObject::new();
            obj.field_str("name", &t.name)
                .field_opt_hash("hash", t.hash.as_ref())
                .field_bool("annotated", annotation.is_some())
                .field_bool("signed", annotation.unwrap_or(false));
            let _ = writeln!(stdout, "{}", obj.finish());
            continue;
        }
        let short = t
            .hash
            .map(|h| format::short_hash(&h, 8))
            .unwrap_or_default();
        let suffix = match annotation {
            Some(true) => "\tsigned",
            Some(false) => "\tannotated",
            None => "",
        };
        let _ = writeln!(stdout, "{} {short}{suffix}", t.name);
    }
    exit::OK
}

/// Resolve the target hash for `target_spec` (or HEAD when `None`).
fn resolve_target(
    store: &ObjectStore,
    layout: &RepoLayout,
    target_spec: Option<&str>,
) -> Result<mkit_core::hash::Hash, (String, u8)> {
    match target_spec {
        Some(spec) => super::revspec::resolve_revision(store, layout, spec)
            .map_err(|e| (format!("{e}"), exit::DATAERR)),
        None => match refs::resolve_head(layout) {
            Ok(Some(h)) => Ok(h),
            _ => Err(("no HEAD commit to tag".to_string(), exit::GENERAL_ERROR)),
        },
    }
}

fn create_lightweight(
    layout: &RepoLayout,
    name: &str,
    target_spec: Option<&str>,
    json: bool,
) -> u8 {
    let emit_err = |msg: &str, code: u8| emit_err_json(msg, code, json);
    let store = match ObjectStore::open(layout) {
        Ok(s) => s,
        Err(e) => return emit_err(&format!("not a mkit repo: {e}"), exit::GENERAL_ERROR),
    };
    let h = match resolve_target(&store, layout, target_spec) {
        Ok(h) => h,
        Err((m, c)) => return emit_err(&m, c),
    };
    // A lightweight tag publishes a root ref to an existing object, so it is
    // also a gc root publisher: hold the lock and re-verify the target under
    // it before writing the ref, so a concurrent `gc --grace-secs 0` can't
    // prune the (possibly unreachable) target between resolve and publish
    // (#267).
    let _lock = match super::acquire_worktree_lock(layout) {
        Ok(l) => l,
        Err(code) => return code,
    };
    if !store.contains(&h) {
        return emit_err(
            &format!(
                "tag target {} no longer exists (pruned concurrently?); aborting",
                format::short_hash(&h, 8)
            ),
            exit::GENERAL_ERROR,
        );
    }
    // `Missing` (issue #206) refuses to silently overwrite an existing
    // tag of the same name.
    match refs::update_tag(layout, name, refs::RefWriteCondition::Missing, &h) {
        Ok(()) => {
            if json {
                let mut obj = JsonObject::new();
                obj.field_bool("ok", true)
                    .field_str("kind", "lightweight")
                    .field_str("name", name)
                    .field_hash("target", &h);
                let mut stdout = std::io::stdout().lock();
                let _ = writeln!(stdout, "{}", obj.finish());
            }
            exit::OK
        }
        Err(refs::RefError::Conflict(_)) => {
            emit_err(&format!("tag '{name}' already exists"), exit::CANTCREAT)
        }
        Err(e) => emit_err(&format!("write tag {name}: {e}"), exit::CANTCREAT),
    }
}

#[allow(clippy::too_many_lines)] // linear flow: resolve + sign + write + report
fn create_annotated(layout: &RepoLayout, opts: &TagOpts, name: &str, json: bool) -> u8 {
    let emit_err = |msg: &str, code: u8| emit_err_json(msg, code, json);
    let store = match ObjectStore::open(layout) {
        Ok(s) => s,
        Err(e) => return emit_err(&format!("not a mkit repo: {e}"), exit::GENERAL_ERROR),
    };
    let cfg = match crate::config::read_or_default(layout) {
        Ok(c) => c,
        Err(e) => return emit_err(&format!("config: {e}"), exit::CONFIG_ERROR),
    };

    // Resolve the target object and remember its type for the tag.
    let target = match resolve_target(&store, layout, opts.target.as_deref()) {
        Ok(h) => h,
        Err((m, c)) => return emit_err(&m, c),
    };
    let target_type = match store.read_object(&target) {
        Ok(o) => o.object_type(),
        Err(e) => return emit_err(&format!("read target: {e}"), exit::NOINPUT),
    };

    // ---- Resolve / prompt for message. ----
    let msg = match &opts.message {
        Some(m) => m.clone(),
        None => match spawn_editor(TAG_EDITMSG_TEMPLATE) {
            Ok(m) if !m.is_empty() => m,
            Ok(_) => return emit_err("empty tag message — aborting", exit::USAGE),
            Err(e) => return emit_err(&format!("editor: {e}"), exit::GENERAL_ERROR),
        },
    };

    // ---- Load signer (also used to derive the tagger fallback). ----
    let mut signer = match super::commit::load_commit_signer(layout, &cfg) {
        Ok(s) => s,
        Err((m, c)) => return emit_err(&m, c),
    };
    let signer_public = match signer.public_key() {
        Ok(p) => p,
        Err((m, c)) => return emit_err(&m, c),
    };
    let tagger = match super::commit::resolve_author(
        opts.author_spec.as_deref(),
        &cfg.user_identity,
        &signer_public,
    ) {
        Ok(id) => id,
        Err(e) => return emit_err(&format!("tagger: {e}"), exit::CONFIG_ERROR),
    };

    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());

    let mut tag = Tag {
        target,
        target_type,
        name: name.as_bytes().to_vec(),
        tagger,
        signer: signer_public,
        message: msg.as_bytes().to_vec(),
        timestamp,
        signature: [0u8; 64],
    };

    if opts.sign {
        match signer.sign_tag(&tag) {
            Ok(sig) => tag.signature = sig,
            Err((m, c)) => return emit_err(&m, c),
        }
    }
    // Annotated-but-unsigned tags keep the zero signature.

    // Hold the repo lock across the tag-object write + ref publish so a
    // concurrent `gc --grace-secs 0` can't prune the just-written tag object
    // before its ref makes it reachable (#267). The repo was validated above
    // (store open), so a non-repo already reported cleanly — not as a lock
    // error. Acquired here (after the editor/signing) to keep the hold tight.
    let _lock = match super::acquire_worktree_lock(layout) {
        Ok(l) => l,
        Err(code) => return code,
    };
    // The target was resolved before the lock; re-verify it still exists now
    // that gc can't run, so we never publish a tag pointing at an object a
    // concurrent `gc --grace-secs 0` pruned in the meantime (#267).
    if !store.contains(&target) {
        return emit_err(
            &format!(
                "tag target {} no longer exists (pruned concurrently?); aborting",
                format::short_hash(&target, 8)
            ),
            exit::GENERAL_ERROR,
        );
    }

    let bytes = match serialize::serialize(&Object::Tag(tag)) {
        Ok(b) => b,
        Err(e) => return emit_err(&format!("serialize tag: {e}"), exit::DATAERR),
    };
    let tag_hash = match store.write(&bytes) {
        Ok(h) => h,
        Err(e) => return emit_err(&format!("store tag: {e}"), exit::CANTCREAT),
    };
    match refs::update_tag(layout, name, refs::RefWriteCondition::Missing, &tag_hash) {
        Ok(()) => {}
        Err(refs::RefError::Conflict(_)) => {
            return emit_err(&format!("tag '{name}' already exists"), exit::CANTCREAT);
        }
        Err(e) => return emit_err(&format!("write tag {name}: {e}"), exit::CANTCREAT),
    }
    let mut stderr = std::io::stderr().lock();
    let kind = if opts.sign { "signed" } else { "annotated" };
    let _ = writeln!(
        stderr,
        "created {kind} tag {name} -> {} ({})",
        format::short_hash(&target, 8),
        ObjectType::name(target_type),
    );
    drop(stderr);
    if json {
        let mut obj = JsonObject::new();
        obj.field_bool("ok", true)
            .field_str("kind", kind)
            .field_str("name", name)
            .field_hash("hash", &tag_hash)
            .field_hash("target", &target)
            .field_str("target_type", ObjectType::name(target_type));
        let mut stdout = std::io::stdout().lock();
        let _ = writeln!(stdout, "{}", obj.finish());
    }
    exit::OK
}

use super::error as emit_err;