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
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
//! `mkit push` — push refs/packs to a remote with CAS safety.
//!
//! Default (no `--all`): push the current branch to its upstream only,
//! with non-fast-forward rejection via CAS (the remote-tracking ref is
//! the lease). `--all` mirrors every `refs/heads/*` (now CAS-safe).
//! `--force` / `--force-with-lease` control the CAS policy; `--dry-run`
//! resolves the plan without contacting the remote.
//!
//! Every endpoint flows through `remote_dispatch::open_trusted`, so the
//! #97 per-endpoint credential gate applies to named remotes too —
//! trust is keyed on the resolved ENDPOINT, never the remote name.

use std::io::Write;

use clap::{Parser, ValueEnum};
use mkit_core::layout::RepoLayout;

use crate::clap_shim;
use crate::config;
use crate::exit;
use crate::format::JsonObject;
use crate::remote_dispatch::{self, PushLease};

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

#[derive(Debug, Parser)]
#[command(
    name = "mkit push",
    about = "Push the current branch to its upstream (or --all branches)."
)]
#[allow(clippy::struct_excessive_bools)]
struct PushOpts {
    /// Remote name to push to (defaults to the branch's upstream remote,
    /// else the configured default remote).
    remote: Option<String>,
    /// Mirror every local branch instead of just the current one.
    #[arg(long)]
    all: bool,
    /// Overwrite the remote branch unconditionally (skip CAS).
    #[arg(short = 'f', long)]
    force: bool,
    /// Record the pushed remote as this branch's upstream, even if one is
    /// already set (`git push -u` / `--set-upstream`).
    #[arg(short = 'u', long = "set-upstream")]
    set_upstream: bool,
    /// Overwrite only if the remote hasn't moved past our last-seen tip.
    #[arg(long)]
    force_with_lease: bool,
    /// Print what would be pushed without contacting the remote.
    #[arg(long)]
    dry_run: bool,
    /// Emit a machine-readable JSON result object to stdout:
    /// `{"ok":true,"remote":"...","endpoint":"...","branch":"...",
    /// "remote_branch":"...","old":"<hex>|null","new":"<hex>",
    /// "forced":<bool>,"up_to_date":<bool>}` on success, or
    /// `{"ok":false,"error":"...","rejected":<bool>,...}` on a
    /// non-fast-forward (CAS) rejection.
    #[arg(long, value_enum, default_value = "default")]
    format: PushFormat,
    /// Suppress transfer progress output on stderr (#711).
    #[arg(short = 'q', long)]
    quiet: bool,
}

#[must_use]
pub fn run(args: &[String]) -> u8 {
    let opts = match clap_shim::parse::<PushOpts>("mkit push", args) {
        Ok(o) => o,
        Err(code) => return code,
    };
    if opts.force && opts.force_with_lease {
        return emit_err(
            "--force and --force-with-lease are mutually exclusive",
            exit::USAGE,
        );
    }
    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,
    };
    let cfg = match config::read_layered(&layout) {
        Ok(c) => c,
        Err(e) => return emit_err(&format!("config: {e}"), exit::CONFIG_ERROR),
    };

    if opts.all {
        push_all(&layout, &cfg, &opts)
    } else {
        push_current(&layout, &cfg, &opts)
    }
}

