Skip to content

Commit

Permalink
feat: improve changelog by switching to patch
Browse files Browse the repository at this point in the history
It replaces the `diffLines` with `structurePatch` and `formatPatch`
to render only the changed lines.

Close #1091
  • Loading branch information
carlosallexandre committed Jan 20, 2025
1 parent fabd6a1 commit 07b9ee8
Showing 1 changed file with 3 additions and 24 deletions.
27 changes: 3 additions & 24 deletions eventcatalog/src/utils/collections/file-diffs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readdir, readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { diffLines, type Change } from 'diff';
import { formatPatch, structuredPatch } from 'diff';
import { html, parse } from 'diff2html';
import { getItemsFromCollectionByIdAndSemverOrLatest } from './util';
import type { CollectionEntry } from 'astro:content';
Expand All @@ -16,29 +16,8 @@ const FILE_EXTENSIONS_TO_INCLUDE = ['.json', '.avro', '.yaml', '.yml', '.proto',
* @returns A string representing the diff in unified format
*/
function generateDiffString(fileName: string, oldStr: string, newStr: string): string {
const diff = diffLines(oldStr, newStr);

// Check if there are any changes
const hasChanges = diff.some((part) => part.added || part.removed);

if (!hasChanges) return '';

let diffString = `diff --git a/${fileName} b/${fileName}\n`;
diffString += `--- a/${fileName}\n`;
diffString += `+++ b/${fileName}\n`;

diff.forEach((part: Change) => {
const prefix = part.added ? '+' : part.removed ? '-' : ' ';
const lines = part.value.split('\n');
// Remove the last element if it's an empty string (which happens if the last line ends with a newline)
if (lines[lines.length - 1] === '') lines.pop();

lines.forEach((line: string) => {
diffString += `${prefix}${line}\n`;
});
});

return diffString;
const jsonPatch = structuredPatch(fileName, fileName, oldStr, newStr);
return jsonPatch.hunks.length == 0 ? '' : formatPatch(jsonPatch);
}

/**
Expand Down

0 comments on commit 07b9ee8

Please sign in to comment.