scrat 0.1.3

Release management tooling focused on sanity retention
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
//! Ship command — thin CLI layer over `scrat_core::ship`.

use anyhow::{Context, bail};
use clap::Args;
use indicatif::{ProgressBar, ProgressStyle};
use inquire::{Confirm, Select};
use owo_colors::OwoColorize;
use tracing::{debug, instrument};

use scrat_core::config::Config;
use scrat_core::ship::{self, PhaseOutcome, ShipEvent, ShipOptions, ShipPlan};

/// Arguments for the `ship` subcommand.
#[derive(Args, Debug, Default)]
pub struct ShipArgs {
    /// Set version explicitly (e.g., "1.2.3" or "v1.2.3")
    #[arg(long, value_name = "VERSION")]
    pub version: Option<String>,

    /// Skip changelog generation
    #[arg(long)]
    pub no_changelog: bool,

    /// Skip publishing to registry
    #[arg(long)]
    pub no_publish: bool,

    /// Skip git push (still commits and tags locally)
    #[arg(long)]
    pub no_push: bool,

    /// Skip GitHub release creation
    #[arg(long)]
    pub no_release: bool,

    /// Skip dependency diff
    #[arg(long)]
    pub no_deps: bool,

    /// Skip release statistics collection
    #[arg(long)]
    pub no_stats: bool,

    /// Skip release notes rendering (uses GitHub auto-generated notes)
    #[arg(long)]
    pub no_notes: bool,

    /// Skip running tests
    #[arg(long)]
    pub no_test: bool,

    /// Skip git tag creation (still commits and pushes)
    #[arg(long)]
    pub no_tag: bool,

    /// Skip entire git phase (commit, tag, push)
    #[arg(long)]
    pub no_git: bool,

    /// Skip `git fetch` during preflight (faster startup, may miss
    /// recent remote changes)
    #[arg(long)]
    pub no_fetch: bool,

    /// Create release as draft (overrides config)
    #[arg(long, conflicts_with = "no_draft")]
    pub draft: bool,

    /// Create release as published, not draft (overrides config)
    #[arg(long, conflicts_with = "draft")]
    pub no_draft: bool,

    /// Preview what would happen without making changes
    #[arg(long)]
    pub dry_run: bool,

    /// Skip confirmation prompt
    #[arg(long, short = 'y')]
    pub yes: bool,
}

