changelog.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import path from "node:path";
  2. import { existsSync, readFileSync } from "fs";
  3. export interface ChangelogEntry {
  4. major: number;
  5. minor: number;
  6. patch: number;
  7. content: string;
  8. }
  9. const GITHUB_REPO = "earendil-works/pi";
  10. const CHANGELOG_LINK_BASE_PATH = "packages/coding-agent";
  11. const LEGACY_REPO_RE = /^https:\/\/github\.com\/(?:badlogic|earendil-works)\/pi-mono(?=\/|$)/;
  12. const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
  13. const INLINE_MARKDOWN_LINK_RE = /(!?\[[^\]\n]+\]\()([^\s)]+)((?:\s+[^)]*)?\))/g;
  14. function entryVersion(entry: ChangelogEntry): string {
  15. return `${entry.major}.${entry.minor}.${entry.patch}`;
  16. }
  17. function normalizeTag(version: string | ChangelogEntry): string {
  18. const versionString = typeof version === "string" ? version : entryVersion(version);
  19. return versionString.startsWith("v") ? versionString : `v${versionString}`;
  20. }
  21. function splitLocalTarget(target: string): { fragment: string; pathPart: string; query: string } {
  22. const hashIndex = target.indexOf("#");
  23. const beforeHash = hashIndex === -1 ? target : target.slice(0, hashIndex);
  24. const fragment = hashIndex === -1 ? "" : target.slice(hashIndex);
  25. const queryIndex = beforeHash.indexOf("?");
  26. if (queryIndex === -1) {
  27. return { fragment, pathPart: beforeHash, query: "" };
  28. }
  29. return {
  30. fragment,
  31. pathPart: beforeHash.slice(0, queryIndex),
  32. query: beforeHash.slice(queryIndex),
  33. };
  34. }
  35. function normalizePathPart(value: string): string {
  36. return value.replaceAll("\\", "/");
  37. }
  38. function resolveRepositoryPath(targetPath: string): string | undefined {
  39. const normalizedTarget = normalizePathPart(targetPath);
  40. const joined = normalizedTarget.startsWith("/")
  41. ? path.posix.normalize(normalizedTarget.replace(/^\/+/, ""))
  42. : path.posix.normalize(path.posix.join(CHANGELOG_LINK_BASE_PATH, normalizedTarget));
  43. if (joined === "." || joined.startsWith("../") || joined === "..") {
  44. return undefined;
  45. }
  46. return joined;
  47. }
  48. function isDirectoryTarget(originalPath: string, repositoryPath: string): boolean {
  49. if (originalPath.endsWith("/")) {
  50. return true;
  51. }
  52. const basename = path.posix.basename(repositoryPath);
  53. return !basename.includes(".");
  54. }
  55. function normalizeChangelogLinkTarget(target: string, tag: string): string {
  56. let canonicalTarget = target.replace(LEGACY_REPO_RE, `https://github.com/${GITHUB_REPO}`);
  57. const repoUrl = `https://github.com/${GITHUB_REPO}`;
  58. for (const route of ["blob", "tree"]) {
  59. for (const branch of ["main", "master"]) {
  60. const floatingRefPrefix = `${repoUrl}/${route}/${branch}/`;
  61. if (canonicalTarget.startsWith(floatingRefPrefix)) {
  62. canonicalTarget = `${repoUrl}/${route}/${tag}/${canonicalTarget.slice(floatingRefPrefix.length)}`;
  63. }
  64. }
  65. }
  66. if (canonicalTarget.startsWith("#") || canonicalTarget.startsWith("//") || URL_SCHEME_RE.test(canonicalTarget)) {
  67. return canonicalTarget;
  68. }
  69. const { fragment, pathPart, query } = splitLocalTarget(canonicalTarget);
  70. if (!pathPart) {
  71. return canonicalTarget;
  72. }
  73. const repositoryPath = resolveRepositoryPath(pathPart);
  74. if (!repositoryPath) {
  75. return canonicalTarget;
  76. }
  77. const route = isDirectoryTarget(pathPart, repositoryPath) ? "tree" : "blob";
  78. return `https://github.com/${GITHUB_REPO}/${route}/${tag}/${encodeURI(repositoryPath)}${query}${fragment}`;
  79. }
  80. export function normalizeChangelogLinks(markdown: string, version: string | ChangelogEntry): string {
  81. const tag = normalizeTag(version);
  82. return markdown.replace(INLINE_MARKDOWN_LINK_RE, (_match, prefix, target, suffix) => {
  83. return `${prefix}${normalizeChangelogLinkTarget(target, tag)}${suffix}`;
  84. });
  85. }
  86. /**
  87. * Parse changelog entries from CHANGELOG.md
  88. * Scans for ## lines and collects content until next ## or EOF
  89. */
  90. export function parseChangelog(changelogPath: string): ChangelogEntry[] {
  91. if (!existsSync(changelogPath)) {
  92. return [];
  93. }
  94. try {
  95. const content = readFileSync(changelogPath, "utf-8");
  96. const lines = content.split("\n");
  97. const entries: ChangelogEntry[] = [];
  98. let currentLines: string[] = [];
  99. let currentVersion: { major: number; minor: number; patch: number } | null = null;
  100. for (const line of lines) {
  101. // Check if this is a version header (## [x.y.z] ...)
  102. if (line.startsWith("## ")) {
  103. // Save previous entry if exists
  104. if (currentVersion && currentLines.length > 0) {
  105. entries.push({
  106. ...currentVersion,
  107. content: currentLines.join("\n").trim(),
  108. });
  109. }
  110. // Try to parse version from this line
  111. const versionMatch = line.match(/##\s+\[?(\d+)\.(\d+)\.(\d+)\]?/);
  112. if (versionMatch) {
  113. currentVersion = {
  114. major: Number.parseInt(versionMatch[1], 10),
  115. minor: Number.parseInt(versionMatch[2], 10),
  116. patch: Number.parseInt(versionMatch[3], 10),
  117. };
  118. currentLines = [line];
  119. } else {
  120. // Reset if we can't parse version
  121. currentVersion = null;
  122. currentLines = [];
  123. }
  124. } else if (currentVersion) {
  125. // Collect lines for current version
  126. currentLines.push(line);
  127. }
  128. }
  129. // Save last entry
  130. if (currentVersion && currentLines.length > 0) {
  131. entries.push({
  132. ...currentVersion,
  133. content: currentLines.join("\n").trim(),
  134. });
  135. }
  136. return entries;
  137. } catch (error) {
  138. console.error(`Warning: Could not parse changelog: ${error}`);
  139. return [];
  140. }
  141. }
  142. /**
  143. * Compare versions. Returns: -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2
  144. */
  145. export function compareVersions(v1: ChangelogEntry, v2: ChangelogEntry): number {
  146. if (v1.major !== v2.major) return v1.major - v2.major;
  147. if (v1.minor !== v2.minor) return v1.minor - v2.minor;
  148. return v1.patch - v2.patch;
  149. }
  150. /**
  151. * Get entries newer than lastVersion
  152. */
  153. export function getNewEntries(entries: ChangelogEntry[], lastVersion: string): ChangelogEntry[] {
  154. // Parse lastVersion
  155. const parts = lastVersion.split(".").map(Number);
  156. const last: ChangelogEntry = {
  157. major: parts[0] || 0,
  158. minor: parts[1] || 0,
  159. patch: parts[2] || 0,
  160. content: "",
  161. };
  162. return entries.filter((entry) => compareVersions(entry, last) > 0);
  163. }
  164. // Re-export getChangelogPath from paths.ts for convenience
  165. export { getChangelogPath } from "../config.ts";