refactor: improve changelog logic (#197)

* refactor: improve changelog logic

Signed-off-by: Ardalan Amini <[email protected]>

* chore: update license comment formatting across all files

Replaced `/*` with `/**` for correct JSDoc-style license comments in all files.
This ensures consistency and compatibility with documentation tools that rely on JSDoc conventions.

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for inputs

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for utils

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for outputs

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for nodes

Signed-off-by: Ardalan Amini <[email protected]>

* test: add missing unit tests

Signed-off-by: Ardalan Amini <[email protected]>

* chore: address PR comments

Signed-off-by: Ardalan Amini <[email protected]>

* chore: address PR comments

Signed-off-by: Ardalan Amini <[email protected]>

---------

Signed-off-by: Ardalan Amini <[email protected]>
This commit is contained in:
Ardalan Amini authored and GitHub committed 2025-06-07 15:37:31 +03:30
1 parent 3c1177539c
commit 9bd6b8698c
95 files changed
+4381 -302

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { commitTypes, defaultCommitType } from "../inputs/index.js";
import { trim } from "../utils/index.js";
import { Node } from "./node.js";
import { TypeNode } from "./type.js";
/**
* Represents a changelog node which organizes and processes commit types into structured changelog entries.
* This class manages the mapping of commit types to their human-readable counterparts, aggregates commit
* types into groups, and generates a formatted output.
*/
export class ChangelogNode extends Node {
public readonly defaultType = defaultCommitType();
public readonly typeMap = commitTypes();
protected readonly types = (new Map<string, TypeNode>);
/**
* Adds a new type or retrieves an existing one from the already added types.
* If the input `type` is not found in the type map, the default type is assigned.
*
* @param [type=""] - The commit type to be mapped and added.
* @returns The corresponding type node that represents the added or existing type.
*/
public addType(type = ""): TypeNode {
const { types, typeMap, defaultType } = this;
// Map the commit type to the human-readable changelog type.
type = typeMap[trim(type)] ?? defaultType;
// Reusing the already added type to group the commits.
if (types.has(type)) return types.get(type)!;
const typeNode = new TypeNode(type);
types.set(type, typeNode);
return typeNode;
}
/**
* Compiles and concatenates the output of all accepted types into a single string, prefixed by the provided prefix.
*
* @param [prefix=""] - A string that is prefixed to each type's printed output.
* @returns A concatenated string of all printed types with the applied prefix, or null if no types are available.
*/
public print(prefix = ""): string | null {
const { types } = this;
if (types.size === 0) return null;
/**
* Using this instead of iterating over the `types` values allows the action users to apply their own custom order.
*/
const acceptedTypes = [...new Set(Object.values(this.typeMap).concat(this.defaultType))];
const parts: string[] = [];
for (const key of acceptedTypes) {
const type = types.get(key);
if (!type) continue;
const printedType = type.print(prefix);
if (printedType) parts.push(printedType);
}
if (parts.length === 0) return null;
// Joined by 2 new lines to have one empty line between each type group.
return parts.join("\n\n");
}
}
+110
View File
@@ -0,0 +1,110 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { mentionAuthors } from "../inputs/index.js";
import { CommitHashNode } from "./commit-hash.js";
import { Node } from "./node.js";
import { PullRequestNode } from "./pull-request.js";
/**
* Represents a node for a commit author, containing information about the author
* and associated references to commits or pull requests.
*/
export class CommitAuthorNode extends Node {
public readonly shouldMentionAuthor = mentionAuthors();
protected readonly references: Array<CommitHashNode | PullRequestNode> = [];
/**
* Initializes a new instance of the commit author node with an optional username.
*
* @param [username] - The commit author username.
*/
public constructor(public readonly username?: string) {
super();
}
/**
* Adds a reference to either a pull request or a commit hash.
* If a pull request is provided, it takes priority over the commit hash.
*
* @param sha - The SHA hash of the commit reference.
* @param [pr] - The optional pull request identifier.
* @returns The created reference node, either a CommitHashNode or a PullRequestNode.
*/
public addReference(sha: string, pr?: string): CommitHashNode | PullRequestNode {
let reference: CommitHashNode | PullRequestNode;
// PR references take priority over commit hash references
if (pr) reference = new PullRequestNode(pr);
else reference = new CommitHashNode(sha);
// Check if a reference already exists to avoid duplicates
for (const existingRef of this.references) {
if (
(!pr && existingRef instanceof CommitHashNode && existingRef.sha === sha)
|| (existingRef instanceof PullRequestNode && existingRef.pr === pr)
) return existingRef;
}
this.references.push(reference);
return reference;
}
/**
* Constructs and returns a formatted string representation based on references and author information.
* It combines references and adds author mention if applicable.
*
* @returns The formatted string representation or null if no parts are available.
*/
public print(): string | null {
const { username, references, serverUrl, shouldMentionAuthor, shouldUseGithubAutolink } = this;
const printedReferences: string[] = [];
for (const reference of references) {
const printedReference = reference.print();
if (printedReference) printedReferences.push(printedReference);
}
const parts: string[] = [];
if (printedReferences.length > 0) parts.push(printedReferences.join(" & "));
if (shouldMentionAuthor && username) {
if (parts.length > 0) parts.push("by");
if (shouldUseGithubAutolink) parts.push(`@${ username }`);
else parts.push(`[@${ username }](${ serverUrl }/${ username })`);
}
if (parts.length === 0) return null;
return parts.join(" ");
}
}
+65
View File
@@ -0,0 +1,65 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { includeCommitLinks } from "../inputs/index.js";
import { Node } from "./node.js";
/**
* Represents a node that holds a commit hash (SHA) and provides functionality
* for generating formatted strings or links based on its state and the repository context.
*/
export class CommitHashNode extends Node {
public readonly shouldNotPrint = !includeCommitLinks();
/**
* Constructs an instance of the commit hash node with a specified SHA string.
*
* @param sha - The SHA string associated with this instance.
*/
public constructor(public readonly sha: string) {
super();
}
/**
* Generates and returns a formatted string based on the current object state.
* If `shouldNotPrint` is true, the method returns null.
* If `shouldUseGithubAutolink` is true, the method directly returns the `sha` value.
* Otherwise,
* it returns a markdown-formatted string linking to the GitHub commit URL constructed using `sha` and `repo.url`.
*
* @returns A formatted string, the `sha` string, or null depending on conditions.
*/
public print(): string | null {
const { sha, shouldUseGithubAutolink, repo, shouldNotPrint } = this;
if (shouldNotPrint) return null;
if (shouldUseGithubAutolink) return sha;
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
return `\`[${ sha.slice(0, 7) }](${ repo.url }/commit/${ sha })\``;
}
}
+102
View File
@@ -0,0 +1,102 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { CommitAuthorNode } from "./commit-author.js";
import { Node } from "./node.js";
/**
* Represents a commit node in a data structure that tracks commit information.
* Extends the `Node` class and contains additional metadata such as description,
* authors, and a flag indicating whether the commit introduces breaking changes.
*/
export class CommitNode extends Node {
protected readonly authors: CommitAuthorNode[] = [];
/**
* Constructs an instance of the class.
*
* @param description - A description of the instance.
* @param [breaking=false] - Indicates whether the instance represents a breaking change.
*/
public constructor(public readonly description: string, public readonly breaking = false) {
super();
}
/**
* Adds a new author or retrieves the previous author if the username matches the last one.
* This optimization helps group consecutive commits by the same author efficiently.
*
* @param [username] - The username of the author to add.
* @returns The added or retrieved author node instance.
*/
public addAuthor(username?: string): CommitAuthorNode {
const { authors } = this;
// Only reuse authors with known usernames.
if (username && authors.length > 0) {
// Only if the last reference is to the same author, reuse the node.
const previousAuthor = authors[authors.length - 1];
if (previousAuthor.username === username) return previousAuthor;
}
const author = new CommitAuthorNode(username);
authors.push(author);
return author;
}
/**
* Constructs and returns a formatted string representation of the commit.
*
* @param [prefix=""] - A string to prefix the formatted output with.
* @returns A formatted string containing the description, authors, and a breaking indicator if applicable.
*/
public print(prefix = ""): string {
const { breaking, description, authors } = this;
const parts: string[] = [];
if (breaking) parts.push("***BREAKING:***");
parts.push(description);
if (authors.length > 0) {
const references: string[] = [];
for (const author of authors) {
const printedAuthor = author.print();
if (printedAuthor) references.push(printedAuthor);
}
if (references.length > 0) parts.push(`(${ references.join(", ") })`);
}
return `${ prefix }* ${ parts.join(" ") }`;
}
}
+32
View File
@@ -0,0 +1,32 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export * from "./changelog.js";
export * from "./commit.js";
export * from "./commit-author.js";
export * from "./commit-hash.js";
export * from "./node.js";
export * from "./pull-request.js";
export * from "./scope.js";
export * from "./type.js";
+48
View File
@@ -0,0 +1,48 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { context } from "@actions/github";
import { useGitHubAutolink } from "../inputs/index.js";
import { repository } from "../utils/index.js";
/**
* Represents the base class for all nodes in the changelog,
* providing shared functionality and requiring implementation of a print method.
*/
export abstract class Node {
public readonly repo = repository();
public readonly serverUrl = context.serverUrl;
public readonly shouldUseGithubAutolink = useGitHubAutolink();
/**
* Outputs a string representation of the changelog node.
*
* @returns The string representation if available, otherwise `null` if no representation exists or is provided.
*/
public abstract print(): string | null;
}
+62
View File
@@ -0,0 +1,62 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { includePRLinks } from "../inputs/index.js";
import { Node } from "./node.js";
/**
* Represents a node associated with a pull request or issue link.
* This class provides functionality to generate formatted links
* for pull requests or issues based on certain conditions.
*/
export class PullRequestNode extends Node {
public readonly shouldNotPrint = !includePRLinks();
/**
* Constructs an instance of the class with the specified `pr` parameter.
*
* @param pr - A string representing the parameter to be assigned to the instance.
*/
public constructor(public readonly pr: string) {
super();
}
/**
* Generates a formatted string representing a pull request or issue link
* based on the method's logic and class properties.
*
* @returns A string with the formatted pull request link or null if printing is disabled.
*/
public print(): string | null {
const { pr, shouldUseGithubAutolink, repo, shouldNotPrint } = this;
if (shouldNotPrint) return null;
if (shouldUseGithubAutolink) return `#${ pr }`;
return `[#${ pr }](${ repo.url }/issues/${ pr })`;
}
}
+91
View File
@@ -0,0 +1,91 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { CommitNode } from "./commit.js";
import { Node } from "./node.js";
/**
* Represents a scope node within a changelog hierarchy, containing a collection of commit nodes.
* A scope node can have an associated scope name and provides functionality to add commits
* and generate formatted output with scope and commit details.
*/
export class ScopeNode extends Node {
protected readonly commits = (new Map<string, CommitNode>);
/**
* Constructs an instance of the scope node.
*
* @param scope An optional string value representing the scope.
*/
public constructor(public readonly scope = "") {
super();
}
/**
* Adds a new commit to the internal collection or retrieves an existing one if it already exists.
*
* @param message The message associated with the commit.
* @param [breaking=false] Indicates whether the commit introduces breaking changes.
* @returns The newly added or existing commit node.
*/
public addCommit(message: string, breaking = false): CommitNode {
const { commits } = this;
const key = `${ breaking }::${ message }`;
if (commits.has(key)) return commits.get(key)!;
const commitNode = new CommitNode(message, breaking);
commits.set(key, commitNode);
return commitNode;
}
/**
* Generates a formatted string representation of the changelog's scope and commits.
*
* @param [prefix=""] Optional string to prepend to each line of the output.
* @returns A formatted string with scope and commit details, or null if there are no commits.
*/
public print(prefix = ""): string | null {
const { scope, commits } = this;
if (commits.size === 0) return null;
const parts: string[] = [];
if (scope) {
parts.push(`${ prefix }* **${ scope }:**`);
prefix += " ";
}
for (const commit of commits.values()) parts.push(commit.print(prefix));
return parts.join("\n");
}
}
+102
View File
@@ -0,0 +1,102 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { trim } from "../utils/index.js";
import { Node } from "./node.js";
import { ScopeNode } from "./scope.js";
/**
* Represents a node for a specific type that manages associated scopes.
* Provides methods to add scopes and retrieve a formatted string representation
* of its contents, including associated scopes and their respective commits.
*/
export class TypeNode extends Node {
protected readonly scopes = (new Map<string, ScopeNode>);
/**
* Constructs an instance of type node class with a specified type.
*
* @param type - The commit type associated with the instance.
*/
public constructor(public readonly type: string) {
super();
}
/**
* Adds a new scope to the scope collection.
* If the scope already exists,
* the existing scope node is returned instead of creating a new one.
*
* @param [scope=""] - The name of the scope to be added.
* @returns The scope node associated with the added or existing scope.
*/
public addScope(scope = ""): ScopeNode {
const { scopes } = this;
scope = trim(scope);
// Reusing the already added scope to group the commits.
if (scopes.has(scope)) return scopes.get(scope)!;
const scopeNode = new ScopeNode(scope);
scopes.set(scope, scopeNode);
return scopeNode;
}
/**
* Prints the commits and their scopes grouped in this type.
*
* @param [prefix=""] - A prefix string to prepend to the output.
* @returns The formatted string representation, or null if no scopes are available.
*/
public print(prefix = ""): string | null {
const { type, scopes } = this;
if (scopes.size === 0) return null;
const parts: string[] = [`${ prefix }## ${ type }`];
/**
* Sorting the scopes to have a consistent output order in all changelogs.
*/
const scopeKeys = [...scopes.keys()].sort((a, b) => a.localeCompare(b));
for (const key of scopeKeys) {
const scope = scopes.get(key)!;
const printedScope = scope.print(prefix);
if (printedScope) parts.push(printedScope);
}
// If only the header exists with no scope content, return null
if (parts.length === 1) return null;
return parts.join("\n");
}
}