/// Execute the ship command.
#[instrument(name = "cmd_ship", skip_all)]
pub fn cmd_ship(
    args: ShipArgs,
    global_json: bool,
    config: &Config,
    cwd: &camino::Utf8Path,
) -> anyhow::Result<()> {
    debug!(
        json_output = global_json,
        dry_run = args.dry_run,
        "executing ship command"
    );

    let skip_confirm = args.yes;

    let draft_override = if args.draft {
        Some(true)
    } else if args.no_draft {
        Some(false)
    } else {
        None
    };

    let ship_cfg = config.ship.as_ref();

    let options = ShipOptions {
        explicit_version: args.version,
        no_changelog: args.no_changelog || ship_cfg.and_then(|s| s.no_changelog).unwrap_or(false),
        no_publish: args.no_publish || ship_cfg.and_then(|s| s.no_publish).unwrap_or(false),
        no_push: args.no_push || ship_cfg.and_then(|s| s.no_push).unwrap_or(false),
        no_release: args.no_release || ship_cfg.and_then(|s| s.no_release).unwrap_or(false),
        no_deps: args.no_deps || ship_cfg.and_then(|s| s.no_deps).unwrap_or(false),
        no_stats: args.no_stats || ship_cfg.and_then(|s| s.no_stats).unwrap_or(false),
        no_notes: args.no_notes || ship_cfg.and_then(|s| s.no_notes).unwrap_or(false),
        dry_run: args.dry_run,
        no_test: args.no_test || ship_cfg.and_then(|s| s.no_test).unwrap_or(false),
        no_tag: args.no_tag || ship_cfg.and_then(|s| s.no_tag).unwrap_or(false),
        no_git: args.no_git || ship_cfg.and_then(|s| s.no_git).unwrap_or(false),
        no_fetch: args.no_fetch || ship_cfg.and_then(|s| s.no_fetch).unwrap_or(false),
        draft_override,
    };

    let is_dry = options.dry_run;

    // Plan the ship (preflight + version resolution)
    let mut plan = ship::plan_ship(cwd, config, options).context("ship planning failed")?;

    // If ecosystem detection failed, prompt the user to select one
    if let ShipPlan::NeedsEcosystemSelection(selection) = plan {
        let ecosystem =
            super::prompt_ecosystem_selection().context("ecosystem selection failed")?;
        plan = ship::resolve_ecosystem_selection(selection, ecosystem)
            .context("re-planning with selected ecosystem failed")?;
    }

    // Resolve interactive version prompt if needed
    let ready = match plan {
        ShipPlan::Ready(r) => r,
        ShipPlan::NeedsInteraction(interactive) => {
            let chosen = prompt_interactive_version(&interactive)
                .context("interactive version selection failed")?;
            ship::resolve_ship_interaction(interactive, chosen)
        }
        ShipPlan::NeedsEcosystemSelection(_) => {
            bail!("ecosystem selection returned NeedsEcosystemSelection again — this is a bug");
        }
    };

    // Post-version validation (tag existence, etc.)
    let validation_failures = ready.validate();
    if !validation_failures.is_empty() {
        if global_json {
            let json = serde_json::to_string_pretty(&validation_failures)?;
            println!("{json}");
        } else {
            for check in &validation_failures {
                let hint = check
                    .skip_flag
                    .as_ref()
                    .map(|f| format!(" (skip with {f})"))
                    .unwrap_or_default();
                eprintln!(
                    "  {} {}: {}{}",
                    "".red(),
                    check.name.bold(),
                    check.message,
                    hint.dimmed(),
                );
            }
        }
        bail!("validation failed — fix issues above before releasing");
    }

    // Display the plan header
    if !global_json {
        if is_dry {
            println!("\n{}", "DRY RUN — no changes will be made".yellow().bold());
        }
        println!(
            "\n{}: {}{}",
            "Ship".bold(),
            ready.bump.previous.to_string().dimmed(),
            ready.bump.next.to_string().green().bold(),
        );
        println!(
            "{}: {} | {}: {}",
            "Strategy".dimmed(),
            ready.bump.strategy,
            "Ecosystem".dimmed(),
            ready.detection.ecosystem,
        );
        println!();
    }

    // Confirm before executing (unless dry-run, --yes, or config says no)
    if !is_dry && !global_json {
        let config_confirm = config.ship.as_ref().and_then(|s| s.confirm).unwrap_or(true);

        if config_confirm && !skip_confirm {
            print_phase_summary(&ready.options, config);
            let confirmed = Confirm::new("Proceed with release?")
                .with_default(true)
                .prompt()
                .context("confirmation prompt failed")?;
            if !confirmed {
                println!("{}", "Ship cancelled.".yellow());
                return Ok(());
            }
            println!();
        }
    }

    // Execute with progress display
    let outcome = ready
        .execute(cwd, |event| {
            if !global_json {
                handle_event(event, is_dry);
            }
        })
        .context("ship failed")?;

    // Display final summary
    if global_json {
        println!("{}", serde_json::to_string_pretty(&outcome)?);
    } else {
        println!();
        if is_dry {
            println!(
                "{} Dry run complete — {} phases previewed, {} hooks would run",
                "".green(),
                outcome.phases.len(),
                outcome.hooks_run,
            );
        } else {
            print_shipit_squirrel();
            println!(
                "{} Shipped {} ({} phases, {} hooks)",
                "".green().bold(),
                outcome.tag.green().bold(),
                outcome.phases.len(),
                outcome.hooks_run,
            );
        }
    }

    Ok(())
}

/// Handle a ship event for terminal progress display.
fn handle_event(event: ShipEvent, is_dry: bool) {
    match event {
        ShipEvent::PhaseStarted(phase) => {
            let spinner = ProgressBar::new_spinner();
            // The literal template appears in the expect message so a crash
            // report names the specific input indicatif rejected. The `{...}`
            // segments are indicatif's spinner syntax, not format args.
            #[allow(clippy::literal_string_with_formatting_args)]
            let spinner_style = ProgressStyle::with_template("  {spinner:.cyan} {msg}")
                .expect("indicatif must accept literal template '  {spinner:.cyan} {msg}'")
                .tick_strings(&["", "", "", "", "", "", "", "", "", ""]);
            spinner.set_style(spinner_style);
            spinner.set_message(format!("{phase}..."));
            // For now we finish immediately since phases are synchronous.
            // The spinner shows briefly to indicate activity.
            spinner.finish_and_clear();
        }
        ShipEvent::PhaseCompleted(phase, outcome) => match outcome {
            PhaseOutcome::Success { message } => {
                let prefix = if is_dry { "" } else { "" };
                println!(
                    "  {} {} {}",
                    prefix.green(),
                    format!("{phase}").bold(),
                    message.dimmed(),
                );
            }
            PhaseOutcome::Skipped { reason } => {
                println!(
                    "  {} {} {}",
                    "".yellow(),
                    format!("{phase}").bold(),
                    format!("skipped: {reason}").dimmed(),
                );
            }
        },
        ShipEvent::HooksStarted {
            phase,
            count,
            commands,
            will_execute,
        } => {
            if will_execute {
                debug!(%phase, count, "running hooks");
            } else {
                // Dry-run: show what hooks would run
                for cmd in &commands {
                    println!("    {} {}", "hook →".dimmed(), cmd.cyan(),);
                }
            }
        }
        ShipEvent::HooksCompleted { phase, count } => {
            debug!(%phase, count, "hooks completed");
        }
    }
}

