@hamzaahmadaslam/commit-changelog 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +233 -2
- package/bin/commit-changelog.mjs +4 -0
- package/package.json +40 -4
- package/src/changelog.mjs +156 -0
- package/src/classify.mjs +257 -0
- package/src/cli.mjs +212 -0
- package/src/conventional.mjs +40 -0
- package/src/errors.mjs +7 -0
- package/src/git.mjs +184 -0
- package/src/jev.mjs +92 -0
- package/src/report.mjs +220 -0
package/src/classify.mjs
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Places every commit of the range: listed in a changelog section, internal, or review. A commit with a known
|
|
2
|
+
// conventional-commit prefix is placed by its prefix. The others are sent to Jev, up to --batch commits per
|
|
3
|
+
// request, with two questions each, and code decides from the answers. The thresholds live here, in code.
|
|
4
|
+
import { sectionFromPrefix } from "./conventional.mjs";
|
|
5
|
+
import { askJev, choice, DEFAULT_MODEL, noul } from "./jev.mjs";
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_THRESHOLD = 0.8;
|
|
8
|
+
export const DEFAULT_BATCH = 20;
|
|
9
|
+
export const MAX_BATCH = 50;
|
|
10
|
+
export const DEFAULT_TIMEOUT_SECONDS = 10;
|
|
11
|
+
/** Estimated tokens of state per request. TypeSafe allows 32k for the state plus the longest question. */
|
|
12
|
+
export const STATE_BUDGET = 16_000;
|
|
13
|
+
/** How much of a message body is sent, in characters. */
|
|
14
|
+
export const MAX_BODY_CHARS = 1_200;
|
|
15
|
+
/** How many changed file names are sent per commit; the rest are only counted. */
|
|
16
|
+
export const MAX_FILES = 20;
|
|
17
|
+
const CONCURRENCY = 4;
|
|
18
|
+
|
|
19
|
+
/** The Keep a Changelog 1.1.0 types of change in the order it lists them, then internal. */
|
|
20
|
+
export const SECTIONS = ["added", "changed", "deprecated", "removed", "fixed", "security", "internal"];
|
|
21
|
+
|
|
22
|
+
export const SECTION_OPTIONS = {
|
|
23
|
+
added: "A new feature, command, option, setting or supported platform that users did not have before.",
|
|
24
|
+
changed: "A change to how existing features behave, look or perform, or to defaults or requirements, that users notice.",
|
|
25
|
+
deprecated: "A feature that still works but is announced as going away in a later release.",
|
|
26
|
+
removed: "A feature, option or supported platform that users had before is taken away.",
|
|
27
|
+
fixed: "A bug fix: something users could run into did not work as intended and now does.",
|
|
28
|
+
security: "A fix for a security vulnerability, or a change that protects users against an attack or a data leak.",
|
|
29
|
+
internal:
|
|
30
|
+
"Nothing users of the software notice: tests, refactoring, code style, comments, documentation, build or CI setup, development tooling or repository housekeeping.",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const USERS_CRITERIA = {
|
|
34
|
+
true: "Users can notice it: behaviour, output, interface, options, defaults, performance, compatibility or requirements change, or a bug or vulnerability they could run into is fixed.",
|
|
35
|
+
false:
|
|
36
|
+
"Only developers notice it: it changes tests, code structure or style, comments, documentation, build or CI setup, or development tooling, and the software works the same for its users.",
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** A rough token count: about four characters per token, which fits English text. Used for batching and estimates. */
|
|
40
|
+
export function estimateTokens(text) {
|
|
41
|
+
return Math.ceil(text.length / 4);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// An address with a dotted domain that ends in letters: "name@example.com", not "package@1.2.3".
|
|
45
|
+
const EMAIL = /[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[A-Za-z]{2,}\b/g;
|
|
46
|
+
// A trailer line that names a person by address, such as "Signed-off-by: Name <name@example.com>".
|
|
47
|
+
const EMAIL_TRAILER = /^[A-Za-z][\w-]*:.*<[^<>\s]+@[^<>\s]+>$/;
|
|
48
|
+
|
|
49
|
+
/** Replaces email addresses with [email]. */
|
|
50
|
+
export function maskEmails(text) {
|
|
51
|
+
return text.replace(EMAIL, "[email]");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The message body as it is sent: trailer lines that carry an email address are dropped, other addresses are
|
|
56
|
+
* masked, runs of blank lines are shortened, and the text is cut at MAX_BODY_CHARS on a word boundary.
|
|
57
|
+
*/
|
|
58
|
+
export function cleanBody(body) {
|
|
59
|
+
const kept = body.split("\n").filter((line) => !EMAIL_TRAILER.test(line.trim()));
|
|
60
|
+
let text = maskEmails(kept.join("\n")).replace(/\n{3,}/g, "\n\n").trim();
|
|
61
|
+
if (text.length > MAX_BODY_CHARS) {
|
|
62
|
+
const cut = text.slice(0, MAX_BODY_CHARS);
|
|
63
|
+
const space = cut.search(/\s\S*$/);
|
|
64
|
+
text = `${(space > MAX_BODY_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()} [...]`;
|
|
65
|
+
}
|
|
66
|
+
return text;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** What Jev sees of one commit: first line, cleaned body and up to MAX_FILES changed file names. No hash, author or date. */
|
|
70
|
+
export function stateEntry(commit) {
|
|
71
|
+
const entry = { subject: maskEmails(commit.firstLine) };
|
|
72
|
+
const body = cleanBody(commit.body);
|
|
73
|
+
if (body) entry.body = body;
|
|
74
|
+
entry.changed_files = commit.files.slice(0, MAX_FILES);
|
|
75
|
+
if (commit.files.length > MAX_FILES) entry.more_changed_files = commit.files.length - MAX_FILES;
|
|
76
|
+
return entry;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The two questions asked about the commit at `commits[at]` in the state. `key` prefixes the question ids. */
|
|
80
|
+
export function questionsFor(key, at) {
|
|
81
|
+
const self = `\`commits[${at}]\``;
|
|
82
|
+
return {
|
|
83
|
+
[`${key}_section`]: choice(
|
|
84
|
+
`${self} is one commit from the history of a software project: its subject line, its message body when it has one, and the names of the files it changed. In which section of the project's changelog does this change belong?`,
|
|
85
|
+
SECTION_OPTIONS,
|
|
86
|
+
),
|
|
87
|
+
[`${key}_users`]: noul(
|
|
88
|
+
`Does the change in ${self} affect the people who use the software, rather than only the people who develop it?`,
|
|
89
|
+
USERS_CRITERIA,
|
|
90
|
+
),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Tokens an entry takes up inside the JSON state, quotes and escapes included. */
|
|
95
|
+
const entryTokens = (entry) => estimateTokens(JSON.stringify(entry));
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Sorts the commits into the ones placed without Jev (by prefix, or an empty message) and the ones to ask, and
|
|
99
|
+
* groups the ones to ask into requests of up to `batch` commits whose state stays under STATE_BUDGET. Every entry
|
|
100
|
+
* keeps its commit, so the report can list them in history order.
|
|
101
|
+
*/
|
|
102
|
+
export function planCommits(commits, { batch = DEFAULT_BATCH, model = DEFAULT_MODEL } = {}) {
|
|
103
|
+
const entries = commits.map((commit) => {
|
|
104
|
+
if (!commit.firstLine) {
|
|
105
|
+
return { commit, decidedBy: "none", prefix: null, outcome: "review", section: null, reasons: ["empty_message"], answer: null };
|
|
106
|
+
}
|
|
107
|
+
const prefix = sectionFromPrefix(commit.firstLine, commit.body);
|
|
108
|
+
if (prefix) {
|
|
109
|
+
const outcome = prefix.section === "internal" ? "internal" : "listed";
|
|
110
|
+
return { commit, decidedBy: "prefix", prefix, outcome, section: prefix.section, reasons: [], answer: null };
|
|
111
|
+
}
|
|
112
|
+
return { commit, decidedBy: "jev", prefix: null, outcome: null, section: null, reasons: [], answer: null };
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const asked = entries.filter((entry) => entry.decidedBy === "jev").map((entry, n) => ({ entry, key: `c${n}`, state: stateEntry(entry.commit) }));
|
|
116
|
+
const requests = [];
|
|
117
|
+
let i = 0;
|
|
118
|
+
while (i < asked.length) {
|
|
119
|
+
const group = [asked[i]];
|
|
120
|
+
let tokens = entryTokens(asked[i].state);
|
|
121
|
+
let j = i + 1;
|
|
122
|
+
while (j < asked.length && group.length < batch) {
|
|
123
|
+
const more = entryTokens(asked[j].state);
|
|
124
|
+
if (tokens + more > STATE_BUDGET) break;
|
|
125
|
+
tokens += more;
|
|
126
|
+
group.push(asked[j++]);
|
|
127
|
+
}
|
|
128
|
+
const questions = {};
|
|
129
|
+
const targets = group.map((item, at) => {
|
|
130
|
+
Object.assign(questions, questionsFor(item.key, at));
|
|
131
|
+
return { key: item.key, at, entry: item.entry };
|
|
132
|
+
});
|
|
133
|
+
requests.push({ targets, body: { model, state: { commits: group.map((item) => item.state) }, questions } });
|
|
134
|
+
i = j;
|
|
135
|
+
}
|
|
136
|
+
return { entries, requests, asked: asked.length };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Estimated input tokens of a plan, per request and in total, for --dry-run. */
|
|
140
|
+
export function estimatePlan(plan) {
|
|
141
|
+
const perRequest = plan.requests.map((request) => estimateTokens(JSON.stringify(request.body)));
|
|
142
|
+
const tokens = perRequest.reduce((sum, n) => sum + n, 0);
|
|
143
|
+
return { perRequest, tokens };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const isProbability = (value) => typeof value === "number" && value >= 0 && value <= 1;
|
|
147
|
+
|
|
148
|
+
/** The two answers for one commit from a response, or null when either is missing or malformed. */
|
|
149
|
+
export function readAnswer(answers, key) {
|
|
150
|
+
const section = answers?.[`${key}_section`];
|
|
151
|
+
const users = answers?.[`${key}_users`]?.noul;
|
|
152
|
+
if (!isProbability(users)) return null;
|
|
153
|
+
if (!SECTIONS.includes(section?.choice) || !isProbability(section.confidence)) return null;
|
|
154
|
+
if (!section.probabilities || typeof section.probabilities !== "object") return null;
|
|
155
|
+
return { section: { choice: section.choice, confidence: section.confidence, probabilities: section.probabilities }, users };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Rounding keeps float noise (1 - 0.8 is 0.19999999999999996) from moving an answer that sits on the threshold.
|
|
159
|
+
const round = (value) => Math.round(value * 1e6) / 1e6;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Places one commit from its answers. The section counts only when its confidence is at or above `threshold`; the
|
|
163
|
+
* users answer counts as yes at or above `threshold` and as no at or below 1 - `threshold`.
|
|
164
|
+
* listed: a confident section other than internal, and a confident yes.
|
|
165
|
+
* internal: a confident internal, and a confident no.
|
|
166
|
+
* review: anything else, with the reasons.
|
|
167
|
+
*/
|
|
168
|
+
export function decide(answer, threshold = DEFAULT_THRESHOLD) {
|
|
169
|
+
const { section, users } = answer;
|
|
170
|
+
const sure = round(section.confidence) >= threshold;
|
|
171
|
+
const yes = round(users) >= threshold;
|
|
172
|
+
const no = round(1 - users) >= threshold;
|
|
173
|
+
const internal = section.choice === "internal";
|
|
174
|
+
if (sure && !internal && yes) return { outcome: "listed", section: section.choice, reasons: [] };
|
|
175
|
+
if (sure && internal && no) return { outcome: "internal", section: "internal", reasons: [] };
|
|
176
|
+
const reasons = [];
|
|
177
|
+
if (!sure) reasons.push("unsure_section");
|
|
178
|
+
if (!yes && !no) reasons.push("unsure_users");
|
|
179
|
+
if (sure && ((internal && yes) || (!internal && no))) reasons.push("answers_disagree");
|
|
180
|
+
return { outcome: "review", section: section.choice, reasons };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Runs `worker` over `items` with at most `limit` at a time; stops starting new work after the first failure. */
|
|
184
|
+
async function mapLimit(items, limit, worker) {
|
|
185
|
+
const results = new Array(items.length);
|
|
186
|
+
let next = 0;
|
|
187
|
+
let failed = false;
|
|
188
|
+
const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
189
|
+
while (!failed && next < items.length) {
|
|
190
|
+
const index = next++;
|
|
191
|
+
try {
|
|
192
|
+
results[index] = await worker(items[index]);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
failed = true;
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
await Promise.all(lanes);
|
|
200
|
+
return results;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Counts of a finished run. */
|
|
204
|
+
export function summarize(entries) {
|
|
205
|
+
const summary = { commits: entries.length, listed: 0, internal: 0, review: 0, by_prefix: 0, asked: 0 };
|
|
206
|
+
for (const entry of entries) {
|
|
207
|
+
summary[entry.outcome]++;
|
|
208
|
+
if (entry.decidedBy === "prefix") summary.by_prefix++;
|
|
209
|
+
if (entry.decidedBy === "jev") summary.asked++;
|
|
210
|
+
}
|
|
211
|
+
return summary;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Sends every request in the plan (four at a time) and places every commit:
|
|
216
|
+
* { model, threshold, entries: [{ commit, decidedBy, prefix, outcome, section, reasons, answer }], summary, usage }.
|
|
217
|
+
* Entries are in history order. A plan without requests makes no call and needs no key. Any TypeSafe error
|
|
218
|
+
* (missing key, 401, 422, 429 or 529 after retries, timeout) stops the run with a JevError.
|
|
219
|
+
*/
|
|
220
|
+
export async function runPlan(plan, options = {}) {
|
|
221
|
+
const {
|
|
222
|
+
threshold = DEFAULT_THRESHOLD,
|
|
223
|
+
apiKey,
|
|
224
|
+
model = DEFAULT_MODEL,
|
|
225
|
+
timeoutSeconds = DEFAULT_TIMEOUT_SECONDS,
|
|
226
|
+
retries = 3,
|
|
227
|
+
fetchImpl,
|
|
228
|
+
onProgress,
|
|
229
|
+
} = options;
|
|
230
|
+
let done = 0;
|
|
231
|
+
const responses = await mapLimit(plan.requests, CONCURRENCY, async (request) => {
|
|
232
|
+
const response = await askJev(request.body.state, request.body.questions, {
|
|
233
|
+
apiKey,
|
|
234
|
+
model,
|
|
235
|
+
timeoutMs: timeoutSeconds * 1000,
|
|
236
|
+
retries,
|
|
237
|
+
fetchImpl,
|
|
238
|
+
});
|
|
239
|
+
onProgress?.(++done, plan.requests.length);
|
|
240
|
+
return response;
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const outcomes = new Map();
|
|
244
|
+
plan.requests.forEach((request, i) => {
|
|
245
|
+
for (const { key, entry } of request.targets) {
|
|
246
|
+
const answer = readAnswer(responses[i].answers, key);
|
|
247
|
+
outcomes.set(entry, answer ? { answer, ...decide(answer, threshold) } : { answer: null, outcome: "review", section: null, reasons: ["no_answer"] });
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
const entries = plan.entries.map((entry) => (outcomes.has(entry) ? { ...entry, ...outcomes.get(entry) } : entry));
|
|
251
|
+
const usage = {
|
|
252
|
+
requests: responses.length,
|
|
253
|
+
input_tokens: responses.reduce((sum, r) => sum + (Number(r.usage?.input_tokens) || 0), 0),
|
|
254
|
+
output_tokens: responses.reduce((sum, r) => sum + (Number(r.usage?.output_tokens) || 0), 0),
|
|
255
|
+
};
|
|
256
|
+
return { model: responses[0]?.model ?? model, threshold, entries, summary: summarize(entries), usage };
|
|
257
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// The command line: parses options, reads the commits, places them, and prints the report, the JSON or the dry
|
|
2
|
+
// run, or adds the section to a changelog file. main() takes its environment, output streams, working folder, clock
|
|
3
|
+
// and fetch as arguments, so tests run it without a network.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { buildSection, checkChangelog, isUnreleased, UNRELEASED, writeChangelog } from "./changelog.mjs";
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_BATCH,
|
|
10
|
+
DEFAULT_THRESHOLD,
|
|
11
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
12
|
+
MAX_BATCH,
|
|
13
|
+
planCommits,
|
|
14
|
+
runPlan,
|
|
15
|
+
} from "./classify.mjs";
|
|
16
|
+
import { UserError } from "./errors.mjs";
|
|
17
|
+
import { openRepository, readCommits, resolveRange } from "./git.mjs";
|
|
18
|
+
import { DEFAULT_MODEL, JevError } from "./jev.mjs";
|
|
19
|
+
import { dryRunJson, formatDryRun, formatReport, toJson } from "./report.mjs";
|
|
20
|
+
|
|
21
|
+
export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
22
|
+
|
|
23
|
+
export const USAGE = `Usage: commit-changelog [repository] [options]
|
|
24
|
+
|
|
25
|
+
Reads the commits between two refs of a local git repository and prints a Keep a Changelog section with each
|
|
26
|
+
commit's own first line in the section it belongs in. A conventional-commit prefix (feat:, fix:, docs: ...) places
|
|
27
|
+
a commit directly; Jev is asked about the others, and commits it is unsure of are listed for review.
|
|
28
|
+
|
|
29
|
+
Options:
|
|
30
|
+
--from <ref> start after this tag, branch or commit (default: the last tag before --to)
|
|
31
|
+
--to <ref> end at this tag, branch or commit (default: HEAD)
|
|
32
|
+
--version-label <text> the version in the section heading, such as 1.3.0 (default: ${UNRELEASED})
|
|
33
|
+
--date <YYYY-MM-DD> the release date in the heading (default: today; needs --version-label)
|
|
34
|
+
--include-internal also list internal commits, under Internal
|
|
35
|
+
--write <file> add the section to this changelog file above the older releases
|
|
36
|
+
--threshold <p> confidence needed to place a commit, above 0.5 and up to 1 (default ${DEFAULT_THRESHOLD})
|
|
37
|
+
--batch <n> commits per request, 1 to ${MAX_BATCH} (default ${DEFAULT_BATCH})
|
|
38
|
+
--timeout <seconds> time limit for each request (default ${DEFAULT_TIMEOUT_SECONDS})
|
|
39
|
+
--json print JSON instead of the report
|
|
40
|
+
--dry-run print the commits, the questions and a token estimate; send and write nothing
|
|
41
|
+
-h, --help show this help
|
|
42
|
+
-v, --version show the version
|
|
43
|
+
|
|
44
|
+
Environment:
|
|
45
|
+
TYPESAFE_API_KEY your TypeSafe API key (needed when a commit has no conventional-commit prefix)
|
|
46
|
+
TYPESAFE_MODEL the model to use (default ${DEFAULT_MODEL})
|
|
47
|
+
|
|
48
|
+
Exit codes: 0 every commit placed, 1 at least one commit to review, 2 error.
|
|
49
|
+
`;
|
|
50
|
+
|
|
51
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
52
|
+
|
|
53
|
+
/** A YYYY-MM-DD date that exists in the calendar, or a UserError. */
|
|
54
|
+
export function checkDate(value) {
|
|
55
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
56
|
+
if (match) {
|
|
57
|
+
const [year, month, day] = match.slice(1).map(Number);
|
|
58
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
59
|
+
if (date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day) return value;
|
|
60
|
+
}
|
|
61
|
+
throw new UserError(`--date must be a date written as YYYY-MM-DD, such as 2026-10-01, not "${value}".`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function checkLabel(value) {
|
|
65
|
+
const label = value.trim();
|
|
66
|
+
if (!label || label.length > 100 || /[[\]\u0000-\u001f\u007f]/.test(label)) {
|
|
67
|
+
throw new UserError(`--version-label must be a short version such as 1.3.0, without brackets, not "${value}".`);
|
|
68
|
+
}
|
|
69
|
+
return label;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseOptions(argv, now) {
|
|
73
|
+
let parsed;
|
|
74
|
+
try {
|
|
75
|
+
parsed = parseArgs({
|
|
76
|
+
args: argv,
|
|
77
|
+
allowPositionals: true,
|
|
78
|
+
options: {
|
|
79
|
+
from: { type: "string" },
|
|
80
|
+
to: { type: "string" },
|
|
81
|
+
"version-label": { type: "string" },
|
|
82
|
+
date: { type: "string" },
|
|
83
|
+
"include-internal": { type: "boolean", default: false },
|
|
84
|
+
write: { type: "string" },
|
|
85
|
+
threshold: { type: "string" },
|
|
86
|
+
batch: { type: "string" },
|
|
87
|
+
timeout: { type: "string" },
|
|
88
|
+
json: { type: "boolean", default: false },
|
|
89
|
+
"dry-run": { type: "boolean", default: false },
|
|
90
|
+
help: { type: "boolean", short: "h", default: false },
|
|
91
|
+
version: { type: "boolean", short: "v", default: false },
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw new UserError(`${error.message} Run commit-changelog --help for the options.`);
|
|
96
|
+
}
|
|
97
|
+
const { values, positionals } = parsed;
|
|
98
|
+
if (values.help || values.version) return { help: values.help, version: values.version };
|
|
99
|
+
if (positionals.length > 1) {
|
|
100
|
+
throw new UserError("Give at most one repository folder. Run commit-changelog --help for usage.");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const threshold = values.threshold === undefined ? DEFAULT_THRESHOLD : Number(values.threshold);
|
|
104
|
+
if (!(threshold > 0.5 && threshold <= 1)) {
|
|
105
|
+
throw new UserError(`--threshold must be a number above 0.5 and at most 1, not "${values.threshold}".`);
|
|
106
|
+
}
|
|
107
|
+
const batch = values.batch === undefined ? DEFAULT_BATCH : Number(values.batch);
|
|
108
|
+
if (!Number.isInteger(batch) || batch < 1 || batch > MAX_BATCH) {
|
|
109
|
+
throw new UserError(`--batch must be a whole number from 1 to ${MAX_BATCH}, not "${values.batch}".`);
|
|
110
|
+
}
|
|
111
|
+
const timeoutSeconds = values.timeout === undefined ? DEFAULT_TIMEOUT_SECONDS : Number(values.timeout);
|
|
112
|
+
if (!(timeoutSeconds > 0 && timeoutSeconds <= 600)) {
|
|
113
|
+
throw new UserError(`--timeout must be a number of seconds above 0 and at most 600, not "${values.timeout}".`);
|
|
114
|
+
}
|
|
115
|
+
const label = values["version-label"] === undefined ? UNRELEASED : checkLabel(values["version-label"]);
|
|
116
|
+
let date = null;
|
|
117
|
+
if (isUnreleased(label)) {
|
|
118
|
+
if (values.date !== undefined) throw new UserError("--date needs --version-label: an Unreleased section has no date.");
|
|
119
|
+
} else {
|
|
120
|
+
const today = now();
|
|
121
|
+
date = values.date === undefined ? `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}` : checkDate(values.date);
|
|
122
|
+
}
|
|
123
|
+
if (values.write !== undefined && !values.write.trim()) throw new UserError("--write needs a file name, such as CHANGELOG.md.");
|
|
124
|
+
return {
|
|
125
|
+
repository: positionals[0] ?? ".",
|
|
126
|
+
from: values.from,
|
|
127
|
+
to: values.to ?? "HEAD",
|
|
128
|
+
label: isUnreleased(label) ? UNRELEASED : label,
|
|
129
|
+
date,
|
|
130
|
+
includeInternal: values["include-internal"],
|
|
131
|
+
write: values.write,
|
|
132
|
+
threshold,
|
|
133
|
+
batch,
|
|
134
|
+
timeoutSeconds,
|
|
135
|
+
json: values.json,
|
|
136
|
+
dryRun: values["dry-run"],
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Runs the tool. Returns the exit code: 0 every commit placed, 1 at least one commit to review, 2 an error. */
|
|
141
|
+
export async function main(argv, io = {}) {
|
|
142
|
+
const {
|
|
143
|
+
env = process.env,
|
|
144
|
+
stdout = process.stdout,
|
|
145
|
+
stderr = process.stderr,
|
|
146
|
+
fetchImpl = globalThis.fetch,
|
|
147
|
+
cwd = process.cwd(),
|
|
148
|
+
now = () => new Date(),
|
|
149
|
+
} = io;
|
|
150
|
+
const write = (stream, text) => stream.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
151
|
+
try {
|
|
152
|
+
const options = parseOptions(argv, now);
|
|
153
|
+
if (options.help || options.version) {
|
|
154
|
+
write(stdout, options.help ? USAGE : VERSION);
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const repo = await openRepository(options.repository, { cwd });
|
|
159
|
+
const range = await resolveRange(repo, { from: options.from, to: options.to });
|
|
160
|
+
const commits = await readCommits(repo, range);
|
|
161
|
+
const model = env.TYPESAFE_MODEL?.trim() || DEFAULT_MODEL;
|
|
162
|
+
const plan = planCommits(commits, { batch: options.batch, model });
|
|
163
|
+
const meta = {
|
|
164
|
+
version: VERSION,
|
|
165
|
+
range,
|
|
166
|
+
label: options.label,
|
|
167
|
+
date: options.date,
|
|
168
|
+
heading: `[${options.label}]`,
|
|
169
|
+
includeInternal: options.includeInternal,
|
|
170
|
+
batch: options.batch,
|
|
171
|
+
model,
|
|
172
|
+
writeFile: options.write ?? null,
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
if (options.dryRun) {
|
|
176
|
+
write(stdout, options.json ? JSON.stringify(dryRunJson(plan, meta), null, 2) : formatDryRun(plan, meta));
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// A --write that would fail anyway fails now, before any token is spent.
|
|
181
|
+
const target = options.write ? path.resolve(cwd, options.write) : null;
|
|
182
|
+
if (target) checkChangelog(target, options.label);
|
|
183
|
+
const apiKey = env.TYPESAFE_API_KEY?.trim();
|
|
184
|
+
if (plan.requests.length && !apiKey) {
|
|
185
|
+
throw new UserError(
|
|
186
|
+
`TYPESAFE_API_KEY is not set, and Jev has to be asked about ${plan.asked} ${plan.asked === 1 ? "commit" : "commits"} ` +
|
|
187
|
+
"without a conventional-commit prefix. Get a key at https://typesafe.ai and export it first, or use --dry-run " +
|
|
188
|
+
"to see what would be sent.",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
const progress = stderr.isTTY
|
|
192
|
+
? (done, total) => stderr.write(`\rasked ${done} of ${total} requests${done === total ? "\n" : ""}`)
|
|
193
|
+
: undefined;
|
|
194
|
+
const result = await runPlan(plan, {
|
|
195
|
+
threshold: options.threshold,
|
|
196
|
+
apiKey,
|
|
197
|
+
model,
|
|
198
|
+
timeoutSeconds: options.timeoutSeconds,
|
|
199
|
+
fetchImpl,
|
|
200
|
+
onProgress: progress,
|
|
201
|
+
});
|
|
202
|
+
const section = buildSection(result.entries, { label: options.label, date: options.date, includeInternal: options.includeInternal });
|
|
203
|
+
const written = target && section.text ? writeChangelog(target, section.text, options.label) : null;
|
|
204
|
+
const outcome = { ...meta, section, written };
|
|
205
|
+
write(stdout, options.json ? JSON.stringify(toJson(result, outcome), null, 2) : formatReport(result, outcome));
|
|
206
|
+
return result.summary.review > 0 ? 1 : 0;
|
|
207
|
+
} catch (error) {
|
|
208
|
+
const known = error instanceof UserError || error instanceof JevError;
|
|
209
|
+
write(stderr, `commit-changelog: ${known ? error.message : `unexpected error: ${error?.message ?? error}`}`);
|
|
210
|
+
return 2;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Reads a conventional-commit prefix ("feat: ...", "fix(parser)!: ...") from a commit's first line. A commit whose
|
|
2
|
+
// type is in PREFIX_SECTIONS is placed by that type, in code, and is never sent to Jev.
|
|
3
|
+
|
|
4
|
+
/** The section each conventional-commit type goes to. Other types (revert, or a team's own) are asked like any commit. */
|
|
5
|
+
export const PREFIX_SECTIONS = {
|
|
6
|
+
feat: "added",
|
|
7
|
+
fix: "fixed",
|
|
8
|
+
perf: "changed",
|
|
9
|
+
docs: "internal",
|
|
10
|
+
style: "internal",
|
|
11
|
+
refactor: "internal",
|
|
12
|
+
test: "internal",
|
|
13
|
+
build: "internal",
|
|
14
|
+
ci: "internal",
|
|
15
|
+
chore: "internal",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// type, optional (scope), optional !, then a colon, a space and the description.
|
|
19
|
+
const PREFIX = /^([A-Za-z]+)(?:\(([^()\r\n]*)\))?(!)?: \S/;
|
|
20
|
+
const BREAKING_FOOTER = /^BREAKING[ -]CHANGE: /m;
|
|
21
|
+
|
|
22
|
+
/** The prefix of a first line as { type, scope, breaking }, or null when it has none. Types are not case sensitive. */
|
|
23
|
+
export function parsePrefix(firstLine) {
|
|
24
|
+
const match = PREFIX.exec(firstLine);
|
|
25
|
+
if (!match) return null;
|
|
26
|
+
return { type: match[1].toLowerCase(), scope: match[2] ?? null, breaking: Boolean(match[3]) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The section a commit's prefix decides, as { type, scope, breaking, section }, or null when Jev should be asked.
|
|
31
|
+
* A breaking change (a ! after the type, or a BREAKING CHANGE footer) always affects users, so a breaking commit
|
|
32
|
+
* of an internal type such as refactor goes to changed.
|
|
33
|
+
*/
|
|
34
|
+
export function sectionFromPrefix(firstLine, body = "") {
|
|
35
|
+
const prefix = parsePrefix(firstLine);
|
|
36
|
+
if (!prefix || !Object.hasOwn(PREFIX_SECTIONS, prefix.type)) return null;
|
|
37
|
+
const breaking = prefix.breaking || BREAKING_FOOTER.test(body);
|
|
38
|
+
const section = breaking && PREFIX_SECTIONS[prefix.type] === "internal" ? "changed" : PREFIX_SECTIONS[prefix.type];
|
|
39
|
+
return { ...prefix, breaking, section };
|
|
40
|
+
}
|