package com.ankurm.releasenotes; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class ReleaseNotesTest { static final String LINKS = "https://git.example/acme/shop"; @TempDir Path tmp; // ---------------------------------------------------------------- 01 @Test void parsesConventionalCommits() throws Exception { String[][] cases = { {"feat(api): add order listing endpoint (#1)", ""}, {"fix: stop retrying on 4xx", ""}, {"Feat(UI): Capital letters are tolerated", ""}, {"refactor(core)!: rename Order.id to Order.orderId", ""}, {"chore: bump deps", "BREAKING CHANGE: the minimum JDK is now 21,\nupdate your CI.\n\nRefs: #9"}, {"feat!: drop the v1 API", ""}, {"Revert \"feat(cli): add --json output flag\"", ""}, {"Fixed stuff", ""}, {"wip: half done", ""}, {"feat add a thing without a colon", ""}, {"feat(api):no space after the colon", ""}, }; Transcript t = new Transcript("01-commit-parsing.txt"); t.line(String.format("%-52s %-9s %-6s %-8s %-4s %s", "subject", "type", "scope", "breaking", "PR", "conventional")); for (String[] c : cases) { var p = ConventionalCommit.parse(c[0], c[1]); t.line(String.format("%-52s %-9s %-6s %-8s %-4s %s", c[0], p.type(), p.scope(), p.breaking(), p.prNumber(), p.conventional())); } var footer = ConventionalCommit.parse("chore: bump deps", cases[4][1]); t.line(""); t.line("breaking note from footer: " + footer.breakingNote()); t.write(); assertThat(ConventionalCommit.parse(cases[0][0], "").prNumber()).isEqualTo(1); assertThat(ConventionalCommit.parse(cases[2][0], "").type()).isEqualTo("feat"); assertThat(ConventionalCommit.parse(cases[3][0], "").breaking()).isTrue(); assertThat(footer.breaking()).isTrue(); assertThat(footer.breakingNote()).isEqualTo("the minimum JDK is now 21, update your CI."); assertThat(ConventionalCommit.parse(cases[6][0], "").type()).isEqualTo("revert"); assertThat(ConventionalCommit.parse(cases[7][0], "").type()).isEqualTo("other"); assertThat(ConventionalCommit.parse(cases[8][0], "").type()).isEqualTo("other"); assertThat(ConventionalCommit.parse(cases[9][0], "").conventional()).isFalse(); assertThat(ConventionalCommit.parse(cases[10][0], "").conventional()).isFalse(); } // ---------------------------------------------------------------- 02 @Test void readsHistoryWithJGit() throws Exception { try (Fixture f = Fixture.releaseHistory(tmp); GitHistory h = new GitHistory(tmp)) { Transcript t = new Transcript("02-history-range.txt"); var range = h.commitsBetween("v1.0.0", "v1.1.0"); long rawCount = 0; for (RevCommit ignored : f.git.log().addRange(h.commitOf("v1.0.0"), h.commitOf("v1.1.0")).call()) rawCount++; t.line("$ git log --oneline v1.0.0..v1.1.0 (oldest first, merge commits skipped)"); for (CommitInfo c : range) { t.line(String.format("%s %-62s files=%d +%d -%d", c.shortSha(), c.subject(), c.filesChanged(), c.added(), c.deleted())); } t.line(""); t.line("commits git log walks: " + rawCount + ", commits kept after skipping merges: " + range.size()); var root = h.commitsUpTo("v1.0.0").getFirst(); t.line(""); t.line("root commit " + root.shortSha() + ": files=" + root.filesChanged() + " +" + root.added() + " -" + root.deleted() + " (diffed against an empty tree, it has no parent)"); t.line(""); t.line("annotated tag v1.0.0: ref points at " + h.rawTagTarget("v1.0.0").name().substring(0, 7) + ", peels to commit " + h.peeledTagTarget("v1.0.0").name().substring(0, 7) + ", commitOf says " + h.commitOf("v1.0.0").name().substring(0, 7)); t.line("lightweight tag v1.1.0: ref points at " + h.rawTagTarget("v1.1.0").name().substring(0, 7) + ", commitOf says " + h.commitOf("v1.1.0").name().substring(0, 7)); t.line(""); t.line("previousTag(v1.1.0) = " + h.previousTag("v1.1.0").orElse("none")); t.line("previousTag(v1.0.0) = " + h.previousTag("v1.0.0").orElse("none")); t.write(); assertThat(rawCount).isEqualTo(range.size() + 1); assertThat(range).hasSize(10); assertThat(range.getFirst().subject()).startsWith("feat(cli)"); assertThat(root.filesChanged()).isEqualTo(3); assertThat(h.rawTagTarget("v1.0.0")).isNotEqualTo(h.commitOf("v1.0.0")); assertThat(h.peeledTagTarget("v1.0.0")).isEqualTo(h.commitOf("v1.0.0")); assertThat(h.rawTagTarget("v1.1.0")).isEqualTo(h.commitOf("v1.1.0")); assertThat(h.previousTag("v1.1.0")).contains("v1.0.0"); assertThat(h.previousTag("v1.0.0")).isEmpty(); } } // ---------------------------------------------------------------- 03 @Test void groupsAndRendersNotes() throws Exception { try (Fixture f = Fixture.releaseHistory(tmp); GitHistory h = new GitHistory(tmp)) { var commits = h.commitsBetween("v1.0.0", "v1.1.0"); ReleaseModel m = ReleaseModel.group(commits); String md = ReleaseNotes.render("v1.1.0", ReleaseNotes.dateOf(commits.getLast()), ReleaseNotes.fallbackHighlights(m), m, LINKS); Transcript t = new Transcript("03-grouped-release-notes.txt"); t.line("group sizes: " + m.byType().entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().size()) .collect(Collectors.joining(", "))); long other = m.count("other"); t.line("not in conventional form (type other): " + other + " of " + commits.size()); t.line("bump implied by the commits: " + m.bump() + ", current " + SemVer.parse("v1.0.0").orElseThrow() + " -> next " + SemVer.parse("v1.0.0").orElseThrow().apply(m.bump())); t.line(""); t.block(md); t.write(); assertThat(m.bump()).isEqualTo(SemVer.Bump.MAJOR); assertThat(m.count("feat")).isEqualTo(2); // cli and search; the revert is its own type assertThat(m.count("revert")).isEqualTo(1); assertThat(m.count("other")).isEqualTo(2); assertThat(md).contains("### Breaking changes").contains("Order.getId() is now Order.getOrderId(), update every caller."); assertThat(md.indexOf("### Breaking changes")).isLessThan(md.indexOf("### Features")); assertThat(md).contains("[#5](" + LINKS + "/pulls/5)"); assertThat(md).contains("internal change"); } } // ---------------------------------------------------------------- 04 @Test void guardsTheModelsAnswer() throws Exception { try (Fixture f = Fixture.releaseHistory(tmp); GitHistory h = new GitHistory(tmp)) { var commits = h.commitsBetween("v1.0.0", "v1.1.0"); String fallback = ReleaseNotes.fallbackHighlights(ReleaseModel.group(commits)); StubChatModel stub = new StubChatModel(); Highlights hi = new Highlights(stub); Transcript t = new Transcript("04-model-guard.txt"); t.line("--- what the model receives ---"); var honest = hi.write("v1.1.0", commits, fallback); t.block(stub.prompts.getFirst()); t.line(""); t.line("HONEST -> from model: " + honest.fromModel() + " text: " + honest.text()); assertThat(honest.fromModel()).isTrue(); for (var mode : List.of(StubChatModel.Mode.INVENT_REFERENCES, StubChatModel.Mode.WRITE_HEADING, StubChatModel.Mode.RAMBLE)) { stub.mode = mode; var r = hi.write("v1.1.0", commits, fallback); t.line(String.format("%-15s -> from model: %s rejected because: %s", mode, r.fromModel(), r.rejection())); t.line(" shipped text: " + r.text()); assertThat(r.fromModel()).isFalse(); assertThat(r.text()).isEqualTo(fallback); } t.write(); } } // ---------------------------------------------------------------- 05 @Test void describesAPullRequest() throws Exception { try (Fixture f = Fixture.releaseHistory(tmp); GitHistory h = new GitHistory(tmp)) { f.branch("feature/csv-export"); f.write("src/Export.java", "class Export {\n" + " void write() { /* row */ }\n".repeat(150) + "}\n"); f.commit("feat(export): add CSV export (#7)"); f.write("src/Export.java", "class Export {\n" + " void write() { /* quoted row */ }\n".repeat(150) + "}\n"); f.commit("fix(export): escape quotes in CSV"); f.write("package-lock.json", "{\"lock\":\"" + "x".repeat(5000) + "\"}\n"); f.commit("chore: update package-lock.json"); f.checkout("main"); f.write("README.md", "# shop\n\nNow with a longer README.\n"); f.commit("docs: expand README"); var three = h.branchDiff("main", "feature/csv-export"); var two = h.directDiff("main", "feature/csv-export"); Transcript t = new Transcript("05-pull-request-description.txt"); t.line("files in the PR by merge-base diff (what Gitea shows): " + three.stream().map(FileDiff::path).toList()); t.line("files by comparing the two branch tips (merge base forgotten): " + two.stream().map(FileDiff::path).toList()); StubChatModel stub = new StubChatModel(); var tight = new PrDescription(stub, DiffBudget.defaults()).describe(h, "main", "feature/csv-export"); var loose = new PrDescription(stub, new DiffBudget(Integer.MAX_VALUE, Integer.MAX_VALUE, List.of())).describe(h, "main", "feature/csv-export"); t.line(""); t.line("prompt size with the default budget: " + tight.promptChars() + " characters; with no budget: " + loose.promptChars()); t.line("budget: included=" + tight.budgeted().included() + " truncated=" + tight.budgeted().truncated() + " names-only=" + tight.budgeted().namesOnly()); t.line("title: " + tight.title()); t.line(""); t.block(tight.body()); t.write(); assertThat(three).extracting(FileDiff::path).containsExactly("package-lock.json", "src/Export.java"); assertThat(two).extracting(FileDiff::path).contains("README.md"); assertThat(tight.promptChars()).isLessThan(loose.promptChars()); assertThat(tight.budgeted().namesOnly()).containsExactly("package-lock.json"); assertThat(tight.budgeted().truncated()).isEqualTo(1); assertThat(tight.summaryFromModel()).isTrue(); assertThat(tight.body()).contains("## Summary").contains("## Files").doesNotContain("README.md"); } } // ---------------------------------------------------------------- 06 @Test void publishesIdempotently() throws Exception { try (FakeGitea gitea = new FakeGitea("secret")) { var client = new GiteaClient(gitea.apiBase(), "acme/shop", "secret"); Transcript t = new Transcript("06-gitea-publish.txt"); var first = client.upsertRelease("v1.1.0", "v1.1.0", "notes, take one", false, false, "main"); var second = client.upsertRelease("v1.1.0", "v1.1.0", "notes, take two", false, false, "main"); t.line("release run 1: " + first.action() + " id=" + first.id()); t.line("release run 2: " + second.action() + " id=" + second.id() + " body now: " + gitea.releases.get("v1.1.0").path("body").asString()); var pr1 = client.upsertPullRequest("main", "feature/csv-export", "Add CSV export", "body one"); var pr2 = client.upsertPullRequest("main", "feature/csv-export", "Add CSV export (+2 more)", "body two"); t.line("pull request run 1: " + pr1.action() + " #" + pr1.id()); t.line("pull request run 2: " + pr2.action() + " #" + pr2.id() + " title now: " + gitea.pulls.get("main...feature/csv-export").path("title").asString()); var wrong = new GiteaClient(gitea.apiBase(), "acme/shop", "not-the-token"); String message = null; try { wrong.upsertRelease("v9.9.9", "v9.9.9", "x", false, false, "main"); } catch (IllegalStateException e) { message = e.getMessage(); } t.line("wrong token: " + message); t.line(""); t.line("requests the server saw:"); gitea.log.forEach(l -> t.line(" " + l)); t.write(); assertThat(first.action()).isEqualTo("created"); assertThat(second.action()).isEqualTo("updated"); assertThat(second.id()).isEqualTo(first.id()); assertThat(pr1.action()).isEqualTo("created"); assertThat(pr2.id()).isEqualTo(pr1.id()); assertThat(message).contains("401"); assertThat(gitea.log.stream().filter(l -> l.startsWith("POST /repos/acme/shop/releases")).count()).isEqualTo(1); assertThat(gitea.log.stream().filter(l -> l.contains("PATCH /repos/acme/shop/releases")).findFirst().orElseThrow()) .doesNotContain("tag_name"); } } @Test void emptyRangeStillRenders() throws Exception { try (Fixture f = Fixture.releaseHistory(tmp); GitHistory h = new GitHistory(tmp)) { assertThat(h.commitsBetween("v1.1.0", "v1.1.0")).isEmpty(); assertThatThrownBy(() -> h.commitOf("v9.9.9")).isInstanceOf(IllegalArgumentException.class); } } // ---------------------------------------------------------------- 07 @Test void commandLineRunsOnARealRepository() throws Exception { try (Fixture f = Fixture.releaseHistory(tmp)) { var captured = new java.io.ByteArrayOutputStream(); var old = System.out; System.setOut(new java.io.PrintStream(captured, true, java.nio.charset.StandardCharsets.UTF_8)); try { ReleaseNotesApp.main(new String[]{tmp.toString(), "v1.1.0", LINKS}); } finally { System.setOut(old); } String out = captured.toString(java.nio.charset.StandardCharsets.UTF_8); Transcript t = new Transcript("07-command-line.txt"); t.line("$ java -cp ... com.ankurm.releasenotes.ReleaseNotesApp v1.1.0 " + LINKS); t.block(out.lines().limit(12).collect(Collectors.joining("\n"))); t.line("[... " + (out.lines().count() - 12) + " more lines]"); t.write(); assertThat(out).startsWith("## v1.1.0 (2026-01-20)"); assertThat(out).contains("This stub counts 2 features and 1 fix"); } } }