/// Default push: current branch → its upstream, CAS-protected.
#[allow(clippy::too_many_lines)] // linear flow: resolve + no-op + push + report
fn push_current(layout: &RepoLayout, cfg: &config::LayeredConfig, opts: &PushOpts) -> u8 {
    let json = matches!(opts.format, PushFormat::Json);
    let branch = match mkit_core::refs::read_head(layout) {
        Ok(mkit_core::refs::Head::Branch(b)) => b,
        Ok(mkit_core::refs::Head::Detached(_)) => {
            return emit_err_json(
                "cannot push a detached HEAD; check out a branch first",
                exit::CONFIG_ERROR,
                json,
            );
        }
        Err(e) => return emit_err_json(&format!("read HEAD: {e}"), exit::CONFIG_ERROR, json),
    };

    // Resolve the (remote, remote-branch) to push to. An explicit
    // `mkit push <remote> [branch]`-style positional remote overrides
    // the configured upstream; otherwise fall back to the upstream.
    let (remote_name, remote_branch) = match &opts.remote {
        Some(name) => (name.clone(), branch.clone()),
        None => match config::resolve_upstream(cfg, &branch) {
            Some(up) => (up.remote, up.branch),
            None => {
                return emit_err_json(
                    &format!(
                        "no upstream configured for branch '{branch}' and no default remote; \
                         run `mkit push <remote>` to push it (the upstream will be remembered)"
                    ),
                    exit::CONFIG_ERROR,
                    json,
                );
            }
        },
    };

    let Some(resolved) = config::resolve_remote(cfg, &remote_name) else {
        return emit_err_json(
            &format!(
                "unknown remote '{remote_name}' — add it with `mkit remote add {remote_name} <url>`"
            ),
            exit::CONFIG_ERROR,
            json,
        );
    };

    // Snapshot the local tip and the last-seen remote-tracking ref so we
    // can render git's ref-update summary block and detect a no-op push.
    let local_tip = mkit_core::refs::read_ref(layout, &branch).ok().flatten();
    let old_tracked = mkit_core::refs::read_remote_ref(layout, &resolved.name, &remote_branch)
        .ok()
        .flatten();
    // Nothing to do when the remote-tracking ref already matches the local
    // tip (and we're not forcing). Matches git's `Everything up-to-date`.
    if !opts.force && local_tip.is_some() && local_tip == old_tracked {
        let mut stderr = std::io::stderr().lock();
        let _ = writeln!(stderr, "Everything up-to-date");
        if json {
            let mut obj = JsonObject::new();
            obj.field_bool("ok", true)
                .field_str("remote", &resolved.name)
                .field_str("endpoint", &resolved.endpoint)
                .field_str("branch", &branch)
                .field_str("remote_branch", &remote_branch)
                .field_opt_hash("old", old_tracked.as_ref())
                .field_opt_hash("new", old_tracked.as_ref())
                .field_bool("forced", false)
                .field_bool("up_to_date", true);
            emit_json_stdout(obj);
        }
        return exit::OK;
    }

    let lease = lease_for(opts);
    if opts.dry_run {
        let mut stderr = std::io::stderr().lock();
        let _ = writeln!(
            stderr,
            "(dry-run) would push {branch} -> {}:{remote_branch} ({})",
            resolved.name, resolved.endpoint
        );
        if json {
            let mut obj = JsonObject::new();
            obj.field_bool("ok", true)
                .field_bool("dry_run", true)
                .field_str("remote", &resolved.name)
                .field_str("endpoint", &resolved.endpoint)
                .field_str("branch", &branch)
                .field_str("remote_branch", &remote_branch);
            emit_json_stdout(obj);
        }
        return exit::OK;
    }

    let tx = match remote_dispatch::open_trusted(
        &resolved.endpoint,
        resolved.repo_chosen,
        cfg,
        layout,
    ) {
        Ok(tx) => tx,
        Err(remote_dispatch::DispatchError::UntrustedRemote(msg)) => {
            return emit_err_json(&msg, exit::CONFIG_ERROR, json);
        }
        Err(e) => return emit_err_json(&format!("open remote: {e}"), exit::PROTOCOL_ERROR, json),
    };

    let push_outcome = {
        // Scoped tightly around the transfer call so the progress
        // guard's final `, done.` line lands before the git-shaped
        // `To <url>` / ref-update summary printed below, not after it.
        let _progress = crate::progress::start(
            "Writing objects",
            None,
            crate::progress::should_report(opts.quiet),
        );
        remote_dispatch::push_branch_tracked(
            layout.worktree_root(),
            tx.as_ref(),
            &resolved.name,
            &branch,
            &remote_branch,
            lease,
        )
    };
    match push_outcome {
        Ok(new_tip) => {
            // Remember the upstream so a bare `mkit push` works next
            // time (Git-like first-push convenience). Only persisted
            // when not already set, and never for a detached/forced
            // overwrite of an unrelated branch.
            record_upstream(
                layout,
                cfg,
                &branch,
                &resolved.name,
                &remote_branch,
                opts.set_upstream,
            );
            // git-style ref-update summary block: `To <url>` then one
            // `<old>..<new>` / `* [new branch]` / `+ …(forced)` line.
            // On a store error during the ancestry check, assume a
            // fast-forward (don't mislabel an ordinary push as forced).
            let forced =
                !remote_dispatch::is_fast_forward(layout.worktree_root(), old_tracked, new_tip)
                    .unwrap_or(true);
            let mut stderr = std::io::stderr().lock();
            let _ = writeln!(stderr, "To {}", resolved.endpoint);
            let _ = writeln!(
                stderr,
                "{}",
                crate::format::ref_update_line(
                    old_tracked.as_ref(),
                    &new_tip,
                    &branch,
                    &remote_branch,
                    forced,
                )
            );
            if json {
                let mut obj = JsonObject::new();
                obj.field_bool("ok", true)
                    .field_str("remote", &resolved.name)
                    .field_str("endpoint", &resolved.endpoint)
                    .field_str("branch", &branch)
                    .field_str("remote_branch", &remote_branch)
                    .field_opt_hash("old", old_tracked.as_ref())
                    .field_hash("new", &new_tip)
                    .field_bool("forced", forced)
                    .field_bool("up_to_date", false);
                emit_json_stdout(obj);
            }
            exit::OK
        }
        Err(remote_dispatch::DispatchError::NonFastForwardPush { branch: rejected }) => {
            let mut stderr = std::io::stderr().lock();
            let _ = writeln!(stderr, "To {}", resolved.endpoint);
            let _ = writeln!(
                stderr,
                "{}",
                crate::format::ref_rejected_line(&rejected, &rejected)
            );
            drop(stderr);
            let msg = format!(
                "updates were rejected for '{rejected}' (non-fast-forward); \
                 `mkit fetch` and merge/rebase first, or re-run with --force-with-lease / --force"
            );
            if json {
                let mut obj = JsonObject::new();
                obj.field_bool("ok", false)
                    .field_bool("rejected", true)
                    .field_str("remote", &resolved.name)
                    .field_str("endpoint", &resolved.endpoint)
                    .field_str("branch", &rejected)
                    .field_str("remote_branch", &remote_branch)
                    .field_str("error", &msg);
                emit_json_stdout(obj);
            }
            emit_err(&msg, exit::GENERAL_ERROR)
        }
        Err(remote_dispatch::DispatchError::Interrupted) => {
            emit_err_json("push: interrupted", exit::TEMPFAIL, json)
        }
        Err(e) => emit_err_json(&format!("push: {e}"), exit::GENERAL_ERROR, json),
    }
}

