jj_release_core 0.11.0

Core library for jj-release: semantic releases for jj-vcs
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Changelog generation

use std::{
    fs,
    io::{self, IsTerminal, Write},
    path::{Path, PathBuf},
};

use jiff::Zoned;
use semver::Version;

use crate::{
    Config, ReleaseContext, Tag, WorkspaceMember, bump,
    commits::{self, CommitInfo},
    config::{Versioning, WorkspaceConfig},
    detect,
    errors::{ReleaseError, Result},
    manifest::{CargoManifest, ManifestBackend},
    workspace,
};

use jj_release_changelog::{self as changelog, ChangelogLayout, ForgeRepo, Release};

// Output targets

/// Where `print_changelog` sends its output.
#[derive(Debug, Clone, Copy)]
pub enum ChangelogOutput<'a> {
    /// Print to stdout.
    Stdout,
    /// Write to this exact file. Root layout only.
    Path(&'a Path),
    /// Write to the configured file(s): `[changelog].file` at the root,
    /// or in each member directory with `layout = "per-member"`.
    Configured,
}

impl ChangelogOutput<'_> {
    /// The root changelog file to write, or `None` to print.
    fn root_file(self, config: &Config, root: &Path) -> Option<PathBuf> {
        match self {
            Self::Stdout => None,
            Self::Path(path) => Some(path.to_path_buf()),
            Self::Configured => Some(root.join(&config.changelog.file)),
        }
    }

    /// `member`'s changelog file to write, or `None` to print.
    /// Only `Configured` writes member files; `--output` names a single file.
    fn member_file(self, root: &Path, member: &WorkspaceMember, file: &str) -> Option<PathBuf> {
        matches!(self, Self::Configured).then(|| member_changelog_path(root, member, file))
    }
}

/// `--output` names a single file, which can't hold per-member changelogs.
fn check_target(config: &Config, target: ChangelogOutput<'_>) -> Result<()> {
    if member_layout_ws(config).is_some() && matches!(target, ChangelogOutput::Path(_)) {
        return Err(ReleaseError::Message(
            "--output writes a single file; with layout = \"per-member\" use --write".into(),
        ));
    }
    Ok(())
}

// Entry points

/// Renders the changelog section(s) for the pending release and prints them
/// or prepends them to the changelog file(s), depending on `target`.
/// With `full`, regenerates the complete changelog instead.
///
/// # Errors
///
/// Returns an error if `target` is a single path but the layout writes member
/// changelogs, or if reading a manifest, listing tags, fetching commit
/// history, or writing a changelog file fails.
pub fn print_changelog(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
    target: ChangelogOutput<'_>,
    full: bool,
) -> Result<()> {
    if full {
        return print_full_changelog(ctx, config, root, target);
    }
    check_target(config, target)?;

    let written = match member_layout_ws(config) {
        None => pending_root(ctx, config, root, target, false)?,
        Some(ws) => {
            let layout = config.changelog.layout;
            let root_count = if layout.includes_root() {
                pending_root(ctx, config, root, target, true)?
            } else {
                0
            };
            // With `Both`, the root changelog already covers a member at ".".
            let skip_root_member = layout == ChangelogLayout::Both;
            root_count + pending_members(ctx, config, root, ws, target, skip_root_member)?
        }
    };

    if written == 0 {
        println!("No changelog entries since the last release.");
    }

    Ok(())
}