/// Display interactive context and prompt the user to pick a version.
fn prompt_interactive_version(
    plan: &ship::InteractiveShip,
) -> anyhow::Result<scrat_core::semver::Version> {
    let ctx = &plan.bump.context;

    // Show recent commits
    if ctx.recent_commits.is_empty() {
        println!("{}", "No commits since last tag.".yellow());
    } else {
        println!("{}", "Recent commits:".bold().underline());
        let display_count = ctx.recent_commits.len().min(10);
        for (hash, subject) in ctx.recent_commits.iter().take(display_count) {
            println!("  {} {}", hash.dimmed(), subject);
        }
        let remaining = ctx.recent_commits.len().saturating_sub(display_count);
        if remaining > 0 {
            println!("  {} ... and {remaining} more", "".dimmed());
        }
        println!();
    }

    // Show current version
    if let Some(ref v) = ctx.current_version {
        println!("{}: {}", "Current version".dimmed(), v);
    } else {
        println!(
            "{}: {}",
            "Current version".dimmed(),
            "none (first release)".yellow()
        );
    }

    // Build selection options
    let options: Vec<String> = ctx
        .candidates
        .iter()
        .map(|c| format!("{} ({})", c.version, c.level))
        .collect();

    if options.is_empty() {
        bail!("no version candidates available");
    }

    let selection = Select::new("Select version:", options)
        .prompt()
        .context("version selection cancelled")?;

    // Parse the version back from the selection
    let version_str = selection
        .split_once(' ')
        .map(|(v, _)| v)
        .unwrap_or(&selection);

    scrat_core::version::parse_version(version_str).context("failed to parse selected version")
}

/// Print a summary of phases and hooks before the confirmation prompt.
fn print_phase_summary(options: &ShipOptions, config: &Config) {
    let phases: &[(&str, bool)] = &[
        ("test", !options.no_test),
        ("bump", true),
        ("publish", !options.no_publish),
        ("git", !options.no_git),
        ("release", !options.no_release),
    ];

    let active: Vec<&str> = phases
        .iter()
        .filter(|(_, on)| *on)
        .map(|(n, _)| *n)
        .collect();
    let skipped: Vec<&str> = phases
        .iter()
        .filter(|(_, on)| !*on)
        .map(|(n, _)| *n)
        .collect();

    print!("  {}: {}", "Phases".dimmed(), active.join(", ").bold());
    if !skipped.is_empty() {
        print!(" {}", format!("(skip: {})", skipped.join(", ")).dimmed());
    }
    println!();

    let hook_count = count_hooks(config);
    if hook_count > 0 {
        println!(
            "  {}: {} hook command{}",
            "Hooks".dimmed(),
            hook_count,
            if hook_count == 1 { "" } else { "s" }
        );
    }

    println!();
}

/// Count total hook commands configured.
fn count_hooks(config: &Config) -> usize {
    let Some(hooks) = config.hooks.as_ref() else {
        return 0;
    };
    [
        hooks.pre_ship.as_ref(),
        hooks.post_ship.as_ref(),
        hooks.pre_test.as_ref(),
        hooks.post_test.as_ref(),
        hooks.pre_bump.as_ref(),
        hooks.post_bump.as_ref(),
        hooks.pre_publish.as_ref(),
        hooks.post_publish.as_ref(),
        hooks.pre_tag.as_ref(),
        hooks.post_tag.as_ref(),
        hooks.pre_release.as_ref(),
        hooks.post_release.as_ref(),
    ]
    .iter()
    .filter_map(|h| h.as_ref())
    .map(|cmds| cmds.len())
    .sum()
}

/// Print the :shipit: squirrel — a scrat tradition.
fn print_shipit_squirrel() {
    println!();

    if !crate::terminal::render_shipit() {
        println!("  {}", ":shipit:".bold());
    }

    println!("  {}", "SHIP IT!".bold());
    println!();
}