larust-cli 0.15.0

A Laravel-shaped web framework for Rust.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! `xr release [--major|--minor|--patch]` - a thin front-end over plain
//! `git`/file commands, the same shape `xr audit`/`xr update` already
//! use over `cargo audit`/`cargo update` - not a new deployment
//! mechanism, and not a git reimplementation. Prepares a release:
//! optionally bumps this app's own `Cargo.toml` version, builds release
//! notes from the commits since the last tag (grouped by this
//! workspace's own commit-type convention - `feat`/`fix`/`refactor`/
//! `perf`/`docs`/`test`/`ci`/`chore`), and creates a local, annotated
//! git tag.
//!
//! **Deliberately never pushes anything, and never deploys anything.**
//! Pushing a tag/branch is visible to everyone else with access to the
//! remote and can't be quietly undone the way a local commit can - this
//! command stops at "ready to push, whenever you decide to," and prints
//! the exact command to run next rather than running it. `xr deploy`
//! (a separate, already-existing command) is still the thing that
//! actually builds and restarts the app - running on whichever machine
//! actually serves it, pulling whatever `git ref` that machine's own
//! remote/checkout points at by then. This command only prepares the
//! *tag*; wiring a server to fetch and deploy automatically on push
//! (git's own `post-receive` hook, "push to deploy") is a separate,
//! already-well-understood pattern this command doesn't need to
//! reinvent - see `docs/deployment-and-desktop-apps.md`.
//!
//! **Why bumping commits before tagging, not just tagging bare**: a tag
//! with no corresponding version bump still works (pass no `--major`/
//! `--minor`/`--patch` flag, and the current `Cargo.toml` version is
//! tagged as-is), but when a bump *is* requested, the changed
//! `Cargo.toml` needs to land in a real commit for the tag to point at
//! something that actually matches the version string it's named after
//! - an uncommitted file change isn't part of any commit's tree at all.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Bump {
    Major,
    Minor,
    Patch,
}