/// Generates and outputs a comprehensive changelog from the repository's entire history.
///
///# Errors
///
/// Returns an error if:
/// - The VCS backend fails to list tags or log commits.
/// - The local manifest version cannot be read.
/// - Writing to the provided `output` file fails.
pub fn print_full_changelog(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
    target: ChangelogOutput<'_>,
) -> Result<()> {
    check_target(config, target)?;
    let forge = forge_repo(config, root);

    let Some(ws) = member_layout_ws(config) else {
        return full_root(ctx, config, root, target, forge.as_ref());
    };
    let includes_root = config.changelog.layout.includes_root();
    if includes_root {
        full_root(ctx, config, root, target, forge.as_ref())?;
    }

    let file = &config.changelog.file;
    for member in &ws.members {
        if includes_root && is_root_member(member) {
            continue;
        }
        let prefix = member_tag_prefix(config, ws, member);
        let fileset = workspace::member_fileset(member, &ws.members);
        let content = build_full_changelog(ctx, config, prefix, Some(&fileset), forge.as_ref())?;

        let header = member_display_path(member, file);
        emit(
            target.member_file(root, member, file).as_deref(),
            Some(&header),
            &content,
            WriteMode::Replace,
        )?;
    }

    Ok(())
}

/// A compare link from `prev` to `next`, or to the tip when `next` is `None`.
/// `None` without a forge repo or a previous release to compare against.
fn compare_link(
    forge: Option<&ForgeRepo>,
    prev: Option<&Version>,
    next: Option<&Version>,
    prefix: &str,
) -> Option<String> {
    Some(forge?.compare_link(prev?, next, prefix))
}

// Pending release

struct PendingChanges {
    latest: Option<Tag>,
    commits: Vec<CommitInfo>,
}

impl PendingChanges {
    /// Commits since the latest `prefix` tag (or all history before the first
    /// release), optionally limited to those touching `fileset`.
    fn since_last_tag(
        ctx: &ReleaseContext<'_>,
        prefix: &str,
        fileset: Option<&str>,
    ) -> Result<Self> {
        let latest = commits::latest_version_tag(ctx.backend, prefix)?;
        let since = commits::since_revision(latest.as_ref());
        let commits = log_commits(ctx, &format!("{since}..@"), fileset)?;
        Ok(Self { latest, commits })
    }

    fn latest_version(&self) -> Option<&Version> {
        self.latest.as_ref().map(|tag| &tag.version)
    }

    /// The version the pending section is headed with: `None` renders
    /// `[Unreleased]` (the manifest hasn't been bumped past the latest tag),
    /// `Some` is the next version.
    fn next_version(&self, current: &Version, config: &Config) -> Option<Version> {
        let latest = self.latest_version();
        if latest.is_some_and(|latest| current <= latest) {
            return None;
        }
        // A pre-release manifest is chosen with `--pre`, not computed from commits.
        if !current.pre.is_empty() {
            return Some(current.clone());
        }
        let bump = commits::initial_development_bump(
            commits::compute_bump(&self.commits),
            latest.unwrap_or(current),
            config.bump.features_bump_patch_before_1_0,
        );
        Some(bump::next_version(latest, current, bump))
    }
}

/// Repo-wide changes since the last `release.tag_prefix` tag, with the
/// version they'd release as.
fn repo_pending(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
) -> Result<(PendingChanges, Option<Version>)> {
    let current = ctx.manifest.read_version(root)?;
    let pending = PendingChanges::since_last_tag(ctx, &config.release.tag_prefix, None)?;
    let version = pending.next_version(&current, config);
    Ok((pending, version))
}

/// Changes to `member` since its own last tag.
fn member_pending(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    ws: &WorkspaceConfig,
    member: &WorkspaceMember,
) -> Result<PendingChanges> {
    let fileset = workspace::member_fileset(member, &ws.members);
    PendingChanges::since_last_tag(ctx, member_tag_prefix(config, ws, member), Some(&fileset))
}

/// The root changelog section: one section for a single crate or unified
/// workspace, or named per-member sections for an independent workspace.
fn pending_root(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
    target: ChangelogOutput<'_>,
    show_header: bool,
) -> Result<usize> {
    if let Some(ws) = independent_ws(config) {
        return pending_independent_root(ctx, config, root, ws, target, show_header);
    }

    let (pending, version) = repo_pending(ctx, config, root)?;
    let compare_url = compare_link(
        forge_repo(config, root).as_ref(),
        pending.latest_version(),
        version.as_ref(),
        &config.release.tag_prefix,
    );

    let Some(section) = changelog::render_pending_section(
        None,
        &pending.commits,
        version.as_ref(),
        Some(&today()),
        &config.changelog,
        compare_url.as_deref(),
    ) else {
        return Ok(0);
    };

    let header = show_header.then(|| Path::new(&config.changelog.file));
    emit(
        target.root_file(config, root).as_deref(),
        header,
        &section,
        WriteMode::Prepend,
    )?;
    Ok(1)
}

