Files
alfresco-ng2-components/lib/cli/scripts/changelog.ts
Bartosz Sekula 3f232e75bc AAE-48934 Eslint v9 migration (#12110)
* update

* update

* update

* working

* cr

* cr

* update

* use nx boundaries

* fixes

* fixes

* fixes

* cr

* cr

* update

* update

* update

* cr

* fix null

* cr

* cr

* cr

* cr

* cr

* update

* update

* update

* update

* update

* remove some duplications

* fix units
2026-08-03 12:12:48 +02:00

337 lines
9.7 KiB
JavaScript

#!/usr/bin/env node
/*!
* @license
* Copyright © 2005-2026 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { argv, exit } from 'node:process';
import { parseArgs } from 'node:util';
import { spawnSync } from 'node:child_process';
import * as path from 'path';
import { logger } from './logger';
import * as fs from 'fs';
import { escapeHtml } from './utils';
interface Commit {
hash: string;
author: string;
author_email: string;
date: string;
subject: string;
}
interface DiffOptions {
/**
* Commit range, e.g. "master..develop"
*/
range: string;
/**
* Working directory
*/
dir: string;
/**
* Max number of commits
*/
max?: number;
/**
* Number of commits to skip from the top
*/
skip?: number;
/**
* Exclude commits by the author
*/
exclude?: string;
}
/**
* Get the remote URL for the cloned git repository
*
* @param workingDir Repository directory
* @returns URL pointing to the git remote
*/
function getRemote(workingDir: string): string {
// Use spawnSync with array arguments for safer command execution (prevents shell injection)
const result = spawnSync('git', ['config', '--get', 'remote.origin.url'], {
cwd: workingDir,
encoding: 'utf-8',
shell: false
});
if (result.error) {
throw new Error(`Failed to get git remote: ${result.error.message}`);
}
if (result.status !== 0) {
throw new Error(`git config command failed with exit code ${result.status}: ${result.stderr}`);
}
return result.stdout.trim();
}
/**
* Get the list of commits based on the configuration options
*
* @param options Logging options
* @returns Collection of Commit objects
*/
function getCommits(options: DiffOptions): Array<Commit> {
let authorFilter = (options.exclude || '')
.split(',')
.map((str) => str.trim().replace(/\\/g, ''))
.join('|');
if (!authorFilter) {
authorFilter = `bot|Alfresco Build User`;
}
// Build git command arguments array for safe execution (prevents shell injection)
const args = [
'log',
options.range,
'--no-merges',
'--first-parent',
// this format is needed to allow parsing all characters in the commit message and safely convert to JSON
'--format={ ^@^hash^@^: ^@^%h^@^, ^@^author^@^: ^@^%an^@^, ^@^author_email^@^: ^@^%ae^@^, ^@^date^@^: ^@^%ad^@^, ^@^subject^@^: ^@^%s^@^ }'
];
if (options.max !== undefined) {
args.push(`--max-count=${options.max}`);
}
if (options.skip !== undefined) {
args.push(`--skip=${options.skip}`);
}
// Use spawnSync with array arguments for safer command execution
const result = spawnSync('git', args, {
cwd: options.dir,
encoding: 'utf-8',
shell: false,
maxBuffer: 10 * 1024 * 1024 // 10MB to handle large git logs
});
if (result.error) {
throw new Error(`Failed to get git commits: ${result.error.message}`);
}
if (result.status !== 0) {
throw new Error(`git log command failed with exit code ${result.status}: ${result.stderr}`);
}
let log = result.stdout;
// https://stackoverflow.com/a/13928240/14644447
log = JSON.stringify(log.trim()).slice(1, -1).replace(/\^@\^/gm, '"');
if (log.endsWith(',')) {
log = log.substring(0, log.length - 1);
}
return log
.split('\\n')
.map((str: string) => {
try {
return JSON.parse(str) as Commit;
} catch {
logger.error(`Unparsable commit message: ${str}, dropping it... Please apply manual fix.`);
return null;
}
})
.filter((commit) => commit !== null)
.filter((commit: Commit) => commitAuthorAllowed(commit, authorFilter));
}
/**
* Check if commit author is allowed
*
* @param commit git commit
* @param authorFilter filter
* @returns `true` if author is allowed, otherwise `false`
*/
function commitAuthorAllowed(commit: Commit, authorFilter: string): boolean {
const filterRegex = RegExp(authorFilter);
return !(filterRegex.test(commit.author) || filterRegex.test(commit.author_email));
}
/**
* Render changelog as Markdown.
*
* @param commits list of commits
* @param projName project name
* @param projVersion project version
* @param repoUrl repository URL
* @returns rendered Markdown string
*/
function renderChangelogMd(commits: Commit[], projName: string, projVersion: string, repoUrl: string): string {
const lines = commits.map((c) => `- [${c.hash}](${repoUrl}/commit/${c.hash}) ${escapeHtml(c.subject)}`);
return `---
Title: Changelog for ${escapeHtml(projName)} v${escapeHtml(projVersion)}
---
# Changelog
${lines.join('\n')}
`;
}
/**
* Render changelog as HTML.
*
* @param commits list of commits
* @param projName project name
* @param projVersion project version
* @param repoUrl repository URL
* @returns rendered HTML string
*/
function renderChangelogHtml(commits: Commit[], projName: string, projVersion: string, repoUrl: string): string {
const items = commits
.map((c) => ` <li>\n <a href="${repoUrl}/commit/${c.hash}">[${c.hash}]</a> ${escapeHtml(c.subject)}\n </li>`)
.join('\n');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Changelog for ${escapeHtml(projName)} v${escapeHtml(projVersion)}</title>
</head>
<body>
<h1>Changelog</h1>
<ul>
${items}
</ul>
</body>
</html>`;
}
/**
* Changelog command
*
* @param _args (unused)
* @param workingDir working directory
* @returns void
*/
export default function main(_args: string[], workingDir: string) {
if (argv.includes('-h') || argv.includes('--help')) {
console.log(`
Usage: changelog [options]
Generate changelog report for two branches of git repository
Options:
-v, --version Output the version number
-r, --range <range> Commit range, e.g. origin/master..develop (default: "origin/master..develop")
-d, --dir <dir> Working directory (default: working directory)
-m, --max <number> Limit the number of commits to output
-o, --output <dir> Output directory, will use console output if not defined
--skip <number> Skip number commits before starting to show the commit output
-f, --format <format> Output format (md, html) (default: "md")
-e, --exclude <string> Exclude authors from the output, comma-delimited list
-h, --help Display help for command
`);
exit(0);
}
if (argv.includes('-v') || argv.includes('--version')) {
console.log('0.0.1');
exit(0);
}
const { values } = parseArgs({
args: argv.slice(2),
options: {
range: {
type: 'string',
short: 'r',
default: 'origin/master..develop'
},
dir: {
type: 'string',
short: 'd'
},
max: {
type: 'string',
short: 'm'
},
output: {
type: 'string',
short: 'o'
},
skip: {
type: 'string'
},
format: {
type: 'string',
short: 'f',
default: 'md'
},
exclude: {
type: 'string',
short: 'e'
}
},
allowPositionals: true
});
const dir = path.resolve((values.dir as string) || workingDir);
const range = values.range as string;
const skip = values.skip ? parseInt(values.skip as string, 10) : undefined;
const max = values.max ? parseInt(values.max as string, 10) : undefined;
const format = values.format as string;
const output = values.output as string | undefined;
const exclude = values.exclude as string | undefined;
const remote = getRemote(dir);
let repo_url = remote;
if (repo_url.endsWith('.git')) {
repo_url = repo_url.substring(0, repo_url.length - 4);
}
const commits = getCommits({
dir,
range,
skip,
max,
exclude
});
const packagePath = path.resolve(dir, 'package.json');
if (!fs.existsSync(packagePath)) {
console.error('The package.json file was not found');
exit(1);
}
return new Promise((resolve) => {
const packageJson = JSON.parse(fs.readFileSync(packagePath).toString());
const text =
format === 'html'
? renderChangelogHtml(commits, packageJson.name, packageJson.version, repo_url)
: renderChangelogMd(commits, packageJson.name, packageJson.version, repo_url);
if (output) {
const outputDir = path.resolve(output);
const outputFile = path.join(outputDir, `changelog-${packageJson.version}.${format}`);
console.log('Writing changelog to', outputFile);
fs.writeFileSync(outputFile, text);
} else {
console.log(text);
}
resolve(0);
});
}