All files parse.js

100% Statements 63/63
92.47% Branches 86/93
100% Functions 12/12
100% Lines 62/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 2653x 3x                                               136x                                 3x       7x 7x 38x     7x                                                         3x       116x     116x 116x 116x 116x   116x                   116x 24x 24x   24x                     116x                                   3x         96x     96x 96x 96x 96x   96x 12x     96x 13x     96x   96x                           3x           13x 13x   13x   95x 3x   95x   95x 86x   86x   86x 45x           86x   86x     13x                                   3x         5x 5x   5x 1x     5x 10x     2x 2x   2x 2x   6x 6x       5x           3x                
const { generalCommitType, conventionalCommitType, OPTIONS } = require('./global');
const { getGit, getReleaseCommit, getLinkUrls } = require('./cmds');
 
/**
 * Parse and format commit messages
 *
 * @module Parse
 */
 
/**
 * Retrieves and combines conventional commit types with optional support for non-conventional commits.
 *
 * This function returns the standard conventional commit types from the 'conventional-commit-types'
 * package and optionally includes a general catch-all type for non-conventional commits.
 * The result is used to categorize and process commit messages throughout the application.
 *
 * @param {object} [options=OPTIONS] - Configuration options
 * @param {boolean} options.isAllowNonConventionalCommits - Whether to include the general commit type for non-conventional commits
 * @returns {{
 *     feat:{description:string, title:string, value:string},
 *     fix:{description:string, title:string, value:string},
 *     chore:{description:string, title:string, value:string,
 *     general:({description:string, title:string, value:string}|undefined)}
 *     }} Combined commit types
 */
const getCommitType = ({ isAllowNonConventionalCommits } = OPTIONS) => ({
  ...conventionalCommitType,
  ...(isAllowNonConventionalCommits && generalCommitType)
});
 
/**
 * Retrieves the commit hashes for generating comparison links in the changelog.
 *
 * This function finds the hash of the last release commit and the most recent commit
 * in the current branch. These hashes are used to create comparison links in the
 * changelog that show all changes between releases.
 *
 * @param {object} [settings={}] - Function overrides for customization
 * @param {getGit} [settings.getGit=getGit] - Function to get all commits
 * @param {getReleaseCommit} [settings.getReleaseCommit=getReleaseCommit] - Function to get the last release commit
 * @returns {{first:(string|null), last:(string|null)}} Commit hashes for comparison
 */
const getComparisonCommitHashes = ({
  getGit: getAliasGit = getGit,
  getReleaseCommit: getAliasReleaseCommit = getReleaseCommit
} = {}) => {
  const releaseCommitHash = getAliasReleaseCommit().split(/\s/)[0];
  const rest = getAliasGit()
    .map(({ commit }) => commit.trim().split(/\s/)[0])
    .reverse();
 
  return {
    first: releaseCommitHash || null,
    last: (releaseCommitHash && rest.pop()) || null
  };
};
 
/**
 * Parses a git commit message into structured components.
 *
 * This function extracts various parts of a commit message including the hash,
 * type, scope, description, and pull request number. It handles both conventional
 * commit format and non-conventional formats, falling back to a general type
 * for commits that don't follow the conventional format.
 *
 * @param {object} [params={}] - Parameters for parsing
 * @param {string} params.message - The raw commit message to parse
 * @param {boolean} [params.isBreaking=false] - Whether the commit contains breaking changes
 * @param {object} [settings={}] - Function overrides for customization
 * @param {getCommitType} [settings.getCommitType=getCommitType] - Function to get commit types
 * @returns {{
 *     hash:string,
 *     typeScope:(string|undefined),
 *     type:(string|undefined),
 *     scope:(string|undefined),
 *     description:(string|undefined),
 *     prNumber:(string|undefined),
 *     isBreaking:boolean
 *     }} Parsed commit message components
 */