/// Root layout, independent versioning: one named section per member with
/// changes since its own last tag, all in the root changelog.
fn pending_independent_root(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
    ws: &WorkspaceConfig,
    target: ChangelogOutput<'_>,
    show_header: bool,
) -> Result<usize> {
    let today = today();
    let mut sections = Vec::new();

    for member in &ws.members {
        let pending = member_pending(ctx, config, ws, member)?;

        if pending.commits.is_empty() {
            continue;
        }

        let version = pending.next_version(&member_current_version(root, member)?, config);
        sections.extend(changelog::render_pending_section(
            Some(&member.name),
            &pending.commits,
            version.as_ref(),
            Some(&today),
            &config.changelog,
            None,
        ));
    }

    if sections.is_empty() {
        return Ok(0);
    }
    let header = show_header.then(|| Path::new(&config.changelog.file));

    emit(
        target.root_file(config, root).as_deref(),
        header,
        &sections.join("\n"),
        WriteMode::Prepend,
    )?;

    Ok(sections.len())
}

fn pending_members(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
    ws: &WorkspaceConfig,
    target: ChangelogOutput<'_>,
    skip_root_member: bool,
) -> Result<usize> {
    // Unified members all release at one version, computed from the whole repo.
    let unified_version = match ws.versioning {
        Versioning::Unified => Some(repo_pending(ctx, config, root)?.1),
        Versioning::Independent => None,
    };

    let today = today();
    let file = &config.changelog.file;
    let mut written = 0;

    for member in &ws.members {
        if skip_root_member && is_root_member(member) {
            continue;
        }
        let pending = member_pending(ctx, config, ws, member)?;
        if pending.commits.is_empty() {
            continue;
        }
        let version = match &unified_version {
            Some(version) => version.clone(),
            None => pending.next_version(&member_current_version(root, member)?, config),
        };
        let Some(section) = changelog::render_pending_section(
            None,
            &pending.commits,
            version.as_ref(),
            Some(&today),
            &config.changelog,
            None,
        ) else {
            continue;
        };

        let header = member_display_path(member, file);
        emit(
            target.member_file(root, member, file).as_deref(),
            Some(&header),
            &section,
            WriteMode::Prepend,
        )?;

        written += 1;
    }
    Ok(written)
}

// Full history

/// The complete root changelog, regenerated from every `release.tag_prefix` tag.
fn full_root(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    root: &Path,
    target: ChangelogOutput<'_>,
    forge: Option<&ForgeRepo>,
) -> Result<()> {
    let content = match independent_ws(config) {
        Some(ws) => build_independent_full_changelog(ctx, config, ws, forge)?,
        None => build_full_changelog(ctx, config, &config.release.tag_prefix, None, forge)?,
    };
    emit(
        target.root_file(config, root).as_deref(),
        None,
        &content,
        WriteMode::Replace,
    )
}