/// `--all`: mirror every local branch to the remote (CAS-safe).
fn push_all(layout: &RepoLayout, cfg: &config::LayeredConfig, opts: &PushOpts) -> u8 {
    let json = matches!(opts.format, PushFormat::Json);
    let remote_name = opts
        .remote
        .clone()
        .unwrap_or_else(|| config::DEFAULT_REMOTE_NAME.to_owned());
    let Some(resolved) = config::resolve_remote(cfg, &remote_name) else {
        return emit_err_json(
            "no remote configured — use `mkit remote add <url>`",
            exit::CONFIG_ERROR,
            json,
        );
    };
    if opts.dry_run {
        let mut stderr = std::io::stderr().lock();
        let _ = writeln!(
            stderr,
            "(dry-run) would mirror all branches to {} ({})",
            resolved.name, resolved.endpoint
        );
        if json {
            let mut obj = JsonObject::new();
            obj.field_bool("ok", true)
                .field_bool("dry_run", true)
                .field_str("remote", &resolved.name)
                .field_str("endpoint", &resolved.endpoint);
            emit_json_stdout(obj);
        }
        return exit::OK;
    }
    let tx = match remote_dispatch::open_trusted(
        &resolved.endpoint,
        resolved.repo_chosen,
        cfg,
        layout,
    ) {
        Ok(tx) => tx,
        Err(remote_dispatch::DispatchError::UntrustedRemote(msg)) => {
            return emit_err_json(&msg, exit::CONFIG_ERROR, json);
        }
        Err(e) => return emit_err_json(&format!("open remote: {e}"), exit::PROTOCOL_ERROR, json),
    };
    let push_outcome = {
        let _progress = crate::progress::start(
            "Writing objects",
            None,
            crate::progress::should_report(opts.quiet),
        );
        remote_dispatch::push_all_with(
            layout.worktree_root(),
            tx.as_ref(),
            Some(&resolved.name),
            opts.force,
        )
    };
    match push_outcome {
        Ok(n) => {
            let mut stderr = std::io::stderr().lock();
            let _ = writeln!(
                stderr,
                "pushed {n} ref(s) to {} ({})",
                resolved.name, resolved.endpoint
            );
            if json {
                let mut obj = JsonObject::new();
                obj.field_bool("ok", true)
                    .field_str("remote", &resolved.name)
                    .field_str("endpoint", &resolved.endpoint)
                    .field_u64("ref_count", n as u64);
                emit_json_stdout(obj);
            }
            exit::OK
        }
        Err(remote_dispatch::DispatchError::NonFastForwardPush { branch }) => {
            let msg = format!(
                "updates were rejected for '{branch}' (non-fast-forward); \
                 `mkit fetch` first, or re-run with --force"
            );
            if json {
                let mut obj = JsonObject::new();
                obj.field_bool("ok", false)
                    .field_bool("rejected", true)
                    .field_str("remote", &resolved.name)
                    .field_str("endpoint", &resolved.endpoint)
                    .field_str("branch", &branch)
                    .field_str("error", &msg);
                emit_json_stdout(obj);
            }
            emit_err(&msg, exit::GENERAL_ERROR)
        }
        Err(remote_dispatch::DispatchError::Interrupted) => {
            emit_err_json("push: interrupted", exit::TEMPFAIL, json)
        }
        Err(e) => emit_err_json(&format!("push: {e}"), exit::GENERAL_ERROR, json),
    }
}