const parseCommitMessage = (
  { message, isBreaking = false } = {},
  { getCommitType: getAliasCommitType = getCommitType } = {}
) => {
  const commitType = getAliasCommitType();
  let output;
 
  const [hashTypeScope, ...descriptionEtAll] = message.trim().split(/:/);
  const [description, ...partialPr] = descriptionEtAll.join(' ').trim().split(/\(#/);
  const [hash, ...typeScope] = hashTypeScope.replace(/!$/, '').trim().split(/\s/);
  const [type, scope = ''] = typeScope.join(' ').trim().split('(');
 
  output = {
    hash,
    typeScope: typeScope.join(' ').trim() || undefined,
    type: commitType?.[type]?.value || undefined,
    scope: scope.split(')')[0] || undefined,
    description: description.trim() || undefined,
    prNumber: (partialPr.join('(#').trim() || '').replace(/\D/g, '') || undefined,
    isBreaking
  };
 
  if (!output.type || (output.type && !descriptionEtAll?.length)) {
    const [hash, ...descriptionEtAll] = message.trim().split(/\s/);
    const [description, ...partialPr] = descriptionEtAll.join(' ').trim().split(/\(#/);
 
    output = {
      hash,
      typeScope: undefined,
      type: generalCommitType.general.value,
      scope: undefined,
      description: description.trim(),
      prNumber: (partialPr.join('(#').trim() || '').replace(/\D/g, ''),
      isBreaking
    };
  }
 
  return output;
};
 
/**
 * Format commit message for CHANGELOG.md
 *
 * @param {object} [params={}]
 * @param {string} params.scope
 * @param {string} params.description
 * @param {string|number|*} params.prNumber
 * @param {string} params.hash
 * @param {boolean} params.isBreaking
 * @param {object} [options=OPTIONS]
 * @param {boolean} options.isBasic
 * @param {object} [settings={}]
 * @param {getLinkUrls} [settings.getLinkUrls=getLinkUrls]
 * @returns {string}
 */
const formatChangelogMessage = (
  { scope, description, prNumber, hash, isBreaking } = {},
  { isBasic } = OPTIONS,
  { getLinkUrls: getAliasLinkUrls = getLinkUrls } = {}
) => {
  const { commitUrl, prUrl } = getAliasLinkUrls();
  let output;
 
  const updatedBreaking = (isBreaking && '\u26A0 ') || '';
  const updatedScope = (scope && `**${scope}**`) || '';
  let updatedPr = (prNumber && `(#${prNumber})`) || '';
  let updatedHash = (hash && `(${hash.substring(0, 7)})`) || '';
 
  if (!isBasic && prUrl && updatedPr) {
    updatedPr = `([#${prNumber}](${new URL(prNumber, prUrl).href}))`;
  }
 
  if (!isBasic && commitUrl && updatedHash) {
    updatedHash = `([${hash.substring(0, 7)}](${new URL(hash, commitUrl).href}))`;
  }
 
  output = `* ${updatedBreaking}${updatedScope} ${description || hash} ${updatedPr} ${updatedHash}`;
 
  return output;
};
 
/**
 * Return an object of commit groupings based on "conventional-commit-types"
 *
 * @param {object} [settings={}]
 * @param {getCommitType} [settings.getCommitType=getCommitType]
 * @param {getGit} [settings.getGit=getGit]
 * @param {formatChangelogMessage} [settings.formatChangelogMessage=formatChangelogMessage]
 * @param {parseCommitMessage} [settings.parseCommitMessage=parseCommitMessage]
 * @returns {{'Bug Fixes': {commits: string[], title: string}, Chores: {commits: string[],
 *     title: string}, Features: {commits: string[], title: string}}}
 */
const parseCommits = ({
  getCommitType: getAliasCommitType = getCommitType,
  getGit: getAliasGit = getGit,
  formatChangelogMessage: formatAliasChangelogMessage = formatChangelogMessage,
  parseCommitMessage: parseAliasCommitMessage = parseCommitMessage
} = {}) => {
  const commitType = getAliasCommitType();
  let isBreakingChanges = false;
 
  const commits = getAliasGit()
    .map(({ commit: message, isBreaking }) => {
      if (isBreaking === true) {
        isBreakingChanges = true;
      }
      return parseAliasCommitMessage({ message, isBreaking });
    })
    .filter(obj => obj.type in commitType)
    .map(obj => ({ ...obj, typeLabel: obj.type }))
    .reduce((groups, { typeLabel, ...messageProps }) => {
      const updatedGroups = groups;
 
      if (!updatedGroups[typeLabel]) {
        updatedGroups[typeLabel] = {
          ...commitType[typeLabel],
          commits: []
        };
      }
 
      updatedGroups[typeLabel].commits.push(formatAliasChangelogMessage({ typeLabel, ...messageProps }));
 
      return updatedGroups;
    }, {});
 
  return {
    commits,
    isBreakingChanges
  };
};
 
/**
 * Apply a clear weight to commit types, determine MAJOR, MINOR, PATCH
 *
 * @param {object} [params={}]
 * @param {{ feat: { commits: Array }, refactor: { commits: Array }, fix: { commits: Array } }} [params.commits={}]
 * @param {boolean} [params.isBreakingChanges=false] Apply a 'major' weight if true
 * @param {object} [options=OPTIONS]
 * @param {boolean} [options.isOverrideVersion=false]
 * @param {object} [settings={}]
 * @param {getCommitType} [settings.getCommitType=getCommitType]
 * @returns {{bump: ('major'|'minor'|'patch'), weight: number}}
 */
const semverBump = (
  { commits: parsedCommits = {}, isBreakingChanges = false } = {},
  { isOverrideVersion = false } = OPTIONS,
  { getCommitType: getAliasCommitType = getCommitType } = {}
) => {
  const commitType = getAliasCommitType();
  let weight = 0;
 
  if (isBreakingChanges === true) {
    weight += 100;
  }
 
  Object.entries(parsedCommits).forEach(([key, { commits = [] }]) => {
    switch (key) {
      case commitType?.feat?.value:
      case commitType?.['revert']?.value:
        weight += 10 * commits.length;
        break;
      case commitType?.refactor?.value:
        weight += commits.length;
        break;
      default:
        weight += 0.1 * commits.length;
        break;
    }
  });
 
  return {
    bump: (isOverrideVersion && 'override') || (weight >= 100 && 'major') || (weight >= 10 && 'minor') || 'patch',
    weight
  };
};
 
module.exports = {
  getCommitType,
  getComparisonCommitHashes,
  formatChangelogMessage,
  parseCommitMessage,
  parseCommits,
  semverBump
};