mirror of
https://github.com/PaulHatch/semantic-version.git
synced 2026-04-09 01:24:17 +00:00
feat(cli): add standalone CLI tool for semantic versioning
This commit is contained in:
parent
bdf7908364
commit
726912b971
55 changed files with 2305 additions and 2850 deletions
|
|
@ -1,39 +1,39 @@
|
|||
/** Represents the input configuration for the semantic-version action */
|
||||
export class ActionConfig {
|
||||
/** Set to specify a specific branch, default is the current HEAD */
|
||||
public branch: string = "HEAD";
|
||||
/** The prefix to use to identify tags */
|
||||
public tagPrefix: string = "v";
|
||||
/** (Deprecated) Use branches instead of tags */
|
||||
public useBranches: boolean = false;
|
||||
/** If true, the branch will be used to select the maximum version. */
|
||||
public versionFromBranch: string | boolean = false;
|
||||
/** A string which, if present in a git commit, indicates that a change represents a major (breaking) change. Wrap with '/' to match using a regular expression. */
|
||||
public majorPattern: string = "/!:|BREAKING CHANGE:/";
|
||||
/** A string which indicates the flags used by the `majorPattern` regular expression. */
|
||||
public majorFlags: string = "";
|
||||
/** A string which, if present in a git commit, indicates that a change represents a minor (feature) change. Wrap with '/' to match using a regular expression. */
|
||||
public minorPattern: string = "/feat:/";
|
||||
/** A string which indicates the flags used by the `minorPattern` regular expression. */
|
||||
public minorFlags: string = "";
|
||||
/** Pattern to use when formatting output version */
|
||||
public versionFormat: string = '${major}.${minor}.${patch}';
|
||||
/** Path to check for changes. If any changes are detected in the path the 'changed' output will true. Enter multiple paths separated by spaces. */
|
||||
public changePath: string = '';
|
||||
/** Use to create a named sub-version. This value will be appended to tags created for this version. */
|
||||
public namespace: string = "";
|
||||
/** If true, every commit will be treated as a bump to the version. */
|
||||
public bumpEachCommit: boolean = false;
|
||||
/** If true, the body of commits will also be searched for major/minor patterns to determine the version type */
|
||||
public searchCommitBody: boolean = false;
|
||||
/** The output method used to generate list of users, 'csv' or 'json'. Default is 'csv'. */
|
||||
public userFormatType: string = "csv";
|
||||
/** Prevents pre-v1.0.0 version from automatically incrementing the major version. If enabled, when the major version is 0, major releases will be treated as minor and minor as patch. Note that the versionType output is unchanged. */
|
||||
public enablePrereleaseMode: boolean = false;
|
||||
/** If bump_each_commit is also set to true, setting this value will cause the version to increment only if the pattern specified is matched. */
|
||||
public bumpEachCommitPatchPattern: string = "";
|
||||
/** If enabled, diagnostic information will be added to the action output. */
|
||||
public debug: boolean = false;
|
||||
/** Diagnostics to replay */
|
||||
public replay: string = '';
|
||||
}
|
||||
/** Set to specify a specific branch, default is the current HEAD */
|
||||
public branch: string = "HEAD";
|
||||
/** The prefix to use to identify tags */
|
||||
public tagPrefix: string = "v";
|
||||
/** (Deprecated) Use branches instead of tags */
|
||||
public useBranches: boolean = false;
|
||||
/** If true, the branch will be used to select the maximum version. */
|
||||
public versionFromBranch: string | boolean = false;
|
||||
/** A string which, if present in a git commit, indicates that a change represents a major (breaking) change. Wrap with '/' to match using a regular expression. */
|
||||
public majorPattern: string = "/!:|BREAKING CHANGE:/";
|
||||
/** A string which indicates the flags used by the `majorPattern` regular expression. */
|
||||
public majorFlags: string = "";
|
||||
/** A string which, if present in a git commit, indicates that a change represents a minor (feature) change. Wrap with '/' to match using a regular expression. */
|
||||
public minorPattern: string = "/feat:/";
|
||||
/** A string which indicates the flags used by the `minorPattern` regular expression. */
|
||||
public minorFlags: string = "";
|
||||
/** Pattern to use when formatting output version */
|
||||
public versionFormat: string = "${major}.${minor}.${patch}";
|
||||
/** Path to check for changes. If any changes are detected in the path the 'changed' output will true. Enter multiple paths separated by spaces. */
|
||||
public changePath: string = "";
|
||||
/** Use to create a named sub-version. This value will be appended to tags created for this version. */
|
||||
public namespace: string = "";
|
||||
/** If true, every commit will be treated as a bump to the version. */
|
||||
public bumpEachCommit: boolean = false;
|
||||
/** If true, the body of commits will also be searched for major/minor patterns to determine the version type */
|
||||
public searchCommitBody: boolean = false;
|
||||
/** The output method used to generate list of users, 'csv' or 'json'. Default is 'csv'. */
|
||||
public userFormatType: string = "csv";
|
||||
/** Prevents pre-v1.0.0 version from automatically incrementing the major version. If enabled, when the major version is 0, major releases will be treated as minor and minor as patch. Note that the versionType output is unchanged. */
|
||||
public enablePrereleaseMode: boolean = false;
|
||||
/** If bump_each_commit is also set to true, setting this value will cause the version to increment only if the pattern specified is matched. */
|
||||
public bumpEachCommitPatchPattern: string = "";
|
||||
/** If enabled, diagnostic information will be added to the action output. */
|
||||
public debug: boolean = false;
|
||||
/** Diagnostics to replay */
|
||||
public replay: string = "";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,34 +1,38 @@
|
|||
// Using require instead of import to support integration testing
|
||||
import * as exec from '@actions/exec';
|
||||
import { DebugManager } from './DebugManager';
|
||||
import * as exec from "@actions/exec";
|
||||
import { DebugManager } from "./DebugManager";
|
||||
|
||||
export const cmd = async (command: string, ...args: any): Promise<string> => {
|
||||
const debugManager = DebugManager.getInstance();
|
||||
|
||||
const debugManager = DebugManager.getInstance();
|
||||
if (debugManager.isReplayMode()) {
|
||||
return debugManager.replayCommand(command, args);
|
||||
}
|
||||
|
||||
if (debugManager.isReplayMode()) {
|
||||
return debugManager.replayCommand(command, args);
|
||||
}
|
||||
let output = "",
|
||||
errors = "";
|
||||
const options = {
|
||||
silent: true,
|
||||
listeners: {
|
||||
stdout: (data: any) => {
|
||||
output += data.toString();
|
||||
},
|
||||
stderr: (data: any) => {
|
||||
errors += data.toString();
|
||||
},
|
||||
ignoreReturnCode: true,
|
||||
silent: true,
|
||||
},
|
||||
};
|
||||
|
||||
let output = '', errors = '';
|
||||
const options = {
|
||||
silent: true,
|
||||
listeners: {
|
||||
stdout: (data: any) => { output += data.toString(); },
|
||||
stderr: (data: any) => { errors += data.toString(); },
|
||||
ignoreReturnCode: true,
|
||||
silent: true
|
||||
}
|
||||
};
|
||||
let caughtError: any = null;
|
||||
try {
|
||||
await exec.exec(command, args, options);
|
||||
} catch (err) {
|
||||
caughtError = err;
|
||||
}
|
||||
|
||||
let caughtError: any = null;
|
||||
try {
|
||||
await exec.exec(command, args, options);
|
||||
} catch (err) {
|
||||
caughtError = err;
|
||||
}
|
||||
debugManager.recordCommand(command, args, output, errors, caughtError);
|
||||
|
||||
debugManager.recordCommand(command, args, output, errors, caughtError);
|
||||
|
||||
return output;
|
||||
};
|
||||
return output;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,25 +1,24 @@
|
|||
import { CsvUserFormatter } from './formatting/CsvUserFormatter'
|
||||
import { BranchVersioningTagFormatter } from './formatting/BranchVersioningTagFormatter'
|
||||
import { DefaultTagFormatter } from './formatting/DefaultTagFormatter'
|
||||
import { DefaultVersionFormatter } from './formatting/DefaultVersionFormatter'
|
||||
import { JsonUserFormatter } from './formatting/JsonUserFormatter'
|
||||
import { TagFormatter } from './formatting/TagFormatter'
|
||||
import { UserFormatter } from './formatting/UserFormatter'
|
||||
import { VersionFormatter } from './formatting/VersionFormatter'
|
||||
import { CommitsProvider } from './providers/CommitsProvider'
|
||||
import { CurrentCommitResolver } from './providers/CurrentCommitResolver'
|
||||
import { DefaultCommitsProvider } from './providers/DefaultCommitsProvider'
|
||||
import { DefaultCurrentCommitResolver } from './providers/DefaultCurrentCommitResolver'
|
||||
import { DefaultVersionClassifier } from './providers/DefaultVersionClassifier'
|
||||
import { LastReleaseResolver } from './providers/LastReleaseResolver'
|
||||
import { DefaultLastReleaseResolver } from './providers/DefaultLastReleaseResolver'
|
||||
import { VersionClassifier } from './providers/VersionClassifier'
|
||||
import { BumpAlwaysVersionClassifier } from './providers/BumpAlwaysVersionClassifier'
|
||||
import { ActionConfig } from './ActionConfig';
|
||||
import { DebugManager } from './DebugManager';
|
||||
import { CsvUserFormatter } from "./formatting/CsvUserFormatter";
|
||||
import { BranchVersioningTagFormatter } from "./formatting/BranchVersioningTagFormatter";
|
||||
import { DefaultTagFormatter } from "./formatting/DefaultTagFormatter";
|
||||
import { DefaultVersionFormatter } from "./formatting/DefaultVersionFormatter";
|
||||
import { JsonUserFormatter } from "./formatting/JsonUserFormatter";
|
||||
import { TagFormatter } from "./formatting/TagFormatter";
|
||||
import { UserFormatter } from "./formatting/UserFormatter";
|
||||
import { VersionFormatter } from "./formatting/VersionFormatter";
|
||||
import { CommitsProvider } from "./providers/CommitsProvider";
|
||||
import { CurrentCommitResolver } from "./providers/CurrentCommitResolver";
|
||||
import { DefaultCommitsProvider } from "./providers/DefaultCommitsProvider";
|
||||
import { DefaultCurrentCommitResolver } from "./providers/DefaultCurrentCommitResolver";
|
||||
import { DefaultVersionClassifier } from "./providers/DefaultVersionClassifier";
|
||||
import { LastReleaseResolver } from "./providers/LastReleaseResolver";
|
||||
import { DefaultLastReleaseResolver } from "./providers/DefaultLastReleaseResolver";
|
||||
import { VersionClassifier } from "./providers/VersionClassifier";
|
||||
import { BumpAlwaysVersionClassifier } from "./providers/BumpAlwaysVersionClassifier";
|
||||
import { ActionConfig } from "./ActionConfig";
|
||||
import { DebugManager } from "./DebugManager";
|
||||
|
||||
export class ConfigurationProvider {
|
||||
|
||||
constructor(config: ActionConfig) {
|
||||
this.config = config;
|
||||
DebugManager.getInstance().initializeConfig(config);
|
||||
|
|
@ -27,11 +26,17 @@ export class ConfigurationProvider {
|
|||
|
||||
private config: ActionConfig;
|
||||
|
||||
public GetCurrentCommitResolver(): CurrentCommitResolver { return new DefaultCurrentCommitResolver(this.config); }
|
||||
public GetCurrentCommitResolver(): CurrentCommitResolver {
|
||||
return new DefaultCurrentCommitResolver(this.config);
|
||||
}
|
||||
|
||||
public GetLastReleaseResolver(): LastReleaseResolver { return new DefaultLastReleaseResolver(this.config); }
|
||||
public GetLastReleaseResolver(): LastReleaseResolver {
|
||||
return new DefaultLastReleaseResolver(this.config);
|
||||
}
|
||||
|
||||
public GetCommitsProvider(): CommitsProvider { return new DefaultCommitsProvider(this.config); }
|
||||
public GetCommitsProvider(): CommitsProvider {
|
||||
return new DefaultCommitsProvider(this.config);
|
||||
}
|
||||
|
||||
public GetVersionClassifier(): VersionClassifier {
|
||||
if (this.config.bumpEachCommit) {
|
||||
|
|
@ -40,7 +45,9 @@ export class ConfigurationProvider {
|
|||
return new DefaultVersionClassifier(this.config);
|
||||
}
|
||||
|
||||
public GetVersionFormatter(): VersionFormatter { return new DefaultVersionFormatter(this.config); }
|
||||
public GetVersionFormatter(): VersionFormatter {
|
||||
return new DefaultVersionFormatter(this.config);
|
||||
}
|
||||
|
||||
public GetTagFormatter(branchName: string): TagFormatter {
|
||||
if (this.config.versionFromBranch) {
|
||||
|
|
@ -51,10 +58,14 @@ export class ConfigurationProvider {
|
|||
|
||||
public GetUserFormatter(): UserFormatter {
|
||||
switch (this.config.userFormatType) {
|
||||
case 'json': return new JsonUserFormatter(this.config);
|
||||
case 'csv': return new CsvUserFormatter(this.config);
|
||||
case "json":
|
||||
return new JsonUserFormatter(this.config);
|
||||
case "csv":
|
||||
return new CsvUserFormatter(this.config);
|
||||
default:
|
||||
throw new Error(`Unknown user format type: ${this.config.userFormatType}, supported types: json, csv`);
|
||||
throw new Error(
|
||||
`Unknown user format type: ${this.config.userFormatType}, supported types: json, csv`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,115 +1,134 @@
|
|||
import { ActionConfig } from "./ActionConfig";
|
||||
|
||||
|
||||
/** Utility class for managing debug mode and diagnostic information */
|
||||
export class DebugManager {
|
||||
private constructor() { }
|
||||
private constructor() {}
|
||||
|
||||
private static instance: DebugManager;
|
||||
/** Returns the singleton instance of the DebugManager */
|
||||
public static getInstance(): DebugManager {
|
||||
if (!DebugManager.instance) {
|
||||
DebugManager.instance = new DebugManager();
|
||||
}
|
||||
return DebugManager.instance;
|
||||
private static instance: DebugManager;
|
||||
/** Returns the singleton instance of the DebugManager */
|
||||
public static getInstance(): DebugManager {
|
||||
if (!DebugManager.instance) {
|
||||
DebugManager.instance = new DebugManager();
|
||||
}
|
||||
return DebugManager.instance;
|
||||
}
|
||||
|
||||
/** Clears the singleton instance of the DebugManager (used for testing) */
|
||||
public static clearState() {
|
||||
DebugManager.instance = new DebugManager();
|
||||
}
|
||||
|
||||
private debugEnabled: boolean = false;
|
||||
private replayMode: boolean = false;
|
||||
private diagnosticInfo: DiagnosticInfo | null = null;
|
||||
|
||||
/** Returns true if debug mode is enabled */
|
||||
public isDebugEnabled(): boolean {
|
||||
return this.debugEnabled;
|
||||
}
|
||||
|
||||
/** Returns true if replay mode is enabled */
|
||||
public isReplayMode(): boolean {
|
||||
return this.replayMode;
|
||||
}
|
||||
|
||||
initializeConfig(config: ActionConfig) {
|
||||
if (config.debug) {
|
||||
this.setDebugEnabled(true);
|
||||
} else if (config.replay.length > 0) {
|
||||
this.replayFromDiagnostics(config.replay);
|
||||
}
|
||||
}
|
||||
|
||||
/** Enables or disables debug mode, also clears any existing diagnostics info */
|
||||
public setDebugEnabled(enableDebug: boolean = true): void {
|
||||
this.debugEnabled = enableDebug;
|
||||
this.replayMode = false;
|
||||
this.diagnosticInfo = new DiagnosticInfo();
|
||||
}
|
||||
|
||||
/** Enables replay mode and loads the diagnostic information from the specified string */
|
||||
public replayFromDiagnostics(diagnostics: string): void {
|
||||
this.debugEnabled = false;
|
||||
this.replayMode = true;
|
||||
this.diagnosticInfo = JSON.parse(diagnostics);
|
||||
}
|
||||
|
||||
/** Returns a JSON string containing the diagnostic information for this run */
|
||||
public getDebugOutput(emptyRepo: boolean = false): string {
|
||||
return this.isDebugEnabled() ? JSON.stringify(this.diagnosticInfo) : "";
|
||||
}
|
||||
|
||||
/** Records a command and its output for diagnostic purposes */
|
||||
public recordCommand(
|
||||
command: string,
|
||||
args: any[],
|
||||
output: string,
|
||||
stderr: string,
|
||||
error: any,
|
||||
): void {
|
||||
if (this.isDebugEnabled()) {
|
||||
this.diagnosticInfo?.recordCommand(command, args, output, stderr, error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Replays the specified command and returns the output */
|
||||
public replayCommand(command: string, args: any[]): string {
|
||||
if (this.diagnosticInfo === null) {
|
||||
throw new Error("No diagnostic information available for replay");
|
||||
}
|
||||
|
||||
/** Clears the singleton instance of the DebugManager (used for testing) */
|
||||
public static clearState() {
|
||||
DebugManager.instance = new DebugManager();
|
||||
const commandResult = this.diagnosticInfo.commands.find(
|
||||
(c) =>
|
||||
c.command === command &&
|
||||
JSON.stringify(c.args) === JSON.stringify(args),
|
||||
);
|
||||
if (!commandResult) {
|
||||
throw new Error(`No result found in diagnostic for command "${command}"`);
|
||||
}
|
||||
|
||||
|
||||
private debugEnabled: boolean = false;
|
||||
private replayMode: boolean = false;
|
||||
private diagnosticInfo: DiagnosticInfo | null = null;
|
||||
|
||||
/** Returns true if debug mode is enabled */
|
||||
public isDebugEnabled(): boolean {
|
||||
return this.debugEnabled;
|
||||
if (commandResult.error) {
|
||||
throw commandResult.error;
|
||||
}
|
||||
|
||||
/** Returns true if replay mode is enabled */
|
||||
public isReplayMode(): boolean {
|
||||
return this.replayMode;
|
||||
}
|
||||
|
||||
initializeConfig(config: ActionConfig) {
|
||||
if (config.debug) {
|
||||
this.setDebugEnabled(true);
|
||||
} else if (config.replay.length > 0) {
|
||||
this.replayFromDiagnostics(config.replay);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Enables or disables debug mode, also clears any existing diagnostics info */
|
||||
public setDebugEnabled(enableDebug: boolean = true): void {
|
||||
this.debugEnabled = enableDebug;
|
||||
this.replayMode = false;
|
||||
this.diagnosticInfo = new DiagnosticInfo();
|
||||
};
|
||||
|
||||
/** Enables replay mode and loads the diagnostic information from the specified string */
|
||||
public replayFromDiagnostics(diagnostics: string): void {
|
||||
this.debugEnabled = false
|
||||
this.replayMode = true;
|
||||
this.diagnosticInfo = JSON.parse(diagnostics);
|
||||
}
|
||||
|
||||
/** Returns a JSON string containing the diagnostic information for this run */
|
||||
public getDebugOutput(emptyRepo: boolean = false): string {
|
||||
return this.isDebugEnabled() ? JSON.stringify(this.diagnosticInfo) : '';
|
||||
}
|
||||
|
||||
/** Records a command and its output for diagnostic purposes */
|
||||
public recordCommand(command: string, args: any[], output: string, stderr: string, error: any): void {
|
||||
if (this.isDebugEnabled()) {
|
||||
this.diagnosticInfo?.recordCommand(command, args, output, stderr, error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Replays the specified command and returns the output */
|
||||
public replayCommand(command: string, args: any[]): string {
|
||||
if (this.diagnosticInfo === null) {
|
||||
throw new Error('No diagnostic information available for replay');
|
||||
}
|
||||
|
||||
const commandResult = this.diagnosticInfo.commands.find(c => c.command === command && JSON.stringify(c.args) === JSON.stringify(args));
|
||||
if (!commandResult) {
|
||||
throw new Error(`No result found in diagnostic for command "${command}"`);
|
||||
}
|
||||
if (commandResult.error) {
|
||||
throw commandResult.error;
|
||||
}
|
||||
if (commandResult.stderr) {
|
||||
console.error(commandResult.stderr);
|
||||
}
|
||||
return commandResult.output;
|
||||
if (commandResult.stderr) {
|
||||
console.error(commandResult.stderr);
|
||||
}
|
||||
return commandResult.output;
|
||||
}
|
||||
}
|
||||
|
||||
/** Represents a CLI command result */
|
||||
class CommandResult {
|
||||
public command: string;
|
||||
public args: any[];
|
||||
public output: string;
|
||||
public stderr: string;
|
||||
public error: any;
|
||||
public constructor(command: string, args: any[], output: string, stderr: string, error: any) {
|
||||
this.command = command;
|
||||
this.args = args;
|
||||
this.output = output;
|
||||
this.stderr = stderr;
|
||||
this.error = error;
|
||||
}
|
||||
public command: string;
|
||||
public args: any[];
|
||||
public output: string;
|
||||
public stderr: string;
|
||||
public error: any;
|
||||
public constructor(
|
||||
command: string,
|
||||
args: any[],
|
||||
output: string,
|
||||
stderr: string,
|
||||
error: any,
|
||||
) {
|
||||
this.command = command;
|
||||
this.args = args;
|
||||
this.output = output;
|
||||
this.stderr = stderr;
|
||||
this.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Represents the result of the commands executed for a run */
|
||||
class DiagnosticInfo {
|
||||
public commands: CommandResult[] = [];
|
||||
public empty: boolean = false;
|
||||
public recordCommand(command: string, args: any[], output: string, stderr: string, error: any): void {
|
||||
this.commands.push(new CommandResult(command, args, output, stderr, error));
|
||||
}
|
||||
}
|
||||
public commands: CommandResult[] = [];
|
||||
public empty: boolean = false;
|
||||
public recordCommand(
|
||||
command: string,
|
||||
args: any[],
|
||||
output: string,
|
||||
stderr: string,
|
||||
error: any,
|
||||
): void {
|
||||
this.commands.push(new CommandResult(command, args, output, stderr, error));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ export class VersionResult {
|
|||
* @param changed - True if the version was changed, otherwise false
|
||||
* @param isTagged - True if the commit had a tag that matched the `versionTag` format
|
||||
* @param authors - Authors formatted according to the format mode (e.g. JSON, CSV, YAML, etc.)
|
||||
* @param currentCommit - The current commit hash
|
||||
* @param currentCommit - The current commit hash
|
||||
* @param previousCommit - The previous commit hash
|
||||
* @param previousVersion - The previous version
|
||||
* @param debugOutput - Diagnostic information, if debug is enabled
|
||||
|
|
@ -34,5 +34,6 @@ export class VersionResult {
|
|||
public currentCommit: string,
|
||||
public previousCommit: string,
|
||||
public previousVersion: string,
|
||||
public debugOutput: string) { }
|
||||
public debugOutput: string,
|
||||
) {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,37 @@
|
|||
import { ConfigurationProvider } from './ConfigurationProvider';
|
||||
import { VersionResult } from './VersionResult';
|
||||
import { VersionType } from './providers/VersionType';
|
||||
import { UserInfo } from './providers/UserInfo';
|
||||
import { VersionInformation } from './providers/VersionInformation';
|
||||
import { DebugManager } from './DebugManager';
|
||||
import { ConfigurationProvider } from "./ConfigurationProvider";
|
||||
import { VersionResult } from "./VersionResult";
|
||||
import { VersionType } from "./providers/VersionType";
|
||||
import { UserInfo } from "./providers/UserInfo";
|
||||
import { VersionInformation } from "./providers/VersionInformation";
|
||||
import { DebugManager } from "./DebugManager";
|
||||
|
||||
export async function runAction(configurationProvider: ConfigurationProvider): Promise<VersionResult> {
|
||||
|
||||
const currentCommitResolver = configurationProvider.GetCurrentCommitResolver();
|
||||
export async function runAction(
|
||||
configurationProvider: ConfigurationProvider,
|
||||
): Promise<VersionResult> {
|
||||
const currentCommitResolver =
|
||||
configurationProvider.GetCurrentCommitResolver();
|
||||
const lastReleaseResolver = configurationProvider.GetLastReleaseResolver();
|
||||
const commitsProvider = configurationProvider.GetCommitsProvider();
|
||||
const versionClassifier = configurationProvider.GetVersionClassifier();
|
||||
const versionFormatter = configurationProvider.GetVersionFormatter();
|
||||
const tagFormatter = configurationProvider.GetTagFormatter(await currentCommitResolver.ResolveBranchNameAsync());
|
||||
const tagFormatter = configurationProvider.GetTagFormatter(
|
||||
await currentCommitResolver.ResolveBranchNameAsync(),
|
||||
);
|
||||
const userFormatter = configurationProvider.GetUserFormatter();
|
||||
|
||||
const debugManager = DebugManager.getInstance();
|
||||
|
||||
if (await currentCommitResolver.IsEmptyRepoAsync()) {
|
||||
|
||||
const versionInfo = new VersionInformation(0, 0, 0, 0, VersionType.None, [], false, false);
|
||||
const versionInfo = new VersionInformation(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
VersionType.None,
|
||||
[],
|
||||
false,
|
||||
false,
|
||||
);
|
||||
return new VersionResult(
|
||||
versionInfo.major,
|
||||
versionInfo.minor,
|
||||
|
|
@ -30,34 +42,51 @@ export async function runAction(configurationProvider: ConfigurationProvider): P
|
|||
tagFormatter.Format(versionInfo),
|
||||
versionInfo.changed,
|
||||
versionInfo.isTagged,
|
||||
userFormatter.Format('author', []),
|
||||
'',
|
||||
'',
|
||||
tagFormatter.Parse(tagFormatter.Format(versionInfo)).join('.'),
|
||||
debugManager.getDebugOutput(true)
|
||||
userFormatter.Format("author", []),
|
||||
"",
|
||||
"",
|
||||
tagFormatter.Parse(tagFormatter.Format(versionInfo)).join("."),
|
||||
debugManager.getDebugOutput(true),
|
||||
);
|
||||
}
|
||||
|
||||
const currentCommit = await currentCommitResolver.ResolveAsync();
|
||||
const lastRelease = await lastReleaseResolver.ResolveAsync(currentCommit, tagFormatter);
|
||||
const commitSet = await commitsProvider.GetCommitsAsync(lastRelease.hash, currentCommit);
|
||||
const classification = await versionClassifier.ClassifyAsync(lastRelease, commitSet);
|
||||
const lastRelease = await lastReleaseResolver.ResolveAsync(
|
||||
currentCommit,
|
||||
tagFormatter,
|
||||
);
|
||||
const commitSet = await commitsProvider.GetCommitsAsync(
|
||||
lastRelease.hash,
|
||||
currentCommit,
|
||||
);
|
||||
const classification = await versionClassifier.ClassifyAsync(
|
||||
lastRelease,
|
||||
commitSet,
|
||||
);
|
||||
|
||||
const { isTagged } = lastRelease;
|
||||
const { major, minor, patch, increment, type, changed } = classification;
|
||||
|
||||
// At this point all necessary data has been pulled from the database, create
|
||||
// version information to be used by the formatters
|
||||
let versionInfo = new VersionInformation(major, minor, patch, increment, type, commitSet.commits, changed, isTagged);
|
||||
let versionInfo = new VersionInformation(
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
increment,
|
||||
type,
|
||||
commitSet.commits,
|
||||
changed,
|
||||
isTagged,
|
||||
);
|
||||
|
||||
// Group all the authors together, count the number of commits per author
|
||||
const allAuthors = versionInfo.commits
|
||||
.reduce((acc: any, commit) => {
|
||||
const key = `${commit.author} <${commit.authorEmail}>`;
|
||||
acc[key] = acc[key] || { n: commit.author, e: commit.authorEmail, c: 0 };
|
||||
acc[key].c++;
|
||||
return acc;
|
||||
}, {});
|
||||
const allAuthors = versionInfo.commits.reduce((acc: any, commit) => {
|
||||
const key = `${commit.author} <${commit.authorEmail}>`;
|
||||
acc[key] = acc[key] || { n: commit.author, e: commit.authorEmail, c: 0 };
|
||||
acc[key].c++;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const authors = Object.values(allAuthors)
|
||||
.map((u: any) => new UserInfo(u.n, u.e, u.c))
|
||||
|
|
@ -73,10 +102,10 @@ export async function runAction(configurationProvider: ConfigurationProvider): P
|
|||
tagFormatter.Format(versionInfo),
|
||||
versionInfo.changed,
|
||||
versionInfo.isTagged,
|
||||
userFormatter.Format('author', authors),
|
||||
userFormatter.Format("author", authors),
|
||||
currentCommit,
|
||||
lastRelease.hash,
|
||||
`${lastRelease.major}.${lastRelease.minor}.${lastRelease.patch}`,
|
||||
debugManager.getDebugOutput()
|
||||
debugManager.getDebugOutput(),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
146
src/cli.ts
Normal file
146
src/cli.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { Command } from "commander";
|
||||
import { runAction } from "./action";
|
||||
import { ConfigurationProvider } from "./ConfigurationProvider";
|
||||
import { ActionConfig } from "./ActionConfig";
|
||||
import * as process from "process";
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("semantic-version")
|
||||
.description("Automated semantic versioning for Git repositories")
|
||||
.version(process.env.SEMANTIC_VERSION || "0.0.0-dev")
|
||||
.option(
|
||||
"-B, --branch <branch>",
|
||||
"Specific branch to analyze (default: current HEAD)",
|
||||
"HEAD",
|
||||
)
|
||||
.option("-t, --tag-prefix <prefix>", 'Version tag prefix (e.g., "v")', "v")
|
||||
.option(
|
||||
"-p, --path <path>",
|
||||
"Path to check for changes (multiple paths separated by spaces)",
|
||||
"",
|
||||
)
|
||||
.option("-n, --namespace <namespace>", "Namespace for version tags", "")
|
||||
.option(
|
||||
"-M, --major-pattern <pattern>",
|
||||
"Regex pattern for major version bumps",
|
||||
"/!:|BREAKING CHANGE:/",
|
||||
)
|
||||
.option("--major-flags <flags>", "Flags for major pattern regex", "")
|
||||
.option(
|
||||
"-m, --minor-pattern <pattern>",
|
||||
"Regex pattern for minor version bumps",
|
||||
"/feat:/",
|
||||
)
|
||||
.option("--minor-flags <flags>", "Flags for minor pattern regex", "")
|
||||
.option(
|
||||
"--version-format <format>",
|
||||
"Version format template",
|
||||
"${major}.${minor}.${patch}",
|
||||
)
|
||||
.option("-b, --bump-each-commit", "Bump version for each commit", false)
|
||||
.option(
|
||||
"--bump-each-commit-patch-pattern <pattern>",
|
||||
"Pattern for patch bumps when bump-each-commit is enabled",
|
||||
"",
|
||||
)
|
||||
.option(
|
||||
"-s, --search-commit-body",
|
||||
"Search commit body for version patterns",
|
||||
false,
|
||||
)
|
||||
.option("-d, --debug", "Enable debug output", false)
|
||||
.option(
|
||||
"--version-from-branch [pattern]",
|
||||
"Use branch name for version selection (optionally provide a regex pattern)",
|
||||
)
|
||||
.option(
|
||||
"--enable-prerelease-mode",
|
||||
"Prevents pre-v1.0.0 major version increments",
|
||||
false,
|
||||
)
|
||||
.option(
|
||||
"--user-format-type <type>",
|
||||
"Output format for users (csv, json)",
|
||||
"csv",
|
||||
)
|
||||
.option("--format <format>", "Output format (json, text)", "text")
|
||||
.action(async (options) => {
|
||||
try {
|
||||
// Create ActionConfig from CLI options
|
||||
const config = new ActionConfig();
|
||||
config.branch = options.branch;
|
||||
config.tagPrefix = options.tagPrefix;
|
||||
config.versionFormat = options.versionFormat;
|
||||
config.changePath = options.path;
|
||||
config.namespace = options.namespace;
|
||||
config.majorPattern = options.majorPattern;
|
||||
config.majorFlags = options.majorFlags || "";
|
||||
config.minorPattern = options.minorPattern;
|
||||
config.minorFlags = options.minorFlags || "";
|
||||
config.bumpEachCommit = options.bumpEachCommit;
|
||||
config.bumpEachCommitPatchPattern =
|
||||
options.bumpEachCommitPatchPattern || "";
|
||||
config.searchCommitBody = options.searchCommitBody;
|
||||
// versionFromBranch can be true (flag only) or a string (custom pattern)
|
||||
config.versionFromBranch = options.versionFromBranch ?? false;
|
||||
config.enablePrereleaseMode = options.enablePrereleaseMode;
|
||||
config.userFormatType = options.userFormatType;
|
||||
config.debug = options.debug;
|
||||
|
||||
// Create ConfigurationProvider with the config
|
||||
const configProvider = new ConfigurationProvider(config);
|
||||
|
||||
const result = await runAction(configProvider);
|
||||
|
||||
if (options.format === "json") {
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
version: result.formattedVersion,
|
||||
versionTag: result.versionTag,
|
||||
major: result.major,
|
||||
minor: result.minor,
|
||||
patch: result.patch,
|
||||
increment: result.increment,
|
||||
versionType: result.versionType,
|
||||
changed: result.changed,
|
||||
isTagged: result.isTagged,
|
||||
authors: result.authors,
|
||||
currentCommit: result.currentCommit,
|
||||
previousCommit: result.previousCommit,
|
||||
previousVersion: result.previousVersion,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
console.log(result.formattedVersion);
|
||||
if (options.debug) {
|
||||
console.error("Version details:");
|
||||
console.error(` Major: ${result.major}`);
|
||||
console.error(` Minor: ${result.minor}`);
|
||||
console.error(` Patch: ${result.patch}`);
|
||||
console.error(` Type: ${result.versionType}`);
|
||||
console.error(` Changed: ${result.changed}`);
|
||||
if (result.previousVersion) {
|
||||
console.error(` Previous: ${result.previousVersion}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
console.error("Error:", error instanceof Error ? error.message : error);
|
||||
if (options.debug && error instanceof Error && error.stack) {
|
||||
console.error(error.stack);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program.parse();
|
||||
|
|
@ -7,19 +7,19 @@ export class DefaultTagFormatter implements TagFormatter {
|
|||
|
||||
private tagPrefix: string;
|
||||
private namespace: string;
|
||||
private namespaceSeperator: string;
|
||||
private namespaceSeparator: string;
|
||||
|
||||
constructor(config: ActionConfig) {
|
||||
this.namespace = config.namespace;
|
||||
this.tagPrefix = config.tagPrefix;
|
||||
this.namespaceSeperator = '-'; // maybe make configurable in the future
|
||||
this.namespaceSeparator = '-'; // maybe make configurable in the future
|
||||
}
|
||||
|
||||
public Format(versionInfo: VersionInformation): string {
|
||||
const result = `${this.tagPrefix}${versionInfo.major}.${versionInfo.minor}.${versionInfo.patch}`;
|
||||
|
||||
if (!!this.namespace) {
|
||||
return `${result}${this.namespaceSeperator}${this.namespace}`;
|
||||
if (this.namespace) {
|
||||
return `${result}${this.namespaceSeparator}${this.namespace}`;
|
||||
}
|
||||
|
||||
return result;
|
||||
|
|
@ -27,8 +27,8 @@ export class DefaultTagFormatter implements TagFormatter {
|
|||
|
||||
public GetPattern(): string {
|
||||
|
||||
if (!!this.namespace) {
|
||||
return `${this.tagPrefix}*[0-9].*[0-9].*[0-9]${this.namespaceSeperator}${this.namespace}`;
|
||||
if (this.namespace) {
|
||||
return `${this.tagPrefix}*[0-9].*[0-9].*[0-9]${this.namespaceSeparator}${this.namespace}`;
|
||||
}
|
||||
|
||||
return `${this.tagPrefix}*[0-9].*[0-9].*[0-9]`;
|
||||
|
|
@ -63,18 +63,18 @@ export class DefaultTagFormatter implements TagFormatter {
|
|||
}
|
||||
|
||||
return [major, minor, patch];
|
||||
};
|
||||
}
|
||||
|
||||
public IsValid(tag: string): boolean {
|
||||
const regexEscape = (literal: string) => literal.replace(/\W/g, '\\$&');
|
||||
const tagPrefix = regexEscape(this.tagPrefix);
|
||||
const namespaceSeperator = regexEscape(this.namespaceSeperator);
|
||||
const namespaceSeparator = regexEscape(this.namespaceSeparator);
|
||||
const namespace = regexEscape(this.namespace);
|
||||
|
||||
if (!!this.namespace) {
|
||||
return new RegExp(`^${tagPrefix}[0-9]+\.[0-9]+\.[0-9]+${namespaceSeperator}${namespace}$`).test(tag);
|
||||
if (this.namespace) {
|
||||
return new RegExp(`^${tagPrefix}[0-9]+\\.[0-9]+\\.[0-9]+${namespaceSeparator}${namespace}$`).test(tag);
|
||||
}
|
||||
|
||||
return new RegExp(`^${tagPrefix}[0-9]+\.[0-9]+\.[0-9]+$`).test(tag);
|
||||
return new RegExp(`^${tagPrefix}[0-9]+\\.[0-9]+\\.[0-9]+$`).test(tag);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
2461
src/main.test.ts
2461
src/main.test.ts
File diff suppressed because it is too large
Load diff
99
src/main.ts
99
src/main.ts
|
|
@ -1,23 +1,35 @@
|
|||
import { runAction } from './action';
|
||||
import { ActionConfig } from './ActionConfig';
|
||||
import { ConfigurationProvider } from './ConfigurationProvider';
|
||||
import { VersionResult } from './VersionResult';
|
||||
import * as core from '@actions/core';
|
||||
import { VersionType } from './providers/VersionType';
|
||||
import { runAction } from "./action";
|
||||
import { ActionConfig } from "./ActionConfig";
|
||||
import { ConfigurationProvider } from "./ConfigurationProvider";
|
||||
import { VersionResult } from "./VersionResult";
|
||||
import * as core from "@actions/core";
|
||||
import { VersionType } from "./providers/VersionType";
|
||||
|
||||
function setOutput(versionResult: VersionResult) {
|
||||
const { major, minor, patch, increment, versionType, formattedVersion, versionTag, changed, isTagged, authors, currentCommit, previousCommit, previousVersion, debugOutput } = versionResult;
|
||||
const {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
increment,
|
||||
versionType,
|
||||
formattedVersion,
|
||||
versionTag,
|
||||
changed,
|
||||
isTagged,
|
||||
authors,
|
||||
currentCommit,
|
||||
previousCommit,
|
||||
previousVersion,
|
||||
debugOutput,
|
||||
} = versionResult;
|
||||
|
||||
const repository = process.env.GITHUB_REPOSITORY;
|
||||
|
||||
if (!changed) {
|
||||
core.info('No changes detected for this commit');
|
||||
core.info("No changes detected for this commit");
|
||||
}
|
||||
|
||||
core.info(`Version is ${formattedVersion}`);
|
||||
if (repository !== undefined) {
|
||||
core.info(`To create a release for this version, go to https://github.com/${repository}/releases/new?tag=${versionTag}&target=${currentCommit.split('/').slice(-1)[0]}`);
|
||||
}
|
||||
|
||||
core.setOutput("version", formattedVersion);
|
||||
core.setOutput("major", major.toString());
|
||||
|
|
@ -36,56 +48,59 @@ function setOutput(versionResult: VersionResult) {
|
|||
}
|
||||
|
||||
export async function run() {
|
||||
|
||||
function toBool(value: string): boolean {
|
||||
if (!value || value.toLowerCase() === 'false') {
|
||||
if (!value || value.toLowerCase() === "false") {
|
||||
return false;
|
||||
} else if (value.toLowerCase() === 'true') {
|
||||
} else if (value.toLowerCase() === "true") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
function toStringOrBool(value: string): string | boolean {
|
||||
if (!value || value === 'false') {
|
||||
if (!value || value === "false") {
|
||||
return false;
|
||||
}
|
||||
if (value === 'true') {
|
||||
if (value === "true") {
|
||||
return true;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
const config: ActionConfig = {
|
||||
branch: core.getInput('branch'),
|
||||
tagPrefix: core.getInput('tag_prefix'),
|
||||
useBranches: toBool(core.getInput('use_branches')),
|
||||
versionFromBranch: toStringOrBool(core.getInput('version_from_branch')),
|
||||
majorPattern: core.getInput('major_pattern'),
|
||||
minorPattern: core.getInput('minor_pattern'),
|
||||
majorFlags: core.getInput('major_regexp_flags'),
|
||||
minorFlags: core.getInput('minor_regexp_flags'),
|
||||
versionFormat: core.getInput('version_format'),
|
||||
changePath: core.getInput('change_path'),
|
||||
namespace: core.getInput('namespace'),
|
||||
bumpEachCommit: toBool(core.getInput('bump_each_commit')),
|
||||
searchCommitBody: toBool(core.getInput('search_commit_body')),
|
||||
userFormatType: core.getInput('user_format_type'),
|
||||
enablePrereleaseMode: toBool(core.getInput('enable_prerelease_mode')),
|
||||
bumpEachCommitPatchPattern: core.getInput('bump_each_commit_patch_pattern'),
|
||||
debug: toBool(core.getInput('debug')),
|
||||
replay: ''
|
||||
branch: core.getInput("branch"),
|
||||
tagPrefix: core.getInput("tag_prefix"),
|
||||
useBranches: toBool(core.getInput("use_branches")),
|
||||
versionFromBranch: toStringOrBool(core.getInput("version_from_branch")),
|
||||
majorPattern: core.getInput("major_pattern"),
|
||||
minorPattern: core.getInput("minor_pattern"),
|
||||
majorFlags: core.getInput("major_regexp_flags"),
|
||||
minorFlags: core.getInput("minor_regexp_flags"),
|
||||
versionFormat: core.getInput("version_format"),
|
||||
changePath: core.getInput("change_path"),
|
||||
namespace: core.getInput("namespace"),
|
||||
bumpEachCommit: toBool(core.getInput("bump_each_commit")),
|
||||
searchCommitBody: toBool(core.getInput("search_commit_body")),
|
||||
userFormatType: core.getInput("user_format_type"),
|
||||
enablePrereleaseMode: toBool(core.getInput("enable_prerelease_mode")),
|
||||
bumpEachCommitPatchPattern: core.getInput("bump_each_commit_patch_pattern"),
|
||||
debug: toBool(core.getInput("debug")),
|
||||
replay: "",
|
||||
};
|
||||
|
||||
if (config.useBranches) {
|
||||
core.warning(`The 'use_branches' input option is deprecated, please see the documentation for more information on how to use branches`);
|
||||
core.warning(
|
||||
`The 'use_branches' input option is deprecated, please see the documentation for more information on how to use branches`,
|
||||
);
|
||||
}
|
||||
|
||||
if (config.versionFormat === '' && core.getInput('format') !== '') {
|
||||
core.warning(`The 'format' input is deprecated, use 'versionFormat' instead`);
|
||||
config.versionFormat = core.getInput('format');
|
||||
if (config.versionFormat === "" && core.getInput("format") !== "") {
|
||||
core.warning(
|
||||
`The 'format' input is deprecated, use 'versionFormat' instead`,
|
||||
);
|
||||
config.versionFormat = core.getInput("format");
|
||||
}
|
||||
if (core.getInput('short_tags') !== '') {
|
||||
if (core.getInput("short_tags") !== "") {
|
||||
core.warning(`The 'short_tags' input option is no longer supported`);
|
||||
}
|
||||
|
||||
|
|
@ -94,4 +109,4 @@ export async function run() {
|
|||
setOutput(result);
|
||||
}
|
||||
|
||||
run();
|
||||
run();
|
||||
|
|
|
|||
|
|
@ -25,14 +25,14 @@ export class DefaultLastReleaseResolver implements LastReleaseResolver {
|
|||
currentTag = tagFormatter.IsValid(currentTag) ? currentTag : '';
|
||||
const isTagged = currentTag !== '';
|
||||
|
||||
const [currentMajor, currentMinor, currentPatch] = !!currentTag ? tagFormatter.Parse(currentTag) : [null, null, null];
|
||||
const [currentMajor, currentMinor, currentPatch] = currentTag ? tagFormatter.Parse(currentTag) : [null, null, null];
|
||||
|
||||
let tagsCount = 0;
|
||||
|
||||
let tag = '';
|
||||
try {
|
||||
const refPrefixPattern = this.useBranches ? 'refs/heads/' : 'refs/tags/';
|
||||
if (!!currentTag) {
|
||||
if (currentTag) {
|
||||
// If we already have the current branch tagged, we are checking for the previous one
|
||||
// so that we will have an accurate increment (assuming the new tag is the expected one)
|
||||
const command = `git for-each-ref --sort=-v:*refname --format=%(refname:short) --merged=${current} ${refPrefixPattern}${releasePattern}`;
|
||||
|
|
@ -63,9 +63,9 @@ export class DefaultLastReleaseResolver implements LastReleaseResolver {
|
|||
// polluted with a bunch of warnings.
|
||||
|
||||
if (tagsCount > 0) {
|
||||
core.warning(`None of the ${tagsCount} tags(s) found were valid version tags for the present configuration. If this is unexpected, check to ensure that the configuration is correct and matches the tag format you are using.`);
|
||||
core.warning(`None of the ${tagsCount} tags(s) found were valid version tags for the present configuration. If this is unexpected, check to ensure that the configuration is correct and matches the tag format you are using. If you have not yet tagged this repo with a version tag, this can be ignored.`);
|
||||
} else {
|
||||
core.warning('No tags are present for this repository. If this is unexpected, check to ensure that tags have been pulled from the remote.');
|
||||
core.warning('No tags are present for this repository. If this is unexpected, check to ensure that tags have been pulled from the remote. If you have not yet tagged this repo with a version tag, this can be ignored.');
|
||||
}
|
||||
}
|
||||
const [major, minor, patch] = tagFormatter.Parse('');
|
||||
|
|
|
|||
187
src/test-abstraction.ts
Normal file
187
src/test-abstraction.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
import * as cp from "child_process";
|
||||
import * as path from "path";
|
||||
import { runAction } from "./action";
|
||||
import { ConfigurationProvider } from "./ConfigurationProvider";
|
||||
import { ActionConfig } from "./ActionConfig";
|
||||
import { DebugManager } from "./DebugManager";
|
||||
import { VersionResult } from "./VersionResult";
|
||||
|
||||
export type TestInterface = "action" | "cli";
|
||||
|
||||
export interface TestRunner {
|
||||
runSemanticVersion(
|
||||
config: Partial<ActionConfig>,
|
||||
cwd: string,
|
||||
): Promise<VersionResult>;
|
||||
}
|
||||
|
||||
export class ActionTestRunner implements TestRunner {
|
||||
async runSemanticVersion(
|
||||
config: Partial<ActionConfig>,
|
||||
cwd: string,
|
||||
): Promise<VersionResult> {
|
||||
DebugManager.clearState();
|
||||
const fullConfig = new ActionConfig();
|
||||
Object.assign(fullConfig, config);
|
||||
|
||||
const originalCwd = process.cwd();
|
||||
try {
|
||||
process.chdir(cwd);
|
||||
return await runAction(new ConfigurationProvider(fullConfig));
|
||||
} finally {
|
||||
process.chdir(originalCwd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class CLITestRunner implements TestRunner {
|
||||
private cliPath: string;
|
||||
|
||||
constructor() {
|
||||
this.cliPath = path.join(__dirname, "..", "lib", "cli.js");
|
||||
}
|
||||
|
||||
private toKebabCase(str: string): string {
|
||||
return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
||||
}
|
||||
|
||||
async runSemanticVersion(
|
||||
config: Partial<ActionConfig>,
|
||||
cwd: string,
|
||||
): Promise<VersionResult> {
|
||||
const args: string[] = ["node", this.cliPath, "--format", "json"];
|
||||
|
||||
// Special case: changePath maps to --path
|
||||
const cliOptionOverrides: Record<string, string> = {
|
||||
changePath: "path",
|
||||
};
|
||||
|
||||
// Dynamically build CLI arguments from config
|
||||
for (const [key, value] of Object.entries(config)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
|
||||
// Get CLI option name
|
||||
const cliOptionName = cliOptionOverrides[key] || this.toKebabCase(key);
|
||||
|
||||
// Handle boolean flags
|
||||
if (typeof value === "boolean") {
|
||||
if (value) {
|
||||
args.push(`--${cliOptionName}`);
|
||||
}
|
||||
} else {
|
||||
// Handle string/number values
|
||||
args.push(`--${cliOptionName}`, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Use execFileSync instead of execSync to avoid shell escaping issues
|
||||
const output = cp.execFileSync("node", args.slice(1), {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"], // Capture stdout and stderr
|
||||
});
|
||||
|
||||
// Parse JSON output - filter out warning lines that start with ::warning::
|
||||
const lines = output
|
||||
.split("\n")
|
||||
.filter((line) => !line.startsWith("::warning::"));
|
||||
|
||||
// Find the start and end of JSON block
|
||||
const startIndex = lines.findIndex((line) => line.trim().startsWith("{"));
|
||||
const endIndex = lines.findIndex((line) => line.trim() === "}");
|
||||
|
||||
if (startIndex === -1 || endIndex === -1) {
|
||||
throw new Error(`No JSON output found from CLI. Output was: ${output}`);
|
||||
}
|
||||
|
||||
// Extract JSON lines and join them
|
||||
const jsonLines = lines.slice(startIndex, endIndex + 1);
|
||||
const jsonString = jsonLines.join("\n");
|
||||
|
||||
let cliResult;
|
||||
try {
|
||||
cliResult = JSON.parse(jsonString);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Failed to parse JSON. Output was: "${output}". JSON string extracted: "${jsonString}"`,
|
||||
);
|
||||
}
|
||||
|
||||
// Map CLI output to VersionResult format
|
||||
return new VersionResult(
|
||||
cliResult.major,
|
||||
cliResult.minor,
|
||||
cliResult.patch,
|
||||
cliResult.increment,
|
||||
cliResult.versionType,
|
||||
cliResult.version,
|
||||
cliResult.versionTag,
|
||||
cliResult.changed,
|
||||
cliResult.isTagged,
|
||||
cliResult.authors,
|
||||
cliResult.currentCommit,
|
||||
cliResult.previousCommit,
|
||||
cliResult.previousVersion,
|
||||
"", // debugOutput - not returned by CLI
|
||||
);
|
||||
} catch (error: any) {
|
||||
if (error.stdout) {
|
||||
// Try to parse error output - filter out warning lines
|
||||
const errorOutput = error.stdout.toString();
|
||||
const lines = errorOutput
|
||||
.split("\n")
|
||||
.filter((line: string) => !line.startsWith("::warning::"));
|
||||
|
||||
// Find the start and end of JSON block
|
||||
const startIndex = lines.findIndex((line: string) =>
|
||||
line.trim().startsWith("{"),
|
||||
);
|
||||
const endIndex = lines.findIndex((line: string) => line.trim() === "}");
|
||||
|
||||
if (startIndex !== -1 && endIndex !== -1) {
|
||||
// Extract JSON lines and join them
|
||||
const jsonLines = lines.slice(startIndex, endIndex + 1);
|
||||
const jsonString = jsonLines.join("\n");
|
||||
|
||||
let cliResult;
|
||||
try {
|
||||
cliResult = JSON.parse(jsonString);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Failed to parse JSON from error output. Output was: "${errorOutput}". JSON string extracted: "${jsonString}"`,
|
||||
);
|
||||
}
|
||||
return new VersionResult(
|
||||
cliResult.major,
|
||||
cliResult.minor,
|
||||
cliResult.patch,
|
||||
cliResult.increment,
|
||||
cliResult.versionType,
|
||||
cliResult.version,
|
||||
cliResult.versionTag,
|
||||
cliResult.changed,
|
||||
cliResult.isTagged,
|
||||
cliResult.authors,
|
||||
cliResult.currentCommit,
|
||||
cliResult.previousCommit,
|
||||
cliResult.previousVersion,
|
||||
"", // debugOutput - not returned by CLI
|
||||
);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createTestRunner(type: TestInterface): TestRunner {
|
||||
switch (type) {
|
||||
case "action":
|
||||
return new ActionTestRunner();
|
||||
case "cli":
|
||||
return new CLITestRunner();
|
||||
default:
|
||||
throw new Error(`Unknown test interface: ${type}`);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue