Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: migration to ESM #201

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions bin/cli.js → bin/cli.mjs
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}
15 changes: 8 additions & 7 deletions command.js → command.mjs
100755 → 100644
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -150,17 +151,17 @@ 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,
group: 'Preset Configuration:',
});
});

module.exports = yargs;
export default yargsObj;
14 changes: 11 additions & 3 deletions defaults.js → defaults.mjs
Original file line number Diff line number Diff line change
@@ -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',
Expand All @@ -15,7 +23,7 @@ const defaults = {
dryRun: false,
tagForce: false,
gitTagFallback: true,
preset: require.resolve('conventional-changelog-conventionalcommits'),
preset: preset,
npmPublishHint: undefined,
};

Expand All @@ -41,4 +49,4 @@ defaults.bumpFiles = defaults.packageFiles.concat([
'npm-shrinkwrap.json',
]);

module.exports = defaults;
export default defaults;
36 changes: 18 additions & 18 deletions index.js → index.mjs
100755 → 100644
Original file line number Diff line number Diff line change
@@ -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.
*/
Expand Down Expand Up @@ -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}`,
);
}

Expand All @@ -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:
Expand All @@ -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);
Expand All @@ -92,4 +92,4 @@ module.exports = async function standardVersion(argv) {
printError(args, err.message);
throw err;
}
};
}
23 changes: 0 additions & 23 deletions lib/checkpoint.js

This file was deleted.

23 changes: 23 additions & 0 deletions lib/checkpoint.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import util from 'util';
import chalk from 'chalk';
import figures from 'figures';

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);
}),
),
),
);
}
}
12 changes: 6 additions & 6 deletions lib/configuration.js → lib/configuration.mjs
Original file line number Diff line number Diff line change
@@ -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',
Expand All @@ -9,15 +9,15 @@ const CONFIGURATION_FILES = [
'.versionrc.js',
];

module.exports.getConfiguration = function () {
export async function getConfiguration() {
let config = {};
const configPath = findUp.sync(CONFIGURATION_FILES);
if (!configPath) {
return config;
}
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 {
Expand All @@ -38,4 +38,4 @@ module.exports.getConfiguration = function () {
}

return config;
};
}
10 changes: 3 additions & 7 deletions lib/detect-package-manager.js → lib/detect-package-manager.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -39,15 +39,11 @@ function getTypeofLockFile(cwd = '.') {
});
}

const detectPMByLockFile = async (cwd) => {
export const detectPMByLockFile = async (cwd) => {
const type = await getTypeofLockFile(cwd);
if (type) {
return type;
}

return 'npm';
};

module.exports = {
detectPMByLockFile,
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = function (rawMsg, newVersion) {
export default function (rawMsg, newVersion) {
const message = String(rawMsg);
return message.replace(/{{currentTag}}/g, newVersion);
};
}
12 changes: 6 additions & 6 deletions lib/latest-semver-tag.js → lib/latest-semver-tag.mjs
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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]);
});
});
};
}
55 changes: 27 additions & 28 deletions lib/lifecycles/bump.js → lib/lifecycles/bump.mjs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -116,7 +115,7 @@ function getReleaseType(prerelease, expectedReleaseType, currentVersion) {
if (
shouldContinuePrerelease(currentVersion, expectedReleaseType) ||
getTypePriority(getCurrentActiveType(currentVersion)) >
getTypePriority(expectedReleaseType)
getTypePriority(expectedReleaseType)
) {
return 'prerelease';
}
Expand Down Expand Up @@ -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,
Expand All @@ -219,28 +218,28 @@ 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 {
if (dotgit.ignore(updater.filename)) {
console.debug(
`Not updating file '${updater.filename}', as it is ignored in Git`,
);
return;
continue;
}
const stat = fs.lstatSync(configPath);

if (!stat.isFile()) {
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);
Expand All @@ -257,7 +256,7 @@ function updateConfigs(args, newVersion) {
} catch (err) {
if (err.code !== 'ENOENT') console.warn(err.message);
}
});
}
}

module.exports = Bump;
export default Bump;
Loading
Loading