pub fn run(bump: Option<Bump>) -> Result<()> {
    ensure_clean_working_tree()?;

    let cargo_toml_path = Path::new("Cargo.toml");
    anyhow::ensure!(
        cargo_toml_path.is_file(),
        "no Cargo.toml found here (run this from an app's own root)"
    );
    let contents = std::fs::read_to_string(cargo_toml_path)
        .with_context(|| format!("reading {}", cargo_toml_path.display()))?;
    let current_version = read_package_version(&contents).with_context(|| {
        format!(
            "couldn't find a `version = \"...\"` line under [package] in {}",
            cargo_toml_path.display()
        )
    })?;

    // Computed from *current* `HEAD`, before any version-bump commit
    // below - so a bump's own "chore: release vX.Y.Z" commit doesn't
    // show up inside the very notes describing everything since the
    // last release.
    //
    // `git describe` fails outright when there's no tag at all yet (a
    // real, expected case for a project's first release, not an error
    // worth propagating) - falls back to every commit in the repo.
    let last_tag = run_git_output(&["describe", "--tags", "--abbrev=0"]).ok();
    let range = match &last_tag {
        Some(prev) if !prev.trim().is_empty() => format!("{}..HEAD", prev.trim()),
        _ => "HEAD".to_string(),
    };
    let log = run_git_output(&["log", &range, "--pretty=format:%s"])?;
    let notes = release_notes(&log);

    let version = match bump {
        Some(bump) => {
            let bumped = bump_version(&current_version, bump).with_context(|| {
                format!(
                    "Cargo.toml's version {current_version:?} isn't a plain major.minor.patch \
                     triple - bump it by hand instead"
                )
            })?;
            let updated = set_package_version(&contents, &current_version, &bumped)
                .context("found the [package] version line once, then lost it - this is a bug")?;
            std::fs::write(cargo_toml_path, updated)
                .with_context(|| format!("writing {}", cargo_toml_path.display()))?;
            let synced = sync_internal_dependency_versions(&current_version, &bumped)
                .context("failed to sync internal larust-* dependency versions")?;
            if !synced.is_empty() {
                println!(
                    "Synced internal dependency versions in: {}",
                    synced
                        .iter()
                        .map(|p| p.display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                );
            }
            run_git(&["commit", "-am", &format!("chore: release v{bumped}")])
                .context("failed to commit the version bump")?;
            println!("Bumped Cargo.toml: {current_version} -> {bumped}");
            bumped
        }
        None => current_version,
    };

    let tag = format!("v{version}");
    let existing = run_git_output(&["tag", "--list", &tag])?;
    anyhow::ensure!(
        existing.trim().is_empty(),
        "tag {tag} already exists - pass --major/--minor/--patch to release a new version, or \
         delete the existing tag yourself (`git tag -d {tag}`) if this one needs redoing"
    );

    let tag_message = if notes.is_empty() {
        tag.clone()
    } else {
        format!("{tag}\n\n{notes}")
    };
    run_git(&["tag", "-a", &tag, "-m", &tag_message]).context("failed to create the git tag")?;

    println!("\nCreated tag {tag} locally - nothing pushed yet.");
    if !notes.is_empty() {
        println!("\n{notes}");
    }
    println!(
        "\nWhen ready:\n    git push && git push origin {tag}\n\nThen deploy on the server that \
         actually runs this app:\n    xr deploy"
    );

    Ok(())
}

fn ensure_clean_working_tree() -> Result<()> {
    let status = run_git_output(&["status", "--porcelain"])?;
    anyhow::ensure!(
        status.trim().is_empty(),
        "the working tree isn't clean - commit or stash your changes before running `xr release`"
    );
    Ok(())
}

/// Finds the `version = "..."` line inside `Cargo.toml`'s `[package]`
/// table - or, for a pure workspace manifest with no `[package]` section
/// at all (this repository's own root `Cargo.toml`, 31 member crates
/// sharing one version via `version.workspace = true`), `[workspace.
/// package]` instead. Either way, never some dependency's own inline
/// `version = "..."` (`serde = { version = "1" }`), which shares the
/// exact same bare key name a naive whole-file search would match. A
/// small, deliberately narrow line scanner rather than pulling in a
/// `toml`-parsing dependency for reading and rewriting one field - the
/// same "duplicate a few lines rather than add a dependency for them"
/// reasoning this codebase already applies elsewhere (e.g. `model.rs`'s
/// own `now_unix_secs`, ported rather than depending on `larust-queue`
/// for an identical one).
fn package_version_line_index(cargo_toml: &str) -> Option<usize> {
    let mut in_package_section = false;
    for (i, line) in cargo_toml.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') {
            in_package_section = trimmed == "[package]" || trimmed == "[workspace.package]";
            continue;
        }
        if in_package_section && trimmed.starts_with("version") {
            let rest = trimmed["version".len()..].trim_start();
            if rest.starts_with('=') {
                return Some(i);
            }
        }
    }
    None
}

fn extract_quoted_value(line: &str) -> Option<String> {
    let (_, rhs) = line.split_once('=')?;
    let rhs = rhs.trim();
    let rhs = rhs.strip_prefix('"')?;
    let rhs = rhs.strip_suffix('"')?;
    Some(rhs.to_string())
}

fn read_package_version(cargo_toml: &str) -> Option<String> {
    let index = package_version_line_index(cargo_toml)?;
    extract_quoted_value(cargo_toml.lines().nth(index)?)
}

fn set_package_version(cargo_toml: &str, old_version: &str, new_version: &str) -> Option<String> {
    let index = package_version_line_index(cargo_toml)?;
    let old_quoted = format!("\"{old_version}\"");
    let new_quoted = format!("\"{new_version}\"");
    let rewritten: Vec<String> = cargo_toml
        .lines()
        .enumerate()
        .map(|(i, line)| {
            if i == index {
                line.replacen(&old_quoted, &new_quoted, 1)
            } else {
                line.to_string()
            }
        })
        .collect();
    let mut joined = rewritten.join("\n");
    if cargo_toml.ends_with('\n') {
        joined.push('\n');
    }
    Some(joined)
}

