Add release-notes-ai module: JGit history, Conventional Commit grouping, guarded Spring AI highlights, PR descriptions and idempotent Gitea publishing on Spring AI 2.1.0

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7h4ZNF4BDUpJk3Zou
This commit is contained in:
Claude
2026-11-29 01:58:28 +05:30
parent 1e8e90258a
commit 943351bccb
28 changed files with 1694 additions and 0 deletions
+2
View File
@@ -19,6 +19,7 @@ facts, so the build fails when a claim stops being true.
| `claude-code-spring` | Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ | a Spring Boot 4.2 orders service with a complete committed Claude Code setup: `CLAUDE.md`, a path-scoped rule, two skills, four hooks (command guard, protected files, tests after edit, a Stop gate) run against real hook JSON, project-scoped `.mcp.json` generated by the real `claude mcp` CLI, and tests that lint the setup | | `claude-code-spring` | Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ | a Spring Boot 4.2 orders service with a complete committed Claude Code setup: `CLAUDE.md`, a path-scoped rule, two skills, four hooks (command guard, protected files, tests after edit, a Stop gate) run against real hook JSON, project-scoped `.mcp.json` generated by the real `claude mcp` CLI, and tests that lint the setup |
| `mcp-stateless` | MCP 2026-07-28 for Java Developers: Migrating an MCP Server to the Stateless Spec | one order server as a 2025-era stateful and a 2026-07-28 stateless Spring AI server, behind a round-robin balancer, with multi-round-trip requests, a version router and real SDK clients | | `mcp-stateless` | MCP 2026-07-28 for Java Developers: Migrating an MCP Server to the Stateless Spec | one order server as a 2025-era stateful and a 2026-07-28 stateless Spring AI server, behind a round-robin balancer, with multi-round-trip requests, a version router and real SDK clients |
| `code-search-mcp` | Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings) | JavaParser indexes a four-module sample monorepo, a swappable `Embedder` (offline hashing or any `/v1/embeddings` endpoint) ranks methods by what they do, `find_usages` compares name matching with the symbol solver, and the three tools are served on the 2026-07-28 stateless spec with the 2.2.0 modern SDK, tested over raw HTTP, two server instances and the SDK client | | `code-search-mcp` | Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings) | JavaParser indexes a four-module sample monorepo, a swappable `Embedder` (offline hashing or any `/v1/embeddings` endpoint) ranks methods by what they do, `find_usages` compares name matching with the symbol solver, and the three tools are served on the 2026-07-28 stateless spec with the 2.2.0 modern SDK, tested over raw HTTP, two server instances and the SDK client |
| `release-notes-ai` | AI Release Notes and PR Descriptions in Java: JGit, Spring AI and Gitea | JGit reads a real repository, commits are grouped by Conventional Commit type, release notes and a version bump are computed in code, a Spring AI model writes only the opening paragraph behind a guard that rejects invented PR numbers and hashes, and a Gitea client creates or updates the release and PR so a rerun edits instead of failing; tested with a stub model and a local fake Gitea |
## Versions (verified on Maven Central, 2026-10-11) ## Versions (verified on Maven Central, 2026-10-11)
@@ -38,6 +39,7 @@ facts, so the build fails when a claim stops being true.
| MCP Java SDK `io.modelcontextprotocol.sdk:mcp` | 2.1.0 | verified on Maven Central 2026-11-08; `mcp-sdk-plain` only; pom-only aggregator over `mcp-core` and `mcp-json-jackson3` | | MCP Java SDK `io.modelcontextprotocol.sdk:mcp` | 2.1.0 | verified on Maven Central 2026-11-08; `mcp-sdk-plain` only; pom-only aggregator over `mcp-core` and `mcp-json-jackson3` |
| Jetty `jetty-ee11-servlet` | 12.1.14 | `mcp-sdk-plain` only; the SDK declares the servlet API as `provided`, so HTTP needs a container | | Jetty `jetty-ee11-servlet` | 12.1.14 | `mcp-sdk-plain` only; the SDK declares the servlet API as `provided`, so HTTP needs a container |
| Spring Boot / Spring AI (client example) | 4.1.2 / 2.0.2 | `mcp-sdk-plain/examples/spring-ai-client` only, a standalone project | | Spring Boot / Spring AI (client example) | 4.1.2 / 2.0.2 | `mcp-sdk-plain/examples/spring-ai-client` only, a standalone project |
| JGit `org.eclipse.jgit` | 7.8.1.202611041320-r | verified on Maven Central 2026-11-29; `release-notes-ai` only, with Spring Boot 4.2.0 / Spring AI 2.1.0 |
| Koog `koog-agents-jvm` | 1.3.0 | verified on Maven Central 2026-11-11; `koog` module only. `koog-spring-boot-starter` is 1.3.0-beta and brings Spring Boot 3.5.14, which is why this module uses Spring Boot 3.5.16 and not the 4.x of the others | | Koog `koog-agents-jvm` | 1.3.0 | verified on Maven Central 2026-11-11; `koog` module only. `koog-spring-boot-starter` is 1.3.0-beta and brings Spring Boot 3.5.14, which is why this module uses Spring Boot 3.5.16 and not the 4.x of the others |
| Kotlin `kotlin-stdlib` | 2.3.10 | the Spring Boot 3.5.16 BOM pins 1.9.25 and would win; the `koog` pom imports the Kotlin BOMs first | | Kotlin `kotlin-stdlib` | 2.3.10 | the Spring Boot 3.5.16 BOM pins 1.9.25 and would win; the `koog` pom imports the Kotlin BOMs first |
| Spring Boot (`claude-code-spring`) | 4.2.0 | GA 2026-11-19, verified on Maven Central 2026-11-21; `claude-code-spring` only | | Spring Boot (`claude-code-spring`) | 4.2.0 | GA 2026-11-19, verified on Maven Central 2026-11-21; `claude-code-spring` only |
+1
View File
@@ -23,6 +23,7 @@
<module>claude-code-spring</module> <module>claude-code-spring</module>
<module>mcp-stateless</module> <module>mcp-stateless</module>
<module>code-search-mcp</module> <module>code-search-mcp</module>
<module>release-notes-ai</module>
</modules> </modules>
<properties> <properties>
+43
View File
@@ -0,0 +1,43 @@
# release-notes-ai
Companion code for the ankurm.com post *AI Release Notes and PR Descriptions in Java: JGit, Spring AI and Gitea*.
It reads a real Git repository with JGit, groups commits by Conventional Commit type, works out the next version,
renders release notes in code, asks a Spring AI `ChatModel` only for a short opening paragraph (and a PR summary),
rejects any answer that cites a commit or PR number it was not given, and publishes to Gitea so that running twice
edits instead of failing.
Every transcript in `output/` is written by the test that asserts the same facts: `mvn test` regenerates all of them.
The tests build a real repository with JGit (fixed dates, so the hashes are stable). The language model is
`StubChatModel`, a deterministic stand-in, and Gitea is `FakeGitea`, a small local HTTP server in the test sources.
Neither is the real thing and the post says so.
| Class | Job |
|---|---|
| `ConventionalCommit` | parse `type(scope)!: description`, `BREAKING CHANGE:` footers and `(#123)` suffixes |
| `GitHistory` | JGit: commits between two refs, previous tag, merge base, per-commit and per-branch diffs |
| `ReleaseModel`, `SemVer` | group by type and compute the version bump |
| `ReleaseNotes` | Markdown rendering, links and the no-model fallback sentence |
| `Highlights` | the one model call for release notes, plus the answer guard |
| `DiffBudget`, `PrDescription` | cap what the model sees of a branch diff and build the PR body |
| `GiteaClient` | create-or-update a release and a pull request |
| `StubChatModel` | stand-in model with modes that misbehave on purpose |
## Run
```
mvn -pl release-notes-ai test # JDK 25
```
| Output | Shows |
|---|---|
| `01-commit-parsing.txt` | what the parser does with eleven messages, good and bad |
| `02-history-range.txt` | `v1.0.0..v1.1.0` read with JGit, the root-commit and annotated-tag traps, previous tag |
| `03-grouped-release-notes.txt` | grouped, ordered notes and the implied version |
| `04-model-guard.txt` | the exact prompt, and three bad answers rejected |
| `05-pull-request-description.txt` | merge-base diff, diff budget, the PR body |
| `06-gitea-publish.txt` | create then update for a release and a PR, a 401, and the requests seen |
| `07-command-line.txt` | `ReleaseNotesApp` on the fixture repository |
To use a real model, put any Spring AI `ChatModel` (Anthropic, OpenAI, Ollama) where `new StubChatModel()` is constructed.
No other code changes.
@@ -0,0 +1,14 @@
subject type scope breaking PR conventional
feat(api): add order listing endpoint (#1) feat api false 1 true
fix: stop retrying on 4xx fix null false null true
Feat(UI): Capital letters are tolerated feat UI false null true
refactor(core)!: rename Order.id to Order.orderId refactor core true null true
chore: bump deps chore null true null true
feat!: drop the v1 API feat null true null true
Revert "feat(cli): add --json output flag" revert null false null true
Fixed stuff other null false null false
wip: half done other null false null false
feat add a thing without a colon other null false null false
feat(api):no space after the colon other null false null false
breaking note from footer: the minimum JDK is now 21, update your CI.
@@ -0,0 +1,21 @@
$ git log --oneline v1.0.0..v1.1.0 (oldest first, merge commits skipped)
6e9776a feat(cli): add --json output flag (#3) files=1 +1 -0
6ba3519 fix: stop retrying on 4xx files=1 +1 -0
4ab0a75 docs: explain retry policy files=1 +1 -0
0082b4d Fixed stuff files=1 +1 -0
a061359 refactor(core)!: rename Order.id to Order.orderId files=1 +1 -1
2ff8458 perf(db): batch inserts in OrderRepository (#5) files=1 +1 -0
633f424 wip: half done files=1 +1 -0
92049cc feat(search): add fuzzy search (#6) files=1 +1 -0
08cccc3 docs: document back-off files=1 +1 -1
dedef67 Revert "feat(cli): add --json output flag" files=1 +1 -1
commits git log walks: 11, commits kept after skipping merges: 10
root commit 84be7a6: files=3 +3 -0 (diffed against an empty tree, it has no parent)
annotated tag v1.0.0: ref points at 03c7aed, peels to commit 17deac5, commitOf says 17deac5
lightweight tag v1.1.0: ref points at dedef67, commitOf says dedef67
previousTag(v1.1.0) = v1.0.0
previousTag(v1.0.0) = none
@@ -0,0 +1,40 @@
group sizes: feat=2, fix=1, perf=1, revert=1, docs=2, refactor=1, other=2
not in conventional form (type other): 2 of 10
bump implied by the commits: MAJOR, current 1.0.0 -> next 2.0.0
## v1.1.0 (2026-01-20)
This release contains 10 commits: 2 features and 1 bug fix. 1 breaking change is listed first.
### Breaking changes
- Order.getId() is now Order.getOrderId(), update every caller. ([a061359](https://git.example/acme/shop/commit/a061359aeddbe07c20c074b3fa1f909575076a49))
### Features
- **cli:** add --json output flag ([#3](https://git.example/acme/shop/pulls/3), [6e9776a](https://git.example/acme/shop/commit/6e9776a52f5a1cff3f185922acc3b5b311a2e24c))
- **search:** add fuzzy search ([#6](https://git.example/acme/shop/pulls/6), [92049cc](https://git.example/acme/shop/commit/92049cc1cace8c099d1e230ac7345e515060c3e0))
### Bug fixes
- stop retrying on 4xx ([6ba3519](https://git.example/acme/shop/commit/6ba351972dff78b9436ba097060dc16376fcf465))
### Performance
- **db:** batch inserts in OrderRepository ([#5](https://git.example/acme/shop/pulls/5), [2ff8458](https://git.example/acme/shop/commit/2ff8458d4673dd88e3e2a4573920ecc153289733))
### Reverts
- Revert: feat(cli): add --json output flag ([dedef67](https://git.example/acme/shop/commit/dedef67f9d283bc967fc636499eadf00fc146995))
### Documentation
- explain retry policy ([4ab0a75](https://git.example/acme/shop/commit/4ab0a75eb6ca0b36e6de1214b8cee9f2c39f9818))
- document back-off ([08cccc3](https://git.example/acme/shop/commit/08cccc3e3c6a1fd41797f14fb4641ea29a60b837))
### Other changes
- Fixed stuff ([0082b4d](https://git.example/acme/shop/commit/0082b4d1b55c3785247a2314c2595e1d37b72723))
- wip: half done ([633f424](https://git.example/acme/shop/commit/633f424efeee2017682d4b7ed7ff8e1a08f3d6e9))
_1 internal change (refactor, test, build, ci, chore, style) not listed._
@@ -0,0 +1,25 @@
--- what the model receives ---
[SYSTEM]
You write the opening paragraph of release notes for developers.
Use only the commits in the list. Do not invent pull request numbers or commit hashes.
Write at most three sentences of plain prose: no headings, no bullet lists.
[USER]
Release v1.1.0. Commits:
- 6e9776a feat(cli): add --json output flag (#3)
- 6ba3519 fix: stop retrying on 4xx
- 4ab0a75 docs: explain retry policy
- 0082b4d other: Fixed stuff
- a061359 refactor(core): rename Order.id to Order.orderId [BREAKING]
- 2ff8458 perf(db): batch inserts in OrderRepository (#5)
- 633f424 other: wip: half done
- 92049cc feat(search): add fuzzy search (#6)
- 08cccc3 docs: document back-off
- dedef67 revert: feat(cli): add --json output flag
HONEST -> from model: true text: This stub counts 2 features and 1 fix; the first feature is "add --json output flag (#3)" (6e9776a).
INVENT_REFERENCES -> from model: false rejected because: cites #999, which is not in the commit list
shipped text: This release contains 10 commits: 2 features and 1 bug fix. 1 breaking change is listed first.
WRITE_HEADING -> from model: false rejected because: contains a markdown heading
shipped text: This release contains 10 commits: 2 features and 1 bug fix. 1 breaking change is listed first.
RAMBLE -> from model: false rejected because: longer than 600 characters
shipped text: This release contains 10 commits: 2 features and 1 bug fix. 1 breaking change is listed first.
@@ -0,0 +1,28 @@
files in the PR by merge-base diff (what Gitea shows): [package-lock.json, src/Export.java]
files by comparing the two branch tips (merge base forgotten): [README.md, package-lock.json, src/Export.java]
prompt size with the default budget: 1739 characters; with no budget: 11076
budget: included=1 truncated=1 names-only=[package-lock.json]
title: Add CSV export (+2 more)
## Summary
This stub counts 1 feature and 1 fix; the first feature is "add CSV export (#7)" (1cbba95).
## Changes
- `feat` add CSV export (1cbba95)
- `fix` escape quotes in CSV (0b05321)
- `chore` update package-lock.json (6454b34)
## Files
| File | Change | + | - |
|---|---|---|---|
| `package-lock.json` | modify | 1 | 1 |
| `src/Export.java` | add | 152 | 0 |
## Checklist
- [ ] Tests pass
- [ ] Docs updated if behaviour changed
@@ -0,0 +1,16 @@
release run 1: created id=100
release run 2: updated id=100 body now: notes, take two
pull request run 1: created #11
pull request run 2: updated #11 title now: Add CSV export (+2 more)
wrong token: Gitea answered 401: {"message":"token is required"}
requests the server saw:
GET /repos/acme/shop/releases/tags/v1.1.0 -> 404
POST /repos/acme/shop/releases -> 201 fields=[tag_name, name, body, draft, prerelease, target_commitish]
GET /repos/acme/shop/releases/tags/v1.1.0 -> 200
PATCH /repos/acme/shop/releases/100 -> 200 fields=[name, body, draft, prerelease, target_commitish]
GET /repos/acme/shop/pulls?state=open&limit=50&page=1 -> 200
POST /repos/acme/shop/pulls -> 201 fields=[base, head, title, body]
GET /repos/acme/shop/pulls?state=open&limit=50&page=1 -> 200
PATCH /repos/acme/shop/pulls/11 -> 201 fields=[body, title]
GET /repos/acme/shop/releases/tags/v9.9.9 -> 401
@@ -0,0 +1,14 @@
$ java -cp ... com.ankurm.releasenotes.ReleaseNotesApp <repo> v1.1.0 https://git.example/acme/shop
## v1.1.0 (2026-01-20)
This stub counts 2 features and 1 fix; the first feature is "add --json output flag (#3)" (6e9776a).
### Breaking changes
- Order.getId() is now Order.getOrderId(), update every caller. ([a061359](https://git.example/acme/shop/commit/a061359aeddbe07c20c074b3fa1f909575076a49))
### Features
- **cli:** add --json output flag ([#3](https://git.example/acme/shop/pulls/3), [6e9776a](https://git.example/acme/shop/commit/6e9776a52f5a1cff3f185922acc3b5b311a2e24c))
- **search:** add fuzzy search ([#6](https://git.example/acme/shop/pulls/6), [92049cc](https://git.example/acme/shop/commit/92049cc1cace8c099d1e230ac7345e515060c3e0))
[... 24 more lines]
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm.agents</groupId>
<artifactId>java-ai-agents</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>release-notes-ai</artifactId>
<name>AI release notes and PR descriptions: JGit, Spring AI and Gitea</name>
<properties>
<!-- Verified on Maven Central 2026-11-29. These override the parent's older values for this module only. -->
<spring-boot.version>4.2.0</spring-boot.version>
<spring-ai.version>2.1.0</spring-ai.version>
<jgit.version>7.8.1.202611041320-r</jgit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>${jgit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-client-chat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,12 @@
package com.ankurm.releasenotes;
import java.time.Instant;
/** What we keep about one commit: identity, message and the size of its diff against its first parent. */
public record CommitInfo(String sha, String subject, String body, String author, Instant when,
int filesChanged, int added, int deleted, ConventionalCommit parsed) {
public String shortSha() {
return sha.substring(0, 7);
}
}
@@ -0,0 +1,63 @@
package com.ankurm.releasenotes;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* One commit message read as a Conventional Commit: {@code type(scope)!: description}, an optional body
* and optional footers. Anything that does not match becomes type {@code other}; it is never dropped.
*/
public record ConventionalCommit(String type, String scope, String description, boolean breaking,
String breakingNote, Integer prNumber, boolean conventional) {
private static final Pattern HEADER =
Pattern.compile("^(?<type>[A-Za-z]+)(\\((?<scope>[^)]+)\\))?(?<bang>!)?: (?<desc>.+)$");
private static final Pattern PR_SUFFIX = Pattern.compile("\\s\\(#(\\d+)\\)$");
private static final Pattern BREAKING_FOOTER =
Pattern.compile("(?m)^BREAKING[ -]CHANGE: (.+(?:\\n(?!\\n|[A-Za-z-]+: ).+)*)");
private static final Pattern REVERT = Pattern.compile("^Revert \"(.+)\"$");
/** The types this generator knows. An unknown word before the colon ("wip:") is not a type. */
public static final Set<String> KNOWN = Set.of("feat", "fix", "perf", "refactor", "docs", "test",
"build", "ci", "chore", "style", "revert");
public static ConventionalCommit parse(String subject, String body) {
String s = subject.strip();
Integer pr = null;
Matcher pm = PR_SUFFIX.matcher(s);
if (pm.find()) {
pr = Integer.valueOf(pm.group(1));
s = s.substring(0, pm.start());
}
String note = null;
Matcher bf = BREAKING_FOOTER.matcher(body == null ? "" : body);
if (bf.find()) {
note = bf.group(1).replace("\n", " ").strip();
}
Matcher rv = REVERT.matcher(s);
if (rv.matches()) {
return new ConventionalCommit("revert", null, rv.group(1), note != null, note, pr, true);
}
Matcher m = HEADER.matcher(s);
if (m.matches()) {
String type = m.group("type").toLowerCase(Locale.ROOT);
if (KNOWN.contains(type)) {
boolean breaking = m.group("bang") != null || note != null;
return new ConventionalCommit(type, m.group("scope"), m.group("desc"), breaking, note, pr, true);
}
}
return new ConventionalCommit("other", null, s, note != null, note, pr, false);
}
public Optional<String> scopeOpt() {
return Optional.ofNullable(scope);
}
public static List<String> order() {
return List.of("feat", "fix", "perf", "revert", "docs", "refactor", "test", "build", "ci", "chore", "style", "other");
}
}
@@ -0,0 +1,39 @@
package com.ankurm.releasenotes;
import java.util.ArrayList;
import java.util.List;
/**
* Decides how much of a diff a model gets to see. Files matching a skip suffix (lock files, minified assets)
* are listed by name only. Every other patch is cut at {@code perFileChars}, and once {@code totalChars} is
* used up the remaining files are listed by name only too.
*/
public record DiffBudget(int perFileChars, int totalChars, List<String> skipSuffixes) {
public record Budgeted(String text, int included, int truncated, List<String> namesOnly) {}
public static DiffBudget defaults() {
return new DiffBudget(1500, 6000, List.of(".lock", "package-lock.json", ".min.js", ".svg", ".png"));
}
public Budgeted apply(List<FileDiff> files) {
StringBuilder sb = new StringBuilder();
List<String> namesOnly = new ArrayList<>();
int included = 0, truncated = 0;
for (FileDiff f : files) {
boolean skip = skipSuffixes.stream().anyMatch(f.path()::endsWith);
if (skip || sb.length() >= totalChars) {
namesOnly.add(f.path());
continue;
}
String patch = f.patch();
if (patch.length() > perFileChars) {
patch = patch.substring(0, perFileChars) + "\n[... " + (f.patch().length() - perFileChars) + " more characters cut ...]\n";
truncated++;
}
sb.append(patch).append('\n');
included++;
}
return new Budgeted(sb.toString(), included, truncated, namesOnly);
}
}
@@ -0,0 +1,4 @@
package com.ankurm.releasenotes;
/** One file of a branch diff: path, lines added/deleted and the unified patch text. */
public record FileDiff(String path, String changeType, int added, int deleted, String patch) {}
@@ -0,0 +1,237 @@
package com.ankurm.releasenotes;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.eclipse.jgit.treewalk.AbstractTreeIterator;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.EmptyTreeIterator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/** Reads commits, tags and diffs from a local repository with JGit. Nothing here talks to a network or a model. */
public final class GitHistory implements AutoCloseable {
private final Git git;
private final Repository repo;
public GitHistory(Path dir) {
try {
this.git = Git.open(dir.toFile());
this.repo = git.getRepository();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Resolves a name to the COMMIT it points at, peeling an annotated tag if there is one. */
public ObjectId commitOf(String ref) {
try {
ObjectId id = repo.resolve(ref + "^{commit}");
if (id == null) {
throw new IllegalArgumentException("Cannot resolve " + ref);
}
return id;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** What the tag ref itself points at: the tag object for an annotated tag, the commit for a lightweight one. */
public ObjectId rawTagTarget(String tag) {
try {
Ref r = repo.exactRef("refs/tags/" + tag);
return r == null ? null : r.getObjectId();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public ObjectId peeledTagTarget(String tag) {
try {
Ref r = repo.exactRef("refs/tags/" + tag);
Ref p = repo.getRefDatabase().peel(r);
return p.getPeeledObjectId() != null ? p.getPeeledObjectId() : p.getObjectId();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** The highest MAJOR.MINOR.PATCH tag that is an ancestor of {@code head} and is not {@code head} itself. */
public Optional<String> previousTag(String head) {
try (RevWalk rw = new RevWalk(repo)) {
RevCommit headCommit = rw.parseCommit(commitOf(head));
String best = null;
SemVer bestV = null;
for (Ref ref : repo.getRefDatabase().getRefsByPrefix("refs/tags/")) {
String name = ref.getName().substring("refs/tags/".length());
Optional<SemVer> v = SemVer.parse(name);
if (v.isEmpty()) {
continue;
}
RevCommit tagCommit = rw.parseCommit(commitOf(name));
if (tagCommit.equals(headCommit) || !rw.isMergedInto(tagCommit, headCommit)) {
continue;
}
if (bestV == null || v.get().compareTo(bestV) > 0) {
best = name;
bestV = v.get();
}
}
return Optional.ofNullable(best);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Commits reachable from {@code to} but not from {@code from} (git's from..to), oldest first, merges skipped. */
public List<CommitInfo> commitsBetween(String from, String to) {
try (RevWalk rw = new RevWalk(repo)) {
List<CommitInfo> out = new ArrayList<>();
var log = git.log().addRange(commitOf(from), commitOf(to)).call();
for (RevCommit c : log) {
if (c.getParentCount() > 1) {
continue;
}
out.add(describe(c));
}
Collections.reverse(out);
return out;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/** Every commit reachable from {@code to}: used for a first release, where there is no previous tag. */
public List<CommitInfo> commitsUpTo(String to) {
try {
List<CommitInfo> out = new ArrayList<>();
for (RevCommit c : git.log().add(commitOf(to)).call()) {
if (c.getParentCount() > 1) {
continue;
}
out.add(describe(c));
}
Collections.reverse(out);
return out;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private CommitInfo describe(RevCommit c) throws IOException {
String full = c.getFullMessage();
int nl = full.indexOf('\n');
String subject = nl < 0 ? full.strip() : full.substring(0, nl).strip();
String body = nl < 0 ? "" : full.substring(nl + 1).strip();
int files = 0, add = 0, del = 0;
for (FileDiff d : diffTrees(parentTree(c), treeOf(c), false)) {
files++;
add += d.added();
del += d.deleted();
}
return new CommitInfo(c.getName(), subject, body, c.getAuthorIdent().getName(),
c.getAuthorIdent().getWhenAsInstant(), files, add, del, ConventionalCommit.parse(subject, body));
}
private AbstractTreeIterator parentTree(RevCommit c) throws IOException {
if (c.getParentCount() == 0) {
return new EmptyTreeIterator(); // the root commit has no parent: diff against an empty tree
}
try (RevWalk rw = new RevWalk(repo)) {
return treeOf(rw.parseCommit(c.getParent(0)));
}
}
private AbstractTreeIterator treeOf(RevCommit c) throws IOException {
try (ObjectReader reader = repo.newObjectReader()) {
CanonicalTreeParser p = new CanonicalTreeParser();
p.reset(reader, c.getTree());
return p;
}
}
/** The merge base of two branches: where a pull request's diff starts (git's three-dot diff). */
public ObjectId mergeBase(String a, String b) {
try (RevWalk rw = new RevWalk(repo)) {
rw.setRevFilter(RevFilter.MERGE_BASE);
rw.markStart(rw.parseCommit(commitOf(a)));
rw.markStart(rw.parseCommit(commitOf(b)));
RevCommit base = rw.next();
if (base == null) {
throw new IllegalArgumentException(a + " and " + b + " share no history");
}
return base;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Files changed between the merge base of base/head and head, each with its unified patch. */
public List<FileDiff> branchDiff(String base, String head) {
try (RevWalk rw = new RevWalk(repo)) {
RevCommit mb = rw.parseCommit(mergeBase(base, head));
RevCommit h = rw.parseCommit(commitOf(head));
return diffTrees(treeOf(mb), treeOf(h), true);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** The tip of {@code base} against the tip of {@code head}: what you get if you forget the merge base. */
public List<FileDiff> directDiff(String base, String head) {
try (RevWalk rw = new RevWalk(repo)) {
return diffTrees(treeOf(rw.parseCommit(commitOf(base))), treeOf(rw.parseCommit(commitOf(head))), false);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private List<FileDiff> diffTrees(AbstractTreeIterator a, AbstractTreeIterator b, boolean withPatch) throws IOException {
List<FileDiff> out = new ArrayList<>();
ByteArrayOutputStream sink = new ByteArrayOutputStream();
try (DiffFormatter df = new DiffFormatter(sink)) {
df.setRepository(repo);
df.setDetectRenames(true);
for (DiffEntry e : df.scan(a, b)) {
int add = 0, del = 0;
for (Edit ed : df.toFileHeader(e).toEditList()) {
add += ed.getEndB() - ed.getBeginB();
del += ed.getEndA() - ed.getBeginA();
}
String patch = "";
if (withPatch) {
sink.reset();
df.format(e);
patch = sink.toString(StandardCharsets.UTF_8);
}
String path = e.getChangeType() == DiffEntry.ChangeType.DELETE ? e.getOldPath() : e.getNewPath();
out.add(new FileDiff(path, e.getChangeType().name(), add, del, patch));
}
}
out.sort(Comparator.comparing(FileDiff::path));
return out;
}
@Override
public void close() {
git.close();
}
}
@@ -0,0 +1,121 @@
package com.ankurm.releasenotes;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Publishes to Gitea, and is safe to run twice: a second run edits the release or pull request the first run
* created instead of failing with 409. (The swagger document says a pull request PATCH answers 201, so both 200 and 201 are accepted there.) The endpoints and field names were read from this server's own
* swagger document (Gitea 1.27.3).
*/
public final class GiteaClient {
public record Outcome(String action, long id, String url) {}
private final HttpClient http = HttpClient.newHttpClient();
private final JsonMapper json = JsonMapper.builder().build();
private final String apiBase;
private final String repo;
private final String token;
public GiteaClient(String apiBase, String repo, String token) {
this.apiBase = apiBase;
this.repo = repo;
this.token = token;
}
public Outcome upsertRelease(String tag, String name, String body, boolean draft, boolean prerelease, String targetCommitish) {
Response existing = send("GET", "/repos/" + repo + "/releases/tags/" + enc(tag), null);
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("tag_name", tag);
payload.put("name", name);
payload.put("body", body);
payload.put("draft", draft);
payload.put("prerelease", prerelease);
payload.put("target_commitish", targetCommitish);
if (existing.status == 404) {
Response r = expect(send("POST", "/repos/" + repo + "/releases", payload), 201);
return new Outcome("created", r.json.path("id").asLong(), r.json.path("html_url").asString());
}
expect(existing, 200);
long id = existing.json.path("id").asLong();
payload.remove("tag_name"); // an edit that names the tag again is a rename, not what we want
Response r = expect(send("PATCH", "/repos/" + repo + "/releases/" + id, payload), 200);
return new Outcome("updated", id, r.json.path("html_url").asString());
}
public Outcome upsertPullRequest(String base, String head, String title, String body) {
JsonNode existing = findOpenPullRequest(base, head);
if (existing == null) {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("base", base);
payload.put("head", head);
payload.put("title", title);
payload.put("body", body);
Response r = expect(send("POST", "/repos/" + repo + "/pulls", payload), 201);
return new Outcome("created", r.json.path("number").asLong(), r.json.path("html_url").asString());
}
long number = existing.path("number").asLong();
Response r = expect(send("PATCH", "/repos/" + repo + "/pulls/" + number, Map.of("title", title, "body", body)), 200, 201);
return new Outcome("updated", number, r.json.path("html_url").asString());
}
/**
* Looks through the open pull requests for one with this base and head branch. The list endpoint is used
* instead of {@code GET /pulls/{base}/{head}} because a branch name such as feature/x has a slash in it, and
* how a slash in that path segment is routed is not something the swagger document settles.
*/
private JsonNode findOpenPullRequest(String base, String head) {
for (int page = 1; page <= 20; page++) {
Response r = expect(send("GET", "/repos/" + repo + "/pulls?state=open&limit=50&page=" + page, null), 200);
if (r.json.size() == 0) {
return null;
}
for (JsonNode pr : r.json) {
if (pr.path("base").path("ref").asString().equals(base) && pr.path("head").path("ref").asString().equals(head)) {
return pr;
}
}
}
return null;
}
private record Response(int status, JsonNode json, String raw) {}
private Response expect(Response r, int... ok) {
for (int s : ok) if (r.status == s) return r;
throw new IllegalStateException("Gitea answered " + r.status + ": " + r.raw);
}
private Response send(String method, String path, Object payload) {
try {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(apiBase + path))
.header("Authorization", "token " + token).header("Accept", "application/json");
if (payload == null) {
b.method(method, HttpRequest.BodyPublishers.noBody());
} else {
b.header("Content-Type", "application/json")
.method(method, HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload)));
}
HttpResponse<String> res = http.send(b.build(), HttpResponse.BodyHandlers.ofString());
JsonNode node = res.body().isBlank() ? json.createObjectNode() : json.readTree(res.body());
return new Response(res.statusCode(), node, res.body());
} catch (IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
}
private static String enc(String s) {
return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20");
}
}
@@ -0,0 +1,82 @@
package com.ankurm.releasenotes;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The only place a model is asked to write anything. It gets a closed list of commits and may write a few
* sentences about them. {@link #check} then rejects any answer that cites a commit hash or a pull request
* number that was not in the list, runs too long or contains a heading, and the caller falls back to a
* sentence built by code.
*/
public final class Highlights {
static final String SYSTEM = """
You write the opening paragraph of release notes for developers.
Use only the commits in the list. Do not invent pull request numbers or commit hashes.
Write at most three sentences of plain prose: no headings, no bullet lists.""";
private static final Pattern PR = Pattern.compile("#(\\d+)");
private static final Pattern HASH = Pattern.compile("\\b[0-9a-f]{7}\\b");
static final int MAX_CHARS = 600;
public record Result(String text, boolean fromModel, String rejection) {}
private final ChatClient client;
public Highlights(ChatModel model) {
this.client = ChatClient.create(model);
}
/** The user message: one line per commit, with the references the model is allowed to cite. */
public static String userMessage(String title, List<CommitInfo> commits) {
StringBuilder sb = new StringBuilder("Release " + title + ". Commits:\n");
for (CommitInfo c : commits) {
ConventionalCommit p = c.parsed();
sb.append("- ").append(c.shortSha()).append(' ').append(p.type());
p.scopeOpt().ifPresent(s -> sb.append('(').append(s).append(')'));
sb.append(": ").append(p.description());
if (p.prNumber() != null) sb.append(" (#").append(p.prNumber()).append(')');
if (p.breaking()) sb.append(" [BREAKING]");
sb.append('\n');
}
return sb.toString();
}
public Result write(String title, List<CommitInfo> commits, String fallback) {
String answer = client.prompt().system(SYSTEM).user(userMessage(title, commits)).call().content();
Optional<String> problem = check(answer, commits);
return problem.isEmpty() ? new Result(answer.strip(), true, null) : new Result(fallback, false, problem.get());
}
/** Empty when the answer is acceptable, otherwise why it was rejected. */
public static Optional<String> check(String answer, List<CommitInfo> commits) {
if (answer == null || answer.isBlank()) return Optional.of("empty answer");
if (answer.length() > MAX_CHARS) return Optional.of("longer than " + MAX_CHARS + " characters");
if (answer.lines().anyMatch(l -> l.startsWith("#") && l.length() > 1 && l.charAt(1) == ' ' || l.startsWith("##"))) {
return Optional.of("contains a markdown heading");
}
Set<String> prs = new HashSet<>();
Set<String> shas = new HashSet<>();
for (CommitInfo c : commits) {
shas.add(c.shortSha());
if (c.parsed().prNumber() != null) prs.add(String.valueOf(c.parsed().prNumber()));
}
Matcher m = PR.matcher(answer);
while (m.find()) {
if (!prs.contains(m.group(1))) return Optional.of("cites #" + m.group(1) + ", which is not in the commit list");
}
m = HASH.matcher(answer);
while (m.find()) {
if (!shas.contains(m.group())) return Optional.of("cites " + m.group() + ", which is not in the commit list");
}
return Optional.empty();
}
}
@@ -0,0 +1,83 @@
package com.ankurm.releasenotes;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import java.util.List;
import java.util.Optional;
/** Builds a pull request title and body from the commits and the budgeted diff between two branches. */
public final class PrDescription {
static final String SYSTEM = """
You write the Summary section of a pull request description for reviewers.
Use only the commits and diff provided. Do not invent pull request numbers or commit hashes.
Write at most three sentences of plain prose: no headings, no bullet lists.""";
public record Result(String title, String body, boolean summaryFromModel, String rejection,
DiffBudget.Budgeted budgeted, int promptChars) {}
private final ChatClient client;
private final DiffBudget budget;
public PrDescription(ChatModel model, DiffBudget budget) {
this.client = ChatClient.create(model);
this.budget = budget;
}
public Result describe(GitHistory history, String base, String head) {
List<CommitInfo> commits = history.commitsBetween(history.mergeBase(base, head).name(), head);
List<FileDiff> files = history.branchDiff(base, head);
ReleaseModel model = ReleaseModel.group(commits);
DiffBudget.Budgeted b = budget.apply(files);
String user = Highlights.userMessage(head + " into " + base, commits)
+ "\nFiles changed: " + files.size() + "\n\nDiff:\n" + b.text();
String answer = client.prompt().system(SYSTEM).user(user).call().content();
Optional<String> problem = Highlights.check(answer, commits);
boolean ok = problem.isEmpty();
int add = files.stream().mapToInt(FileDiff::added).sum();
int del = files.stream().mapToInt(FileDiff::deleted).sum();
String summary = ok ? answer.strip() : commits.size() + " commit" + (commits.size() == 1 ? "" : "s")
+ " touching " + files.size() + " file" + (files.size() == 1 ? "" : "s") + " (+" + add + "/-" + del + ").";
StringBuilder sb = new StringBuilder("## Summary\n\n").append(summary).append("\n\n");
if (!model.breaking().isEmpty()) {
sb.append("## Breaking changes\n\n");
for (CommitInfo c : model.breaking()) {
sb.append("- ").append(c.parsed().breakingNote() != null ? c.parsed().breakingNote() : c.parsed().description())
.append(" (").append(c.shortSha()).append(")\n");
}
sb.append('\n');
}
sb.append("## Changes\n\n");
for (var e : model.byType().entrySet()) {
for (CommitInfo c : e.getValue()) {
sb.append("- `").append(e.getKey()).append("` ").append(c.parsed().description())
.append(" (").append(c.shortSha()).append(")\n");
}
}
sb.append("\n## Files\n\n| File | Change | + | - |\n|---|---|---|---|\n");
for (FileDiff f : files) {
sb.append("| `").append(f.path()).append("` | ").append(f.changeType().toLowerCase())
.append(" | ").append(f.added()).append(" | ").append(f.deleted()).append(" |\n");
}
sb.append("\n## Checklist\n\n- [ ] Tests pass\n- [ ] Docs updated if behaviour changed\n");
return new Result(title(commits, head), sb.toString(), ok, problem.orElse(null), b, user.length());
}
/** One commit: its description. Several: the most significant one (breaking, then feat, then fix), plus a count. */
static String title(List<CommitInfo> commits, String head) {
if (commits.isEmpty()) return head;
CommitInfo lead = commits.stream()
.max(java.util.Comparator.comparingInt(PrDescription::rank)).orElseThrow();
String t = lead.parsed().description();
t = Character.toUpperCase(t.charAt(0)) + t.substring(1);
return commits.size() == 1 ? t : t + " (+" + (commits.size() - 1) + " more)";
}
private static int rank(CommitInfo c) {
if (c.parsed().breaking()) return 4;
return switch (c.parsed().type()) { case "feat" -> 3; case "fix" -> 2; default -> 1; };
}
}
@@ -0,0 +1,38 @@
package com.ankurm.releasenotes;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Commits grouped by conventional-commit type, plus the version bump they imply. Pure data, no model. */
public record ReleaseModel(List<CommitInfo> commits, Map<String, List<CommitInfo>> byType,
List<CommitInfo> breaking, SemVer.Bump bump) {
public static ReleaseModel group(List<CommitInfo> commits) {
Map<String, List<CommitInfo>> byType = new LinkedHashMap<>();
for (String t : ConventionalCommit.order()) {
byType.put(t, new ArrayList<>());
}
List<CommitInfo> breaking = new ArrayList<>();
for (CommitInfo c : commits) {
byType.get(c.parsed().type()).add(c);
if (c.parsed().breaking()) {
breaking.add(c);
}
}
byType.values().removeIf(List::isEmpty);
return new ReleaseModel(commits, byType, breaking, bumpFor(byType, breaking));
}
private static SemVer.Bump bumpFor(Map<String, List<CommitInfo>> byType, List<CommitInfo> breaking) {
if (!breaking.isEmpty()) return SemVer.Bump.MAJOR;
if (byType.containsKey("feat")) return SemVer.Bump.MINOR;
if (byType.containsKey("fix") || byType.containsKey("perf")) return SemVer.Bump.PATCH;
return SemVer.Bump.NONE;
}
public int count(String type) {
return byType.getOrDefault(type, List.of()).size();
}
}
@@ -0,0 +1,74 @@
package com.ankurm.releasenotes;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
/** Renders the grouped commits as Markdown. Every line that names a commit or a PR is produced by code, not by a model. */
public final class ReleaseNotes {
private static final Map<String, String> TITLES = Map.of(
"feat", "Features", "fix", "Bug fixes", "perf", "Performance", "revert", "Reverts",
"docs", "Documentation", "other", "Other changes");
/** Types that are listed only as a count, because readers of release notes rarely want them. */
private static final List<String> INTERNAL = List.of("refactor", "test", "build", "ci", "chore", "style");
private ReleaseNotes() {}
public static String render(String version, LocalDate date, String highlights, ReleaseModel m, String linkBase) {
StringBuilder sb = new StringBuilder();
sb.append("## ").append(version).append(" (").append(date).append(")\n\n");
if (highlights != null && !highlights.isBlank()) {
sb.append(highlights).append("\n\n");
}
if (!m.breaking().isEmpty()) {
sb.append("### Breaking changes\n\n");
for (CommitInfo c : m.breaking()) {
String note = c.parsed().breakingNote() != null ? c.parsed().breakingNote() : c.parsed().description();
sb.append("- ").append(note).append(" (").append(ref(c, linkBase)).append(")\n");
}
sb.append('\n');
}
for (var e : m.byType().entrySet()) {
if (!TITLES.containsKey(e.getKey())) continue;
sb.append("### ").append(TITLES.get(e.getKey())).append("\n\n");
for (CommitInfo c : e.getValue()) {
sb.append("- ");
c.parsed().scopeOpt().ifPresent(s -> sb.append("**").append(s).append(":** "));
sb.append(e.getKey().equals("revert") ? "Revert: " : "").append(c.parsed().description()).append(" (").append(ref(c, linkBase)).append(")\n");
}
sb.append('\n');
}
int internal = INTERNAL.stream().mapToInt(m::count).sum();
if (internal > 0) {
sb.append("_").append(internal).append(" internal change").append(internal == 1 ? "" : "s")
.append(" (refactor, test, build, ci, chore, style) not listed._\n");
}
return sb.toString().stripTrailing() + "\n";
}
static String ref(CommitInfo c, String linkBase) {
String commit = "[" + c.shortSha() + "](" + linkBase + "/commit/" + c.sha() + ")";
if (c.parsed().prNumber() == null) return commit;
return "[#" + c.parsed().prNumber() + "](" + linkBase + "/pulls/" + c.parsed().prNumber() + "), " + commit;
}
/** A sentence built from counts alone, used when the model is unavailable or its answer is rejected. */
public static String fallbackHighlights(ReleaseModel m) {
int f = m.count("feat"), x = m.count("fix");
StringBuilder sb = new StringBuilder("This release contains ")
.append(m.commits().size()).append(" commit").append(m.commits().size() == 1 ? "" : "s");
sb.append(": ").append(f).append(" feature").append(f == 1 ? "" : "s").append(" and ")
.append(x).append(" bug fix").append(x == 1 ? "" : "es").append('.');
if (!m.breaking().isEmpty()) {
int b = m.breaking().size();
sb.append(' ').append(b).append(" breaking change").append(b == 1 ? " is" : "s are").append(" listed first.");
}
return sb.toString();
}
public static LocalDate dateOf(CommitInfo c) {
return c.when().atOffset(ZoneOffset.UTC).toLocalDate();
}
}
@@ -0,0 +1,26 @@
package com.ankurm.releasenotes;
import java.nio.file.Path;
import java.time.LocalDate;
/**
* Command line: {@code ReleaseNotesApp <repo-dir> <tag-or-ref> [link-base]} prints the release notes for the
* commits since the previous version tag. It uses {@link StubChatModel}; wire a real Spring AI ChatModel in
* its place to get model-written highlights. It never posts anything: publishing is {@link GiteaClient}.
*/
public final class ReleaseNotesApp {
public static void main(String[] args) {
Path dir = Path.of(args[0]);
String ref = args[1];
String linkBase = args.length > 2 ? args[2] : "https://git.example/acme/shop";
try (GitHistory history = new GitHistory(dir)) {
var prev = history.previousTag(ref);
var commits = prev.isPresent() ? history.commitsBetween(prev.get(), ref) : history.commitsUpTo(ref);
ReleaseModel model = ReleaseModel.group(commits);
var hi = new Highlights(new StubChatModel()).write(ref, commits, ReleaseNotes.fallbackHighlights(model));
LocalDate date = commits.isEmpty() ? LocalDate.now() : ReleaseNotes.dateOf(commits.getLast());
System.out.print(ReleaseNotes.render(ref, date, hi.text(), model, linkBase));
}
}
}
@@ -0,0 +1,42 @@
package com.ankurm.releasenotes;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** A plain MAJOR.MINOR.PATCH version read from a tag such as {@code v1.4.2}. Pre-release tags are not versions here. */
public record SemVer(int major, int minor, int patch) implements Comparable<SemVer> {
private static final Pattern TAG = Pattern.compile("^v?(\\d+)\\.(\\d+)\\.(\\d+)$");
public enum Bump { NONE, PATCH, MINOR, MAJOR }
public static Optional<SemVer> parse(String tag) {
Matcher m = TAG.matcher(tag);
if (!m.matches()) {
return Optional.empty();
}
return Optional.of(new SemVer(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3))));
}
public SemVer apply(Bump bump) {
return switch (bump) {
case MAJOR -> new SemVer(major + 1, 0, 0);
case MINOR -> new SemVer(major, minor + 1, 0);
case PATCH -> new SemVer(major, minor, patch + 1);
case NONE -> this;
};
}
@Override
public int compareTo(SemVer o) {
if (major != o.major) return Integer.compare(major, o.major);
if (minor != o.minor) return Integer.compare(minor, o.minor);
return Integer.compare(patch, o.patch);
}
@Override
public String toString() {
return major + "." + minor + "." + patch;
}
}
@@ -0,0 +1,60 @@
package com.ankurm.releasenotes;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import java.util.ArrayList;
import java.util.List;
/**
* NOT a language model. A deterministic stand-in so the whole pipeline runs with no API key: it counts the
* feat/fix lines in the prompt and names the first feature, and records every prompt it receives. Its
* {@link Mode} values let tests force the three ways a real model misbehaves. Replace it with any Spring AI
* {@code ChatModel} bean (Anthropic, OpenAI, Ollama) and nothing else in this module changes.
*/
public final class StubChatModel implements ChatModel {
public enum Mode { HONEST, INVENT_REFERENCES, WRITE_HEADING, RAMBLE }
/** Every prompt received, rendered as [SYSTEM] and [USER] sections. */
public final List<String> prompts = new ArrayList<>();
public Mode mode = Mode.HONEST;
@Override
public ChatResponse call(Prompt prompt) {
String text = prompt.getContents();
StringBuilder rendered = new StringBuilder();
for (var message : prompt.getInstructions()) {
rendered.append('[').append(message.getMessageType()).append("]\n").append(message.getText()).append('\n');
}
prompts.add(rendered.toString());
int feats = 0, fixes = 0;
String firstFeat = null, firstSha = null;
for (String line : text.split("\n")) {
if (!line.startsWith("- ")) continue;
String[] parts = line.substring(2).split(" ", 3);
if (parts.length < 3) continue;
if (parts[1].startsWith("feat")) {
feats++;
if (firstFeat == null) {
firstFeat = parts[2];
firstSha = parts[0];
}
} else if (parts[1].startsWith("fix")) {
fixes++;
}
}
String out = "This stub counts " + feats + " feature" + (feats == 1 ? "" : "s") + " and " + fixes + " fix"
+ (fixes == 1 ? "" : "es") + (firstFeat == null ? "." : "; the first feature is \"" + firstFeat + "\" (" + firstSha + ").");
out = switch (mode) {
case HONEST -> out;
case INVENT_REFERENCES -> out + " It also closes #999 and fixes the regression from deadbee.";
case WRITE_HEADING -> "## Highlights\n" + out;
case RAMBLE -> (out + " ").repeat(12);
};
return new ChatResponse(List.of(new Generation(new AssistantMessage(out))));
}
}
@@ -0,0 +1,130 @@
package com.ankurm.releasenotes;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* NOT Gitea. A small HTTP server that answers the seven calls GiteaClient makes, using the status codes from
* Gitea 1.27.3's swagger document, and records every request. It lets the client's real HTTP code run
* without writing to a real repository.
*/
final class FakeGitea implements AutoCloseable {
final List<String> log = new ArrayList<>();
final Map<String, JsonNode> releases = new HashMap<>();
final Map<String, JsonNode> pulls = new HashMap<>();
private final JsonMapper json = JsonMapper.builder().build();
private final HttpServer server;
private int nextId = 100;
FakeGitea(String expectedToken) throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/api/v1/", ex -> {
try {
handle(ex, expectedToken);
} catch (Exception e) {
reply(ex, 500, "{\"message\":\"" + e + "\"}");
}
});
server.start();
}
String apiBase() {
return "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1";
}
private void handle(HttpExchange ex, String token) throws IOException {
String path = ex.getRequestURI().getRawPath().substring("/api/v1".length());
String method = ex.getRequestMethod();
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
String auth = ex.getRequestHeaders().getFirst("Authorization");
if (!("token " + token).equals(auth)) {
record(method, path, 401, null);
reply(ex, 401, "{\"message\":\"token is required\"}");
return;
}
String[] p = path.split("/"); // "", repos, owner, repo, kind, ...
String kind = p.length > 4 ? p[4] : "";
if (kind.equals("releases") && p.length == 7 && p[5].equals("tags") && method.equals("GET")) {
JsonNode r = releases.get(p[6]);
record(method, path, r == null ? 404 : 200, null);
reply(ex, r == null ? 404 : 200, r == null ? "{\"message\":\"release does not exist\"}" : r.toString());
} else if (kind.equals("releases") && p.length == 5 && method.equals("POST")) {
JsonNode in = json.readTree(body);
String tag = in.path("tag_name").asString();
var out = json.createObjectNode().put("id", nextId++).put("tag_name", tag)
.put("html_url", "http://fake/releases/tag/" + tag).put("body", in.path("body").asString())
.put("draft", in.path("draft").asBoolean());
releases.put(tag, out);
record(method, path, 201, in);
reply(ex, 201, out.toString());
} else if (kind.equals("releases") && p.length == 6 && method.equals("PATCH")) {
JsonNode in = json.readTree(body);
JsonNode old = releases.values().stream().filter(r -> r.path("id").asString().equals(p[5])).findFirst().orElseThrow();
var out = (tools.jackson.databind.node.ObjectNode) old;
out.put("body", in.path("body").asString());
record(method, path, 200, in);
reply(ex, 200, out.toString());
} else if (kind.equals("pulls") && p.length == 5 && method.equals("GET")) {
String query = ex.getRequestURI().getRawQuery();
boolean firstPage = query != null && query.contains("page=1");
var list = json.createArrayNode();
if (firstPage) pulls.values().forEach(list::add);
record(method, path + "?" + query, 200, null);
reply(ex, 200, list.toString());
} else if (kind.equals("pulls") && p.length == 5 && method.equals("POST")) {
JsonNode in = json.readTree(body);
var out = json.createObjectNode().put("number", nextId++ - 90).put("title", in.path("title").asString())
.put("body", in.path("body").asString()).put("html_url", "http://fake/pulls/" + (nextId - 91));
out.putObject("base").put("ref", in.path("base").asString());
out.putObject("head").put("ref", in.path("head").asString());
pulls.put(in.path("base").asString() + "..." + in.path("head").asString(), out);
record(method, path, 201, in);
reply(ex, 201, out.toString());
} else if (kind.equals("pulls") && p.length == 6 && method.equals("PATCH")) {
JsonNode in = json.readTree(body);
var out = (tools.jackson.databind.node.ObjectNode) pulls.values().stream()
.filter(r -> r.path("number").asString().equals(p[5])).findFirst().orElseThrow();
out.put("title", in.path("title").asString()).put("body", in.path("body").asString());
record(method, path, 201, in);
reply(ex, 201, out.toString());
} else {
record(method, path, 404, null);
reply(ex, 404, "{\"message\":\"not found\"}");
}
}
private void record(String method, String path, int status, JsonNode in) {
String fields = in == null ? "" : " fields=" + fieldNames(in);
log.add(method + " " + path + " -> " + status + fields);
}
private static List<String> fieldNames(JsonNode n) {
List<String> names = new ArrayList<>();
n.propertyNames().forEach(names::add);
return names;
}
private void reply(HttpExchange ex, int status, String body) throws IOException {
byte[] b = body.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(status, b.length);
ex.getResponseBody().write(b);
ex.close();
}
@Override
public void close() {
server.stop(0);
}
}
@@ -0,0 +1,118 @@
package com.ankurm.releasenotes;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeCommand;
import org.eclipse.jgit.lib.PersonIdent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.TimeZone;
/**
* Builds a real Git repository on disk with JGit. Author, committer and tagger dates are fixed, so the commit
* hashes are the same on every run and the transcripts in output/ diff cleanly.
*/
final class Fixture implements AutoCloseable {
final Path dir;
final Git git;
private Instant clock = Instant.parse("2026-01-05T10:00:00Z");
Fixture(Path dir) throws Exception {
this.dir = dir;
this.git = Git.init().setDirectory(dir.toFile()).setInitialBranch("main").call();
// A developer's global ~/.gitconfig (commit.gpgsign=true, gpg.format=ssh) leaks into JGit and makes
// every commit here fail with UnsupportedSigningFormatException. Pin it off for this repository.
var cfg = git.getRepository().getConfig();
cfg.setBoolean("commit", null, "gpgsign", false);
cfg.setBoolean("tag", null, "gpgsign", false);
cfg.save();
}
private PersonIdent who() {
clock = clock.plus(1, ChronoUnit.DAYS);
return new PersonIdent("Dev One", "[email protected]", clock, TimeZone.getTimeZone("UTC").toZoneId());
}
Fixture write(String path, String content) throws IOException {
Path p = dir.resolve(path);
Files.createDirectories(p.getParent());
Files.writeString(p, content);
return this;
}
String commit(String message) throws Exception {
git.add().addFilepattern(".").call();
PersonIdent id = who();
return git.commit().setSign(false).setMessage(message).setAuthor(id).setCommitter(id).call().getName();
}
Fixture annotatedTag(String name) throws Exception {
git.tag().setSigned(false).setName(name).setAnnotated(true).setMessage("Release " + name).setTagger(who()).call();
return this;
}
Fixture lightTag(String name) throws Exception {
git.tag().setSigned(false).setName(name).setAnnotated(false).call();
return this;
}
Fixture branch(String name) throws Exception {
git.checkout().setCreateBranch(true).setName(name).call();
return this;
}
Fixture checkout(String name) throws Exception {
git.checkout().setName(name).call();
return this;
}
/**
* JGit's merge command stamps the merge commit with the wall clock, which would change every later hash on
* every run. So the merge is prepared without committing and then committed with a fixed date.
*/
void mergeNoFf(String branch, String message) throws Exception {
git.merge().include(git.getRepository().findRef(branch)).setFastForward(MergeCommand.FastForwardMode.NO_FF)
.setCommit(false).call();
commit(message);
}
/** The release history used by most tests. v1.0.0 is annotated, v1.1.0 is lightweight. */
static Fixture releaseHistory(Path dir) throws Exception {
Fixture f = new Fixture(dir);
f.write("README.md", "# shop\n").write("src/Order.java", "class Order { int id; }\n")
.write("package-lock.json", "{}\n");
f.commit("chore: initial commit");
f.write("src/OrderApi.java", "class OrderApi { void list() {} }\n").commit("feat(api): add order listing endpoint (#1)");
f.write("src/OrderApi.java", "class OrderApi { void list() {} int get(int id) { return 404; } }\n")
.commit("fix(api): return 404 for unknown order id (#2)");
f.annotatedTag("v1.0.0");
f.write("src/Cli.java", "class Cli { boolean json; }\n").commit("feat(cli): add --json output flag (#3)");
f.write("src/Retry.java", "class Retry { int max = 3; }\n").commit("fix: stop retrying on 4xx");
f.write("docs/retry.md", "Retries happen on 5xx only.\n").commit("docs: explain retry policy");
f.write("src/Misc.java", "class Misc {}\n").commit("Fixed stuff");
f.write("src/Order.java", "class Order { int orderId; }\n")
.commit("refactor(core)!: rename Order.id to Order.orderId\n\nBREAKING CHANGE: Order.getId() is now Order.getOrderId(),\nupdate every caller.\n\nRefs: #4");
f.write("src/OrderRepository.java", "class OrderRepository { void saveAll() {} }\n").commit("perf(db): batch inserts in OrderRepository (#5)");
f.write("src/Wip.java", "class Wip {}\n").commit("wip: half done");
f.branch("feature/search");
f.write("src/Search.java", "class Search { boolean fuzzy; }\n").commit("feat(search): add fuzzy search (#6)");
f.checkout("main");
f.write("docs/retry.md", "Retries happen on 5xx only. Back-off is exponential.\n").commit("docs: document back-off");
f.mergeNoFf("feature/search", "Merge branch 'feature/search'");
f.write("src/Cli.java", "class Cli {}\n").commit("Revert \"feat(cli): add --json output flag\"\n\nThis reverts commit abc1234.");
f.lightTag("v1.1.0");
return f;
}
@Override
public void close() {
git.close();
}
}
@@ -0,0 +1,278 @@
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 <repo> 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");
}
}
}
@@ -0,0 +1,25 @@
package com.ankurm.releasenotes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects lines and writes them to output/NN-name.txt, so the test IS the transcript. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String file;
Transcript(String file) { this.file = file; }
void line(String s) { lines.add(s); }
void block(String s) { s.stripTrailing().lines().forEach(lines::add); }
void write() throws IOException {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.write(dir.resolve(file), lines);
}
}