/// Consume a [`JsonObject`] and print it as one line to stdout.
fn emit_json_stdout(obj: JsonObject) {
    let mut stdout = std::io::stdout().lock();
    let _ = writeln!(stdout, "{}", obj.finish());
}

/// `error(msg, code)` plus, when `json` is set, a `{"ok":false,...}`
/// line on stdout — so every exit path (not just the documented
/// CAS-rejection shape) leaves `--format=json` callers with a
/// self-contained stdout payload.
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);
        emit_json_stdout(obj);
    }
    emit_err(msg, code)
}

fn lease_for(opts: &PushOpts) -> PushLease {
    if opts.force {
        PushLease::Force
    } else if opts.force_with_lease {
        PushLease::WithLease
    } else {
        PushLease::FastForward
    }
}

/// Persist `branch.<b>.{remote,merge}` after a successful first push, so
/// a subsequent bare `mkit push` resolves the upstream. Best-effort: a
/// write failure is non-fatal (the push already succeeded).
fn record_upstream(
    layout: &RepoLayout,
    cfg: &config::LayeredConfig,
    branch: &str,
    remote: &str,
    remote_branch: &str,
    force: bool,
) {
    // Without `-u`, only record on the FIRST push (git-like convenience);
    // `-u`/`--set-upstream` re-points the upstream even if already set.
    if !force
        && cfg
            .merged
            .branch_upstreams
            .get(branch)
            .is_some_and(|u| !u.remote.is_empty())
    {
        return;
    }
    // Re-read the on-disk REPO config (not the merged view) and add the
    // upstream entry without disturbing the existing remotes / flat
    // fields. Using the repo layer ensures user-scoped values (e.g. a
    // private `user.email`) are never materialized into `.mkit/config`.
    let Ok(layered) = config::read_layered(layout) else {
        return;
    };
    let mut on_disk = layered.repo;
    on_disk.branch_upstreams.insert(
        branch.to_owned(),
        config::Upstream {
            remote: remote.to_owned(),
            branch: remote_branch.to_owned(),
        },
    );
    let _ = config::write(layout, &on_disk);
}

use super::error as emit_err;