/// Companion to bumping `[workspace.package] version` itself: Cargo has
/// no `.workspace = true` shorthand usable from *inside* a `[workspace.
/// dependencies]` table (only from a member's own `[dependencies]`,
/// referencing *its own* `[package]`) - see this repository's root
/// `Cargo.toml`'s own comment on that table. Every internal `larust-* =
/// { path = "...", version = "<old>" }` requirement across the whole
/// workspace is a hardcoded string that has to be kept in sync by hand,
/// or this is a real, not hypothetical, correctness bug waiting to ship:
/// a `^0.5.0` requirement doesn't match a published `0.6.0` at all
/// (semver's own caret-range rule before 1.0), so a freshly-published
/// crate's own internal dependency on a sibling crate would silently
/// keep resolving to the *old*, stale sibling version once published,
/// not the new one sitting right next to it in the same release.
///
/// A no-op (returns an empty list, touches nothing) for a plain
/// scaffolded app's `Cargo.toml`, which has no `crates/` directory and
/// no internal `larust-*` dependencies of its own to keep in sync -
/// this only ever does real work against this repository's own
/// workspace root.
fn sync_internal_dependency_versions(old_version: &str, new_version: &str) -> Result<Vec<PathBuf>> {
    let mut touched = Vec::new();
    if !Path::new("crates").is_dir() {
        return Ok(touched);
    }
    let old_quoted = format!("version = \"{old_version}\"");
    let new_quoted = format!("version = \"{new_version}\"");
    for path in workspace_cargo_toml_paths()? {
        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        if !contents.contains(&old_quoted) {
            continue;
        }
        let rewritten = rewrite_internal_dependency_versions(&contents, &old_quoted, &new_quoted);
        if rewritten != contents {
            std::fs::write(&path, rewritten)
                .with_context(|| format!("writing {}", path.display()))?;
            touched.push(path);
        }
    }
    Ok(touched)
}

/// Every member crate's own `Cargo.toml`, plus the workspace root's -
/// `crates/*/Cargo.toml` is read directly rather than trusting the root
/// manifest's own `members = ["crates/*"]` glob to mean exactly that
/// (it does today, but re-deriving it from the glob string would be
/// more fragile than just listing `crates/`'s real subdirectories).
fn workspace_cargo_toml_paths() -> Result<Vec<PathBuf>> {
    let mut paths = vec![PathBuf::from("Cargo.toml")];
    for entry in std::fs::read_dir("crates").context("reading crates/")? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            let candidate = entry.path().join("Cargo.toml");
            if candidate.is_file() {
                paths.push(candidate);
            }
        }
    }
    Ok(paths)
}

/// Rewrites only a `larust-*` dependency line's `version = "<old>"` - an
/// unrelated third-party dependency (`axum`, `tokio`, ...) happening to
/// share the exact same version *string* by coincidence is explicitly
/// not touched, the identical "narrow line-scanner, not a blind replace"
/// discipline `set_package_version` already applies to the `[package]`/
/// `[workspace.package]` line itself.
fn rewrite_internal_dependency_versions(
    contents: &str,
    old_quoted: &str,
    new_quoted: &str,
) -> String {
    let rewritten: Vec<String> = contents
        .lines()
        .map(|line| {
            if line.trim_start().starts_with("larust-") && line.contains(old_quoted) {
                line.replacen(old_quoted, new_quoted, 1)
            } else {
                line.to_string()
            }
        })
        .collect();
    let mut joined = rewritten.join("\n");
    if contents.ends_with('\n') {
        joined.push('\n');
    }
    joined
}

