From 21a7b6041fde2c33c9c51ca9d9f6b8e135f7f1e8 Mon Sep 17 00:00:00 2001 From: Matt Travi Date: Sat, 27 Aug 2022 00:20:13 -0500 Subject: [PATCH] wip(esm): initial module type conversion for #2543 --- index.js | 47 ++++--- lib/branches/expand.js | 10 +- lib/branches/get-tags.js | 17 ++- lib/branches/index.js | 22 +-- lib/branches/normalize.js | 29 ++-- lib/definitions/branches.js | 14 +- lib/definitions/constants.js | 30 ++--- lib/definitions/errors.js | 172 ++++++++++++++++-------- lib/definitions/plugins.js | 12 +- lib/get-commits.js | 10 +- lib/get-config.js | 24 ++-- lib/get-error.js | 8 +- lib/get-git-auth-url.js | 16 ++- lib/get-last-release.js | 12 +- lib/get-logger.js | 10 +- lib/get-next-version.js | 10 +- lib/get-release-to-add.js | 14 +- lib/git.js | 72 ++++------ lib/hide-sensitive.js | 8 +- lib/plugins/index.js | 18 +-- lib/plugins/normalize.js | 18 +-- lib/plugins/pipeline.js | 12 +- lib/plugins/utils.js | 19 +-- lib/utils.js | 54 +++----- lib/verify.js | 12 +- package-lock.json | 12 +- package.json | 7 +- test/branches/branches.test.js | 8 +- test/branches/expand.test.js | 6 +- test/branches/get-tags.test.js | 6 +- test/branches/normalize.test.js | 4 +- test/cli.test.js | 10 +- test/definitions/branches.test.js | 4 +- test/definitions/plugins.test.js | 6 +- test/fixtures/index.js | 2 +- test/fixtures/multi-plugin.js | 2 +- test/fixtures/plugin-error-inherited.js | 6 +- test/fixtures/plugin-error.js | 4 +- test/fixtures/plugin-errors.js | 6 +- test/fixtures/plugin-identity.js | 2 +- test/fixtures/plugin-log-env.js | 4 +- test/fixtures/plugin-noop.js | 2 +- test/fixtures/plugin-result-config.js | 2 +- test/get-commits.test.js | 8 +- test/get-config.test.js | 20 +-- test/get-git-auth-url.test.js | 6 +- test/get-last-release.test.js | 4 +- test/get-logger.test.js | 6 +- test/get-next-version.test.js | 6 +- test/get-release-to-add.test.js | 4 +- test/git.test.js | 56 ++++---- test/helpers/git-utils.js | 83 ++++-------- test/helpers/gitbox.js | 18 ++- test/helpers/mockserver.js | 22 ++- test/helpers/npm-registry.js | 22 ++- test/helpers/npm-utils.js | 6 +- test/hide-sensitive.test.js | 8 +- test/index.test.js | 39 +++--- test/plugins/normalize.test.js | 8 +- test/plugins/pipeline.test.js | 8 +- test/plugins/plugins.test.js | 16 +-- test/plugins/utils.test.js | 4 +- test/utils.test.js | 26 ++-- test/verify.test.js | 8 +- 64 files changed, 574 insertions(+), 567 deletions(-) diff --git a/index.js b/index.js index b5b67a6458..d37b7fd0d6 100644 --- a/index.js +++ b/index.js @@ -1,24 +1,27 @@ -const {pick} = require('lodash'); -const marked = require('marked'); -const envCi = require('env-ci'); -const hookStd = require('hook-std'); -const semver = require('semver'); -const AggregateError = require('aggregate-error'); +import {createRequire} from 'node:module'; +import {pick} from 'lodash-es'; +import * as marked from 'marked'; +import envCi from 'env-ci'; +import hookStd from 'hook-std'; +import semver from 'semver'; +import AggregateError from 'aggregate-error'; +import hideSensitive from './lib/hide-sensitive.js'; +import getConfig from './lib/get-config.js'; +import verify from './lib/verify.js'; +import getNextVersion from './lib/get-next-version.js'; +import getCommits from './lib/get-commits.js'; +import getLastRelease from './lib/get-last-release.js'; +import getReleaseToAdd from './lib/get-release-to-add.js'; +import {extractErrors, makeTag} from './lib/utils.js'; +import getGitAuthUrl from './lib/get-git-auth-url.js'; +import getBranches from './lib/branches/index.js'; +import getLogger from './lib/get-logger.js'; +import {addNote, getGitHead, getTagHead, isBranchUpToDate, push, pushNotes, tag, verifyAuth} from './lib/git.js'; +import getError from './lib/get-error.js'; +import {COMMIT_EMAIL, COMMIT_NAME} from './lib/definitions/constants.js'; + +const require = createRequire(import.meta.url); const pkg = require('./package.json'); -const hideSensitive = require('./lib/hide-sensitive'); -const getConfig = require('./lib/get-config'); -const verify = require('./lib/verify'); -const getNextVersion = require('./lib/get-next-version'); -const getCommits = require('./lib/get-commits'); -const getLastRelease = require('./lib/get-last-release'); -const getReleaseToAdd = require('./lib/get-release-to-add'); -const {extractErrors, makeTag} = require('./lib/utils'); -const getGitAuthUrl = require('./lib/get-git-auth-url'); -const getBranches = require('./lib/branches'); -const getLogger = require('./lib/get-logger'); -const {verifyAuth, isBranchUpToDate, getGitHead, tag, push, pushNotes, getTagHead, addNote} = require('./lib/git'); -const getError = require('./lib/get-error'); -const {COMMIT_NAME, COMMIT_EMAIL} = require('./lib/definitions/constants'); let markedOptionsSet = false; async function terminalOutput(text) { @@ -247,7 +250,7 @@ async function callFail(context, plugins, err) { } } -module.exports = async (cliOptions = {}, {cwd = process.cwd(), env = process.env, stdout, stderr} = {}) => { +export default async (cliOptions = {}, {cwd = process.cwd(), env = process.env, stdout, stderr} = {}) => { const {unhook} = hookStd( {silent: false, streams: [process.stdout, process.stderr, stdout, stderr].filter(Boolean)}, hideSensitive(env) @@ -278,4 +281,4 @@ module.exports = async (cliOptions = {}, {cwd = process.cwd(), env = process.env unhook(); throw error; } -}; +} diff --git a/lib/branches/expand.js b/lib/branches/expand.js index 3deea97c0e..6ecb828c44 100644 --- a/lib/branches/expand.js +++ b/lib/branches/expand.js @@ -1,8 +1,8 @@ -const {isString, remove, omit, mapValues, template} = require('lodash'); -const micromatch = require('micromatch'); -const {getBranches} = require('../git'); +import {isString, mapValues, omit, remove, template} from 'lodash-es'; +import micromatch from 'micromatch'; +import {getBranches} from '../git.js'; -module.exports = async (repositoryUrl, {cwd}, branches) => { +export default async (repositoryUrl, {cwd}, branches) => { const gitBranches = await getBranches(repositoryUrl, {cwd}); return branches.reduce( @@ -15,4 +15,4 @@ module.exports = async (repositoryUrl, {cwd}, branches) => { ], [] ); -}; +} diff --git a/lib/branches/get-tags.js b/lib/branches/get-tags.js index 8cffbeb405..080cb54e12 100644 --- a/lib/branches/get-tags.js +++ b/lib/branches/get-tags.js @@ -1,10 +1,13 @@ -const {template, escapeRegExp} = require('lodash'); -const semver = require('semver'); -const pReduce = require('p-reduce'); -const debug = require('debug')('semantic-release:get-tags'); -const {getTags, getNote} = require('../../lib/git'); +import {escapeRegExp, template} from 'lodash-es'; +import semver from 'semver'; +import pReduce from 'p-reduce'; +import debugTags from 'debug'; +import {getNote, getTags} from '../../lib/git.js'; -module.exports = async ({cwd, env, options: {tagFormat}}, branches) => { +const debug = debugTags('semantic-release:get-tags'); + + +export default async ({cwd, env, options: {tagFormat}}, branches) => { // Generate a regex to parse tags formatted with `tagFormat` // by replacing the `version` variable in the template by `(.+)`. // The `tagFormat` is compiled with space as the `version` as it's an invalid tag character, @@ -30,4 +33,4 @@ module.exports = async ({cwd, env, options: {tagFormat}}, branches) => { }, [] ); -}; +} diff --git a/lib/branches/index.js b/lib/branches/index.js index 951500dc47..0e058311b7 100644 --- a/lib/branches/index.js +++ b/lib/branches/index.js @@ -1,14 +1,14 @@ -const {isString, isRegExp} = require('lodash'); -const AggregateError = require('aggregate-error'); -const pEachSeries = require('p-each-series'); -const DEFINITIONS = require('../definitions/branches'); -const getError = require('../get-error'); -const {fetch, fetchNotes, verifyBranchName} = require('../git'); -const expand = require('./expand'); -const getTags = require('./get-tags'); -const normalize = require('./normalize'); +import {isRegExp, isString} from 'lodash-es'; +import AggregateError from 'aggregate-error'; +import pEachSeries from 'p-each-series'; +import * as DEFINITIONS from '../definitions/branches.js'; +import getError from '../get-error.js'; +import {fetch, fetchNotes, verifyBranchName} from '../git.js'; +import expand from './expand.js'; +import getTags from './get-tags.js'; +import * as normalize from './normalize.js'; -module.exports = async (repositoryUrl, ciBranch, context) => { +export default async (repositoryUrl, ciBranch, context) => { const {cwd, env} = context; const remoteBranches = await expand( @@ -68,4 +68,4 @@ module.exports = async (repositoryUrl, ciBranch, context) => { } return [...result.maintenance, ...result.release, ...result.prerelease]; -}; +} diff --git a/lib/branches/normalize.js b/lib/branches/normalize.js index 369bd9d717..09f9785c98 100644 --- a/lib/branches/normalize.js +++ b/lib/branches/normalize.js @@ -1,19 +1,18 @@ -const {sortBy, isNil} = require('lodash'); -const semverDiff = require('semver-diff'); -const {FIRST_RELEASE, RELEASE_TYPE} = require('../definitions/constants'); -const { - tagsToVersions, - isMajorRange, +import {isNil, sortBy} from 'lodash-es'; +import semverDiff from 'semver-diff'; +import {FIRST_RELEASE, RELEASE_TYPE} from '../definitions/constants.js'; +import { + getFirstVersion, + getLatestVersion, + getLowerBound, getRange, getUpperBound, - getLowerBound, highest, + isMajorRange, lowest, - getLatestVersion, - getFirstVersion, - getRange, -} = require('../utils'); + tagsToVersions +} from '../utils.js'; -function maintenance({maintenance, release}) { +export function maintenance({maintenance, release}) { return sortBy( maintenance.map(({name, range, channel, ...rest}) => ({ ...rest, @@ -55,7 +54,7 @@ function maintenance({maintenance, release}) { }); } -function release({release}) { +export function release({release}) { if (release.length === 0) { return release; } @@ -89,7 +88,7 @@ function release({release}) { }); } -function prerelease({prerelease}) { +export function prerelease({prerelease}) { return prerelease.map(({name, prerelease, channel, tags, ...rest}) => { const preid = prerelease === true ? name : prerelease; return { @@ -102,5 +101,3 @@ function prerelease({prerelease}) { }; }); } - -module.exports = {maintenance, release, prerelease}; diff --git a/lib/definitions/branches.js b/lib/definitions/branches.js index c47fc65683..f23d048488 100644 --- a/lib/definitions/branches.js +++ b/lib/definitions/branches.js @@ -1,24 +1,22 @@ -const {isNil, uniqBy} = require('lodash'); -const semver = require('semver'); -const {isMaintenanceRange} = require('../utils'); +import {isNil, uniqBy} from 'lodash-es'; +import semver from 'semver'; +import {isMaintenanceRange} from '../utils.js'; -const maintenance = { +export const maintenance = { filter: ({name, range}) => (!isNil(range) && range !== false) || isMaintenanceRange(name), branchValidator: ({range}) => (isNil(range) ? true : isMaintenanceRange(range)), branchesValidator: (branches) => uniqBy(branches, ({range}) => semver.validRange(range)).length === branches.length, }; -const prerelease = { +export const prerelease = { filter: ({prerelease}) => !isNil(prerelease) && prerelease !== false, branchValidator: ({name, prerelease}) => Boolean(prerelease) && Boolean(semver.valid(`1.0.0-${prerelease === true ? name : prerelease}.1`)), branchesValidator: (branches) => uniqBy(branches, 'prerelease').length === branches.length, }; -const release = { +export const release = { // eslint-disable-next-line unicorn/no-fn-reference-in-iterator filter: (branch) => !maintenance.filter(branch) && !prerelease.filter(branch), branchesValidator: (branches) => branches.length <= 3 && branches.length > 0, }; - -module.exports = {maintenance, prerelease, release}; diff --git a/lib/definitions/constants.js b/lib/definitions/constants.js index 999999c9ac..d75b7a174d 100644 --- a/lib/definitions/constants.js +++ b/lib/definitions/constants.js @@ -1,29 +1,17 @@ -const RELEASE_TYPE = ['patch', 'minor', 'major']; +export const RELEASE_TYPE = ['patch', 'minor', 'major']; -const FIRST_RELEASE = '1.0.0'; +export const FIRST_RELEASE = '1.0.0'; -const FIRSTPRERELEASE = '1'; +export const FIRSTPRERELEASE = '1'; -const COMMIT_NAME = 'semantic-release-bot'; +export const COMMIT_NAME = 'semantic-release-bot'; -const COMMIT_EMAIL = 'semantic-release-bot@martynus.net'; +export const COMMIT_EMAIL = 'semantic-release-bot@martynus.net'; -const RELEASE_NOTES_SEPARATOR = '\n\n'; +export const RELEASE_NOTES_SEPARATOR = '\n\n'; -const SECRET_REPLACEMENT = '[secure]'; +export const SECRET_REPLACEMENT = '[secure]'; -const SECRET_MIN_SIZE = 5; +export const SECRET_MIN_SIZE = 5; -const GIT_NOTE_REF = 'semantic-release'; - -module.exports = { - RELEASE_TYPE, - FIRST_RELEASE, - FIRSTPRERELEASE, - COMMIT_NAME, - COMMIT_EMAIL, - RELEASE_NOTES_SEPARATOR, - SECRET_REPLACEMENT, - SECRET_MIN_SIZE, - GIT_NOTE_REF, -}; +export const GIT_NOTE_REF = 'semantic-release'; diff --git a/lib/definitions/errors.js b/lib/definitions/errors.js index c109f2afab..3a0f12aaad 100644 --- a/lib/definitions/errors.js +++ b/lib/definitions/errors.js @@ -1,7 +1,10 @@ -const {inspect} = require('util'); -const {toLower, isString, trim} = require('lodash'); +import {inspect} from 'node:util'; +import {createRequire} from 'node:module'; +import {isString, toLower, trim} from 'lodash-es'; +import {RELEASE_TYPE} from './constants.js'; + +const require = createRequire(import.meta.url); const pkg = require('../../package.json'); -const {RELEASE_TYPE} = require('./constants'); const [homepage] = pkg.homepage.split('#'); const stringify = (object) => @@ -10,16 +13,19 @@ const linkify = (file) => `${homepage}/blob/master/${file}`; const wordsList = (words) => `${words.slice(0, -1).join(', ')}${words.length > 1 ? ` or ${words[words.length - 1]}` : trim(words[0])}`; -module.exports = { - ENOGITREPO: ({cwd}) => ({ +export function ENOGITREPO({cwd}) { + return { message: 'Not running from a git repository.', details: `The \`semantic-release\` command must be executed from a Git repository. The current working directory is \`${cwd}\`. Please verify your CI configuration to make sure the \`semantic-release\` command is executed from the root of the cloned repository.`, - }), - ENOREPOURL: () => ({ + }; +} + +export function ENOREPOURL() { + return { message: 'The `repositoryUrl` option is required.', details: `The [repositoryUrl option](${linkify( 'docs/usage/configuration.md#repositoryurl' @@ -28,8 +34,11 @@ Please verify your CI configuration to make sure the \`semantic-release\` comman Please make sure to add the \`repositoryUrl\` to the [semantic-release configuration] (${linkify( 'docs/usage/configuration.md' )}).`, - }), - EGITNOPERMISSION: ({options: {repositoryUrl}, branch: {name}}) => ({ + }; +} + +export function EGITNOPERMISSION({options: {repositoryUrl}, branch: {name}}) { + return { message: 'Cannot push to the Git repository.', details: `**semantic-release** cannot push the version tag to the branch \`${name}\` on the remote Git repository with URL \`${repositoryUrl}\`. @@ -37,42 +46,57 @@ This can be caused by: - a misconfiguration of the [repositoryUrl](${linkify('docs/usage/configuration.md#repositoryurl')}) option - the repository being unavailable - or missing push permission for the user configured via the [Git credentials on your CI environment](${linkify( - 'docs/usage/ci-configuration.md#authentication' - )})`, - }), - EINVALIDTAGFORMAT: ({options: {tagFormat}}) => ({ + 'docs/usage/ci-configuration.md#authentication' + )})`, + }; +} + +export function EINVALIDTAGFORMAT({options: {tagFormat}}) { + return { message: 'Invalid `tagFormat` option.', details: `The [tagFormat](${linkify( 'docs/usage/configuration.md#tagformat' )}) must compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description). Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`, - }), - ETAGNOVERSION: ({options: {tagFormat}}) => ({ + }; +} + +export function ETAGNOVERSION({options: {tagFormat}}) { + return { message: 'Invalid `tagFormat` option.', details: `The [tagFormat](${linkify( 'docs/usage/configuration.md#tagformat' )}) option must contain the variable \`version\` exactly once. Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`, - }), - EPLUGINCONF: ({type, required, pluginConf}) => ({ + }; +} + +export function EPLUGINCONF({type, required, pluginConf}) { + return { message: `The \`${type}\` plugin configuration is invalid.`, details: `The [${type} plugin configuration](${linkify(`docs/usage/plugins.md#${toLower(type)}-plugin`)}) ${ required ? 'is required and ' : '' } must be a single or an array of plugins definition. A plugin definition is an npm module name, optionally wrapped in an array with an object. Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`, - }), - EPLUGINSCONF: ({plugin}) => ({ + }; +} + +export function EPLUGINSCONF({plugin}) { + return { message: 'The `plugins` configuration is invalid.', details: `The [plugins](${linkify( 'docs/usage/configuration.md#plugins' )}) option must be an array of plugin definions. A plugin definition is an npm module name, optionally wrapped in an array with an object. The invalid configuration is \`${stringify(plugin)}\`.`, - }), - EPLUGIN: ({pluginName, type}) => ({ + }; +} + +export function EPLUGIN({pluginName, type}) { + return { message: `A plugin configured in the step ${type} is not a valid semantic-release plugin.`, details: `A valid \`${type}\` **semantic-release** plugin must be a function or an object with a function in the property \`${type}\`. @@ -81,8 +105,11 @@ The plugin \`${pluginName}\` doesn't have the property \`${type}\` and cannot be Please refer to the \`${pluginName}\` and [semantic-release plugins configuration](${linkify( 'docs/usage/plugins.md' )}) documentation for more details.`, - }), - EANALYZECOMMITSOUTPUT: ({result, pluginName}) => ({ + }; +} + +export function EANALYZECOMMITSOUTPUT({result, pluginName}) { + return { message: 'The `analyzeCommits` plugin returned an invalid value. It must return a valid semver release type.', details: `The \`analyzeCommits\` plugin must return a valid [semver](https://semver.org) release type. The valid values are: ${RELEASE_TYPE.map( (type) => `\`${type}\`` @@ -97,8 +124,11 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the - A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify( 'docs/developer-guide/plugin.md' )})`, - }), - EGENERATENOTESOUTPUT: ({result, pluginName}) => ({ + }; +} + +export function EGENERATENOTESOUTPUT({result, pluginName}) { + return { message: 'The `generateNotes` plugin returned an invalid value. It must return a `String`.', details: `The \`generateNotes\` plugin must return a \`String\`. @@ -111,8 +141,11 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the - A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify( 'docs/developer-guide/plugin.md' )})`, - }), - EPUBLISHOUTPUT: ({result, pluginName}) => ({ + }; +} + +export function EPUBLISHOUTPUT({result, pluginName}) { + return { message: 'A `publish` plugin returned an invalid value. It must return an `Object`.', details: `The \`publish\` plugins must return an \`Object\`. @@ -125,8 +158,11 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the - A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify( 'docs/developer-guide/plugin.md' )})`, - }), - EADDCHANNELOUTPUT: ({result, pluginName}) => ({ + }; +} + +export function EADDCHANNELOUTPUT({result, pluginName}) { + return { message: 'A `addChannel` plugin returned an invalid value. It must return an `Object`.', details: `The \`addChannel\` plugins must return an \`Object\`. @@ -139,48 +175,66 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the - A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify( 'docs/developer-guide/plugin.md' )})`, - }), - EINVALIDBRANCH: ({branch}) => ({ + }; +} + +export function EINVALIDBRANCH({branch}) { + return { message: 'A branch is invalid in the `branches` configuration.', details: `Each branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must be either a string, a regexp or an object with a \`name\` property. Your configuration for the problematic branch is \`${stringify(branch)}\`.`, - }), - EINVALIDBRANCHNAME: ({branch}) => ({ + }; +} + +export function EINVALIDBRANCHNAME({branch}) { + return { message: 'A branch name is invalid in the `branches` configuration.', details: `Each branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must be a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description). Your configuration for the problematic branch is \`${stringify(branch)}\`.`, - }), - EDUPLICATEBRANCHES: ({duplicates}) => ({ + }; +} + +export function EDUPLICATEBRANCHES({duplicates}) { + return { message: 'The `branches` configuration has duplicate branches.', details: `Each branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must havea unique name. Your configuration contains duplicates for the following branch names: \`${stringify(duplicates)}\`.`, - }), - EMAINTENANCEBRANCH: ({branch}) => ({ + }; +} + +export function EMAINTENANCEBRANCH({branch}) { + return { message: 'A maintenance branch is invalid in the `branches` configuration.', details: `Each maintenance branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must have a \`range\` property formatted like \`N.x\`, \`N.x.x\` or \`N.N.x\` (\`N\` is a number). Your configuration for the problematic branch is \`${stringify(branch)}\`.`, - }), - EMAINTENANCEBRANCHES: ({branches}) => ({ + }; +} + +export function EMAINTENANCEBRANCHES({branches}) { + return { message: 'The maintenance branches are invalid in the `branches` configuration.', details: `Each maintenance branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must have a unique \`range\` property. Your configuration for the problematic branches is \`${stringify(branches)}\`.`, - }), - ERELEASEBRANCHES: ({branches}) => ({ + }; +} + +export function ERELEASEBRANCHES({branches}) { + return { message: 'The release branches are invalid in the `branches` configuration.', details: `A minimum of 1 and a maximum of 3 release branches are required in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' @@ -189,24 +243,33 @@ Your configuration for the problematic branches is \`${stringify(branches)}\`.`, This may occur if your repository does not have a release branch, such as \`master\`. Your configuration for the problematic branches is \`${stringify(branches)}\`.`, - }), - EPRERELEASEBRANCH: ({branch}) => ({ + }; +} + +export function EPRERELEASEBRANCH({branch}) { + return { message: 'A pre-release branch configuration is invalid in the `branches` configuration.', details: `Each pre-release branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must have a \`prerelease\` property valid per the [Semantic Versioning Specification](https://semver.org/#spec-item-9). If the \`prerelease\` property is set to \`true\`, then the \`name\` property is used instead. Your configuration for the problematic branch is \`${stringify(branch)}\`.`, - }), - EPRERELEASEBRANCHES: ({branches}) => ({ + }; +} + +export function EPRERELEASEBRANCHES({branches}) { + return { message: 'The pre-release branches are invalid in the `branches` configuration.', details: `Each pre-release branch in the [branches configuration](${linkify( 'docs/usage/configuration.md#branches' )}) must have a unique \`prerelease\` property. If the \`prerelease\` property is set to \`true\`, then the \`name\` property is used instead. Your configuration for the problematic branches is \`${stringify(branches)}\`.`, - }), - EINVALIDNEXTVERSION: ({nextRelease: {version}, branch: {name, range}, commits, validBranches}) => ({ + }; +} + +export function EINVALIDNEXTVERSION({nextRelease: {version}, branch: {name, range}, commits, validBranches}) { + return { message: `The release \`${version}\` on branch \`${name}\` cannot be published as it is out of range.`, details: `Based on the releases published on other branches, only versions within the range \`${range}\` can be published from branch \`${name}\`. @@ -214,19 +277,22 @@ The following commit${commits.length > 1 ? 's are' : ' is'} responsible for the ${commits.map(({commit: {short}, subject}) => `- ${subject} (${short})`).join('\n')} ${ - commits.length > 1 ? 'Those commits' : 'This commit' -} should be moved to a valid branch with [git merge](https://git-scm.com/docs/git-merge) or [git cherry-pick](https://git-scm.com/docs/git-cherry-pick) and removed from branch \`${name}\` with [git revert](https://git-scm.com/docs/git-revert) or [git reset](https://git-scm.com/docs/git-reset). + commits.length > 1 ? 'Those commits' : 'This commit' + } should be moved to a valid branch with [git merge](https://git-scm.com/docs/git-merge) or [git cherry-pick](https://git-scm.com/docs/git-cherry-pick) and removed from branch \`${name}\` with [git revert](https://git-scm.com/docs/git-revert) or [git reset](https://git-scm.com/docs/git-reset). A valid branch could be ${wordsList(validBranches.map(({name}) => `\`${name}\``))}. See the [workflow configuration documentation](${linkify('docs/usage/workflow-configuration.md')}) for more details.`, - }), - EINVALIDMAINTENANCEMERGE: ({nextRelease: {channel, gitTag, version}, branch: {mergeRange, name}}) => ({ + }; +} + +export function EINVALIDMAINTENANCEMERGE({nextRelease: {channel, gitTag, version}, branch: {mergeRange, name}}) { + return { message: `The release \`${version}\` on branch \`${name}\` cannot be published as it is out of range.`, details: `Only releases within the range \`${mergeRange}\` can be merged into the maintenance branch \`${name}\` and published to the \`${channel}\` distribution channel. The branch \`${name}\` head should be [reset](https://git-scm.com/docs/git-reset) to a previous commit so the commit with tag \`${gitTag}\` is removed from the branch history. See the [workflow configuration documentation](${linkify('docs/usage/workflow-configuration.md')}) for more details.`, - }), -}; + }; +} diff --git a/lib/definitions/plugins.js b/lib/definitions/plugins.js index c2e536ed71..19b5288926 100644 --- a/lib/definitions/plugins.js +++ b/lib/definitions/plugins.js @@ -1,12 +1,12 @@ /* eslint require-atomic-updates: off */ -const {isString, isPlainObject} = require('lodash'); -const {getGitHead} = require('../git'); -const hideSensitive = require('../hide-sensitive'); -const {hideSensitiveValues} = require('../utils'); -const {RELEASE_TYPE, RELEASE_NOTES_SEPARATOR} = require('./constants'); +import {isPlainObject, isString} from 'lodash-es'; +import {getGitHead} from '../git.js'; +import hideSensitive from '../hide-sensitive.js'; +import {hideSensitiveValues} from '../utils.js'; +import {RELEASE_NOTES_SEPARATOR, RELEASE_TYPE} from './constants.js'; -module.exports = { +export default { verifyConditions: { required: false, dryRun: true, diff --git a/lib/get-commits.js b/lib/get-commits.js index 2bd5ec777c..f46bc9d91b 100644 --- a/lib/get-commits.js +++ b/lib/get-commits.js @@ -1,5 +1,7 @@ -const debug = require('debug')('semantic-release:get-commits'); -const {getCommits} = require('./git'); +import debugCommits from 'debug'; +import {getCommits} from './git.js'; + +const debug = debugCommits('semantic-release:get-commits'); /** * Retrieve the list of commits on the current branch since the commit sha associated with the last release, or all the commits of the current branch if there is no last released version. @@ -8,7 +10,7 @@ const {getCommits} = require('./git'); * * @return {Promise>} The list of commits on the branch `branch` since the last release. */ -module.exports = async ({cwd, env, lastRelease: {gitHead: from}, nextRelease: {gitHead: to = 'HEAD'} = {}, logger}) => { +export default async ({cwd, env, lastRelease: {gitHead: from}, nextRelease: {gitHead: to = 'HEAD'} = {}, logger}) => { if (from) { debug('Use from: %s', from); } else { @@ -20,4 +22,4 @@ module.exports = async ({cwd, env, lastRelease: {gitHead: from}, nextRelease: {g logger.log(`Found ${commits.length} commits since last release`); debug('Parsed commits: %o', commits); return commits; -}; +} diff --git a/lib/get-config.js b/lib/get-config.js index 1f16962ac9..ca2ffe29e0 100644 --- a/lib/get-config.js +++ b/lib/get-config.js @@ -1,16 +1,18 @@ -const {castArray, pickBy, isNil, isString, isPlainObject} = require('lodash'); -const readPkgUp = require('read-pkg-up'); -const {cosmiconfig} = require('cosmiconfig'); -const resolveFrom = require('resolve-from'); -const debug = require('debug')('semantic-release:config'); -const {repoUrl} = require('./git'); -const PLUGINS_DEFINITIONS = require('./definitions/plugins'); -const plugins = require('./plugins'); -const {validatePlugin, parseConfig} = require('./plugins/utils'); +import {castArray, isNil, isPlainObject, isString, pickBy} from 'lodash-es'; +import readPkgUp from 'read-pkg-up'; +import {cosmiconfig} from 'cosmiconfig'; +import resolveFrom from 'resolve-from'; +import debugConfig from 'debug'; +import {repoUrl} from './git.js'; +import PLUGINS_DEFINITIONS from './definitions/plugins.js'; +import plugins from './plugins/index.js'; +import {parseConfig, validatePlugin} from './plugins/utils.js'; + +const debug = debugConfig('semantic-release:config'); const CONFIG_NAME = 'release'; -module.exports = async (context, cliOptions) => { +export default async (context, cliOptions) => { const {cwd, env} = context; const {config, filepath} = (await cosmiconfig(CONFIG_NAME).search(cwd)) || {}; @@ -82,7 +84,7 @@ module.exports = async (context, cliOptions) => { debug('options values: %O', options); return {options, plugins: await plugins({...context, options}, pluginsPath)}; -}; +} async function pkgRepoUrl(options) { const {packageJson} = (await readPkgUp(options)) || {}; diff --git a/lib/get-error.js b/lib/get-error.js index 56a09c0d51..d80e9b1c62 100644 --- a/lib/get-error.js +++ b/lib/get-error.js @@ -1,7 +1,7 @@ -const SemanticReleaseError = require('@semantic-release/error'); -const ERROR_DEFINITIONS = require('./definitions/errors'); +import SemanticReleaseError from '@semantic-release/error'; +import * as ERROR_DEFINITIONS from './definitions/errors.js'; -module.exports = (code, ctx = {}) => { +export default (code, ctx = {}) => { const {message, details} = ERROR_DEFINITIONS[code](ctx); return new SemanticReleaseError(message, code, details); -}; +} diff --git a/lib/get-git-auth-url.js b/lib/get-git-auth-url.js index 56b5fc6932..8b5f94e720 100644 --- a/lib/get-git-auth-url.js +++ b/lib/get-git-auth-url.js @@ -1,8 +1,10 @@ -const {parse, format} = require('url'); // eslint-disable-line node/no-deprecated-api -const {isNil} = require('lodash'); -const hostedGitInfo = require('hosted-git-info'); -const {verifyAuth} = require('./git'); -const debug = require('debug')('semantic-release:get-git-auth-url'); +import {format, parse} from 'node:url'; +import {isNil} from 'lodash-es'; +import hostedGitInfo from 'hosted-git-info'; +import debugAuthUrl from 'debug'; +import {verifyAuth} from './git.js'; + +const debug = debugAuthUrl('semantic-release:get-git-auth-url'); /** * Machinery to format a repository URL with the given credentials @@ -57,7 +59,7 @@ async function ensureValidAuthUrl({cwd, env, branch}, authUrl) { * * @return {String} The formatted Git repository URL. */ -module.exports = async (context) => { +export default async (context) => { const {cwd, env, branch} = context; const GIT_TOKENS = { GIT_CREDENTIALS: undefined, @@ -119,4 +121,4 @@ module.exports = async (context) => { } return repositoryUrl; -}; +} diff --git a/lib/get-last-release.js b/lib/get-last-release.js index 110fd85f4f..676b6615f5 100644 --- a/lib/get-last-release.js +++ b/lib/get-last-release.js @@ -1,6 +1,6 @@ -const {isUndefined} = require('lodash'); -const semver = require('semver'); -const {makeTag, isSameChannel} = require('./utils'); +import {isUndefined} from 'lodash-es'; +import semver from 'semver'; +import {isSameChannel, makeTag} from './utils.js'; /** * Last release. @@ -18,7 +18,7 @@ const {makeTag, isSameChannel} = require('./utils'); * * - Filter out the branch tags that are not valid semantic version * - Sort the versions - * - Retrive the highest version + * - Retrieve the highest version * * @param {Object} context semantic-release context. * @param {Object} params Function parameters. @@ -26,7 +26,7 @@ const {makeTag, isSameChannel} = require('./utils'); * * @return {LastRelease} The last tagged release or empty object if none is found. */ -module.exports = ({branch, options: {tagFormat}}, {before} = {}) => { +export default ({branch, options: {tagFormat}}, {before} = {}) => { const [{version, gitTag, channels} = {}] = branch.tags .filter( (tag) => @@ -41,4 +41,4 @@ module.exports = ({branch, options: {tagFormat}}, {before} = {}) => { } return {}; -}; +} diff --git a/lib/get-logger.js b/lib/get-logger.js index d37da6bbb0..20c62a6eb0 100644 --- a/lib/get-logger.js +++ b/lib/get-logger.js @@ -1,7 +1,9 @@ -const {Signale} = require('signale'); -const figures = require('figures'); +import signale from 'signale'; +import figures from 'figures'; -module.exports = ({stdout, stderr}) => +const {Signale} = signale; + +export default ({stdout, stderr}) => new Signale({ config: {displayTimestamp: true, underlineMessage: false, displayLabel: false}, disabled: false, @@ -13,4 +15,4 @@ module.exports = ({stdout, stderr}) => log: {badge: figures.info, color: 'magenta', label: '', stream: [stdout]}, success: {badge: figures.tick, color: 'green', label: '', stream: [stdout]}, }, - }); + }) diff --git a/lib/get-next-version.js b/lib/get-next-version.js index 8734922d3e..bbfaacc4d1 100644 --- a/lib/get-next-version.js +++ b/lib/get-next-version.js @@ -1,8 +1,8 @@ -const semver = require('semver'); -const {FIRST_RELEASE, FIRSTPRERELEASE} = require('./definitions/constants'); -const {isSameChannel, getLatestVersion, tagsToVersions, highest} = require('./utils'); +import semver from 'semver'; +import {FIRST_RELEASE, FIRSTPRERELEASE} from './definitions/constants.js'; +import {getLatestVersion, highest, isSameChannel, tagsToVersions} from './utils.js'; -module.exports = ({branch, nextRelease: {type, channel}, lastRelease, logger}) => { +export default ({branch, nextRelease: {type, channel}, lastRelease, logger}) => { let version; if (lastRelease.version) { const {major, minor, patch} = semver.parse(lastRelease.version); @@ -32,4 +32,4 @@ module.exports = ({branch, nextRelease: {type, channel}, lastRelease, logger}) = } return version; -}; +} diff --git a/lib/get-release-to-add.js b/lib/get-release-to-add.js index a76ce5ef20..32f48b2435 100644 --- a/lib/get-release-to-add.js +++ b/lib/get-release-to-add.js @@ -1,8 +1,8 @@ -const {uniqBy, intersection} = require('lodash'); -const semver = require('semver'); -const semverDiff = require('semver-diff'); -const getLastRelease = require('./get-last-release'); -const {makeTag, getLowerBound} = require('./utils'); +import {intersection, uniqBy} from 'lodash-es'; +import semver from 'semver'; +import semverDiff from 'semver-diff'; +import getLastRelease from './get-last-release.js'; +import {getLowerBound, makeTag} from './utils.js'; /** * Find releases that have been merged from from a higher branch but not added on the channel of the current branch. @@ -11,7 +11,7 @@ const {makeTag, getLowerBound} = require('./utils'); * * @return {Array} Last release and next release to be added on the channel of the current branch. */ -module.exports = (context) => { +export default (context) => { const { branch, branches, @@ -57,4 +57,4 @@ module.exports = (context) => { }, }; } -}; +} diff --git a/lib/git.js b/lib/git.js index c4e7ff4c3d..056e6d413c 100644 --- a/lib/git.js +++ b/lib/git.js @@ -1,8 +1,10 @@ -const gitLogParser = require('git-log-parser'); -const getStream = require('get-stream'); -const execa = require('execa'); -const debug = require('debug')('semantic-release:git'); -const {GIT_NOTE_REF} = require('./definitions/constants'); +import gitLogParser from 'git-log-parser'; +import getStream from 'get-stream'; +import execa from 'execa'; +import debugGit from 'debug'; +import {GIT_NOTE_REF} from './definitions/constants.js'; + +const debug = debugGit('semantic-release:git'); Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}}); @@ -14,7 +16,7 @@ Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', commi * * @return {String} The commit sha of the tag in parameter or `null`. */ -async function getTagHead(tagName, execaOptions) { +export async function getTagHead(tagName, execaOptions) { return (await execa('git', ['rev-list', '-1', tagName], execaOptions)).stdout; } @@ -27,7 +29,7 @@ async function getTagHead(tagName, execaOptions) { * @return {Array} List of git tags. * @throws {Error} If the `git` command fails. */ -async function getTags(branch, execaOptions) { +export async function getTags(branch, execaOptions) { return (await execa('git', ['tag', '--merged', branch], execaOptions)).stdout .split('\n') .map((tag) => tag.trim()) @@ -42,7 +44,7 @@ async function getTags(branch, execaOptions) { * @param {Object} [execaOpts] Options to pass to `execa`. * @return {Promise>} The list of commits between `from` and `to`. */ -async function getCommits(from, to, execaOptions) { +export async function getCommits(from, to, execaOptions) { return ( await getStream.array( gitLogParser.parse( @@ -62,7 +64,7 @@ async function getCommits(from, to, execaOptions) { * @return {Array} List of git branches. * @throws {Error} If the `git` command fails. */ -async function getBranches(repositoryUrl, execaOptions) { +export async function getBranches(repositoryUrl, execaOptions) { return (await execa('git', ['ls-remote', '--heads', repositoryUrl], execaOptions)).stdout .split('\n') .filter(Boolean) @@ -77,7 +79,7 @@ async function getBranches(repositoryUrl, execaOptions) { * * @return {Boolean} `true` if the reference exists, falsy otherwise. */ -async function isRefExists(ref, execaOptions) { +export async function isRefExists(ref, execaOptions) { try { return (await execa('git', ['rev-parse', '--verify', ref], execaOptions)).exitCode === 0; } catch (error) { @@ -99,7 +101,7 @@ async function isRefExists(ref, execaOptions) { * @param {String} branch The repository branch to fetch. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function fetch(repositoryUrl, branch, ciBranch, execaOptions) { +export async function fetch(repositoryUrl, branch, ciBranch, execaOptions) { const isDetachedHead = (await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {...execaOptions, reject: false})).stdout === 'HEAD'; @@ -137,7 +139,7 @@ async function fetch(repositoryUrl, branch, ciBranch, execaOptions) { * @param {String} repositoryUrl The remote repository URL. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function fetchNotes(repositoryUrl, execaOptions) { +export async function fetchNotes(repositoryUrl, execaOptions) { try { await execa( 'git', @@ -159,7 +161,7 @@ async function fetchNotes(repositoryUrl, execaOptions) { * * @return {String} the sha of the HEAD commit. */ -async function getGitHead(execaOptions) { +export async function getGitHead(execaOptions) { return (await execa('git', ['rev-parse', 'HEAD'], execaOptions)).stdout; } @@ -170,7 +172,7 @@ async function getGitHead(execaOptions) { * * @return {string} The value of the remote git URL. */ -async function repoUrl(execaOptions) { +export async function repoUrl(execaOptions) { try { return (await execa('git', ['config', '--get', 'remote.origin.url'], execaOptions)).stdout; } catch (error) { @@ -185,7 +187,7 @@ async function repoUrl(execaOptions) { * * @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise. */ -async function isGitRepo(execaOptions) { +export async function isGitRepo(execaOptions) { try { return (await execa('git', ['rev-parse', '--git-dir'], execaOptions)).exitCode === 0; } catch (error) { @@ -202,7 +204,7 @@ async function isGitRepo(execaOptions) { * * @throws {Error} if not authorized to push. */ -async function verifyAuth(repositoryUrl, branch, execaOptions) { +export async function verifyAuth(repositoryUrl, branch, execaOptions) { try { await execa('git', ['push', '--dry-run', '--no-verify', repositoryUrl, `HEAD:${branch}`], execaOptions); } catch (error) { @@ -220,7 +222,7 @@ async function verifyAuth(repositoryUrl, branch, execaOptions) { * * @throws {Error} if the tag creation failed. */ -async function tag(tagName, ref, execaOptions) { +export async function tag(tagName, ref, execaOptions) { await execa('git', ['tag', tagName, ref], execaOptions); } @@ -232,7 +234,7 @@ async function tag(tagName, ref, execaOptions) { * * @throws {Error} if the push failed. */ -async function push(repositoryUrl, execaOptions) { +export async function push(repositoryUrl, execaOptions) { await execa('git', ['push', '--tags', repositoryUrl], execaOptions); } @@ -244,7 +246,7 @@ async function push(repositoryUrl, execaOptions) { * * @throws {Error} if the push failed. */ -async function pushNotes(repositoryUrl, execaOptions) { +export async function pushNotes(repositoryUrl, execaOptions) { await execa('git', ['push', repositoryUrl, `refs/notes/${GIT_NOTE_REF}`], execaOptions); } @@ -256,7 +258,7 @@ async function pushNotes(repositoryUrl, execaOptions) { * * @return {Boolean} `true` if valid, falsy otherwise. */ -async function verifyTagName(tagName, execaOptions) { +export async function verifyTagName(tagName, execaOptions) { try { return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOptions)).exitCode === 0; } catch (error) { @@ -272,7 +274,7 @@ async function verifyTagName(tagName, execaOptions) { * * @return {Boolean} `true` if valid, falsy otherwise. */ -async function verifyBranchName(branch, execaOptions) { +export async function verifyBranchName(branch, execaOptions) { try { return (await execa('git', ['check-ref-format', `refs/heads/${branch}`], execaOptions)).exitCode === 0; } catch (error) { @@ -289,7 +291,7 @@ async function verifyBranchName(branch, execaOptions) { * * @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise. */ -async function isBranchUpToDate(repositoryUrl, branch, execaOptions) { +export async function isBranchUpToDate(repositoryUrl, branch, execaOptions) { return ( (await getGitHead(execaOptions)) === (await execa('git', ['ls-remote', '--heads', repositoryUrl, branch], execaOptions)).stdout.match(/^(?\w+)?/)[1] @@ -304,7 +306,7 @@ async function isBranchUpToDate(repositoryUrl, branch, execaOptions) { * * @return {Object} the parsed JSON note if there is one, an empty object otherwise. */ -async function getNote(ref, execaOptions) { +export async function getNote(ref, execaOptions) { try { return JSON.parse((await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'show', ref], execaOptions)).stdout); } catch (error) { @@ -324,28 +326,6 @@ async function getNote(ref, execaOptions) { * @param {String} ref The Git reference to add the note to. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function addNote(note, ref, execaOptions) { +export async function addNote(note, ref, execaOptions) { await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'add', '-f', '-m', JSON.stringify(note), ref], execaOptions); } - -module.exports = { - getTagHead, - getTags, - getCommits, - getBranches, - isRefExists, - fetch, - fetchNotes, - getGitHead, - repoUrl, - isGitRepo, - verifyAuth, - tag, - push, - pushNotes, - verifyTagName, - isBranchUpToDate, - verifyBranchName, - getNote, - addNote, -}; diff --git a/lib/hide-sensitive.js b/lib/hide-sensitive.js index 1768c5901b..b05f5a9384 100644 --- a/lib/hide-sensitive.js +++ b/lib/hide-sensitive.js @@ -1,7 +1,7 @@ -const {escapeRegExp, size, isString} = require('lodash'); -const {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('./definitions/constants'); +import {escapeRegExp, isString, size} from 'lodash-es'; +import {SECRET_MIN_SIZE, SECRET_REPLACEMENT} from './definitions/constants.js'; -module.exports = (env) => { +export default (env) => { const toReplace = Object.keys(env).filter((envVar) => { // https://github.com/semantic-release/semantic-release/issues/1558 if (envVar === 'GOPRIVATE') { @@ -17,4 +17,4 @@ module.exports = (env) => { ); return (output) => output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output; -}; +} diff --git a/lib/plugins/index.js b/lib/plugins/index.js index 7fd2286380..c52e12f591 100644 --- a/lib/plugins/index.js +++ b/lib/plugins/index.js @@ -1,12 +1,12 @@ -const {identity, isPlainObject, omit, castArray, isNil, isString} = require('lodash'); -const AggregateError = require('aggregate-error'); -const getError = require('../get-error'); -const PLUGINS_DEFINITIONS = require('../definitions/plugins'); -const {validatePlugin, validateStep, loadPlugin, parseConfig} = require('./utils'); -const pipeline = require('./pipeline'); -const normalize = require('./normalize'); +import {castArray, identity, isNil, isPlainObject, isString, omit} from 'lodash-es'; +import AggregateError from 'aggregate-error'; +import getError from '../get-error.js'; +import PLUGINS_DEFINITIONS from '../definitions/plugins.js'; +import {loadPlugin, parseConfig, validatePlugin, validateStep} from './utils.js'; +import pipeline from './pipeline.js'; +import normalize from './normalize.js'; -module.exports = (context, pluginsPath) => { +export default (context, pluginsPath) => { let {options, logger} = context; const errors = []; @@ -90,4 +90,4 @@ module.exports = (context, pluginsPath) => { } return pluginsConf; -}; +} diff --git a/lib/plugins/normalize.js b/lib/plugins/normalize.js index c9f2ab62cd..a22360fcdf 100644 --- a/lib/plugins/normalize.js +++ b/lib/plugins/normalize.js @@ -1,11 +1,13 @@ -const {isPlainObject, isFunction, noop, cloneDeep, omit} = require('lodash'); -const debug = require('debug')('semantic-release:plugins'); -const getError = require('../get-error'); -const {extractErrors} = require('../utils'); -const PLUGINS_DEFINITIONS = require('../definitions/plugins'); -const {loadPlugin, parseConfig} = require('./utils'); +import {cloneDeep, isFunction, isPlainObject, noop, omit} from 'lodash-es'; +import debugPlugins from 'debug'; +import getError from '../get-error.js'; +import {extractErrors} from '../utils.js'; +import PLUGINS_DEFINITIONS from '../definitions/plugins.js'; +import {loadPlugin, parseConfig} from './utils.js'; -module.exports = (context, type, pluginOpt, pluginsPath) => { +const debug = debugPlugins('semantic-release:plugins'); + +export default (context, type, pluginOpt, pluginsPath) => { const {stdout, stderr, options, logger} = context; if (!pluginOpt) { return noop; @@ -64,4 +66,4 @@ module.exports = (context, type, pluginOpt, pluginsPath) => { } return validator; -}; +} diff --git a/lib/plugins/pipeline.js b/lib/plugins/pipeline.js index 3ed4f4fe8c..3ff6f30d88 100644 --- a/lib/plugins/pipeline.js +++ b/lib/plugins/pipeline.js @@ -1,7 +1,7 @@ -const {identity} = require('lodash'); -const pReduce = require('p-reduce'); -const AggregateError = require('aggregate-error'); -const {extractErrors} = require('../utils'); +import {identity} from 'lodash-es'; +import pReduce from 'p-reduce'; +import AggregateError from 'aggregate-error'; +import {extractErrors} from '../utils.js'; /** * A Function that execute a list of function sequencially. If at least one Function ins the pipeline throws an Error or rejects, the pipeline function rejects as well. @@ -25,7 +25,7 @@ const {extractErrors} = require('../utils'); * * @return {Pipeline} A Function that execute the `steps` sequencially */ -module.exports = (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async (input) => { +export default (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async (input) => { const results = []; const errors = []; await pReduce( @@ -55,4 +55,4 @@ module.exports = (steps, {settleAll = false, getNextInput = identity, transform } return results; -}; +} diff --git a/lib/plugins/utils.js b/lib/plugins/utils.js index 69bba2768b..f3229810b5 100644 --- a/lib/plugins/utils.js +++ b/lib/plugins/utils.js @@ -1,6 +1,9 @@ -const {dirname} = require('path'); -const {isString, isFunction, castArray, isArray, isPlainObject, isNil} = require('lodash'); -const resolveFrom = require('resolve-from'); +import {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {castArray, isArray, isFunction, isNil, isPlainObject, isString} from 'lodash-es'; +import resolveFrom from 'resolve-from'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); const validateSteps = (conf) => { return conf.every((conf) => { @@ -24,7 +27,7 @@ const validateSteps = (conf) => { }); }; -function validatePlugin(conf) { +export function validatePlugin(conf) { return ( isString(conf) || (isArray(conf) && @@ -35,7 +38,7 @@ function validatePlugin(conf) { ); } -function validateStep({required}, conf) { +export function validateStep({required}, conf) { conf = castArray(conf).filter(Boolean); if (required) { return conf.length >= 1 && validateSteps(conf); @@ -44,14 +47,14 @@ function validateStep({required}, conf) { return conf.length === 0 || validateSteps(conf); } -function loadPlugin({cwd}, name, pluginsPath) { +export function loadPlugin({cwd}, name, pluginsPath) { const basePath = pluginsPath[name] ? dirname(resolveFrom.silent(__dirname, pluginsPath[name]) || resolveFrom(cwd, pluginsPath[name])) : __dirname; return isFunction(name) ? name : require(resolveFrom.silent(basePath, name) || resolveFrom(cwd, name)); } -function parseConfig(plugin) { +export function parseConfig(plugin) { let path; let config; if (isArray(plugin)) { @@ -64,5 +67,3 @@ function parseConfig(plugin) { return [path, config || {}]; } - -module.exports = {validatePlugin, validateStep, loadPlugin, parseConfig}; diff --git a/lib/utils.js b/lib/utils.js index 895e9d04d4..ba79a3bdad 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,12 +1,12 @@ -const {isFunction, union, template} = require('lodash'); -const semver = require('semver'); -const hideSensitive = require('./hide-sensitive'); +import {isFunction, template, union} from 'lodash-es'; +import semver from 'semver'; +import hideSensitive from './hide-sensitive.js'; -function extractErrors(err) { +export function extractErrors(err) { return err && isFunction(err[Symbol.iterator]) ? [...err] : [err]; } -function hideSensitiveValues(env, objs) { +export function hideSensitiveValues(env, objs) { const hideFunction = hideSensitive(env); return objs.map((object) => { Object.getOwnPropertyNames(object).forEach((prop) => { @@ -18,19 +18,19 @@ function hideSensitiveValues(env, objs) { }); } -function tagsToVersions(tags) { +export function tagsToVersions(tags) { return tags.map(({version}) => version); } -function isMajorRange(range) { +export function isMajorRange(range) { return /^\d+\.x(?:\.x)?$/i.test(range); } -function isMaintenanceRange(range) { +export function isMaintenanceRange(range) { return /^\d+\.(?:\d+|x)(?:\.x)?$/i.test(range); } -function getUpperBound(range) { +export function getUpperBound(range) { const result = semver.valid(range) ? range : ((semver.validRange(range) || '').match(/<(?\d+\.\d+\.\d+(-\d+)?)$/) || [])[1]; @@ -41,27 +41,27 @@ function getUpperBound(range) { : result; } -function getLowerBound(range) { +export function getLowerBound(range) { return ((semver.validRange(range) || '').match(/(?\d+\.\d+\.\d+)/) || [])[1]; } -function highest(version1, version2) { +export function highest(version1, version2) { return version1 && version2 ? (semver.gt(version1, version2) ? version1 : version2) : version1 || version2; } -function lowest(version1, version2) { +export function lowest(version1, version2) { return version1 && version2 ? (semver.lt(version1, version2) ? version1 : version2) : version1 || version2; } -function getLatestVersion(versions, {withPrerelease} = {}) { +export function getLatestVersion(versions, {withPrerelease} = {}) { return versions.filter((version) => withPrerelease || !semver.prerelease(version)).sort(semver.rcompare)[0]; } -function getEarliestVersion(versions, {withPrerelease} = {}) { +export function getEarliestVersion(versions, {withPrerelease} = {}) { return versions.filter((version) => withPrerelease || !semver.prerelease(version)).sort(semver.compare)[0]; } -function getFirstVersion(versions, lowerBranches) { +export function getFirstVersion(versions, lowerBranches) { const lowerVersion = union(...lowerBranches.map(({tags}) => tagsToVersions(tags))).sort(semver.rcompare); if (lowerVersion[0]) { return versions.sort(semver.compare).find((version) => semver.gt(version, lowerVersion[0])); @@ -70,32 +70,14 @@ function getFirstVersion(versions, lowerBranches) { return getEarliestVersion(versions); } -function getRange(min, max) { +export function getRange(min, max) { return `>=${min}${max ? ` <${max}` : ''}`; } -function makeTag(tagFormat, version) { +export function makeTag(tagFormat, version) { return template(tagFormat)({version}); } -function isSameChannel(channel, otherChannel) { +export function isSameChannel(channel, otherChannel) { return channel === otherChannel || (!channel && !otherChannel); } - -module.exports = { - extractErrors, - hideSensitiveValues, - tagsToVersions, - isMajorRange, - isMaintenanceRange, - getUpperBound, - getLowerBound, - highest, - lowest, - getLatestVersion, - getEarliestVersion, - getFirstVersion, - getRange, - makeTag, - isSameChannel, -}; diff --git a/lib/verify.js b/lib/verify.js index 01fc98d68f..26735b5e3e 100644 --- a/lib/verify.js +++ b/lib/verify.js @@ -1,9 +1,9 @@ -const {template, isString, isPlainObject} = require('lodash'); -const AggregateError = require('aggregate-error'); -const {isGitRepo, verifyTagName} = require('./git'); -const getError = require('./get-error'); +import {isPlainObject, isString, template} from 'lodash-es'; +import AggregateError from 'aggregate-error'; +import {isGitRepo, verifyTagName} from './git.js'; +import getError from './get-error.js'; -module.exports = async (context) => { +export default async (context) => { const { cwd, env, @@ -40,4 +40,4 @@ module.exports = async (context) => { if (errors.length > 0) { throw new AggregateError(errors); } -}; +} diff --git a/package-lock.json b/package-lock.json index 2214f63d19..dcd093d684 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,7 +25,7 @@ "git-log-parser": "^1.2.0", "hook-std": "^2.0.0", "hosted-git-info": "^4.0.0", - "lodash": "^4.17.21", + "lodash-es": "^4.17.21", "marked": "^4.0.10", "marked-terminal": "^5.0.0", "micromatch": "^4.0.2", @@ -8683,6 +8683,11 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, + "node_modules/lodash-es": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz", + "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==" + }, "node_modules/lodash.capitalize": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/lodash.capitalize/-/lodash.capitalize-4.2.1.tgz", @@ -23241,6 +23246,11 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, + "lodash-es": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz", + "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==" + }, "lodash.capitalize": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/lodash.capitalize/-/lodash.capitalize-4.2.1.tgz", diff --git a/package.json b/package.json index 17ef258c0b..263be8752f 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "semantic-release", "description": "Automated semver compliant package publishing", "version": "0.0.0-development", + "type": "module", "author": "Stephan Bönnemann (http://boennemann.me)", "ava": { "files": [ @@ -36,7 +37,7 @@ "git-log-parser": "^1.2.0", "hook-std": "^2.0.0", "hosted-git-info": "^4.0.0", - "lodash": "^4.17.21", + "lodash-es": "^4.17.21", "marked": "^4.0.10", "marked-terminal": "^5.0.0", "micromatch": "^4.0.2", @@ -122,8 +123,8 @@ "lint": "xo", "pretest": "npm run lint", "semantic-release": "./bin/semantic-release.js", - "test": "c8 ava -v", - "test:ci": "c8 ava -v" + "test": "c8 ava --verbose", + "test:ci": "c8 ava --verbose" }, "xo": { "prettier": true, diff --git a/test/branches/branches.test.js b/test/branches/branches.test.js index 266123529a..14c6b743ba 100644 --- a/test/branches/branches.test.js +++ b/test/branches/branches.test.js @@ -1,7 +1,7 @@ -const test = require('ava'); -const {union} = require('lodash'); -const semver = require('semver'); -const td = require('testdouble'); +import test from 'ava'; +import {union} from 'lodash-es'; +import semver from 'semver'; +import * as td from 'testdouble'; const getBranch = (branches, branch) => branches.find(({name}) => name === branch); const release = (branches, name, version) => getBranch(branches, name).tags.push({version}); diff --git a/test/branches/expand.test.js b/test/branches/expand.test.js index 0318d412c0..75acde35b4 100644 --- a/test/branches/expand.test.js +++ b/test/branches/expand.test.js @@ -1,6 +1,6 @@ -const test = require('ava'); -const expand = require('../../lib/branches/expand'); -const {gitRepo, gitCommits, gitCheckout, gitPush} = require('../helpers/git-utils'); +import test from 'ava'; +import expand from '../../lib/branches/expand.js'; +import {gitCheckout, gitCommits, gitPush, gitRepo} from '../helpers/git-utils.js'; test('Expand branches defined with globs', async (t) => { const {cwd, repositoryUrl} = await gitRepo(true); diff --git a/test/branches/get-tags.test.js b/test/branches/get-tags.test.js index 74e0bcbca3..9ef318d0ea 100644 --- a/test/branches/get-tags.test.js +++ b/test/branches/get-tags.test.js @@ -1,6 +1,6 @@ -const test = require('ava'); -const getTags = require('../../lib/branches/get-tags'); -const {gitRepo, gitCommits, gitTagVersion, gitCheckout, gitAddNote} = require('../helpers/git-utils'); +import test from 'ava'; +import getTags from '../../lib/branches/get-tags.js'; +import {gitAddNote, gitCheckout, gitCommits, gitRepo, gitTagVersion} from '../helpers/git-utils.js'; test('Get the valid tags', async (t) => { const {cwd} = await gitRepo(); diff --git a/test/branches/normalize.test.js b/test/branches/normalize.test.js index 9d8a934c64..43badf2fd1 100644 --- a/test/branches/normalize.test.js +++ b/test/branches/normalize.test.js @@ -1,5 +1,5 @@ -const test = require('ava'); -const normalize = require('../../lib/branches/normalize'); +import test from 'ava'; +import * as normalize from '../../lib/branches/normalize.js'; const toTags = (versions) => versions.map((version) => ({version})); diff --git a/test/cli.test.js b/test/cli.test.js index d60743d64c..9807fd5a67 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -1,8 +1,8 @@ -const test = require('ava'); -const {escapeRegExp} = require('lodash'); -const td = require('testdouble'); -const {stub} = require('sinon'); -const {SECRET_REPLACEMENT} = require('../lib/definitions/constants'); +import test from 'ava'; +import {escapeRegExp} from 'lodash-es'; +import * as td from 'testdouble'; +import {stub} from 'sinon'; +import {SECRET_REPLACEMENT} from '../lib/definitions/constants.js'; let previousArgv; let previousEnv; diff --git a/test/definitions/branches.test.js b/test/definitions/branches.test.js index db5cbe38c5..6ccce3bc2a 100644 --- a/test/definitions/branches.test.js +++ b/test/definitions/branches.test.js @@ -1,5 +1,5 @@ -const test = require('ava'); -const {maintenance, prerelease, release} = require('../../lib/definitions/branches'); +import test from 'ava'; +import {maintenance, prerelease, release} from '../../lib/definitions/branches.js'; test('A "maintenance" branch is identified by having a "range" property or a "name" formatted like "N.x", "N.x.x" or "N.N.x"', (t) => { /* eslint-disable unicorn/no-fn-reference-in-iterator */ diff --git a/test/definitions/plugins.test.js b/test/definitions/plugins.test.js index 4b72cca6fe..ec50137e40 100644 --- a/test/definitions/plugins.test.js +++ b/test/definitions/plugins.test.js @@ -1,6 +1,6 @@ -const test = require('ava'); -const plugins = require('../../lib/definitions/plugins'); -const {RELEASE_NOTES_SEPARATOR, SECRET_REPLACEMENT} = require('../../lib/definitions/constants'); +import test from 'ava'; +import plugins from '../../lib/definitions/plugins.js'; +import {RELEASE_NOTES_SEPARATOR, SECRET_REPLACEMENT} from '../../lib/definitions/constants.js'; test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', (t) => { t.false(plugins.analyzeCommits.outputValidator('invalid')); diff --git a/test/fixtures/index.js b/test/fixtures/index.js index cc40a4649c..ead516c976 100644 --- a/test/fixtures/index.js +++ b/test/fixtures/index.js @@ -1 +1 @@ -module.exports = () => {}; +export default () => {} diff --git a/test/fixtures/multi-plugin.js b/test/fixtures/multi-plugin.js index 1691941cd4..d43886e2d2 100644 --- a/test/fixtures/multi-plugin.js +++ b/test/fixtures/multi-plugin.js @@ -1,4 +1,4 @@ -module.exports = { +export default { verifyConditions: () => {}, getLastRelease: () => {}, analyzeCommits: () => {}, diff --git a/test/fixtures/plugin-error-inherited.js b/test/fixtures/plugin-error-inherited.js index b5a592ed62..fd6e6110c1 100644 --- a/test/fixtures/plugin-error-inherited.js +++ b/test/fixtures/plugin-error-inherited.js @@ -1,4 +1,4 @@ -const SemanticReleaseError = require('@semantic-release/error'); +import SemanticReleaseError from '@semantic-release/error'; class InheritedError extends SemanticReleaseError { constructor(message, code) { @@ -9,6 +9,6 @@ class InheritedError extends SemanticReleaseError { } } -module.exports = () => { +export default () => { throw new InheritedError('Inherited error', 'EINHERITED'); -}; +} diff --git a/test/fixtures/plugin-error.js b/test/fixtures/plugin-error.js index 2c3dee2487..a9a3f1b4bb 100644 --- a/test/fixtures/plugin-error.js +++ b/test/fixtures/plugin-error.js @@ -1,5 +1,5 @@ -module.exports = () => { +export default () => { const error = new Error('a'); error.errorProperty = 'errorProperty'; throw error; -}; +} diff --git a/test/fixtures/plugin-errors.js b/test/fixtures/plugin-errors.js index e89211daca..0c5f269a4b 100644 --- a/test/fixtures/plugin-errors.js +++ b/test/fixtures/plugin-errors.js @@ -1,5 +1,5 @@ -const AggregateError = require('aggregate-error'); +import AggregateError from 'aggregate-error'; -module.exports = () => { +export default () => { throw new AggregateError([new Error('a'), new Error('b')]); -}; +} diff --git a/test/fixtures/plugin-identity.js b/test/fixtures/plugin-identity.js index 5a8cc03553..8452a404a3 100644 --- a/test/fixtures/plugin-identity.js +++ b/test/fixtures/plugin-identity.js @@ -1 +1 @@ -module.exports = (pluginConfig, context) => context; +export default (pluginConfig, context) => context diff --git a/test/fixtures/plugin-log-env.js b/test/fixtures/plugin-log-env.js index cccd82ca54..d965a0a28f 100644 --- a/test/fixtures/plugin-log-env.js +++ b/test/fixtures/plugin-log-env.js @@ -1,6 +1,6 @@ -module.exports = (pluginConfig, {env, logger}) => { +export default (pluginConfig, {env, logger}) => { console.log(`Console: Exposing token ${env.MY_TOKEN}`); logger.log(`Log: Exposing token ${env.MY_TOKEN}`); logger.error(`Error: Console token ${env.MY_TOKEN}`); throw new Error(`Throw error: Exposing ${env.MY_TOKEN}`); -}; +} diff --git a/test/fixtures/plugin-noop.js b/test/fixtures/plugin-noop.js index cc40a4649c..ead516c976 100644 --- a/test/fixtures/plugin-noop.js +++ b/test/fixtures/plugin-noop.js @@ -1 +1 @@ -module.exports = () => {}; +export default () => {} diff --git a/test/fixtures/plugin-result-config.js b/test/fixtures/plugin-result-config.js index 1e85ec782c..9caabd16be 100644 --- a/test/fixtures/plugin-result-config.js +++ b/test/fixtures/plugin-result-config.js @@ -1 +1 @@ -module.exports = (pluginConfig, context) => ({pluginConfig, context}); +export default (pluginConfig, context) => ({pluginConfig, context}) diff --git a/test/get-commits.test.js b/test/get-commits.test.js index c50b296989..6e2e5eb421 100644 --- a/test/get-commits.test.js +++ b/test/get-commits.test.js @@ -1,7 +1,7 @@ -const test = require('ava'); -const {stub} = require('sinon'); -const getCommits = require('../lib/get-commits'); -const {gitRepo, gitCommits, gitDetachedHead} = require('./helpers/git-utils'); +import test from 'ava'; +import {stub} from 'sinon'; +import getCommits from '../lib/get-commits.js'; +import {gitCommits, gitDetachedHead, gitRepo} from './helpers/git-utils.js'; test.beforeEach((t) => { // Stub the logger functions diff --git a/test/get-config.test.js b/test/get-config.test.js index 76eab49e8f..3ca6972454 100644 --- a/test/get-config.test.js +++ b/test/get-config.test.js @@ -1,12 +1,14 @@ -const path = require('path'); -const {format} = require('util'); -const test = require('ava'); -const {writeFile, outputJson} = require('fs-extra'); -const {omit} = require('lodash'); -const td = require('testdouble'); -const {stub} = require('sinon'); -const yaml = require('js-yaml'); -const {gitRepo, gitTagVersion, gitCommits, gitShallowClone, gitAddConfig} = require('./helpers/git-utils'); +import path from 'node:path'; +import {format} from 'node:util'; +import test from 'ava'; +import fsExtra from 'fs-extra'; +import {omit} from 'lodash-es'; +import * as td from 'testdouble'; +import {stub} from 'sinon'; +import yaml from 'js-yaml'; +import {gitAddConfig, gitCommits, gitRepo, gitShallowClone, gitTagVersion} from './helpers/git-utils.js'; + +const {outputJson, writeFile} = fsExtra; const DEFAULT_PLUGINS = [ '@semantic-release/commit-analyzer', diff --git a/test/get-git-auth-url.test.js b/test/get-git-auth-url.test.js index a5711785fb..48c72ea0fe 100644 --- a/test/get-git-auth-url.test.js +++ b/test/get-git-auth-url.test.js @@ -1,6 +1,6 @@ -const test = require('ava'); -const getAuthUrl = require('../lib/get-git-auth-url'); -const {gitRepo} = require('./helpers/git-utils'); +import test from 'ava'; +import getAuthUrl from '../lib/get-git-auth-url.js'; +import {gitRepo} from './helpers/git-utils.js'; const env = {GIT_ASKPASS: 'echo', GIT_TERMINAL_PROMPT: 0}; diff --git a/test/get-last-release.test.js b/test/get-last-release.test.js index 726f4cb455..521c2e8b53 100644 --- a/test/get-last-release.test.js +++ b/test/get-last-release.test.js @@ -1,5 +1,5 @@ -const test = require('ava'); -const getLastRelease = require('../lib/get-last-release'); +import test from 'ava'; +import getLastRelease from '../lib/get-last-release.js'; test('Get the highest non-prerelease valid tag', (t) => { const result = getLastRelease({ diff --git a/test/get-logger.test.js b/test/get-logger.test.js index ee64940a02..efa718f054 100644 --- a/test/get-logger.test.js +++ b/test/get-logger.test.js @@ -1,6 +1,6 @@ -const test = require('ava'); -const {spy} = require('sinon'); -const getLogger = require('../lib/get-logger'); +import test from 'ava'; +import {spy} from 'sinon'; +import getLogger from '../lib/get-logger.js'; test('Expose "error", "success" and "log" functions', (t) => { const stdout = spy(); diff --git a/test/get-next-version.test.js b/test/get-next-version.test.js index 63c906f078..58ddff2916 100644 --- a/test/get-next-version.test.js +++ b/test/get-next-version.test.js @@ -1,6 +1,6 @@ -const test = require('ava'); -const {stub} = require('sinon'); -const getNextVersion = require('../lib/get-next-version'); +import test from 'ava'; +import {stub} from 'sinon'; +import getNextVersion from '../lib/get-next-version.js'; test.beforeEach((t) => { // Stub the logger functions diff --git a/test/get-release-to-add.test.js b/test/get-release-to-add.test.js index 80e2cf596c..964bcc4ee3 100644 --- a/test/get-release-to-add.test.js +++ b/test/get-release-to-add.test.js @@ -1,5 +1,5 @@ -const test = require('ava'); -const getReleaseToAdd = require('../lib/get-release-to-add'); +import test from 'ava'; +import getReleaseToAdd from '../lib/get-release-to-add.js'; test('Return versions merged from release to maintenance branch, excluding lower than branch start range', (t) => { const result = getReleaseToAdd({ diff --git a/test/git.test.js b/test/git.test.js index e56f8b6a68..c6c6a95710 100644 --- a/test/git.test.js +++ b/test/git.test.js @@ -1,40 +1,40 @@ -const test = require('ava'); -const tempy = require('tempy'); -const { - getTagHead, - isRefExists, +import test from 'ava'; +import tempy from 'tempy'; +import { + addNote, fetch, + fetchNotes, + getBranches, getGitHead, - repoUrl, - tag, - push, + getNote, + getTagHead, getTags, - getBranches, - isGitRepo, - verifyTagName, isBranchUpToDate, - getNote, - addNote, - fetchNotes, -} = require('../lib/git'); -const { - gitRepo, - gitCommits, - gitCheckout, - gitTagVersion, - gitShallowClone, - gitGetCommits, + isGitRepo, + isRefExists, + push, + repoUrl, + tag, + verifyTagName +} from '../lib/git.js'; +import { gitAddConfig, + gitAddNote, + gitCheckout, + gitCommits, gitCommitTag, - gitRemoteTagHead, - gitPush, gitDetachedHead, gitDetachedHeadFromBranch, - gitAddNote, - gitGetNote, gitFetch, - initGit, -} = require('./helpers/git-utils'); + gitGetCommits, + gitGetNote, + gitPush, + gitRemoteTagHead, + gitRepo, + gitShallowClone, + gitTagVersion, + initGit +} from './helpers/git-utils.js'; test('Get the last commit sha', async (t) => { // Create a git repository, set the current working directory at the root of the repo diff --git a/test/helpers/git-utils.js b/test/helpers/git-utils.js index 85e889fba9..191d37e883 100644 --- a/test/helpers/git-utils.js +++ b/test/helpers/git-utils.js @@ -1,10 +1,10 @@ -const tempy = require('tempy'); -const execa = require('execa'); -const fileUrl = require('file-url'); -const pEachSeries = require('p-each-series'); -const gitLogParser = require('git-log-parser'); -const getStream = require('get-stream'); -const {GIT_NOTE_REF} = require('../../lib/definitions/constants'); +import tempy from 'tempy'; +import execa from 'execa'; +import fileUrl from 'file-url'; +import pEachSeries from 'p-each-series'; +import gitLogParser from 'git-log-parser'; +import getStream from 'get-stream'; +import {GIT_NOTE_REF} from '../../lib/definitions/constants.js'; /** * Commit message information. @@ -23,7 +23,7 @@ const {GIT_NOTE_REF} = require('../../lib/definitions/constants'); * @param {Boolean} withRemote `true` to create a shallow clone of a bare repository. * @return {String} The path of the repository */ -async function initGit(withRemote) { +export async function initGit(withRemote) { const cwd = tempy.directory(); const args = withRemote ? ['--bare', '--initial-branch=master'] : ['--initial-branch=master']; @@ -45,7 +45,7 @@ async function initGit(withRemote) { * @param {String} [branch='master'] The branch to initialize. * @return {String} The path of the clone if `withRemote` is `true`, the path of the repository otherwise. */ -async function gitRepo(withRemote, branch = 'master') { +export async function gitRepo(withRemote, branch = 'master') { let {cwd, repositoryUrl} = await initGit(withRemote); if (withRemote) { await initBareRepo(repositoryUrl, branch); @@ -70,7 +70,7 @@ async function gitRepo(withRemote, branch = 'master') { * @param {String} repositoryUrl The URL of the bare repository. * @param {String} [branch='master'] the branch to initialize. */ -async function initBareRepo(repositoryUrl, branch = 'master') { +export async function initBareRepo(repositoryUrl, branch = 'master') { const cwd = tempy.directory(); await execa('git', ['clone', '--no-hardlinks', repositoryUrl, cwd], {cwd}); await gitCheckout(branch, true, {cwd}); @@ -86,7 +86,7 @@ async function initBareRepo(repositoryUrl, branch = 'master') { * * @returns {Array} The created commits, in reverse order (to match `git log` order). */ -async function gitCommits(messages, execaOptions) { +export async function gitCommits(messages, execaOptions) { await pEachSeries( messages, async (message) => @@ -103,7 +103,7 @@ async function gitCommits(messages, execaOptions) { * * @return {Array} The list of parsed commits. */ -async function gitGetCommits(from, execaOptions) { +export async function gitGetCommits(from, execaOptions) { Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}}); return ( await getStream.array( @@ -126,7 +126,7 @@ async function gitGetCommits(from, execaOptions) { * @param {Boolean} create to create the branch, `false` to checkout an existing branch. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function gitCheckout(branch, create, execaOptions) { +export async function gitCheckout(branch, create, execaOptions) { await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch], execaOptions); } @@ -136,7 +136,7 @@ async function gitCheckout(branch, create, execaOptions) { * @param {String} repositoryUrl The repository remote URL. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function gitFetch(repositoryUrl, execaOptions) { +export async function gitFetch(repositoryUrl, execaOptions) { await execa('git', ['fetch', repositoryUrl], execaOptions); } @@ -147,7 +147,7 @@ async function gitFetch(repositoryUrl, execaOptions) { * * @return {String} The sha of the head commit in the current git repository. */ -async function gitHead(execaOptions) { +export async function gitHead(execaOptions) { return (await execa('git', ['rev-parse', 'HEAD'], execaOptions)).stdout; } @@ -158,7 +158,7 @@ async function gitHead(execaOptions) { * @param {String} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function gitTagVersion(tagName, sha, execaOptions) { +export async function gitTagVersion(tagName, sha, execaOptions) { await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName], execaOptions); } @@ -171,7 +171,7 @@ async function gitTagVersion(tagName, sha, execaOptions) { * @param {Number} [depth=1] The number of commit to clone. * @return {String} The path of the cloned repository. */ -async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) { +export async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) { const cwd = tempy.directory(); await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, repositoryUrl, cwd], { @@ -187,7 +187,7 @@ async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) { * @param {Number} head A commit sha of the remote repo that will become the detached head of the new one. * @return {String} The path of the new repository. */ -async function gitDetachedHead(repositoryUrl, head) { +export async function gitDetachedHead(repositoryUrl, head) { const cwd = tempy.directory(); await execa('git', ['init'], {cwd}); @@ -197,7 +197,7 @@ async function gitDetachedHead(repositoryUrl, head) { return cwd; } -async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) { +export async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) { const cwd = tempy.directory(); await execa('git', ['init'], {cwd}); @@ -215,7 +215,7 @@ async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) { * @param {String} value Config value. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function gitAddConfig(name, value, execaOptions) { +export async function gitAddConfig(name, value, execaOptions) { await execa('git', ['config', '--add', name, value], execaOptions); } @@ -227,7 +227,7 @@ async function gitAddConfig(name, value, execaOptions) { * * @return {String} The sha of the commit associated with `tagName` on the local repository. */ -async function gitTagHead(tagName, execaOptions) { +export async function gitTagHead(tagName, execaOptions) { return (await execa('git', ['rev-list', '-1', tagName], execaOptions)).stdout; } @@ -240,7 +240,7 @@ async function gitTagHead(tagName, execaOptions) { * * @return {String} The sha of the commit associated with `tagName` on the remote repository. */ -async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) { +export async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) { return (await execa('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOptions)).stdout .split('\n') .filter((tag) => Boolean(tag)) @@ -255,7 +255,7 @@ async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) { * * @return {String} The tag associatedwith the sha in parameter or `null`. */ -async function gitCommitTag(gitHead, execaOptions) { +export async function gitCommitTag(gitHead, execaOptions) { return (await execa('git', ['describe', '--tags', '--exact-match', gitHead], execaOptions)).stdout; } @@ -268,7 +268,7 @@ async function gitCommitTag(gitHead, execaOptions) { * * @throws {Error} if the push failed. */ -async function gitPush(repositoryUrl, branch, execaOptions) { +export async function gitPush(repositoryUrl, branch, execaOptions) { await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOptions); } @@ -278,7 +278,7 @@ async function gitPush(repositoryUrl, branch, execaOptions) { * @param {String} ref The ref to merge. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function merge(ref, execaOptions) { +export async function merge(ref, execaOptions) { await execa('git', ['merge', '--no-ff', ref], execaOptions); } @@ -288,7 +288,7 @@ async function merge(ref, execaOptions) { * @param {String} ref The ref to merge. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function mergeFf(ref, execaOptions) { +export async function mergeFf(ref, execaOptions) { await execa('git', ['merge', '--ff', ref], execaOptions); } @@ -298,7 +298,7 @@ async function mergeFf(ref, execaOptions) { * @param {String} ref The ref to merge. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function rebase(ref, execaOptions) { +export async function rebase(ref, execaOptions) { await execa('git', ['rebase', ref], execaOptions); } @@ -309,7 +309,7 @@ async function rebase(ref, execaOptions) { * @param {String} ref The ref to add the note to. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function gitAddNote(note, ref, execaOptions) { +export async function gitAddNote(note, ref, execaOptions) { await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'add', '-m', note, ref], execaOptions); } @@ -319,31 +319,6 @@ async function gitAddNote(note, ref, execaOptions) { * @param {String} ref The ref to get the note from. * @param {Object} [execaOpts] Options to pass to `execa`. */ -async function gitGetNote(ref, execaOptions) { +export async function gitGetNote(ref, execaOptions) { return (await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'show', ref], execaOptions)).stdout; } - -module.exports = { - initGit, - gitRepo, - initBareRepo, - gitCommits, - gitGetCommits, - gitCheckout, - gitFetch, - gitHead, - gitTagVersion, - gitShallowClone, - gitDetachedHead, - gitDetachedHeadFromBranch, - gitAddConfig, - gitTagHead, - gitRemoteTagHead, - gitCommitTag, - gitPush, - merge, - mergeFf, - rebase, - gitAddNote, - gitGetNote, -}; diff --git a/test/helpers/gitbox.js b/test/helpers/gitbox.js index ed033cade8..3fa310a998 100644 --- a/test/helpers/gitbox.js +++ b/test/helpers/gitbox.js @@ -1,7 +1,7 @@ -const Docker = require('dockerode'); -const getStream = require('get-stream'); -const pRetry = require('p-retry'); -const {initBareRepo, gitShallowClone} = require('./git-utils'); +import Docker from 'dockerode'; +import getStream from 'get-stream'; +import pRetry from 'p-retry'; +import {gitShallowClone, initBareRepo} from './git-utils.js'; const IMAGE = 'semanticrelease/docker-gitbox:latest'; const SERVER_PORT = 80; @@ -12,12 +12,12 @@ const GIT_PASSWORD = 'suchsecure'; const docker = new Docker(); let container; -const gitCredential = `${GIT_USERNAME}:${GIT_PASSWORD}`; +export const gitCredential = `${GIT_USERNAME}:${GIT_PASSWORD}`; /** * Download the `gitbox` Docker image, create a new container and start it. */ -async function start() { +export async function start() { await getStream(await docker.pull(IMAGE)); container = await docker.createContainer({ @@ -38,7 +38,7 @@ async function start() { /** * Stop and remote the `mockserver` Docker container. */ -async function stop() { +export async function stop() { await container.stop(); await container.remove(); } @@ -51,7 +51,7 @@ async function stop() { * @param {String} [description=`Repository ${name}`] The repository description. * @return {Object} The `repositoryUrl` (URL without auth) and `authUrl` (URL with auth). */ -async function createRepo(name, branch = 'master', description = `Repository ${name}`) { +export async function createRepo(name, branch = 'master', description = `Repository ${name}`) { const exec = await container.exec({ Cmd: ['repo-admin', '-n', name, '-d', description], AttachStdout: true, @@ -68,5 +68,3 @@ async function createRepo(name, branch = 'master', description = `Repository ${n return {cwd, repositoryUrl, authUrl}; } - -module.exports = {start, stop, gitCredential, createRepo}; diff --git a/test/helpers/mockserver.js b/test/helpers/mockserver.js index 404dd3a605..243fc40727 100644 --- a/test/helpers/mockserver.js +++ b/test/helpers/mockserver.js @@ -1,8 +1,8 @@ -const Docker = require('dockerode'); -const getStream = require('get-stream'); -const got = require('got'); -const pRetry = require('p-retry'); -const {mockServerClient} = require('mockserver-client'); +import Docker from 'dockerode'; +import getStream from 'get-stream'; +import got from 'got'; +import pRetry from 'p-retry'; +import {mockServerClient} from 'mockserver-client'; const IMAGE = 'mockserver/mockserver:latest'; const MOCK_SERVER_PORT = 1080; @@ -13,7 +13,7 @@ let container; /** * Download the `mockserver` Docker image, create a new container and start it. */ -async function start() { +export async function start() { await getStream(await docker.pull(IMAGE)); container = await docker.createContainer({ @@ -38,7 +38,7 @@ async function start() { /** * Stop and remove the `mockserver` Docker container. */ -async function stop() { +export async function stop() { await container.stop(); await container.remove(); } @@ -50,7 +50,7 @@ const client = mockServerClient(MOCK_SERVER_HOST, MOCK_SERVER_PORT); /** * @type {string} the url of the `mockserver` instance */ -const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`; +export const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`; /** * Set up the `mockserver` instance response for a specific request. @@ -65,7 +65,7 @@ const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`; * @param {Object} response.body The JSON object to respond in the response body. * @return {Object} An object representation the expectation. Pass to the `verify` function to validate the `mockserver` has been called with a `request` matching the expectations. */ -async function mock( +export async function mock( path, {body: requestBody, headers: requestHeaders}, {method = 'POST', statusCode = 200, body: responseBody} @@ -96,8 +96,6 @@ async function mock( * @param {Object} expectation The expectation created with `mock` function. * @return {Promise} A Promise that resolves if the expectation is met or reject otherwise. */ -function verify(expectation) { +export function verify(expectation) { return client.verify(expectation); } - -module.exports = {start, stop, mock, verify, url}; diff --git a/test/helpers/npm-registry.js b/test/helpers/npm-registry.js index 2b05fd9a41..459779cdd3 100644 --- a/test/helpers/npm-registry.js +++ b/test/helpers/npm-registry.js @@ -1,9 +1,9 @@ -const Docker = require('dockerode'); -const getStream = require('get-stream'); -const got = require('got'); -const path = require('path'); -const delay = require('delay'); -const pRetry = require('p-retry'); +import path from 'node:path'; +import Docker from 'dockerode'; +import getStream from 'get-stream'; +import got from 'got'; +import delay from 'delay'; +import pRetry from 'p-retry'; const IMAGE = 'verdaccio/verdaccio:4'; const REGISTRY_PORT = 4873; @@ -17,7 +17,7 @@ let container; /** * Download the `npm-registry-docker` Docker image, create a new container and start it. */ -async function start() { +export async function start() { await getStream(await docker.pull(IMAGE)); container = await docker.createContainer({ @@ -55,9 +55,9 @@ async function start() { }); } -const url = `http://${REGISTRY_HOST}:${REGISTRY_PORT}/`; +export const url = `http://${REGISTRY_HOST}:${REGISTRY_PORT}/`; -const authEnv = { +export const authEnv = { npm_config_registry: url, // eslint-disable-line camelcase NPM_USERNAME, NPM_PASSWORD, @@ -67,9 +67,7 @@ const authEnv = { /** * Stop and remote the `npm-registry-docker` Docker container. */ -async function stop() { +export async function stop() { await container.stop(); await container.remove(); } - -module.exports = {start, stop, authEnv, url}; diff --git a/test/helpers/npm-utils.js b/test/helpers/npm-utils.js index 942a31ead4..ea0192a85d 100644 --- a/test/helpers/npm-utils.js +++ b/test/helpers/npm-utils.js @@ -1,7 +1,5 @@ -const execa = require('execa'); +import execa from 'execa'; -async function npmView(packageName, env) { +export async function npmView(packageName, env) { return JSON.parse((await execa('npm', ['view', packageName, '--json'], {env})).stdout); } - -module.exports = {npmView}; diff --git a/test/hide-sensitive.test.js b/test/hide-sensitive.test.js index 14686839e2..7d5b54a07e 100644 --- a/test/hide-sensitive.test.js +++ b/test/hide-sensitive.test.js @@ -1,7 +1,7 @@ -const test = require('ava'); -const {repeat} = require('lodash'); -const hideSensitive = require('../lib/hide-sensitive'); -const {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('../lib/definitions/constants'); +import test from 'ava'; +import {repeat} from 'lodash-es'; +import hideSensitive from '../lib/hide-sensitive.js'; +import {SECRET_MIN_SIZE, SECRET_REPLACEMENT} from '../lib/definitions/constants.js'; test('Replace multiple sensitive environment variable values', (t) => { const env = {SOME_PASSWORD: 'password', SOME_TOKEN: 'secret'}; diff --git a/test/index.test.js b/test/index.test.js index 6d38b4898d..59df22f11f 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1,29 +1,28 @@ -const test = require('ava'); -const {escapeRegExp, isString, sortBy, omit} = require('lodash'); -const td = require('testdouble'); -const {spy, stub} = require('sinon'); -const {WritableStreamBuffer} = require('stream-buffers'); -const AggregateError = require('aggregate-error'); -const SemanticReleaseError = require('@semantic-release/error'); -const {COMMIT_NAME, COMMIT_EMAIL, SECRET_REPLACEMENT} = require('../lib/definitions/constants'); -const { - gitHead: getGitHead, +import test from 'ava'; +import {escapeRegExp, isString, omit, sortBy} from 'lodash-es'; +import * as td from 'testdouble'; +import {spy, stub} from 'sinon'; +import {WritableStreamBuffer} from 'stream-buffers'; +import AggregateError from 'aggregate-error'; +import SemanticReleaseError from '@semantic-release/error'; +import {COMMIT_EMAIL, COMMIT_NAME, SECRET_REPLACEMENT} from '../lib/definitions/constants.js'; +import { + gitAddNote, gitCheckout, - gitTagHead, - gitRepo, gitCommits, - gitTagVersion, - gitRemoteTagHead, + gitGetNote, + gitHead as getGitHead, gitPush, + gitRemoteTagHead, + gitRepo, gitShallowClone, + gitTagHead, + gitTagVersion, merge, mergeFf, - rebase, - gitAddNote, - gitGetNote, -} = require('./helpers/git-utils'); - -const pluginNoop = require.resolve('./fixtures/plugin-noop'); + rebase +} from './helpers/git-utils.js'; +import pluginNoop from './fixtures/plugin-noop.js'; test.beforeEach((t) => { // Stub the logger functions diff --git a/test/plugins/normalize.test.js b/test/plugins/normalize.test.js index 784714b010..a42ca03488 100644 --- a/test/plugins/normalize.test.js +++ b/test/plugins/normalize.test.js @@ -1,7 +1,7 @@ -const test = require('ava'); -const {noop} = require('lodash'); -const {stub} = require('sinon'); -const normalize = require('../../lib/plugins/normalize'); +import test from 'ava'; +import {noop} from 'lodash-es'; +import {stub} from 'sinon'; +import normalize from '../../lib/plugins/normalize.js'; const cwd = process.cwd(); diff --git a/test/plugins/pipeline.test.js b/test/plugins/pipeline.test.js index 5af2a6c26d..cda4f27a5d 100644 --- a/test/plugins/pipeline.test.js +++ b/test/plugins/pipeline.test.js @@ -1,7 +1,7 @@ -const test = require('ava'); -const {stub} = require('sinon'); -const AggregateError = require('aggregate-error'); -const pipeline = require('../../lib/plugins/pipeline'); +import test from 'ava'; +import {stub} from 'sinon'; +import AggregateError from 'aggregate-error'; +import pipeline from '../../lib/plugins/pipeline.js'; test('Execute each function in series passing the same input', async (t) => { const step1 = stub().resolves(1); diff --git a/test/plugins/plugins.test.js b/test/plugins/plugins.test.js index 417e7b0cbe..d89e827754 100644 --- a/test/plugins/plugins.test.js +++ b/test/plugins/plugins.test.js @@ -1,11 +1,11 @@ -const path = require('path'); -const test = require('ava'); -const {copy, outputFile} = require('fs-extra'); -const {stub} = require('sinon'); -const tempy = require('tempy'); -const getPlugins = require('../../lib/plugins'); - -// Save the current working diretory +import path from 'path'; +import test from 'ava'; +import {copy, outputFile} from 'fs-extra'; +import {stub} from 'sinon'; +import tempy from 'tempy'; +import getPlugins from '../../lib/plugins/index.js'; + +// Save the current working directory const cwd = process.cwd(); test.beforeEach((t) => { diff --git a/test/plugins/utils.test.js b/test/plugins/utils.test.js index 99fa42d93b..b477be1988 100644 --- a/test/plugins/utils.test.js +++ b/test/plugins/utils.test.js @@ -1,5 +1,5 @@ -const test = require('ava'); -const {validatePlugin, validateStep, loadPlugin, parseConfig} = require('../../lib/plugins/utils'); +import test from 'ava'; +import {loadPlugin, parseConfig, validatePlugin, validateStep} from '../../lib/plugins/utils.js'; test('validatePlugin', (t) => { const path = 'plugin-module'; diff --git a/test/utils.test.js b/test/utils.test.js index 7ff6d2429c..037727e752 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -1,21 +1,21 @@ -const test = require('ava'); -const AggregateError = require('aggregate-error'); -const { +import test from 'ava'; +import AggregateError from 'aggregate-error'; +import { extractErrors, - tagsToVersions, - isMajorRange, - isMaintenanceRange, - getUpperBound, - getLowerBound, - highest, - lowest, - getLatestVersion, getEarliestVersion, getFirstVersion, + getLatestVersion, + getLowerBound, getRange, - makeTag, + getUpperBound, + highest, + isMaintenanceRange, + isMajorRange, isSameChannel, -} = require('../lib/utils'); + lowest, + makeTag, + tagsToVersions +} from '../lib/utils.js'; test('extractErrors', (t) => { const errors = [new Error('Error 1'), new Error('Error 2')]; diff --git a/test/verify.test.js b/test/verify.test.js index c200025676..5af7382b2a 100644 --- a/test/verify.test.js +++ b/test/verify.test.js @@ -1,7 +1,7 @@ -const test = require('ava'); -const tempy = require('tempy'); -const verify = require('../lib/verify'); -const {gitRepo} = require('./helpers/git-utils'); +import test from 'ava'; +import tempy from 'tempy'; +import verify from '../lib/verify.js'; +import {gitRepo} from './helpers/git-utils.js'; test('Throw a AggregateError', async (t) => { const {cwd} = await gitRepo();