From 5117e0cb702cdf144c0e2146ad150c26fcfac378 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Giancarlo=20Calder=C3=B3n=20C=C3=A1rdenas?= Date: Wed, 23 Oct 2024 00:36:42 -0500 Subject: [PATCH 1/2] refactor!: migrate to ESM BREAKING CHANGE: migration to ESM --- bin/{cli.js => cli.mjs} | 7 ++- command.js => command.mjs | 15 ++--- defaults.js => defaults.mjs | 14 ++++- index.js => index.mjs | 36 ++++++------ lib/checkpoint.js | 26 ++++----- lib/{configuration.js => configuration.mjs} | 12 ++-- ...-manager.js => detect-package-manager.mjs} | 10 +--- ...t-message.js => format-commit-message.mjs} | 4 +- ...st-semver-tag.js => latest-semver-tag.mjs} | 12 ++-- lib/lifecycles/{bump.js => bump.mjs} | 55 +++++++++---------- .../{changelog.js => changelog.mjs} | 44 +++++++-------- lib/lifecycles/{commit.js => commit.mjs} | 20 +++---- lib/lifecycles/{tag.js => tag.mjs} | 20 +++---- lib/{preset-loader.js => preset-loader.mjs} | 8 +-- lib/{print-error.js => print-error.mjs} | 6 +- lib/{run-exec.js => run-exec.mjs} | 12 ++-- lib/{run-execFile.js => run-execFile.mjs} | 11 ++-- ...cle-script.js => run-lifecycle-script.mjs} | 12 ++-- ...ngify-package.js => stringify-package.mjs} | 6 +- lib/updaters/{index.js => index.mjs} | 41 ++++++++------ lib/updaters/types/{csproj.js => csproj.mjs} | 8 +-- lib/updaters/types/{gradle.js => gradle.mjs} | 8 +-- lib/updaters/types/{json.js => json.mjs} | 20 +++---- lib/updaters/types/{maven.js => maven.mjs} | 14 ++--- .../types/{openapi.js => openapi.mjs} | 12 ++-- lib/updaters/types/plain-text.js | 8 +-- lib/updaters/types/{python.js => python.mjs} | 8 +-- lib/updaters/types/{yaml.js => yaml.mjs} | 12 ++-- lib/write-file.js | 8 +-- package.json | 4 +- 30 files changed, 242 insertions(+), 231 deletions(-) rename bin/{cli.js => cli.mjs} (54%) mode change 100755 => 100644 rename command.js => command.mjs (94%) mode change 100755 => 100644 rename defaults.js => defaults.mjs (69%) rename index.js => index.mjs (68%) mode change 100755 => 100644 rename lib/{configuration.js => configuration.mjs} (80%) rename lib/{detect-package-manager.js => detect-package-manager.mjs} (84%) rename lib/{format-commit-message.js => format-commit-message.mjs} (63%) rename lib/{latest-semver-tag.js => latest-semver-tag.mjs} (68%) rename lib/lifecycles/{bump.js => bump.mjs} (86%) rename lib/lifecycles/{changelog.js => changelog.mjs} (73%) rename lib/lifecycles/{commit.js => commit.mjs} (75%) rename lib/lifecycles/{tag.js => tag.mjs} (75%) rename lib/{preset-loader.js => preset-loader.mjs} (69%) rename lib/{print-error.js => print-error.mjs} (69%) rename lib/{run-exec.js => run-exec.mjs} (66%) rename lib/{run-execFile.js => run-execFile.mjs} (66%) rename lib/{run-lifecycle-script.js => run-lifecycle-script.mjs} (62%) rename lib/{stringify-package.js => stringify-package.mjs} (91%) rename lib/updaters/{index.js => index.mjs} (74%) rename lib/updaters/types/{csproj.js => csproj.mjs} (75%) rename lib/updaters/types/{gradle.js => gradle.mjs} (75%) rename lib/updaters/types/{json.js => json.mjs} (50%) rename lib/updaters/types/{maven.js => maven.mjs} (78%) rename lib/updaters/types/{openapi.js => openapi.mjs} (55%) rename lib/updaters/types/{python.js => python.mjs} (87%) rename lib/updaters/types/{yaml.js => yaml.mjs} (53%) diff --git a/bin/cli.js b/bin/cli.mjs old mode 100755 new mode 100644 similarity index 54% rename from bin/cli.js rename to bin/cli.mjs index 4f7e08310..740620c15 --- a/bin/cli.js +++ b/bin/cli.mjs @@ -6,9 +6,10 @@ if (process.version.match(/v(\d+)\./)[1] < 6) { 'commit-and-tag-version: Node v6 or greater is required. `commit-and-tag-version` did not run.', ); } else { - const standardVersion = require('../index'); - const cmdParser = require('../command'); - standardVersion(cmdParser.argv).catch(() => { + const standardVersion = (await import('../index.mjs')).default; + const cmdParser = (await import('../command.mjs')).default; + await standardVersion(cmdParser.argv).catch((err) => { + console.error(err); process.exit(1); }); } diff --git a/command.js b/command.mjs old mode 100755 new mode 100644 similarity index 94% rename from command.js rename to command.mjs index c5d98480e..8a052c127 --- a/command.js +++ b/command.mjs @@ -1,8 +1,9 @@ -const spec = require('conventional-changelog-config-spec'); -const { getConfiguration } = require('./lib/configuration'); -const defaults = require('./defaults'); +import spec from 'conventional-changelog-config-spec'; +import { getConfiguration } from './lib/configuration.mjs'; +import defaults from './defaults.mjs'; +import yargs from 'yargs'; -const yargs = require('yargs') +const yargsObj = yargs() .usage('Usage: $0 [options]') .option('packageFiles', { default: defaults.packageFiles, @@ -150,12 +151,12 @@ const yargs = require('yargs') ) .pkgConf('standard-version') .pkgConf('commit-and-tag-version') - .config(getConfiguration()) + .config(await getConfiguration()) .wrap(97); Object.keys(spec.properties).forEach((propertyKey) => { const property = spec.properties[propertyKey]; - yargs.option(propertyKey, { + yargsObj.option(propertyKey, { type: property.type, describe: property.description, default: defaults[propertyKey] ? defaults[propertyKey] : property.default, @@ -163,4 +164,4 @@ Object.keys(spec.properties).forEach((propertyKey) => { }); }); -module.exports = yargs; +export default yargsObj; diff --git a/defaults.js b/defaults.mjs similarity index 69% rename from defaults.js rename to defaults.mjs index 9cf40e034..1f1b2fbec 100644 --- a/defaults.js +++ b/defaults.mjs @@ -1,4 +1,12 @@ -const spec = require('conventional-changelog-config-spec'); +import spec from 'conventional-changelog-config-spec'; + +let preset = import.meta.resolve('conventional-changelog-conventionalcommits'); + +// Workaround for limitation on `node:path.isAbsolute()` (can't handle file:// on absolute path) +preset = preset.replace("file://", "") + +// Workaround specific to Windows (removes etra slash at the beginning of absolute path) +preset = preset.replace(/^(\/)([A-Z]:\/.*)$/, "$2") const defaults = { infile: 'CHANGELOG.md', @@ -15,7 +23,7 @@ const defaults = { dryRun: false, tagForce: false, gitTagFallback: true, - preset: require.resolve('conventional-changelog-conventionalcommits'), + preset: preset, npmPublishHint: undefined, }; @@ -41,4 +49,4 @@ defaults.bumpFiles = defaults.packageFiles.concat([ 'npm-shrinkwrap.json', ]); -module.exports = defaults; +export default defaults; diff --git a/index.js b/index.mjs old mode 100755 new mode 100644 similarity index 68% rename from index.js rename to index.mjs index c05ff8d61..fcb3a4f22 --- a/index.js +++ b/index.mjs @@ -1,15 +1,15 @@ -const bump = require('./lib/lifecycles/bump'); -const changelog = require('./lib/lifecycles/changelog'); -const commit = require('./lib/lifecycles/commit'); -const fs = require('fs'); -const latestSemverTag = require('./lib/latest-semver-tag'); -const path = require('path'); -const printError = require('./lib/print-error'); -const tag = require('./lib/lifecycles/tag'); -const { resolveUpdaterObjectFromArgument } = require('./lib/updaters'); +import { readFileSync } from 'fs'; +import { resolve } from 'path'; +import bump from './lib/lifecycles/bump.mjs'; +import changelog, { START_OF_LAST_RELEASE_PATTERN } from './lib/lifecycles/changelog.mjs'; +import commit from './lib/lifecycles/commit.mjs'; +import latestSemverTag from './lib/latest-semver-tag.mjs'; +import printError from './lib/print-error.mjs'; +import tag from './lib/lifecycles/tag.mjs'; +import { resolveUpdaterObjectFromArgument } from './lib/updaters/index.mjs'; -module.exports = async function standardVersion(argv) { - const defaults = require('./defaults'); +export default async function standardVersion(argv) { + const defaults = (await import('./defaults.mjs')).default; /** * `--message` (`-m`) support will be removed in the next major version. */ @@ -39,10 +39,10 @@ module.exports = async function standardVersion(argv) { if ( argv.header && - argv.header.search(changelog.START_OF_LAST_RELEASE_PATTERN) !== -1 + argv.header.search(START_OF_LAST_RELEASE_PATTERN) !== -1 ) { throw Error( - `custom changelog header must not match ${changelog.START_OF_LAST_RELEASE_PATTERN}`, + `custom changelog header must not match ${START_OF_LAST_RELEASE_PATTERN}`, ); } @@ -56,11 +56,11 @@ module.exports = async function standardVersion(argv) { const args = Object.assign({}, defaults, argv); let pkg; for (const packageFile of args.packageFiles) { - const updater = resolveUpdaterObjectFromArgument(packageFile); + const updater = await resolveUpdaterObjectFromArgument(packageFile); if (!updater) return; - const pkgPath = path.resolve(process.cwd(), updater.filename); + const pkgPath = resolve(process.cwd(), updater.filename); try { - const contents = fs.readFileSync(pkgPath, 'utf8'); + const contents = readFileSync(pkgPath, 'utf8'); pkg = { version: updater.updater.readVersion(contents), private: @@ -76,7 +76,7 @@ module.exports = async function standardVersion(argv) { } try { let version; - if (pkg && pkg.version) { + if (pkg?.version) { version = pkg.version; } else if (args.gitTagFallback) { version = await latestSemverTag(args.tagPrefix); @@ -92,4 +92,4 @@ module.exports = async function standardVersion(argv) { printError(args, err.message); throw err; } -}; +} diff --git a/lib/checkpoint.js b/lib/checkpoint.js index 634d55534..a5f2e41f1 100644 --- a/lib/checkpoint.js +++ b/lib/checkpoint.js @@ -1,23 +1,23 @@ -const chalk = require('chalk'); -const figures = require('figures'); -const util = require('util'); +import util from 'util'; +import chalk from 'chalk'; +import figures from 'figures'; -module.exports = function (argv, msg, args, figure) { +export default function (argv, msg, args, figure) { const defaultFigure = argv.dryRun ? chalk.yellow(figures.tick) : chalk.green(figures.tick); if (!argv.silent) { console.info( (figure || defaultFigure) + - ' ' + - util.format.apply( - util, - [msg].concat( - args.map(function (arg) { - return chalk.bold(arg); - }), - ), + ' ' + + util.format.apply( + util, + [msg].concat( + args.map(function (arg) { + return chalk.bold(arg); + }), ), + ), ); } -}; +} diff --git a/lib/configuration.js b/lib/configuration.mjs similarity index 80% rename from lib/configuration.js rename to lib/configuration.mjs index f169631ea..0aeaf19a2 100644 --- a/lib/configuration.js +++ b/lib/configuration.mjs @@ -1,6 +1,6 @@ -const path = require('path'); -const findUp = require('find-up'); -const { readFileSync } = require('fs'); +import path from 'path'; +import findUp from 'find-up'; +import { readFileSync } from 'fs'; const CONFIGURATION_FILES = [ '.versionrc', @@ -9,7 +9,7 @@ const CONFIGURATION_FILES = [ '.versionrc.js', ]; -module.exports.getConfiguration = function () { +export async function getConfiguration() { let config = {}; const configPath = findUp.sync(CONFIGURATION_FILES); if (!configPath) { @@ -17,7 +17,7 @@ module.exports.getConfiguration = function () { } const ext = path.extname(configPath); if (ext === '.js' || ext === '.cjs') { - const jsConfiguration = require(configPath); + const jsConfiguration = (await import(configPath)); if (typeof jsConfiguration === 'function') { config = jsConfiguration(); } else { @@ -38,4 +38,4 @@ module.exports.getConfiguration = function () { } return config; -}; +} diff --git a/lib/detect-package-manager.js b/lib/detect-package-manager.mjs similarity index 84% rename from lib/detect-package-manager.js rename to lib/detect-package-manager.mjs index 421da6ed0..fffe4875c 100644 --- a/lib/detect-package-manager.js +++ b/lib/detect-package-manager.mjs @@ -4,8 +4,8 @@ * modified to support only detecting lock file and not detecting global package manager */ -const { promises: fs } = require('fs'); -const { resolve } = require('path'); +import { promises as fs } from 'fs'; +import { resolve } from 'path'; /** * Check if a path exists @@ -39,7 +39,7 @@ function getTypeofLockFile(cwd = '.') { }); } -const detectPMByLockFile = async (cwd) => { +export const detectPMByLockFile = async (cwd) => { const type = await getTypeofLockFile(cwd); if (type) { return type; @@ -47,7 +47,3 @@ const detectPMByLockFile = async (cwd) => { return 'npm'; }; - -module.exports = { - detectPMByLockFile, -}; diff --git a/lib/format-commit-message.js b/lib/format-commit-message.mjs similarity index 63% rename from lib/format-commit-message.js rename to lib/format-commit-message.mjs index f174c66a7..a4c4e7ad5 100644 --- a/lib/format-commit-message.js +++ b/lib/format-commit-message.mjs @@ -1,4 +1,4 @@ -module.exports = function (rawMsg, newVersion) { +export default function (rawMsg, newVersion) { const message = String(rawMsg); return message.replace(/{{currentTag}}/g, newVersion); -}; +} diff --git a/lib/latest-semver-tag.js b/lib/latest-semver-tag.mjs similarity index 68% rename from lib/latest-semver-tag.js rename to lib/latest-semver-tag.mjs index 1230a0d4c..10c229d00 100644 --- a/lib/latest-semver-tag.js +++ b/lib/latest-semver-tag.mjs @@ -1,7 +1,7 @@ -const gitSemverTags = require('git-semver-tags'); -const semver = require('semver'); +import gitSemverTags from 'git-semver-tags'; +import { clean, rcompare } from 'semver'; -module.exports = function (tagPrefix = undefined) { +export default function (tagPrefix = undefined) { return new Promise((resolve, reject) => { gitSemverTags({ tagPrefix }, function (err, tags) { if (err) return reject(err); @@ -10,10 +10,10 @@ module.exports = function (tagPrefix = undefined) { tags = tags.map((tag) => tag.replace(new RegExp('^' + tagPrefix), '')); // ensure that the largest semver tag is at the head. tags = tags.map((tag) => { - return semver.clean(tag); + return clean(tag); }); - tags.sort(semver.rcompare); + tags.sort(rcompare); return resolve(tags[0]); }); }); -}; +} diff --git a/lib/lifecycles/bump.js b/lib/lifecycles/bump.mjs similarity index 86% rename from lib/lifecycles/bump.js rename to lib/lifecycles/bump.mjs index 7db4524e3..f2f373ba7 100644 --- a/lib/lifecycles/bump.js +++ b/lib/lifecycles/bump.mjs @@ -1,17 +1,16 @@ -'use strict'; +import fs from 'fs'; +import path from 'path'; +import semver from 'semver'; +import chalk from 'chalk'; +import conventionalRecommendedBump from 'conventional-recommended-bump'; +import figures from 'figures'; +import DotGitignore from 'dotgitignore'; +import checkpoint from '../checkpoint.mjs'; +import presetLoader from '../preset-loader.mjs'; +import runLifecycleScript from '../run-lifecycle-script.mjs'; +import writeFile from '../write-file.mjs'; +import { resolveUpdaterObjectFromArgument } from '../updaters/index.mjs'; -const chalk = require('chalk'); -const checkpoint = require('../checkpoint'); -const conventionalRecommendedBump = require('conventional-recommended-bump'); -const figures = require('figures'); -const fs = require('fs'); -const DotGitignore = require('dotgitignore'); -const path = require('path'); -const presetLoader = require('../preset-loader'); -const runLifecycleScript = require('../run-lifecycle-script'); -const semver = require('semver'); -const writeFile = require('../write-file'); -const { resolveUpdaterObjectFromArgument } = require('../updaters'); let configsToUpdate = {}; const sanitizeQuotesRegex = /['"]+/g; @@ -83,7 +82,7 @@ async function Bump(args, version) { newVersion = semver.inc(version, releaseType, args.prerelease); } - updateConfigs(args, newVersion); + await updateConfigs(args, newVersion); } else { checkpoint( args, @@ -116,7 +115,7 @@ function getReleaseType(prerelease, expectedReleaseType, currentVersion) { if ( shouldContinuePrerelease(currentVersion, expectedReleaseType) || getTypePriority(getCurrentActiveType(currentVersion)) > - getTypePriority(expectedReleaseType) + getTypePriority(expectedReleaseType) ) { return 'prerelease'; } @@ -196,11 +195,11 @@ function bumpVersion(releaseAs, currentVersion, args) { lernaPackage: args.lernaPackage, ...(args.verbose ? { - debug: console.info.bind( - console, - 'conventional-recommended-bump', - ), - } + debug: console.info.bind( + console, + 'conventional-recommended-bump', + ), + } : {}), }, args.parserOpts, @@ -219,12 +218,12 @@ function bumpVersion(releaseAs, currentVersion, args) { * @param newVersion version number to update to. * @return void */ -function updateConfigs(args, newVersion) { +async function updateConfigs(args, newVersion) { const dotgit = DotGitignore(); - args.bumpFiles.forEach(function (bumpFile) { - const updater = resolveUpdaterObjectFromArgument(bumpFile); + for (const bumpFile of args.bumpFiles) { + const updater = await resolveUpdaterObjectFromArgument(bumpFile); if (!updater) { - return; + continue; } const configPath = path.resolve(process.cwd(), updater.filename); try { @@ -232,7 +231,7 @@ function updateConfigs(args, newVersion) { console.debug( `Not updating file '${updater.filename}', as it is ignored in Git`, ); - return; + continue; } const stat = fs.lstatSync(configPath); @@ -240,7 +239,7 @@ function updateConfigs(args, newVersion) { console.debug( `Not updating '${updater.filename}', as it is not a file`, ); - return; + continue; } const contents = fs.readFileSync(configPath, 'utf8'); const newContents = updater.updater.writeVersion(contents, newVersion); @@ -257,7 +256,7 @@ function updateConfigs(args, newVersion) { } catch (err) { if (err.code !== 'ENOENT') console.warn(err.message); } - }); + } } -module.exports = Bump; +export default Bump; diff --git a/lib/lifecycles/changelog.js b/lib/lifecycles/changelog.mjs similarity index 73% rename from lib/lifecycles/changelog.js rename to lib/lifecycles/changelog.mjs index fcdd13bd4..ce34b2f52 100644 --- a/lib/lifecycles/changelog.js +++ b/lib/lifecycles/changelog.mjs @@ -1,11 +1,13 @@ -const chalk = require('chalk'); -const checkpoint = require('../checkpoint'); -const conventionalChangelog = require('conventional-changelog'); -const fs = require('fs'); -const presetLoader = require('../preset-loader'); -const runLifecycleScript = require('../run-lifecycle-script'); -const writeFile = require('../write-file'); -const START_OF_LAST_RELEASE_PATTERN = +import { readFileSync, accessSync, F_OK } from 'fs'; +import chalk from 'chalk'; +const gray = chalk.gray; +import checkpoint from '../checkpoint.mjs'; +import conventionalChangelog from 'conventional-changelog'; +import presetLoader from '../preset-loader.mjs'; +import runLifecycleScript from '../run-lifecycle-script.mjs'; +import writeFile from '../write-file.mjs'; + +export const START_OF_LAST_RELEASE_PATTERN = /(^#+ \[?[0-9]+\.[0-9]+\.[0-9]+| 1) { diff --git a/lib/lifecycles/tag.js b/lib/lifecycles/tag.mjs similarity index 75% rename from lib/lifecycles/tag.js rename to lib/lifecycles/tag.mjs index 8a0edab0a..2e362f233 100644 --- a/lib/lifecycles/tag.js +++ b/lib/lifecycles/tag.mjs @@ -1,18 +1,18 @@ -const bump = require('../lifecycles/bump'); -const chalk = require('chalk'); -const checkpoint = require('../checkpoint'); -const figures = require('figures'); -const formatCommitMessage = require('../format-commit-message'); -const runExecFile = require('../run-execFile'); -const runLifecycleScript = require('../run-lifecycle-script'); -const { detectPMByLockFile } = require('../detect-package-manager'); +import bump from './bump.mjs'; +import chalk from 'chalk'; +import checkpoint from '../checkpoint.mjs'; +import figures from 'figures'; +import formatCommitMessage from '../format-commit-message.mjs'; +import runExecFile from '../run-execFile.mjs'; +import runLifecycleScript from '../run-lifecycle-script.mjs'; +import { detectPMByLockFile } from '../detect-package-manager.mjs'; -module.exports = async function (newVersion, pkgPrivate, args) { +export default async function (newVersion, pkgPrivate, args) { if (args.skip.tag) return; await runLifecycleScript(args, 'pretag'); await execTag(newVersion, pkgPrivate, args); await runLifecycleScript(args, 'posttag'); -}; +} async function detectPublishHint() { const npmClientName = await detectPMByLockFile(); diff --git a/lib/preset-loader.js b/lib/preset-loader.mjs similarity index 69% rename from lib/preset-loader.js rename to lib/preset-loader.mjs index 0d5bde9ab..c51b3aa80 100644 --- a/lib/preset-loader.js +++ b/lib/preset-loader.mjs @@ -1,11 +1,9 @@ // TODO: this should be replaced with an object we maintain and // describe in: https://github.com/conventional-changelog/conventional-changelog-config-spec -const spec = require('conventional-changelog-config-spec'); +import spec from 'conventional-changelog-config-spec'; -module.exports = (args) => { - const defaultPreset = require.resolve( - 'conventional-changelog-conventionalcommits', - ); +export default (args) => { + const defaultPreset = import.meta.resolve('conventional-changelog-conventionalcommits'); let preset = args.preset || defaultPreset; if (preset === defaultPreset) { preset = { diff --git a/lib/print-error.js b/lib/print-error.mjs similarity index 69% rename from lib/print-error.js rename to lib/print-error.mjs index 298964e8c..95b6d3999 100644 --- a/lib/print-error.js +++ b/lib/print-error.mjs @@ -1,6 +1,6 @@ -const chalk = require('chalk'); +import chalk from 'chalk'; -module.exports = function (args, msg, opts) { +export default function (args, msg, opts) { if (!args.silent) { opts = Object.assign( { @@ -12,4 +12,4 @@ module.exports = function (args, msg, opts) { console[opts.level](chalk[opts.color](msg)); } -}; +} diff --git a/lib/run-exec.js b/lib/run-exec.mjs similarity index 66% rename from lib/run-exec.js rename to lib/run-exec.mjs index 6d4441717..49a2b7d2f 100644 --- a/lib/run-exec.js +++ b/lib/run-exec.mjs @@ -1,9 +1,11 @@ -const { promisify } = require('util'); -const printError = require('./print-error'); +import childProcess from 'child_process'; +import { promisify } from 'util'; +import printError from './print-error.mjs'; -const exec = promisify(require('child_process').exec); -module.exports = async function (args, cmd) { +const exec = promisify(childProcess.exec); + +export default async function (args, cmd) { if (args.dryRun) return; try { const { stderr, stdout } = await exec(cmd); @@ -15,4 +17,4 @@ module.exports = async function (args, cmd) { printError(args, error.stderr || error.message); throw error; } -}; +} diff --git a/lib/run-execFile.js b/lib/run-execFile.mjs similarity index 66% rename from lib/run-execFile.js rename to lib/run-execFile.mjs index e20488ad6..02d4eb4a4 100644 --- a/lib/run-execFile.js +++ b/lib/run-execFile.mjs @@ -1,9 +1,10 @@ -const { promisify } = require('util'); -const printError = require('./print-error'); +import childProcess from "child_process"; +import { promisify } from 'util'; +import printError from './print-error.mjs'; -const execFile = promisify(require('child_process').execFile); +const execFile = promisify(childProcess.execFile); -module.exports = async function (args, cmd, cmdArgs) { +export default async function (args, cmd, cmdArgs) { if (args.dryRun) return; try { const { stderr, stdout } = await execFile(cmd, cmdArgs); @@ -15,4 +16,4 @@ module.exports = async function (args, cmd, cmdArgs) { printError(args, error.stderr || error.message); throw error; } -}; +} diff --git a/lib/run-lifecycle-script.js b/lib/run-lifecycle-script.mjs similarity index 62% rename from lib/run-lifecycle-script.js rename to lib/run-lifecycle-script.mjs index 4e10193cd..dd6f56bf9 100644 --- a/lib/run-lifecycle-script.js +++ b/lib/run-lifecycle-script.mjs @@ -1,9 +1,9 @@ -const chalk = require('chalk'); -const checkpoint = require('./checkpoint'); -const figures = require('figures'); -const runExec = require('./run-exec'); +import chalk from 'chalk'; +import figures from 'figures'; +import runExec from './run-exec.mjs'; +import checkpoint from './checkpoint.mjs'; -module.exports = function (args, hookName) { +export default function (args, hookName) { const scripts = args.scripts; if (!scripts || !scripts[hookName]) return Promise.resolve(); const command = scripts[hookName]; @@ -15,4 +15,4 @@ module.exports = function (args, hookName) { chalk.blue(figures.info), ); return runExec(args, command); -}; +} diff --git a/lib/stringify-package.js b/lib/stringify-package.mjs similarity index 91% rename from lib/stringify-package.js rename to lib/stringify-package.mjs index 8fd32a9ec..96fcde67d 100644 --- a/lib/stringify-package.js +++ b/lib/stringify-package.mjs @@ -16,15 +16,11 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. https://github.com/npm/stringify-package/blob/main/LICENSE */ -'use strict'; - -module.exports = stringifyPackage; - const DEFAULT_INDENT = 2; const CRLF = '\r\n'; const LF = '\n'; -function stringifyPackage(data, indent, newline) { +export default function stringifyPackage(data, indent, newline) { indent = indent || (indent === 0 ? 0 : DEFAULT_INDENT); const json = JSON.stringify(data, null, indent); diff --git a/lib/updaters/index.js b/lib/updaters/index.mjs similarity index 74% rename from lib/updaters/index.js rename to lib/updaters/index.mjs index 9eb6dd93f..40457b00c 100644 --- a/lib/updaters/index.js +++ b/lib/updaters/index.mjs @@ -1,14 +1,24 @@ -const path = require('path'); -const JSON_BUMP_FILES = require('../../defaults').bumpFiles; +import path from 'path'; +import * as json from './types/json.mjs'; +import * as plainText from './types/plain-text.mjs'; +import * as maven from './types/maven.mjs'; +import * as gradle from './types/gradle.mjs'; +import * as csproj from './types/csproj.mjs'; +import * as yaml from './types/yaml.mjs'; +import * as openapi from './types/openapi.mjs'; +import * as python from './types/python.mjs'; +import defaults from '../../defaults.mjs'; + +const JSON_BUMP_FILES = defaults.bumpFiles; const updatersByType = { - json: require('./types/json'), - 'plain-text': require('./types/plain-text'), - maven: require('./types/maven'), - gradle: require('./types/gradle'), - csproj: require('./types/csproj'), - yaml: require('./types/yaml'), - openapi: require('./types/openapi'), - python: require('./types/python'), + json: json, + 'plain-text': plainText, + maven: maven, + gradle: gradle, + csproj: csproj, + yaml: yaml, + openapi: openapi, + python: python, }; const PLAIN_TEXT_BUMP_FILES = ['VERSION.txt', 'version.txt']; @@ -50,9 +60,9 @@ function getUpdaterByFilename(filename) { ); } -function getCustomUpdaterFromPath(updater) { +async function getCustomUpdaterFromPath(updater) { if (typeof updater === 'string') { - return require(path.resolve(process.cwd(), updater)); + return import(path.resolve(process.cwd(), updater)); } if ( typeof updater.readVersion === 'function' && @@ -76,7 +86,7 @@ function isValidUpdater(obj) { ); } -module.exports.resolveUpdaterObjectFromArgument = function (arg) { +export const resolveUpdaterObjectFromArgument = async function (arg) { /** * If an Object was not provided, we assume it's the path/filename * of the updater. @@ -94,7 +104,7 @@ module.exports.resolveUpdaterObjectFromArgument = function (arg) { if (!isValidUpdater(updater.updater)) { try { if (typeof updater.updater === 'string') { - updater.updater = getCustomUpdaterFromPath(updater.updater); + updater.updater = await getCustomUpdaterFromPath(updater.updater); } else if (updater.type) { updater.updater = getUpdaterByType(updater.type); } else { @@ -103,8 +113,7 @@ module.exports.resolveUpdaterObjectFromArgument = function (arg) { } catch (err) { if (err.code !== 'ENOENT') console.warn( - `Unable to obtain updater for: ${JSON.stringify(arg)}\n - Error: ${ - err.message + `Unable to obtain updater for: ${JSON.stringify(arg)}\n - Error: ${err.message }\n - Skipping...`, ); } diff --git a/lib/updaters/types/csproj.js b/lib/updaters/types/csproj.mjs similarity index 75% rename from lib/updaters/types/csproj.js rename to lib/updaters/types/csproj.mjs index 286ea5b7c..6184dafbc 100644 --- a/lib/updaters/types/csproj.js +++ b/lib/updaters/types/csproj.mjs @@ -1,6 +1,6 @@ const versionRegex = /(.*)<\/Version>/; -module.exports.readVersion = function (contents) { +export function readVersion(contents) { const matches = versionRegex.exec(contents); if (matches === null || matches.length !== 2) { throw new Error( @@ -8,8 +8,8 @@ module.exports.readVersion = function (contents) { ); } return matches[1]; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { return contents.replace(versionRegex, `${version}`); -}; +} diff --git a/lib/updaters/types/gradle.js b/lib/updaters/types/gradle.mjs similarity index 75% rename from lib/updaters/types/gradle.js rename to lib/updaters/types/gradle.mjs index 58d9dc879..db96dc5ae 100644 --- a/lib/updaters/types/gradle.js +++ b/lib/updaters/types/gradle.mjs @@ -1,6 +1,6 @@ const versionRegex = /^version\s+=\s+['"]([\d.]+)['"]/m; -module.exports.readVersion = function (contents) { +export function readVersion(contents) { const matches = versionRegex.exec(contents); if (matches === null) { throw new Error( @@ -9,10 +9,10 @@ module.exports.readVersion = function (contents) { } return matches[1]; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { return contents.replace(versionRegex, () => { return `version = "${version}"`; }); -}; +} diff --git a/lib/updaters/types/json.js b/lib/updaters/types/json.mjs similarity index 50% rename from lib/updaters/types/json.js rename to lib/updaters/types/json.mjs index 73e7c7e58..c240010af 100644 --- a/lib/updaters/types/json.js +++ b/lib/updaters/types/json.mjs @@ -1,25 +1,25 @@ -const stringifyPackage = require('../../stringify-package'); -const detectIndent = require('detect-indent'); -const detectNewline = require('detect-newline'); +import detectIndent from 'detect-indent'; +import detectNewline from 'detect-newline'; +import stringifyPackage from '../../stringify-package.mjs'; -module.exports.readVersion = function (contents) { +export function readVersion(contents) { return JSON.parse(contents).version; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { const json = JSON.parse(contents); const indent = detectIndent(contents).indent; const newline = detectNewline(contents); json.version = version; - if (json.packages && json.packages['']) { + if (json.packages?.['']) { // package-lock v2 stores version there too json.packages[''].version = version; } return stringifyPackage(json, indent, newline); -}; +} -module.exports.isPrivate = function (contents) { +export function isPrivate(contents) { return JSON.parse(contents).private; -}; +} diff --git a/lib/updaters/types/maven.js b/lib/updaters/types/maven.mjs similarity index 78% rename from lib/updaters/types/maven.js rename to lib/updaters/types/maven.mjs index 37d81c5be..7e42aafc5 100644 --- a/lib/updaters/types/maven.js +++ b/lib/updaters/types/maven.mjs @@ -1,6 +1,6 @@ -const jsdom = require('jsdom'); -const serialize = require('w3c-xmlserializer'); -const detectNewline = require('detect-newline'); +import jsdom from 'jsdom'; +import serialize from 'w3c-xmlserializer'; +import detectNewline from 'detect-newline'; const CRLF = '\r\n'; const LF = '\n'; @@ -22,12 +22,12 @@ function pomVersionElement(document) { return versionElement; } -module.exports.readVersion = function (contents) { +export function readVersion(contents) { const document = pomDocument(contents); return pomVersionElement(document).textContent; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { const newline = detectNewline(contents); const document = pomDocument(contents); const versionElement = pomVersionElement(document); @@ -41,4 +41,4 @@ module.exports.writeVersion = function (contents, version) { } return xml + LF; -}; +} diff --git a/lib/updaters/types/openapi.js b/lib/updaters/types/openapi.mjs similarity index 55% rename from lib/updaters/types/openapi.js rename to lib/updaters/types/openapi.mjs index 981386be8..7e14fa236 100644 --- a/lib/updaters/types/openapi.js +++ b/lib/updaters/types/openapi.mjs @@ -1,15 +1,15 @@ -const yaml = require('yaml'); -const detectNewline = require('detect-newline'); +import yaml from 'yaml'; +import detectNewline from 'detect-newline'; -module.exports.readVersion = function (contents) { +export function readVersion(contents) { return yaml.parse(contents).info.version; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { const newline = detectNewline(contents); const document = yaml.parseDocument(contents); document.get('info').set('version', version); return document.toString().replace(/\r?\n/g, newline); -}; +} diff --git a/lib/updaters/types/plain-text.js b/lib/updaters/types/plain-text.js index ecc19d33b..3d703780c 100644 --- a/lib/updaters/types/plain-text.js +++ b/lib/updaters/types/plain-text.js @@ -1,7 +1,7 @@ -module.exports.readVersion = function (contents) { +export function readVersion(contents) { return contents; -}; +} -module.exports.writeVersion = function (_contents, version) { +export function writeVersion(_contents, version) { return version; -}; +} diff --git a/lib/updaters/types/python.js b/lib/updaters/types/python.mjs similarity index 87% rename from lib/updaters/types/python.js rename to lib/updaters/types/python.mjs index afaca68a5..7b0e59df8 100644 --- a/lib/updaters/types/python.js +++ b/lib/updaters/types/python.mjs @@ -14,17 +14,17 @@ const getVersionIndex = function (lines) { return { version, lineNumber }; }; -module.exports.readVersion = function (contents) { +export function readVersion(contents) { const lines = contents.split('\n'); const versionIndex = getVersionIndex(lines); return versionIndex.version; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { const lines = contents.split('\n'); const versionIndex = getVersionIndex(lines); const versionLine = lines[versionIndex.lineNumber]; const newVersionLine = versionLine.replace(versionIndex.version, version); lines[versionIndex.lineNumber] = newVersionLine; return lines.join('\n'); -}; +} diff --git a/lib/updaters/types/yaml.js b/lib/updaters/types/yaml.mjs similarity index 53% rename from lib/updaters/types/yaml.js rename to lib/updaters/types/yaml.mjs index 0812514ad..767f566b6 100644 --- a/lib/updaters/types/yaml.js +++ b/lib/updaters/types/yaml.mjs @@ -1,15 +1,15 @@ -const yaml = require('yaml'); -const detectNewline = require('detect-newline'); +import yaml from 'yaml'; +import detectNewline from 'detect-newline'; -module.exports.readVersion = function (contents) { +export function readVersion(contents) { return yaml.parse(contents).version; -}; +} -module.exports.writeVersion = function (contents, version) { +export function writeVersion(contents, version) { const newline = detectNewline(contents); const document = yaml.parseDocument(contents); document.set('version', version); return document.toString().replace(/\r?\n/g, newline); -}; +} diff --git a/lib/write-file.js b/lib/write-file.js index b50ad4222..aff618ad1 100644 --- a/lib/write-file.js +++ b/lib/write-file.js @@ -1,6 +1,6 @@ -const fs = require('fs'); +import { writeFileSync } from 'fs'; -module.exports = function (args, filePath, content) { +export default function (args, filePath, content) { if (args.dryRun) return; - fs.writeFileSync(filePath, content, 'utf8'); -}; + writeFileSync(filePath, content, 'utf8'); +} diff --git a/package.json b/package.json index 27cb140c6..4e3943d33 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "commit-and-tag-version", "version": "12.5.0", "description": "replacement for `npm version` with automatic CHANGELOG generation", - "bin": "bin/cli.js", + "bin": "bin/cli.mjs", "scripts": { "lint": "eslint .", "lint:fix": "npm run lint -- --fix", @@ -13,7 +13,7 @@ "test": "jest", "test:unit": "jest --testPathIgnorePatterns test/git.integration-test.js", "test:git-integration": "jest --testPathPattern test/git.integration-test.js", - "release": "bin/cli.js" + "release": "node bin/cli.mjs" }, "repository": "absolute-version/commit-and-tag-version", "engines": { From 630a21f87c3e767a05ba3b0bfa57b0026ba29568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Giancarlo=20Calder=C3=B3n=20C=C3=A1rdenas?= Date: Wed, 23 Oct 2024 00:37:32 -0500 Subject: [PATCH 2/2] refactor!: complete migration to ESM Split changes into 2 commits to keep history changes on git BREAKING CHANGE: migration to ESM --- lib/{checkpoint.js => checkpoint.mjs} | 0 lib/updaters/types/{plain-text.js => plain-text.mjs} | 0 lib/{write-file.js => write-file.mjs} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename lib/{checkpoint.js => checkpoint.mjs} (100%) rename lib/updaters/types/{plain-text.js => plain-text.mjs} (100%) rename lib/{write-file.js => write-file.mjs} (100%) diff --git a/lib/checkpoint.js b/lib/checkpoint.mjs similarity index 100% rename from lib/checkpoint.js rename to lib/checkpoint.mjs diff --git a/lib/updaters/types/plain-text.js b/lib/updaters/types/plain-text.mjs similarity index 100% rename from lib/updaters/types/plain-text.js rename to lib/updaters/types/plain-text.mjs diff --git a/lib/write-file.js b/lib/write-file.mjs similarity index 100% rename from lib/write-file.js rename to lib/write-file.mjs