/// A plain `major.minor.patch` bump - no pre-release/build-metadata
/// handling (`1.2.3-beta.1`, `1.2.3+build5`). `xr new`'s own scaffolded
/// `Cargo.toml` never writes either form, and nothing in this codebase
/// needs them yet to justify the extra parsing surface.
fn bump_version(current: &str, bump: Bump) -> Option<String> {
    let mut parts = current.split('.');
    let major: u64 = parts.next()?.parse().ok()?;
    let minor: u64 = parts.next()?.parse().ok()?;
    let patch: u64 = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }
    Some(match bump {
        Bump::Major => format!("{}.0.0", major + 1),
        Bump::Minor => format!("{major}.{}.0", minor + 1),
        Bump::Patch => format!("{major}.{minor}.{}", patch + 1),
    })
}

/// Groups commit subjects (`git log --pretty=format:%s`, one per line)
/// by this workspace's own commit-type convention - `feat:`/`fix:`/
/// `refactor:`/`perf:`/`docs:`/`test:`/`ci:`/`chore:`. A subject with no
/// such prefix (or a type this convention doesn't name) lands under
/// "Other" rather than being silently dropped - a non-conforming commit
/// message should still be visible in the notes, not invisible because
/// it didn't match a pattern.
fn release_notes(log: &str) -> String {
    const SECTIONS: &[(&str, &str)] = &[
        ("feat", "Features"),
        ("fix", "Fixes"),
        ("refactor", "Refactoring"),
        ("perf", "Performance"),
        ("docs", "Docs"),
        ("test", "Tests"),
        ("ci", "CI"),
        ("chore", "Chores"),
    ];
    let mut grouped: Vec<Vec<&str>> = vec![Vec::new(); SECTIONS.len()];
    let mut other: Vec<&str> = Vec::new();

    for subject in log.lines().map(str::trim).filter(|s| !s.is_empty()) {
        let matched = SECTIONS.iter().enumerate().find_map(|(i, (prefix, _))| {
            subject
                .strip_prefix(prefix)
                .and_then(|rest| rest.strip_prefix(':'))
                .map(|rest| (i, rest.trim()))
        });
        match matched {
            Some((i, rest)) => grouped[i].push(rest),
            None => other.push(subject),
        }
    }

    let mut out = String::new();
    for (i, (_, label)) in SECTIONS.iter().enumerate() {
        if grouped[i].is_empty() {
            continue;
        }
        out.push_str(label);
        out.push_str(":\n");
        for item in &grouped[i] {
            out.push_str("- ");
            out.push_str(item);
            out.push('\n');
        }
        out.push('\n');
    }
    if !other.is_empty() {
        out.push_str("Other:\n");
        for item in &other {
            out.push_str("- ");
            out.push_str(item);
            out.push('\n');
        }
        out.push('\n');
    }
    out.trim_end().to_string()
}

fn run_git(args: &[&str]) -> Result<()> {
    let status = Command::new("git")
        .args(args)
        .status()
        .with_context(|| format!("failed to run git {}", args.join(" ")))?;
    anyhow::ensure!(status.success(), "git {} failed", args.join(" "));
    Ok(())
}