/// Every `prefix` release, oldest first, plus an `[Unreleased]` release for
/// commits since the last tag. With a fileset, releases with no matching
/// commits are skipped, since most releases won't touch every member.
/// `name` labels each heading, for the aggregated root changelog.
fn full_releases(
    ctx: &ReleaseContext<'_>,
    prefix: &str,
    fileset: Option<&str>,
    forge: Option<&ForgeRepo>,
    name: Option<&str>,
) -> Result<Vec<Release>> {
    let tags = commits::version_tags(ctx.backend, prefix, "tags() & ::@")?;
    let mut releases = Vec::new();
    let mut prev: Option<&Tag> = None;

    for tag in &tags {
        let since = commits::since_revision(prev);
        let commits = log_commits(ctx, &format!("{since}..{}", tag.name), fileset)?;

        if fileset.is_none() || !commits.is_empty() {
            releases.push(Release {
                name: name.map(ToOwned::to_owned),
                version: Some(tag.version.clone()),
                date: Some(ctx.backend.commit_date(&tag.name)?),
                compare_url: compare_link(
                    forge,
                    prev.map(|t| &t.version),
                    Some(&tag.version),
                    prefix,
                ),
                commits,
            });
        }
        prev = Some(tag);
    }

    let since = commits::since_revision(prev);
    let tip = log_commits(ctx, &format!("{since}..@"), fileset)?;
    if !tip.is_empty() {
        releases.push(Release {
            name: name.map(ToOwned::to_owned),
            compare_url: compare_link(forge, prev.map(|t| &t.version), None, prefix),
            commits: tip,
            ..Default::default()
        });
    }
    Ok(releases)
}

/// A full changelog from every `prefix` tag, optionally limited to `fileset`.
fn build_full_changelog(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    prefix: &str,
    fileset: Option<&str>,
    forge: Option<&ForgeRepo>,
) -> Result<String> {
    let releases = full_releases(ctx, prefix, fileset, forge, None)?;
    Ok(changelog::render_changelog(&releases, &config.changelog))
}

/// The root changelog for an independent workspace: every member's releases,
/// each heading named for its member, ordered by date.
fn build_independent_full_changelog(
    ctx: &ReleaseContext<'_>,
    config: &Config,
    ws: &WorkspaceConfig,
    forge: Option<&ForgeRepo>,
) -> Result<String> {
    let mut releases = Vec::new();
    for member in &ws.members {
        let fileset = workspace::member_fileset(member, &ws.members);
        releases.extend(full_releases(
            ctx,
            member_tag_prefix(config, ws, member),
            Some(&fileset),
            forge,
            Some(&member.name),
        )?);
    }
    releases.retain(|r| !changelog::render_body(&r.commits, &config.changelog).is_empty());

    // `render_changelog` takes oldest first. Unreleased sections (no date) go
    // last, so they render at the top. The sort is stable, so a member's
    // releases tagged on the same day stay in version order.
    releases.sort_by(|a, b| {
        (a.date.is_none(), a.date.as_deref()).cmp(&(b.date.is_none(), b.date.as_deref()))
    });
    Ok(changelog::render_changelog(&releases, &config.changelog))
}

// Workspace helpers

fn enabled_ws(config: &Config) -> Option<&WorkspaceConfig> {
    config.workspace.as_ref().filter(|ws| ws.enabled)
}

/// The workspace, if the configured layout writes member changelogs.
fn member_layout_ws(config: &Config) -> Option<&WorkspaceConfig> {
    enabled_ws(config).filter(|_| config.changelog.layout.includes_members())
}

/// The workspace, if its members are versioned independently.
fn independent_ws(config: &Config) -> Option<&WorkspaceConfig> {
    enabled_ws(config).filter(|ws| matches!(ws.versioning, Versioning::Independent))
}

/// The tag prefix `member` releases under.
fn member_tag_prefix<'a>(
    config: &'a Config,
    ws: &WorkspaceConfig,
    member: &'a WorkspaceMember,
) -> &'a str {
    match ws.versioning {
        Versioning::Unified => &config.release.tag_prefix,
        Versioning::Independent => workspace::member_prefix(member, &config.release.tag_prefix),
    }
}

fn member_current_version(root: &Path, member: &WorkspaceMember) -> Result<Version> {
    CargoManifest.read_version(&root.join(&member.path))
}

fn is_root_member(member: &WorkspaceMember) -> bool {
    member.path == "."
}

/// The changelog file for `member`: `<root>/<file>` for a member at ".",
/// otherwise `<root>/<member path>/<file>`.
#[must_use]
pub fn member_changelog_path(root: &Path, member: &WorkspaceMember, file: &str) -> PathBuf {
    if is_root_member(member) {
        root.join(file)
    } else {
        root.join(&member.path).join(file)
    }
}