fn run_git_output(args: &[&str]) -> Result<String> {
    let output = Command::new("git")
        .args(args)
        .output()
        .with_context(|| format!("failed to run git {}", args.join(" ")))?;
    anyhow::ensure!(output.status.success(), "git {} failed", args.join(" "));
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_the_package_version_not_a_dependencys_own() {
        let cargo_toml = "[package]\nname = \"demo\"\nversion = \"1.2.3\"\n\n[dependencies]\nserde = { version = \"1.0.0\" }\n";
        assert_eq!(read_package_version(cargo_toml), Some("1.2.3".to_string()));
    }

    #[test]
    fn returns_none_with_no_package_section_at_all() {
        let cargo_toml = "[workspace]\nmembers = [\".\"]\n";
        assert_eq!(read_package_version(cargo_toml), None);
    }

    #[test]
    fn reads_the_workspace_package_version_when_theres_no_plain_package_section() {
        // This repository's own root `Cargo.toml` shape: a pure workspace
        // manifest, no `[package]` at all, 31 member crates sharing one
        // version via `version.workspace = true`.
        let cargo_toml = "[workspace]\nmembers = [\"crates/*\"]\n\n[workspace.package]\nversion = \"0.5.0\"\nedition = \"2021\"\n";
        assert_eq!(read_package_version(cargo_toml), Some("0.5.0".to_string()));
    }

    #[test]
    fn set_package_version_only_touches_the_package_lines_version() {
        let cargo_toml = "[package]\nname = \"demo\"\nversion = \"1.2.3\"\n\n[dependencies]\nserde = { version = \"1.2.3\" }\n";
        let updated = set_package_version(cargo_toml, "1.2.3", "1.3.0").unwrap();
        assert_eq!(
            updated,
            "[package]\nname = \"demo\"\nversion = \"1.3.0\"\n\n[dependencies]\nserde = { version = \"1.2.3\" }\n"
        );
    }

    #[test]
    fn rewrite_internal_dependency_versions_only_touches_larust_dependency_lines() {
        let cargo_toml = "[workspace.package]\nversion = \"0.5.0\"\n\n[workspace.dependencies]\nlarust-core = { path = \"crates/larust-core\", version = \"0.5.0\" }\naxum = { version = \"0.5.0\" }\n";

        let rewritten = rewrite_internal_dependency_versions(
            cargo_toml,
            "version = \"0.5.0\"",
            "version = \"0.6.0\"",
        );

        assert_eq!(
            rewritten,
            "[workspace.package]\nversion = \"0.5.0\"\n\n[workspace.dependencies]\nlarust-core = { path = \"crates/larust-core\", version = \"0.6.0\" }\naxum = { version = \"0.5.0\" }\n",
            "must rewrite the larust-core line, but leave the [workspace.package] version \
             line and an unrelated third-party dependency's own identical-looking version \
             string untouched: {rewritten}"
        );
    }

    #[test]
    fn bump_version_covers_all_three_kinds() {
        assert_eq!(bump_version("1.2.3", Bump::Major).unwrap(), "2.0.0");
        assert_eq!(bump_version("1.2.3", Bump::Minor).unwrap(), "1.3.0");
        assert_eq!(bump_version("1.2.3", Bump::Patch).unwrap(), "1.2.4");
    }

    #[test]
    fn bump_version_rejects_a_non_triple() {
        assert!(bump_version("1.2.3-beta.1", Bump::Patch).is_none());
        assert!(bump_version("1.2", Bump::Patch).is_none());
        assert!(bump_version("not-a-version", Bump::Patch).is_none());
    }

    #[test]
    fn release_notes_groups_by_commit_type_and_keeps_unrecognized_ones() {
        let log = "feat: add widgets\nfix: broken thing\nfeat: add gadgets\nsomething else entirely\nchore: bump deps";
        let notes = release_notes(log);
        assert_eq!(
            notes,
            "Features:\n- add widgets\n- add gadgets\n\nFixes:\n- broken thing\n\nChores:\n- bump deps\n\nOther:\n- something else entirely"
        );
    }

    #[test]
    fn release_notes_is_empty_for_an_empty_log() {
        assert_eq!(release_notes(""), "");
        assert_eq!(release_notes("\n\n"), "");
    }

    #[test]
    fn release_notes_does_not_confuse_a_type_prefixed_word_with_the_real_type() {
        // "fixture: ..." starts with "fix" but isn't the `fix:` type -
        // the required `:` immediately after the bare type name is what
        // this guards against matching.
        let notes = release_notes("fixture: add test data");
        assert_eq!(notes, "Other:\n- fixture: add test data");
    }
}