/// `<member path>/<file>`, for the `==> ... <==` header when printing.
fn member_display_path(member: &WorkspaceMember, file: &str) -> PathBuf {
    Path::new(&member.path).join(file)
}

// I/O

fn log_commits(
    ctx: &ReleaseContext<'_>,
    revset: &str,
    fileset: Option<&str>,
) -> Result<Vec<CommitInfo>> {
    fileset.map_or_else(
        || ctx.backend.log_commits(revset),
        |fileset| ctx.backend.log_commits_for_path(revset, fileset),
    )
}

/// How changelog content is written to an existing file.
#[derive(Debug, Clone, Copy)]
enum WriteMode {
    /// Insert a pending section above the existing entries.
    Prepend,
    /// Replace the whole file (asking first if it differs).
    Replace,
}

/// Write `content` to `path`, or print it (under `header`, if any) when `path` is `None`.
fn emit(path: Option<&Path>, header: Option<&Path>, content: &str, mode: WriteMode) -> Result<()> {
    let Some(path) = path else {
        if let Some(header) = header {
            println!("==> {} <==", header.display());
        }
        print!("{content}");
        return Ok(());
    };
    match mode {
        WriteMode::Prepend => write_prepended(path, content),
        WriteMode::Replace => write_full(path, content),
    }
}

fn write_prepended(path: &Path, section: &str) -> Result<()> {
    let existing = read_existing(path)?;

    if !existing.trim().is_empty() && !changelog::has_changelog_title(&existing) {
        eprintln!(
            "warning: {} doesn't start with \"# Changelog\"; \
            a Keep a Changelog header was added above its existing content",
            path.display()
        );
    }

    fs::write(path, changelog::prepend_to_file(&existing, section))?;
    println!("✔️ Written to {}", path.display());
    Ok(())
}

/// Write a regenerated changelog, asking first if it would replace different content.
fn write_full(path: &Path, content: &str) -> Result<()> {
    if confirm_overwrite(path, content)? {
        fs::write(path, content)?;
        println!("✓ Written to {}", path.display());
    }
    Ok(())
}

/// For `--full`: ask before replacing an existing changelog whose content
/// differs from what would be written. Non-interactive runs (CI, pipes)
/// refuse instead of overwriting.
fn confirm_overwrite(path: &Path, new: &str) -> Result<bool> {
    let Ok(existing) = fs::read_to_string(path) else {
        return Ok(true); // no file yet
    };
    if existing == new {
        return Ok(true); // nothing would change
    }
    if !io::stdin().is_terminal() {
        eprintln!(
            "skipping {}: it exists with different content (re-run interactively to confirm)",
            path.display()
        );
        return Ok(false);
    }
    eprint!(
        "{} exists and will be replaced. Continue? [y/N] ",
        path.display()
    );
    let _ = io::stderr().flush();
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(matches!(input.trim().to_lowercase().as_str(), "y" | "yes"))
}

fn read_existing(path: &Path) -> Result<String> {
    match fs::read_to_string(path) {
        Ok(content) => Ok(content),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(String::new()),
        Err(error) => Err(error.into()),
    }
}

/// The forge repo for compare links, when `link_headers` is on and both the
/// forge and the repo can be determined.
fn forge_repo(config: &Config, root: &Path) -> Option<ForgeRepo> {
    if !config.changelog.link_headers {
        return None;
    }
    let base = changelog::forge_base_url(&config.release.forge, &config.release.forge_url)?;
    let (owner, repo) = detect::remote_url(root)
        .as_deref()
        .and_then(detect::parse_remote_owner_repo)?;
    Some(ForgeRepo {
        base,
        repo: format!("{owner}/{repo}"),
    })
}

/// Todays date for pending release headings.
fn today() -> String {
    Zoned::now().date().to_string()
}