diff --git a/.eslintrc b/.eslintrc index a2b6f8892..03861c2d6 100644 --- a/.eslintrc +++ b/.eslintrc @@ -12,9 +12,6 @@ "node": true }, "parserOptions": { - "ecmaFeatures": { - "globalReturn": true - }, - "sourceType": "script" + "sourceType": "module" } } diff --git a/.mocharc.json b/.mocharc.json deleted file mode 100644 index dda35cac3..000000000 --- a/.mocharc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "require": "intelli-espower-loader" -} diff --git a/bin/get-metadata b/bin/get-metadata deleted file mode 100755 index b13b7315f..000000000 --- a/bin/get-metadata +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -const path = require('path'); -const { runAsync } = require('../lib/run'); -const { setVerbosityFromEnv } = require('../lib/verbosity'); -setVerbosityFromEnv(); - -const script = path.join(__dirname, 'git-node'); -runAsync(process.execPath, [script, 'metadata', ...process.argv.slice(2)]); diff --git a/bin/get-metadata.js b/bin/get-metadata.js new file mode 100755 index 000000000..bd067bd1d --- /dev/null +++ b/bin/get-metadata.js @@ -0,0 +1,11 @@ +#!/usr/bin/env node + +import { fileURLToPath } from 'node:url'; + +import { runAsync } from '../lib/run.js'; +import { setVerbosityFromEnv } from '../lib/verbosity.js'; + +setVerbosityFromEnv(); + +const script = fileURLToPath(new URL('git-node.js', import.meta.url)); +runAsync(process.execPath, [script, 'metadata', ...process.argv.slice(2)]); diff --git a/bin/git-node b/bin/git-node deleted file mode 100755 index 98159011f..000000000 --- a/bin/git-node +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -const yargs = require('yargs'); -const path = require('path'); -const epilogue = require('../components/git/epilogue'); -const { setVerbosityFromEnv } = require('../lib/verbosity'); -setVerbosityFromEnv(); - -const commandDir = path.join(__dirname, '..', 'components', 'git'); - -/* eslint-disable no-unused-expressions */ -yargs - .commandDir(commandDir, { - exclude: /epilogue/ - }) - .command('help', false, () => {}, (yargs) => { yargs.showHelp(); }) - .demandCommand(1) - .strict() - .epilogue(epilogue) - .help('help') - .argv; diff --git a/bin/git-node.js b/bin/git-node.js new file mode 100755 index 000000000..02c474d7e --- /dev/null +++ b/bin/git-node.js @@ -0,0 +1,29 @@ +#!/usr/bin/env node + +import { readdirSync } from 'fs'; + +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; + +import epilogue from '../components/git/epilogue.js'; +import { setVerbosityFromEnv } from '../lib/verbosity.js'; + +setVerbosityFromEnv(); + +const commandFiles = readdirSync(new URL('../components/git', import.meta.url)) + .filter(file => file !== 'epilogue.js'); + +function importCommand(commandFile) { + return import(new URL(`../components/git/${commandFile}`, import.meta.url)); +} + +Promise.all(commandFiles.map(importCommand)).then((commands) => { + const args = yargs(hideBin(process.argv)); + commands.forEach(command => args.command(command)); + args.command('help', false, () => {}, (yargs) => { yargs.showHelp(); }) + .demandCommand(1) + .strict() + .epilogue(epilogue) + .help('help') + .parse(); +}); diff --git a/bin/ncu-ci b/bin/ncu-ci.js similarity index 90% rename from bin/ncu-ci rename to bin/ncu-ci.js index cd5d0d697..4c52e0bd1 100755 --- a/bin/ncu-ci +++ b/bin/ncu-ci.js @@ -1,48 +1,47 @@ #!/usr/bin/env node -'use strict'; +import yargs from 'yargs'; +import clipboardy from 'clipboardy'; -const { +import { JobParser, parseJobFromURL, - CI_TYPES_KEYS: { - PR, - COMMIT, - BENCHMARK, - CITGM, - CITGM_NOBUILD, - DAILY_MASTER - } -} = require('../lib/ci/ci_type_parser'); -const { setVerbosityFromEnv } = require('../lib/verbosity'); -setVerbosityFromEnv(); - -const { listBuilds } = require('../lib/ci/ci_utils'); - -const { jobCache } = require('../lib/ci/build-types/job'); -const { PRBuild } = require('../lib/ci/build-types/pr_build'); -const { CommitBuild } = require('../lib/ci/build-types/commit_build'); -const { DailyBuild } = require('../lib/ci/build-types/daily_build'); -const { FailureAggregator } = require('../lib/ci/failure_aggregator'); -const { BenchmarkRun } = require('../lib/ci/build-types/benchmark_run'); -const { HealthBuild } = require('../lib/ci/build-types/health_build'); -const { CITGMBuild } = require('../lib/ci/build-types/citgm_build'); -const { + CI_TYPES_KEYS +} from '../lib/ci/ci_type_parser.js'; +import { setVerbosityFromEnv } from '../lib/verbosity.js'; +import { listBuilds } from '../lib/ci/ci_utils.js'; +import { jobCache } from '../lib/ci/build-types/job.js'; +import { PRBuild } from '../lib/ci/build-types/pr_build.js'; +import { CommitBuild } from '../lib/ci/build-types/commit_build.js'; +import { DailyBuild } from '../lib/ci/build-types/daily_build.js'; +import { FailureAggregator } from '../lib/ci/failure_aggregator.js'; +import { BenchmarkRun } from '../lib/ci/build-types/benchmark_run.js'; +import { HealthBuild } from '../lib/ci/build-types/health_build.js'; +import { CITGMBuild } from '../lib/ci/build-types/citgm_build.js'; +import { CITGMComparisonBuild -} = require('../lib/ci/build-types/citgm_comparison_build'); - -const { +} from '../lib/ci/build-types/citgm_comparison_build.js'; +import { RunPRJob -} = require('../lib/ci/run_ci'); -const clipboardy = require('clipboardy'); -const { writeJson, writeFile } = require('../lib/file'); -const { getMergedConfig } = require('../lib/config'); +} from '../lib/ci/run_ci.js'; +import { writeJson, writeFile } from '../lib/file.js'; +import { getMergedConfig } from '../lib/config.js'; +import { runPromise } from '../lib/run.js'; +import auth from '../lib/auth.js'; +import Request from '../lib/request.js'; +import CLI from '../lib/cli.js'; +import { hideBin } from 'yargs/helpers'; + +setVerbosityFromEnv(); -const { runPromise } = require('../lib/run'); -const auth = require('../lib/auth'); -const Request = require('../lib/request'); -const CLI = require('../lib/cli'); -const yargs = require('yargs'); +const { + PR, + COMMIT, + BENCHMARK, + CITGM, + CITGM_NOBUILD, + DAILY_MASTER +} = CI_TYPES_KEYS; const commandKeys = [ 'rate', @@ -53,8 +52,7 @@ const commandKeys = [ 'citgm' ]; -// eslint-disable-next-line no-unused-vars -const argv = yargs +const args = yargs(hideBin(process.argv)) .command({ command: 'rate ', desc: 'Calculate the green rate of a CI job in the last 100 runs', @@ -223,8 +221,9 @@ const argv = yargs } return true; }) - .help() - .argv; + .help(); + +args.parse(); const commandToType = { commit: COMMIT, @@ -564,7 +563,7 @@ async function main(command, argv) { break; } default: - return yargs.showHelp(); + return args.showHelp(); } await commandHandler.initialize(); diff --git a/bin/ncu-config b/bin/ncu-config.js similarity index 89% rename from bin/ncu-config rename to bin/ncu-config.js index e9fe64eaa..30b7f303f 100755 --- a/bin/ncu-config +++ b/bin/ncu-config.js @@ -1,16 +1,16 @@ #!/usr/bin/env node -'use strict'; +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; -const { +import { getConfig, updateConfig, GLOBAL_CONFIG, PROJECT_CONFIG, LOCAL_CONFIG -} = require('../lib/config'); +} from '../lib/config.js'; +import { setVerbosityFromEnv } from '../lib/verbosity.js'; -const { setVerbosityFromEnv } = require('../lib/verbosity'); setVerbosityFromEnv(); -const yargs = require('yargs'); -const argv = yargs +const args = yargs(hideBin(process.argv)) .command({ command: 'set ', desc: 'Set a config variable', @@ -58,8 +58,9 @@ const argv = yargs describe: 'Use project config (./.ncurc)' }) .conflicts('global', 'project') - .help() - .argv; + .help(); + +const argv = args.parse(); function getConfigType(argv) { if (argv.global) { @@ -95,5 +96,5 @@ function listHandler(argv) { } if (!['get', 'set', 'list'].includes(argv._[0])) { - yargs.showHelp(); + args.showHelp(); } diff --git a/bin/ncu-team b/bin/ncu-team.js similarity index 56% rename from bin/ncu-team rename to bin/ncu-team.js index 2cdc62cee..3e2d7d624 100755 --- a/bin/ncu-team +++ b/bin/ncu-team.js @@ -1,33 +1,35 @@ #!/usr/bin/env node -'use strict'; -const Request = require('../lib/request'); -const auth = require('../lib/auth'); -const { runPromise } = require('../lib/run'); -const CLI = require('../lib/cli'); -const TeamInfo = require('../lib/team_info'); +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; + +import Request from '../lib/request.js'; +import auth from '../lib/auth.js'; +import { runPromise } from '../lib/run.js'; +import CLI from '../lib/cli.js'; +import TeamInfo from '../lib/team_info.js'; + +import { setVerbosityFromEnv } from '../lib/verbosity.js'; -const { setVerbosityFromEnv } = require('../lib/verbosity'); setVerbosityFromEnv(); -require('yargs') // eslint-disable-line - .command({ - command: 'list [org]', - desc: 'Get the list of members in a team', - builder: (yargs) => { - yargs - .positional('team', { - describe: 'Name of the team', - type: 'string' - }) - .positional('org', { - describe: 'Name of the organization', - type: 'string', - default: 'nodejs' - }); - }, - handler: handler - }) +yargs(hideBin(process.argv)).command({ + command: 'list [org]', + desc: 'Get the list of members in a team', + builder: (yargs) => { + yargs + .positional('team', { + describe: 'Name of the team', + type: 'string' + }) + .positional('org', { + describe: 'Name of the organization', + type: 'string', + default: 'nodejs' + }); + }, + handler: handler +}) .command({ command: 'sync ', desc: @@ -43,7 +45,7 @@ require('yargs') // eslint-disable-line }) .demandCommand(1, 'must provide a valid command') .help() - .argv; + .parse(); function handler(argv) { runPromise(main(argv)); diff --git a/components/git/backport.js b/components/git/backport.js index 846765ace..60f67cbbc 100644 --- a/components/git/backport.js +++ b/components/git/backport.js @@ -1,10 +1,10 @@ -'use strict'; +import { parsePRFromURL } from '../../lib/links.js'; +import CLI from '../../lib/cli.js'; +import { runPromise } from '../../lib/run.js'; +import BackportSession from '../../lib/backport_session.js'; -const yargs = require('yargs'); -const { parsePRFromURL } = require('../../lib/links'); -const CLI = require('../../lib/cli'); -const { runPromise } = require('../../lib/run'); -const BackportSession = require('../../lib/backport_session'); +export const command = 'backport '; +export const describe = 'Backport a PR to a release staging branch.'; const epilogue = `====================== Example ======================= Demo: https://asciinema.org/a/221244 @@ -23,7 +23,10 @@ $ git node backport 24816 --to 11 ===================================================== `; -function builder(yargs) { +let yargsInstance; + +export function builder(yargs) { + yargsInstance = yargs; return yargs .options({ to: { @@ -40,7 +43,9 @@ function builder(yargs) { .wrap(90); } -async function main(config) { +async function main(argv, parsed) { + const merged = (await import('../../lib/config.js')).getMergedConfig(); + const config = Object.assign({}, argv, parsed, merged); const logStream = process.stdout.isTTY ? process.stdout : process.stderr; const cli = new CLI(logStream); cli.setFigureIndent(0); @@ -49,7 +54,7 @@ async function main(config) { return session.backport(); } -function handler(argv) { +export function handler(argv) { let parsed = {}; const prid = Number.parseInt(argv.identifier); if (!Number.isNaN(prid)) { @@ -57,18 +62,9 @@ function handler(argv) { } else { parsed = parsePRFromURL(argv.identifier); if (!parsed) { - return yargs.showHelp(); + return yargsInstance.showHelp(); } } - const config = require('../../lib/config').getMergedConfig(); - const merged = Object.assign({}, argv, parsed, config); - return runPromise(main(merged)); + return runPromise(main(argv, parsed)); } - -module.exports = { - command: 'backport ', - describe: 'Backport a PR to a release staging branch.', - builder, - handler -}; diff --git a/components/git/epilogue.js b/components/git/epilogue.js index 0d3853966..2482a02f0 100644 --- a/components/git/epilogue.js +++ b/components/git/epilogue.js @@ -1,6 +1,4 @@ -'use strict'; - -module.exports = `Steps to land a pull request: +export default `Steps to land a pull request: ============================================================================== $ cd path/to/node/project diff --git a/components/git/land.js b/components/git/land.js index 5dc2d144a..2e4676180 100644 --- a/components/git/land.js +++ b/components/git/land.js @@ -1,14 +1,15 @@ -'use strict'; - -const auth = require('../../lib/auth'); -const { parsePRFromURL } = require('../../lib/links'); -const { getMetadata } = require('../metadata'); -const CLI = require('../../lib/cli'); -const Request = require('../../lib/request'); -const { runPromise } = require('../../lib/run'); -const LandingSession = require('../../lib/landing_session'); -const epilogue = require('./epilogue'); -const yargs = require('yargs'); +import auth from '../../lib/auth.js'; +import { parsePRFromURL } from '../../lib/links.js'; +import { getMetadata } from '../metadata.js'; +import CLI from '../../lib/cli.js'; +import Request from '../../lib/request.js'; +import { runPromise } from '../../lib/run.js'; +import LandingSession from '../../lib/landing_session.js'; +import epilogue from './epilogue.js'; + +export const command = 'land [prid|options]'; +export const describe = + 'Manage the current landing session or start a new one for a pull request'; const landActions = { apply: { @@ -81,7 +82,10 @@ const landOptions = { } }; -function builder(yargs) { +let yargsInstance; + +export function builder(yargs) { + yargsInstance = yargs; return yargs .options(Object.assign({}, landOptions, landActions)) .positional('prid', { @@ -109,7 +113,7 @@ const FINAL = 'final'; const CONTINUE = 'continue'; const ABORT = 'abort'; -function handler(argv) { +export function handler(argv) { if (argv.prid) { if (Number.isInteger(argv.prid)) { return land(START, argv); @@ -120,7 +124,7 @@ function handler(argv) { return land(START, argv); } } - yargs.showHelp(); + yargsInstance.showHelp(); return; } @@ -137,7 +141,7 @@ function handler(argv) { // If the more than one action is provided or no valid action // is provided, show help. - yargs.showHelp(); + yargsInstance.showHelp(); } function land(state, argv) { @@ -155,14 +159,6 @@ function land(state, argv) { }); } -module.exports = { - command: 'land [prid|options]', - describe: - 'Manage the current landing session or start a new one for a pull request', - builder, - handler -}; - async function main(state, argv, cli, dir) { const credentials = await auth({ github: true diff --git a/components/git/metadata.js b/components/git/metadata.js index 3db3a0d6e..274e6f3f8 100644 --- a/components/git/metadata.js +++ b/components/git/metadata.js @@ -1,12 +1,14 @@ -'use strict'; +import { parsePRFromURL } from '../../lib/links.js'; +import { getMetadata } from '../metadata.js'; +import CLI from '../../lib/cli.js'; +import { getMergedConfig } from '../../lib/config.js'; +import { runPromise, IGNORE } from '../../lib/run.js'; -const yargs = require('yargs'); +export const command = 'metadata '; +export const describe = + 'Retrieves metadata for a PR and validates them against nodejs/node PR rules'; -const { parsePRFromURL } = require('../../lib/links'); -const { getMetadata } = require('../metadata'); -const CLI = require('../../lib/cli'); -const config = require('../../lib/config').getMergedConfig(); -const { runPromise, IGNORE } = require('../../lib/run'); +const config = getMergedConfig(); const options = { owner: { @@ -41,7 +43,10 @@ const options = { } }; -function builder(yargs) { +let yargsInstance; + +export function builder(yargs) { + yargsInstance = yargs; return yargs .options(options) .positional('identifier', { @@ -60,7 +65,7 @@ function builder(yargs) { .wrap(90); } -function handler(argv) { +export function handler(argv) { let parsed = {}; const prid = Number.parseInt(argv.identifier); if (!Number.isNaN(prid)) { @@ -68,12 +73,12 @@ function handler(argv) { } else { parsed = parsePRFromURL(argv.identifier); if (!parsed) { - return yargs.showHelp(); + return yargsInstance.showHelp(); } } if (!Number.isInteger(argv.maxCommits) || argv.maxCommits < 0) { - return yargs.showHelp(); + return yargsInstance.showHelp(); } const logStream = process.stdout.isTTY ? process.stdout : process.stderr; @@ -87,11 +92,3 @@ function handler(argv) { } })); } - -module.exports = { - command: 'metadata ', - describe: 'Retrieves metadata for a PR and validates them against ' + - 'nodejs/node PR rules', - builder, - handler -}; diff --git a/components/git/release.js b/components/git/release.js index 0d7fd347f..29d2ba309 100644 --- a/components/git/release.js +++ b/components/git/release.js @@ -1,10 +1,9 @@ -'use strict'; +import CLI from '../../lib/cli.js'; +import ReleasePreparation from '../../lib/prepare_release.js'; +import { runPromise } from '../../lib/run.js'; -const yargs = require('yargs'); - -const CLI = require('../../lib/cli'); -const ReleasePreparation = require('../../lib/prepare_release'); -const { runPromise } = require('../../lib/run'); +export const command = 'release [newVersion|options]'; +export const describe = 'Manage an in-progress release or start a new one.'; const PREPARE = 'prepare'; const PROMOTE = 'promote'; @@ -28,7 +27,10 @@ const releaseOptions = { } }; -function builder(yargs) { +let yargsInstance; + +export function builder(yargs) { + yargsInstance = yargs; return yargs .options(releaseOptions).positional('newVersion', { describe: 'Version number of the release to be prepared or promoted' @@ -37,7 +39,7 @@ function builder(yargs) { 'Prepare a new release of Node.js tagged v1.2.3'); } -function handler(argv) { +export function handler(argv) { if (argv.prepare) { return release(PREPARE, argv); } else if (argv.promote) { @@ -46,7 +48,7 @@ function handler(argv) { // If more than one action is provided or no valid action // is provided, show help. - yargs.showHelp(); + yargsInstance.showHelp(); } function release(state, argv) { @@ -62,14 +64,6 @@ function release(state, argv) { }); } -module.exports = { - command: 'release [newVersion|options]', - describe: - 'Manage an in-progress release or start a new one.', - builder, - handler -}; - async function main(state, argv, cli, dir) { if (state === PREPARE) { const prep = new ReleasePreparation(argv, cli, dir); diff --git a/components/git/status.js b/components/git/status.js index 7fbbea0cb..e5eb19310 100644 --- a/components/git/status.js +++ b/components/git/status.js @@ -1,16 +1,17 @@ -'use strict'; +import path from 'node:path'; +import fs from 'node:fs'; -const path = require('path'); -const fs = require('fs'); - -const { readJson } = require('./../../lib/file'); -const { getNcuDir } = require('./../../lib/config'); - -const CLI = require('../../lib/cli'); +import { readJson } from './../../lib/file.js'; +import { getNcuDir } from './../../lib/config.js'; +import CLI from '../../lib/cli.js'; const cli = new CLI(); -function handler() { +export const command = 'status'; +export const describe = + 'Return status and information about the current git-node land session.'; + +export function handler() { const ncuDir = getNcuDir(process.cwd()); const landPath = path.join(ncuDir, 'land'); @@ -29,10 +30,3 @@ function handler() { cli.warn('No landing session in progress'); } } - -module.exports = { - command: 'status', - describe: 'Return status and information about' + - 'the current git-node land session.', - handler: handler -}; diff --git a/components/git/sync.js b/components/git/sync.js index e36b6c86e..55e288342 100644 --- a/components/git/sync.js +++ b/components/git/sync.js @@ -1,10 +1,11 @@ -'use strict'; +import CLI from '../../lib/cli.js'; +import { runPromise } from '../../lib/run.js'; +import SyncSession from '../../lib/sync_session.js'; -const CLI = require('../../lib/cli'); -const { runPromise } = require('../../lib/run'); -const SyncSession = require('../../lib/sync_session'); +export const command = 'sync'; +export const describe = 'Sync the branch specified by ncu-config.'; -function builder(yargs) { +export function builder(yargs) { return yargs .epilogue('Demo: https://asciinema.org/a/221230') .wrap(90); @@ -18,13 +19,6 @@ async function main() { await session.sync(); } -function handler(argv) { +export function handler(argv) { return runPromise(main()); } - -module.exports = { - command: 'sync', - describe: 'Sync the branch specified by ncu-config.', - builder, - handler -}; diff --git a/components/git/v8.js b/components/git/v8.js index 0793a71fa..170442b8a 100644 --- a/components/git/v8.js +++ b/components/git/v8.js @@ -1,78 +1,74 @@ -'use strict'; +import path from 'node:path'; -const path = require('path'); +import { execa } from 'execa'; +import logSymbols from 'log-symbols'; -const execa = require('execa'); -const logSymbols = require('log-symbols'); +import { minor, major, backport } from '../../lib/update-v8/index.js'; +import { defaultBaseDir } from '../../lib/update-v8/constants.js'; +import { checkCwd } from '../../lib/update-v8/common.js'; -const updateV8 = require('../../lib/update-v8'); -const constants = require('../../lib/update-v8/constants'); -const common = require('../../lib/update-v8/common'); +export const command = 'v8 [major|minor|backport]'; +export const describe = 'Update or patch the V8 engine'; -module.exports = { - command: 'v8 [major|minor|backport]', - describe: 'Update or patch the V8 engine', - builder: (yargs) => { - yargs - .command({ - command: 'major', - desc: 'Do a major upgrade. Replaces the whole deps/v8 directory', - handler: main, - builder: (yargs) => { - yargs.option('branch', { - describe: 'Branch of the V8 repository to use for the upgrade', - default: 'lkgr' - }); - yargs.option('version-bump', { - describe: 'Bump the NODE_MODULE_VERSION constant', +export function builder(yargs) { + yargs + .command({ + command: 'major', + desc: 'Do a major upgrade. Replaces the whole deps/v8 directory', + handler, + builder: (yargs) => { + yargs.option('branch', { + describe: 'Branch of the V8 repository to use for the upgrade', + default: 'lkgr' + }); + yargs.option('version-bump', { + describe: 'Bump the NODE_MODULE_VERSION constant', + default: true + }); + } + }) + .command({ + command: 'minor', + desc: 'Do a minor patch of the current V8 version', + handler + }) + .command({ + command: 'backport ', + desc: 'Backport one or more commits from the V8 repository', + handler, + builder: (yargs) => { + yargs + .option('bump', { + describe: 'Bump V8 embedder version number or patch version', default: true - }); - } - }) - .command({ - command: 'minor', - desc: 'Do a minor patch of the current V8 version', - handler: main - }) - .command({ - command: 'backport ', - desc: 'Backport one or more commits from the V8 repository', - handler: main, - builder: (yargs) => { - yargs - .option('bump', { - describe: 'Bump V8 embedder version number or patch version', - default: true - }) - .option('squash', { - describe: + }) + .option('squash', { + describe: 'If multiple commits are backported, squash them into one', - default: false - }); - } - }) - .demandCommand(1, 'Please provide a valid command') - .option('node-dir', { - describe: 'Directory of a Node.js clone', - default: process.cwd() - }) - .option('base-dir', { - describe: 'Directory where V8 should be cloned', - default: constants.defaultBaseDir - }) - .option('v8-dir', { - describe: 'Directory of an existing V8 clone' - }) - .option('verbose', { - describe: 'Enable verbose output', - boolean: true, - default: false - }); - }, - handler: main -}; + default: false + }); + } + }) + .demandCommand(1, 'Please provide a valid command') + .option('node-dir', { + describe: 'Directory of a Node.js clone', + default: process.cwd() + }) + .option('base-dir', { + describe: 'Directory where V8 should be cloned', + default: defaultBaseDir + }) + .option('v8-dir', { + describe: 'Directory of an existing V8 clone' + }) + .option('verbose', { + describe: 'Enable verbose output', + boolean: true, + default: false + }); +} -function main(argv) { +export function handler(argv) { const options = Object.assign({}, argv); options.nodeDir = path.resolve(options.nodeDir); options.baseDir = path.resolve(options.baseDir); @@ -96,17 +92,17 @@ function main(argv) { Promise.resolve() .then(async() => { - await common.checkCwd(options); + await checkCwd(options); // First element of argv is 'v8' const kind = argv._[1]; options[kind] = true; switch (kind) { case 'minor': - return updateV8.minor(options); + return minor(options); case 'major': - return updateV8.major(options); + return major(options); case 'backport': - return updateV8.backport(options); + return backport(options); } }) .catch((err) => { diff --git a/components/git/wpt.js b/components/git/wpt.js index f6e648a00..f5d1b22cd 100644 --- a/components/git/wpt.js +++ b/components/git/wpt.js @@ -1,18 +1,20 @@ -'use strict'; +import fs from 'node:fs'; +import path from 'node:path'; -const fs = require('fs'); -const path = require('path'); -const Request = require('../../lib/request'); -const CLI = require('../../lib/cli'); -const auth = require('../../lib/auth'); -const { +import Request from '../../lib/request.js'; +import CLI from '../../lib/cli.js'; +import auth from '../../lib/auth.js'; +import { WPTUpdater, ResourcesUpdater, InterfacesUpdater -} = require('../../lib/wpt'); -const { runPromise } = require('../../lib/run'); +} from '../../lib/wpt/index.js'; +import { runPromise } from '../../lib/run.js'; -function builder(yargs) { +export const command = 'wpt '; +export const describe = 'Updates WPT suite'; + +export function builder(yargs) { return yargs .positional('name', { describe: 'Subset of the WPT to update', @@ -80,13 +82,6 @@ async function main(argv) { updaters[0].updateLicense(); } -function handler(argv) { +export function handler(argv) { runPromise(main(argv)); } - -module.exports = { - command: 'wpt ', - describe: 'Updates WPT suite', - builder, - handler -}; diff --git a/components/metadata.js b/components/metadata.js index 122f67508..156341f86 100644 --- a/components/metadata.js +++ b/components/metadata.js @@ -1,15 +1,13 @@ -'use strict'; +import fs from 'node:fs'; -const Request = require('../lib/request'); -const auth = require('../lib/auth'); -const PRData = require('../lib/pr_data'); -const PRSummary = require('../lib/pr_summary'); -const PRChecker = require('../lib/pr_checker'); -const MetadataGenerator = require('../lib/metadata_gen'); +import Request from '../lib/request.js'; +import auth from '../lib/auth.js'; +import PRData from '../lib/pr_data.js'; +import PRSummary from '../lib/pr_summary.js'; +import PRChecker from '../lib/pr_checker.js'; +import MetadataGenerator from '../lib/metadata_gen.js'; -const fs = require('fs'); - -async function getMetadata(argv, skipRefs, cli) { +export async function getMetadata(argv, skipRefs, cli) { const credentials = await auth({ github: true, jenkins: true @@ -49,5 +47,3 @@ async function getMetadata(argv, skipRefs, cli) { checker }; }; - -module.exports = { getMetadata }; diff --git a/lib/auth.js b/lib/auth.js index 8700ae7da..2569b047f 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -1,13 +1,15 @@ -'use strict'; +import assert from 'node:assert'; +import fs from 'node:fs'; +import { ClientRequest } from 'node:http'; +import util from 'node:util'; -const assert = require('assert'); -const fs = require('fs'); -const { ClientRequest } = require('http'); -const util = require('util'); -const ghauth = util.promisify(require('ghauth')); -const { getMergedConfig, getNcurcPath } = require('./config'); +import ghauthBase from 'ghauth'; -module.exports = lazy(auth); +import { getMergedConfig, getNcurcPath } from './config.js'; + +const ghauth = util.promisify(ghauthBase); + +export default lazy(auth); function check(username, token) { assert(typeof username === 'string' && /^[a-zA-Z0-9]*/.test(username)); diff --git a/lib/backport_session.js b/lib/backport_session.js index 6040dcd2b..3a871ccbb 100644 --- a/lib/backport_session.js +++ b/lib/backport_session.js @@ -1,10 +1,6 @@ -'use strict'; - -const Session = require('./session'); -const { runSync, runAsync } = require('./run'); -const { getPrURL, parsePrURL } = require('./links'); - -const { IGNORE } = require('./run'); +import Session from './session.js'; +import { runSync, runAsync, IGNORE } from './run.js'; +import { getPrURL, parsePrURL } from './links.js'; const MAX_HISTORY = 10; const OLDEST_ID = new Map([ @@ -13,7 +9,7 @@ const OLDEST_ID = new Map([ [11, 23000] ]); -class BackportSession extends Session { +export default class BackportSession extends Session { constructor(cli, dir, prid, target) { super(cli, dir, prid); this.target = target; @@ -231,5 +227,3 @@ class BackportSession extends Session { }); } } - -module.exports = BackportSession; diff --git a/lib/cache.js b/lib/cache.js index 1d2e1005b..13b195348 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -1,16 +1,18 @@ -'use strict'; +import path from 'node:path'; +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; -const path = require('path'); -const fs = require('fs'); -const { writeJson, readJson, writeFile, readFile } = require('./file'); +import { writeJson, readJson, writeFile, readFile } from './file.js'; function isAsync(fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } -class Cache { +const parentDir = fileURLToPath(new URL('..', import.meta.url)); + +export default class Cache { constructor(dir) { - this.dir = dir || this.computeCacheDir(path.join(__dirname, '..')); + this.dir = dir || this.computeCacheDir(parentDir); this.originals = {}; this.disabled = true; } @@ -103,5 +105,3 @@ class Cache { } } } - -module.exports = Cache; diff --git a/lib/ci/build-types/benchmark_run.js b/lib/ci/build-types/benchmark_run.js index dfde10fbd..0ceb67e72 100644 --- a/lib/ci/build-types/benchmark_run.js +++ b/lib/ci/build-types/benchmark_run.js @@ -1,9 +1,7 @@ -'use strict'; +import { fold } from '../ci_utils.js'; +import { Job } from './job.js'; -const { Job } = require('./job'); -const { fold } = require('../ci_utils'); - -class BenchmarkRun extends Job { +export class BenchmarkRun extends Job { constructor(cli, request, id) { const path = `job/benchmark-node-micro-benchmarks/${id}/`; super(cli, request, path); @@ -72,5 +70,3 @@ class BenchmarkRun extends Job { return json; } } - -module.exports = { BenchmarkRun }; diff --git a/lib/ci/build-types/citgm_build.js b/lib/ci/build-types/citgm_build.js index 3764b195b..3cf9d0492 100644 --- a/lib/ci/build-types/citgm_build.js +++ b/lib/ci/build-types/citgm_build.js @@ -1,21 +1,20 @@ -'use strict'; - -const { TestBuild } = require('./test_build'); -const { flatten } = require('../../utils'); -const { getNodeName, pad } = require('../ci_utils'); - -const { +import { flatten } from '../../utils.js'; +import { getNodeName, pad } from '../ci_utils.js'; +import { CITGM_MAIN_TREE, CITGM_REPORT_TREE -} = require('../jenkins_constants'); +} from '../jenkins_constants.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { TestBuild } from './test_build.js'; + const { FAILURE_TYPES: { NCU_FAILURE }, FAILURE_CONSTRUCTORS: { [NCU_FAILURE]: NCUFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class CITGMBuild extends TestBuild { +export class CITGMBuild extends TestBuild { constructor(cli, request, job) { const { jobid, noBuild } = job; const path = noBuild @@ -193,5 +192,3 @@ class CITGMBuild extends TestBuild { return output; } } - -module.exports = { CITGMBuild }; diff --git a/lib/ci/build-types/citgm_comparison_build.js b/lib/ci/build-types/citgm_comparison_build.js index 159f85d15..fb6c67756 100644 --- a/lib/ci/build-types/citgm_comparison_build.js +++ b/lib/ci/build-types/citgm_comparison_build.js @@ -1,9 +1,7 @@ -'use strict'; +import { statusType } from '../ci_utils.js'; +import { CITGMBuild } from './citgm_build.js'; -const { statusType } = require('../ci_utils'); -const { CITGMBuild } = require('./citgm_build'); - -class CITGMComparisonBuild { +export class CITGMComparisonBuild { constructor(cli, request, job) { const { jobid, jobid2, noBuild } = job; @@ -174,5 +172,3 @@ class CITGMComparisonBuild { return output; } } - -module.exports = { CITGMComparisonBuild }; diff --git a/lib/ci/build-types/commit_build.js b/lib/ci/build-types/commit_build.js index 684059673..010e98f1f 100644 --- a/lib/ci/build-types/commit_build.js +++ b/lib/ci/build-types/commit_build.js @@ -1,13 +1,13 @@ -'use strict'; +import { flatten } from '../../utils.js'; +import { statusType } from '../ci_utils.js'; +import { COMMIT_TREE } from '../jenkins_constants.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { TestBuild } from './test_build.js'; +import { FannedBuild } from './fanned_build.js'; +import { LinterBuild } from './linter_build.js'; +import { NormalBuild } from './normal_build.js'; +import { TestRun } from './test_run.js'; -const { TestBuild } = require('./test_build'); -const { FannedBuild } = require('./fanned_build'); -const { LinterBuild } = require('./linter_build'); -const { NormalBuild } = require('./normal_build'); -const { TestRun } = require('./test_run'); -const { flatten } = require('../../utils'); -const { statusType } = require('../ci_utils'); -const { COMMIT_TREE } = require('../jenkins_constants'); const { FAILURE_TYPES: { BUILD_FAILURE, @@ -17,9 +17,9 @@ const { [BUILD_FAILURE]: BuildFailure, [NCU_FAILURE]: NCUFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class CommitBuild extends TestBuild { +export class CommitBuild extends TestBuild { constructor(cli, request, id) { const path = `job/node-test-commit/${id}/`; const tree = COMMIT_TREE; @@ -110,5 +110,3 @@ class CommitBuild extends TestBuild { return { result, failures, builds }; } } - -module.exports = { CommitBuild }; diff --git a/lib/ci/build-types/daily_build.js b/lib/ci/build-types/daily_build.js index 7a6d04467..d0dd6ee12 100644 --- a/lib/ci/build-types/daily_build.js +++ b/lib/ci/build-types/daily_build.js @@ -1,9 +1,7 @@ -'use strict'; +import { PR_TREE } from '../jenkins_constants.js'; +import { TestBuild } from './test_build.js'; -const { TestBuild } = require('./test_build'); -const { PR_TREE } = require('../jenkins_constants'); - -class DailyBuild extends TestBuild { +export class DailyBuild extends TestBuild { constructor(cli, request, id) { const path = `job/node-daily-master/${id}/`; const tree = PR_TREE; @@ -24,5 +22,3 @@ class DailyBuild extends TestBuild { return super.formatAsMarkdown(); } } - -module.exports = { DailyBuild }; diff --git a/lib/ci/build-types/fanned_build.js b/lib/ci/build-types/fanned_build.js index 6ad406e44..714a0d488 100644 --- a/lib/ci/build-types/fanned_build.js +++ b/lib/ci/build-types/fanned_build.js @@ -1,10 +1,10 @@ -'use strict'; +import { statusType } from '../ci_utils.js'; +import { flatten } from '../../utils.js'; +import { FANNED_TREE } from '../jenkins_constants.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { Job } from './job.js'; +import { NormalBuild } from './normal_build.js'; -const { Job } = require('./job'); -const { NormalBuild } = require('./normal_build'); -const { statusType } = require('../ci_utils'); -const { flatten } = require('../../utils'); -const { FANNED_TREE } = require('../jenkins_constants'); const { FAILURE_TYPES: { BUILD_FAILURE, @@ -17,9 +17,9 @@ const { [NCU_FAILURE]: NCUFailure, [RESUME_FAILURE]: ResumeFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class FannedBuild extends Job { +export class FannedBuild extends Job { constructor(cli, request, jobName, id, isResumed) { // assert(jobName.includes('fanned')); const path = `job/${jobName}/${id}/`; @@ -85,5 +85,3 @@ class FannedBuild extends Job { return this.failures; } } - -module.exports = { FannedBuild }; diff --git a/lib/ci/build-types/health_build.js b/lib/ci/build-types/health_build.js index 6b0b36000..fdc82f2f4 100644 --- a/lib/ci/build-types/health_build.js +++ b/lib/ci/build-types/health_build.js @@ -1,6 +1,4 @@ -'use strict'; - -const { listBuilds, pad } = require('../ci_utils'); +import { listBuilds, pad } from '../ci_utils.js'; const kHealthKeys = [ 'success', @@ -34,7 +32,7 @@ class Health { } } -class HealthBuild { +export class HealthBuild { constructor(cli, request, ciType, builds) { this.cli = cli; this.request = request; @@ -63,5 +61,3 @@ class HealthBuild { this.cli.log(this.formatAsMarkdown()); } } - -module.exports = { HealthBuild }; diff --git a/lib/ci/build-types/job.js b/lib/ci/build-types/job.js index 7a162da67..6cdb3d289 100644 --- a/lib/ci/build-types/job.js +++ b/lib/ci/build-types/job.js @@ -1,9 +1,9 @@ -'use strict'; +import qs from 'node:querystring'; + +import { CI_DOMAIN } from '../ci_type_parser.js'; +import Cache from '../../cache.js'; +import CIFailureParser from '../ci_failure_parser.js'; -const qs = require('querystring'); -const { CI_DOMAIN } = require('../ci_type_parser'); -const Cache = require('../../cache'); -const CIFailureParser = require('../ci_failure_parser'); const { FAILURE_TYPES: { NCU_FAILURE }, FAILURE_CONSTRUCTORS: { @@ -12,7 +12,7 @@ const { CIResult } = CIFailureParser; -class Job { +export class Job { constructor(cli, request, path, tree) { this.cli = cli; this.request = request; @@ -103,7 +103,7 @@ class Job { } // TODO(joyeecheung): do not cache pending jobs -const jobCache = new Cache(); +export const jobCache = new Cache(); jobCache.wrap(Job, { getConsoleText() { return { key: this.getCacheKey(), ext: '.txt' }; @@ -112,5 +112,3 @@ jobCache.wrap(Job, { return { key: this.getCacheKey(), ext: '.json' }; } }); - -module.exports = { Job, jobCache }; diff --git a/lib/ci/build-types/linter_build.js b/lib/ci/build-types/linter_build.js index d96f4f4a2..9e9b85bfb 100644 --- a/lib/ci/build-types/linter_build.js +++ b/lib/ci/build-types/linter_build.js @@ -1,15 +1,15 @@ -'use strict'; +import { LINTER_TREE } from '../jenkins_constants.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { Job } from './job.js'; -const { Job } = require('./job'); -const { LINTER_TREE } = require('../jenkins_constants'); const { FAILURE_TYPES: { NCU_FAILURE }, FAILURE_CONSTRUCTORS: { [NCU_FAILURE]: NCUFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class LinterBuild extends Job { +export class LinterBuild extends Job { constructor(cli, request, jobName, id) { const path = `job/${jobName}/${id}/`; const tree = LINTER_TREE; @@ -33,5 +33,3 @@ class LinterBuild extends Job { return this.parseConsoleText(); } } - -module.exports = { LinterBuild }; diff --git a/lib/ci/build-types/normal_build.js b/lib/ci/build-types/normal_build.js index af6e8cd0f..7c148b78b 100644 --- a/lib/ci/build-types/normal_build.js +++ b/lib/ci/build-types/normal_build.js @@ -1,10 +1,10 @@ -'use strict'; +import { statusType } from '../ci_utils.js'; +import { flatten } from '../../utils.js'; +import { BUILD_TREE } from '../jenkins_constants.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { Job } from './job.js'; +import { TestRun } from './test_run.js'; -const { Job } = require('./job'); -const { TestRun } = require('./test_run'); -const { statusType } = require('../ci_utils'); -const { flatten } = require('../../utils'); -const { BUILD_TREE } = require('../jenkins_constants'); const { FAILURE_TYPES: { BUILD_FAILURE, @@ -14,9 +14,9 @@ const { [BUILD_FAILURE]: BuildFailure, [NCU_FAILURE]: NCUFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class NormalBuild extends Job { +export class NormalBuild extends Job { constructor(cli, request, jobName, id) { const path = `job/${jobName}/${id}/`; const tree = BUILD_TREE; @@ -87,5 +87,3 @@ class NormalBuild extends Job { return this.failures; } } - -module.exports = { NormalBuild }; diff --git a/lib/ci/build-types/pr_build.js b/lib/ci/build-types/pr_build.js index b95182357..1d9d86354 100644 --- a/lib/ci/build-types/pr_build.js +++ b/lib/ci/build-types/pr_build.js @@ -1,8 +1,8 @@ -'use strict'; +import { PR_TREE } from '../jenkins_constants.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { TestBuild } from './test_build.js'; +import { CommitBuild } from './commit_build.js'; -const { TestBuild } = require('./test_build'); -const { CommitBuild } = require('./commit_build'); -const { PR_TREE } = require('../jenkins_constants'); const { FAILURE_TYPES: { BUILD_FAILURE, @@ -12,9 +12,9 @@ const { [BUILD_FAILURE]: BuildFailure, [NCU_FAILURE]: NCUFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class PRBuild extends TestBuild { +export class PRBuild extends TestBuild { constructor(cli, request, id) { const path = `job/node-test-pull-request/${id}/`; const tree = PR_TREE; @@ -99,5 +99,3 @@ class PRBuild extends TestBuild { return super.formatAsMarkdown(); } } - -module.exports = { PRBuild }; diff --git a/lib/ci/build-types/test_build.js b/lib/ci/build-types/test_build.js index 3e357fb11..4de6b274a 100644 --- a/lib/ci/build-types/test_build.js +++ b/lib/ci/build-types/test_build.js @@ -1,14 +1,13 @@ -'use strict'; +import chalk from 'chalk'; -const chalk = require('chalk'); -const { Job } = require('./job'); -const { shortSha } = require('../../utils'); -const { +import { shortSha } from '../../utils.js'; +import { fold, getNodeName, statusType -} = require('../ci_utils'); -const { CI_DOMAIN } = require('../ci_type_parser'); +} from '../ci_utils.js'; +import { CI_DOMAIN } from '../ci_type_parser.js'; +import { Job } from './job.js'; const resultName = (result) => { return result === null ? 'PENDING' : result.toUpperCase(); @@ -19,7 +18,7 @@ const getUrl = (path) => { return `https://${CI_DOMAIN}/${urlPath}`; }; -class TestBuild extends Job { +export class TestBuild extends Job { constructor(cli, request, path, tree) { super(cli, request, path, tree); @@ -185,5 +184,3 @@ class TestBuild extends Job { return JSON.parse(JSON.stringify(result)); } } - -module.exports = { TestBuild }; diff --git a/lib/ci/build-types/test_run.js b/lib/ci/build-types/test_run.js index 3645cd464..8d60dcf80 100644 --- a/lib/ci/build-types/test_run.js +++ b/lib/ci/build-types/test_run.js @@ -1,16 +1,16 @@ -'use strict'; +import { RUN_TREE } from '../jenkins_constants.js'; +import { getPath } from '../ci_utils.js'; +import CIFailureParser from '../ci_failure_parser.js'; +import { Job } from './job.js'; -const { Job } = require('./job'); -const { RUN_TREE } = require('../jenkins_constants'); -const { getPath } = require('../ci_utils'); const { FAILURE_TYPES: { NCU_FAILURE }, FAILURE_CONSTRUCTORS: { [NCU_FAILURE]: NCUFailure } -} = require('../ci_failure_parser'); +} = CIFailureParser; -class TestRun extends Job { +export class TestRun extends Job { constructor(cli, request, url) { const path = getPath(url); const tree = RUN_TREE; @@ -39,5 +39,3 @@ class TestRun extends Job { return this.parseConsoleText(); } } - -module.exports = { TestRun }; diff --git a/lib/ci/ci_failure_parser.js b/lib/ci/ci_failure_parser.js index 341086782..507f9244d 100644 --- a/lib/ci/ci_failure_parser.js +++ b/lib/ci/ci_failure_parser.js @@ -1,5 +1,3 @@ -'use strict'; - function unique(arr) { return Array.from(new Set(arr).values()); } @@ -286,7 +284,7 @@ const FAILURE_FILTERS = [{ } }]; -class CIFailureParser { +export default class CIFailureParser { constructor(ctx, text) { this.ctx = ctx; this.text = text; @@ -325,4 +323,3 @@ CIFailureParser.FAILURE_TYPES_NAME = { NCU_FAILURE: 'node-core-utils failure', RESUME_FAILURE: 'resume failure' }; -module.exports = CIFailureParser; diff --git a/lib/ci/ci_type_parser.js b/lib/ci/ci_type_parser.js index 2d7abed8e..5adfde19a 100644 --- a/lib/ci/ci_type_parser.js +++ b/lib/ci/ci_type_parser.js @@ -1,11 +1,9 @@ -'use strict'; - -const { parsePRFromURL } = require('../links'); -const PRData = require('../pr_data'); -const { ascending } = require('../utils'); +import { parsePRFromURL } from '../links.js'; +import PRData from '../pr_data.js'; +import { ascending } from '../utils.js'; const CI_URL_RE = /\/\/ci\.nodejs\.org(\S+)/mg; -const CI_DOMAIN = 'ci.nodejs.org'; +export const CI_DOMAIN = 'ci.nodejs.org'; // constants const CITGM = 'CITGM'; @@ -24,14 +22,14 @@ const CI_TYPE_ENUM = { JOB_CI: 1 << 2 }; -const CI_PROVIDERS = { +export const CI_PROVIDERS = { GITHUB: 'github-check', NODEJS: 'nodejs' }; const { JOB_CI, FULL_CI } = CI_TYPE_ENUM; -const CI_TYPES = new Map([ +export const CI_TYPES = new Map([ [CITGM, { name: 'CITGM', jobName: 'citgm-smoker', @@ -94,7 +92,7 @@ const CI_TYPES = new Map([ }] ]); -function isFullCI(key) { +export function isFullCI(key) { const data = CI_TYPES.get(key); if (!data) { return false; @@ -103,7 +101,7 @@ function isFullCI(key) { } // Given a ci.nodejs.org/*** link, parse the job type and ID -function parseJobFromURL(url) { +export function parseJobFromURL(url) { if (typeof url !== 'string') { return undefined; } @@ -125,7 +123,7 @@ function parseJobFromURL(url) { /** * Parse links of CI Jobs posted in a GitHub thread */ -class JobParser { +export class JobParser { /** * @param {{bodyText: string, publishedAt: string}[]} thread */ @@ -191,23 +189,15 @@ JobParser.fromPR = async function(url, cli, request) { return new JobParser(thread); }; -module.exports = { - CI_DOMAIN, - CI_TYPES, - CI_TYPES_KEYS: { - CITGM, - CITGM_NOBUILD, - PR, - COMMIT, - BENCHMARK, - LIBUV, - V8, - NOINTL, - LINTER, - DAILY_MASTER - }, - CI_PROVIDERS, - isFullCI, - JobParser, - parseJobFromURL +export const CI_TYPES_KEYS = { + CITGM, + CITGM_NOBUILD, + PR, + COMMIT, + BENCHMARK, + LIBUV, + V8, + NOINTL, + LINTER, + DAILY_MASTER }; diff --git a/lib/ci/ci_utils.js b/lib/ci/ci_utils.js index d7e9c3343..79fa8a87e 100644 --- a/lib/ci/ci_utils.js +++ b/lib/ci/ci_utils.js @@ -1,23 +1,23 @@ -const { +import qs from 'node:querystring'; + +import { CI_DOMAIN, parseJobFromURL, CI_TYPES -} = require('./ci_type_parser'); - -const qs = require('querystring'); +} from './ci_type_parser.js'; -const statusType = { +export const statusType = { SUCCESS: 'SUCCESS', FAILURE: 'FAILURE', ABORTED: 'ABORTED', UNSTABLE: 'UNSTABLE' }; -function getPath(url) { +export function getPath(url) { return url.replace(`https://${CI_DOMAIN}/`, '').replace('api/json', ''); } -function getNodeName(url) { +export function getNodeName(url) { const re = /\/nodes=(.+?)\//; if (re.test(url)) { return url.match(re)[1]; @@ -26,17 +26,17 @@ function getNodeName(url) { return parts[parts.length - 3]; } -function fold(summary, code) { +export function fold(summary, code) { const dataBlock = '```\n' + code + '\n```'; const summaryBlock = `\n${summary}\n`; return `
${summaryBlock}\n${dataBlock}\n
`; } -function pad(any, length) { +export function pad(any, length) { return (any + '').padEnd(length); } -function markdownRow(...args) { +export function markdownRow(...args) { let result = ''; for (const item of args) { result += `| ${item} `; @@ -50,7 +50,7 @@ function filterBuild(builds, type) { .map(build => parseJobFromURL(build.url)); } -async function listBuilds(cli, request, type) { +export async function listBuilds(cli, request, type) { // assert(type === COMMIT || type === PR) const { jobName } = CI_TYPES.get(type); const tree = 'builds[url,result]'; @@ -77,7 +77,7 @@ async function listBuilds(cli, request, type) { }; } -function getHighlight(f) { +export function getHighlight(f) { if (!f.reason) { f.reason = 'failure not found'; return f.reason; @@ -101,14 +101,3 @@ function getHighlight(f) { .replace(/hudson\.plugins\.git\.GitException: /, '') .replace(/java\.io\.IOException: /, ''); } - -module.exports = { - fold, - getHighlight, - getNodeName, - getPath, - listBuilds, - markdownRow, - pad, - statusType -}; diff --git a/lib/ci/failure_aggregator.js b/lib/ci/failure_aggregator.js index bf88e4745..d8c708938 100644 --- a/lib/ci/failure_aggregator.js +++ b/lib/ci/failure_aggregator.js @@ -1,20 +1,21 @@ -'use strict'; +import _ from 'lodash'; +import chalk from 'chalk'; -const _ = require('lodash'); -const chalk = require('chalk'); -const { getMachineUrl, parsePRFromURL } = require('../links'); -const { FAILURE_TYPES_NAME } = require('./ci_failure_parser'); -const { +import { getMachineUrl, parsePRFromURL } from '../links.js'; +import CIFailureParser from './ci_failure_parser.js'; +import { parseJobFromURL, CI_TYPES -} = require('./ci_type_parser'); -const { +} from './ci_type_parser.js'; +import { fold, getHighlight, markdownRow -} = require('./ci_utils'); +} from './ci_utils.js'; -class FailureAggregator { +const { FAILURE_TYPES_NAME } = CIFailureParser; + +export class FailureAggregator { constructor(cli, data) { this.cli = cli; this.health = data[0]; @@ -149,5 +150,3 @@ class FailureAggregator { } } } - -module.exports = { FailureAggregator }; diff --git a/lib/ci/jenkins_constants.js b/lib/ci/jenkins_constants.js index ae3d18fca..ca896d156 100644 --- a/lib/ci/jenkins_constants.js +++ b/lib/ci/jenkins_constants.js @@ -4,36 +4,25 @@ const ACTION_TREE = 'actions[parameters[name,value]]'; const CHANGE_FIELDS = 'commitId,author[absoluteUrl,fullName],authorEmail,' + 'msg,date'; const CHANGE_TREE = `changeSet[items[${CHANGE_FIELDS}]]`; -const PR_TREE = +export const PR_TREE = `result,url,number,${ACTION_TREE},${CHANGE_TREE},builtOn,` + `subBuilds[${BUILD_FIELDS},build[subBuilds[${BUILD_FIELDS}]]]`; -const COMMIT_TREE = +export const COMMIT_TREE = `result,url,number,${ACTION_TREE},${CHANGE_TREE},builtOn,` + `subBuilds[${BUILD_FIELDS}]`; -const CITGM_MAIN_TREE = +export const CITGM_MAIN_TREE = `result,url,number,${ACTION_TREE},${CHANGE_TREE},builtOn`; -const FANNED_TREE = +export const FANNED_TREE = `result,url,number,subBuilds[phaseName,${BUILD_FIELDS}]`; // hudson.tasks.test.MatrixTestResult const RESULT_TREE = 'result[suites[cases[name,status]]]'; -const CITGM_REPORT_TREE = +export const CITGM_REPORT_TREE = `failCount,skipCount,totalCount,childReports[child[url],${RESULT_TREE}]`; // hudson.matrix.MatrixBuild -const BUILD_TREE = 'result,runs[url,number,result],builtOn'; -const LINTER_TREE = 'result,url,number,builtOn'; +export const BUILD_TREE = 'result,runs[url,number,result],builtOn'; +export const LINTER_TREE = 'result,url,number,builtOn'; const CAUSE_TREE = 'upstreamBuild,upstreamProject,shortDescription,_class'; -const RUN_TREE = `actions[causes[${CAUSE_TREE}]],builtOn`; - -module.exports = { - PR_TREE, - COMMIT_TREE, - CITGM_MAIN_TREE, - FANNED_TREE, - CITGM_REPORT_TREE, - BUILD_TREE, - LINTER_TREE, - RUN_TREE -}; +export const RUN_TREE = `actions[causes[${CAUSE_TREE}]],builtOn`; diff --git a/lib/ci/run_ci.js b/lib/ci/run_ci.js index 350983c16..beead3dcc 100644 --- a/lib/ci/run_ci.js +++ b/lib/ci/run_ci.js @@ -1,18 +1,16 @@ -'use strict'; +import FormData from 'form-data'; -const FormData = require('form-data'); - -const { +import { CI_DOMAIN, CI_TYPES, CI_TYPES_KEYS -} = require('./ci_type_parser'); +} from './ci_type_parser.js'; -const CI_CRUMB_URL = `https://${CI_DOMAIN}/crumbIssuer/api/json`; +export const CI_CRUMB_URL = `https://${CI_DOMAIN}/crumbIssuer/api/json`; const CI_PR_NAME = CI_TYPES.get(CI_TYPES_KEYS.PR).jobName; -const CI_PR_URL = `https://${CI_DOMAIN}/job/${CI_PR_NAME}/build`; +export const CI_PR_URL = `https://${CI_DOMAIN}/job/${CI_PR_NAME}/build`; -class RunPRJob { +export class RunPRJob { constructor(cli, request, owner, repo, prid) { this.cli = cli; this.request = request; @@ -80,5 +78,3 @@ class RunPRJob { return true; } } - -module.exports = { RunPRJob, CI_CRUMB_URL, CI_PR_URL }; diff --git a/lib/cli.js b/lib/cli.js index cde951773..f42e248a8 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -1,10 +1,8 @@ -'use strict'; +import ora from 'ora'; +import chalk from 'chalk'; +import inquirer from 'inquirer'; -const ora = require('ora'); -const chalk = require('chalk'); -const inquirer = require('inquirer'); - -const { warning, error, info, success } = require('./figures'); +import { warning, error, info, success } from './figures.js'; const SPINNER_STATUS = { SUCCESS: 'success', @@ -25,7 +23,7 @@ function head(text, length = 11) { return chalk.bold(text.padEnd(length)); } -class CLI { +export default class CLI { constructor(stream) { this.stream = stream || process.stderr; this.spinner = ora({ stream: this.stream }); @@ -173,5 +171,3 @@ class CLI { CLI.SPINNER_STATUS = SPINNER_STATUS; CLI.QUESTION_TYPE = QUESTION_TYPE; - -module.exports = CLI; diff --git a/lib/collaborators.js b/lib/collaborators.js index 3049de124..2bb25f067 100644 --- a/lib/collaborators.js +++ b/lib/collaborators.js @@ -1,6 +1,4 @@ -'use strict'; - -const fs = require('fs'); +import fs from 'node:fs'; const TSC_TITLE = '### TSC (Technical Steering Committee)'; const TSCE_TITLE = '### TSC Emeriti'; @@ -11,7 +9,7 @@ const CONTACT_RE = /\* +\[(.+?)\]\(.+?\) +-\s+\*\*([^*]+?)\*\* +(?:<|\\<|<<)( const TSC = 'TSC'; const COLLABORATOR = 'COLLABORATOR'; -class Collaborator { +export class Collaborator { constructor(login, name, email, type) { this.login = login; // This is not lowercased this.name = name; @@ -43,7 +41,7 @@ Collaborator.TYPES = { TSC, COLLABORATOR }; -async function getCollaborators(cli, request, argv) { +export async function getCollaborators(cli, request, argv) { const { readme, owner, repo } = argv; let readmeText; if (readme) { @@ -130,13 +128,7 @@ function parseCollaborators(readme, cli) { * @param {Map} collaborators * @param {{login?: string}} user */ -function isCollaborator(collaborators, user) { +export function isCollaborator(collaborators, user) { return (user && user.login && // could be a ghost collaborators.get(user.login.toLowerCase())); } - -module.exports = { - getCollaborators, - Collaborator, - isCollaborator -}; diff --git a/lib/config.js b/lib/config.js index 8eaf40ee3..3fb937d97 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,18 +1,13 @@ -'use strict'; +import path from 'node:path'; +import os from 'node:os'; -const path = require('path'); -const os = require('os'); -const { readJson, writeJson } = require('./file'); +import { readJson, writeJson } from './file.js'; -const GLOBAL_CONFIG = Symbol('globalConfig'); -const PROJECT_CONFIG = Symbol('projectConfig'); -const LOCAL_CONFIG = Symbol('localConfig'); +export const GLOBAL_CONFIG = Symbol('globalConfig'); +export const PROJECT_CONFIG = Symbol('projectConfig'); +export const LOCAL_CONFIG = Symbol('localConfig'); -exports.GLOBAL_CONFIG = GLOBAL_CONFIG; -exports.PROJECT_CONFIG = PROJECT_CONFIG; -exports.LOCAL_CONFIG = LOCAL_CONFIG; - -function getNcurcPath() { +export function getNcurcPath() { if (process.env.XDG_CONFIG_HOME !== 'undefined' && process.env.XDG_CONFIG_HOME !== undefined) { return path.join(process.env.XDG_CONFIG_HOME, 'ncurc'); @@ -20,21 +15,20 @@ function getNcurcPath() { return path.join(os.homedir(), '.ncurc'); } } -exports.getNcurcPath = getNcurcPath; -exports.getMergedConfig = function(dir, home) { - const globalConfig = exports.getConfig(GLOBAL_CONFIG, home); - const projectConfig = exports.getConfig(PROJECT_CONFIG, dir); - const localConfig = exports.getConfig(LOCAL_CONFIG, dir); +export function getMergedConfig(dir, home) { + const globalConfig = getConfig(GLOBAL_CONFIG, home); + const projectConfig = getConfig(PROJECT_CONFIG, dir); + const localConfig = getConfig(LOCAL_CONFIG, dir); return Object.assign(globalConfig, projectConfig, localConfig); }; -exports.getConfig = function(configType, dir) { - const configPath = exports.getConfigPath(configType, dir); +export function getConfig(configType, dir) { + const configPath = getConfigPath(configType, dir); return readJson(configPath); }; -exports.getConfigPath = function(configType, dir) { +export function getConfigPath(configType, dir) { switch (configType) { case GLOBAL_CONFIG: return getNcurcPath(); @@ -43,7 +37,7 @@ exports.getConfigPath = function(configType, dir) { return projectRcPath; } case LOCAL_CONFIG: { - const ncuDir = exports.getNcuDir(dir); + const ncuDir = getNcuDir(dir); const configPath = path.join(ncuDir, 'config'); return configPath; } @@ -52,23 +46,23 @@ exports.getConfigPath = function(configType, dir) { } }; -exports.writeConfig = function(configType, obj, dir) { - writeJson(exports.getConfigPath(configType, dir), obj); +export function writeConfig(configType, obj, dir) { + writeJson(getConfigPath(configType, dir), obj); }; -exports.updateConfig = function(configType, obj, dir) { - const config = exports.getConfig(configType, dir); - const configPath = exports.getConfigPath(configType, dir); +export function updateConfig(configType, obj, dir) { + const config = getConfig(configType, dir); + const configPath = getConfigPath(configType, dir); writeJson(configPath, Object.assign(config, obj)); }; -exports.getHomeDir = function(home) { +export function getHomeDir(home) { if (process.env.XDG_CONFIG_HOME) { return process.env.XDG_CONFIG_HOME; } return home || os.homedir(); }; -exports.getNcuDir = function(dir) { +export function getNcuDir(dir) { return path.join(dir || process.cwd(), '.ncu'); }; diff --git a/lib/deprecations.js b/lib/deprecations.js index ae9a31193..0118762b0 100644 --- a/lib/deprecations.js +++ b/lib/deprecations.js @@ -1,13 +1,12 @@ -'use strict'; +import { promises as fs } from 'node:fs'; +import path from 'node:path'; -const { promises: fs } = require('fs'); -const path = require('path'); -const replace = require('replace-in-file'); +import replace from 'replace-in-file'; const newDeprecationPattern = /<\s*a id="DEP0([X]+[0-9]*)+"[^>]*><\s*\/\s*a>/g; -async function getUnmarkedDeprecations() { +export async function getUnmarkedDeprecations() { const deprecationFilePath = path.resolve('doc', 'api', 'deprecations.md'); const deprecationFile = await fs.readFile(deprecationFilePath, 'utf8'); @@ -18,7 +17,7 @@ async function getUnmarkedDeprecations() { return unmarkedDeprecations; } -async function updateDeprecations(unmarkedDeprecations) { +export async function updateDeprecations(unmarkedDeprecations) { const deprecationPattern = /<\s*a id="DEP0([0-9]{3})+"[^>]*><\s*\/\s*a>/g; @@ -49,8 +48,3 @@ async function updateDeprecations(unmarkedDeprecations) { depNumber++; } } - -module.exports = { - updateDeprecations, - getUnmarkedDeprecations -}; diff --git a/lib/figures.js b/lib/figures.js index 814b69ab2..abca9f23f 100644 --- a/lib/figures.js +++ b/lib/figures.js @@ -1,13 +1,7 @@ -'use strict'; +import chalk from 'chalk'; +import figures from 'figures'; -const chalk = require('chalk'); -const { - tick, cross, info: infoRaw, warning: warningRaw -} = require('figures'); - -module.exports = { - warning: chalk.yellow(warningRaw), - error: chalk.red(cross), - info: chalk.blue(infoRaw), - success: chalk.green(tick) -}; +export const warning = chalk.yellow(figures.warning); +export const error = chalk.red(figures.cross); +export const info = chalk.blue(figures.info); +export const success = chalk.green(figures.tick); diff --git a/lib/file.js b/lib/file.js index 3213f4ddf..b556fca25 100644 --- a/lib/file.js +++ b/lib/file.js @@ -1,9 +1,7 @@ -'use strict'; +import fs from 'node:fs'; +import path from 'node:path'; -const fs = require('fs'); -const path = require('path'); - -exports.appendFile = function(file, content) { +export function appendFile(file, content) { const parts = path.parse(file); if (!fs.existsSync(parts.dir)) { fs.mkdirSync(parts.dir, { recursive: true }); @@ -12,7 +10,7 @@ exports.appendFile = function(file, content) { fs.appendFileSync(file, content, 'utf8'); }; -exports.writeFile = function(file, content) { +export function writeFile(file, content) { const parts = path.parse(file); if (parts.dir !== '' && !fs.existsSync(parts.dir)) { fs.mkdirSync(parts.dir, { recursive: true }); @@ -21,19 +19,19 @@ exports.writeFile = function(file, content) { fs.writeFileSync(file, content, 'utf8'); }; -exports.writeJson = function(file, obj) { - exports.writeFile(file, JSON.stringify(obj, null, 2)); +export function writeJson(file, obj) { + writeFile(file, JSON.stringify(obj, null, 2)); }; -exports.readFile = function(file) { +export function readFile(file) { if (fs.existsSync(file)) { return fs.readFileSync(file, 'utf8'); } return ''; }; -exports.readJson = function(file) { - const content = exports.readFile(file); +export function readJson(file) { + const content = readFile(file); if (content) { return JSON.parse(content); } diff --git a/lib/github/tree.js b/lib/github/tree.js index a64bb22f5..4f1668619 100644 --- a/lib/github/tree.js +++ b/lib/github/tree.js @@ -1,10 +1,9 @@ -'use strict'; +import { flatten } from '../utils.js'; const COMMIT_QUERY = 'LastCommit'; const TREE_QUERY = 'TreeEntries'; -const { flatten } = require('../utils'); -class GitHubTree { +export default class GitHubTree { constructor(cli, request, argv) { this.cli = cli; this.request = request; @@ -143,7 +142,7 @@ function clean(path) { } // Uncomment this when testing to avoid extra network costs -// const Cache = require('../cache'); +// import Cache from '../cache.js'; // const treeCache = new Cache(); // treeCache.wrap(GitHubTree, { @@ -161,5 +160,3 @@ function clean(path) { // } // }); // treeCache.enable(); - -module.exports = GitHubTree; diff --git a/lib/landing_session.js b/lib/landing_session.js index 92749334c..e5115fe4b 100644 --- a/lib/landing_session.js +++ b/lib/landing_session.js @@ -1,19 +1,16 @@ -'use strict'; +import os from 'node:os'; -const path = require('path'); -const os = require('os'); -const { +import { getUnmarkedDeprecations, updateDeprecations -} = require('./deprecations'); - -const { +} from './deprecations.js'; +import { runAsync, runSync, forceRunAsync -} = require('./run'); -const Session = require('./session'); -const { +} from './run.js'; +import Session from './session.js'; +import { shortSha, isGhAvailable, getEditor -} = require('./utils'); +} from './utils.js'; const isWindows = process.platform === 'win32'; @@ -23,7 +20,7 @@ const LINT_RESULTS = { SUCCESS: 'success' }; -class LandingSession extends Session { +export default class LandingSession extends Session { constructor(cli, req, dir, { prid, backport, lint, autorebase, fixupAll, checkCI, oneCommitMax @@ -397,9 +394,9 @@ class LandingSession extends Session { } } const strayVerbose = this.getStrayCommits(true); - const validateCommand = path.join( - __dirname, - '../node_modules/.bin/core-validate-commit' + (isWindows ? '.cmd' : '') + const validateCommand = new URL( + '../node_modules/.bin/core-validate-commit' + (isWindows ? '.cmd' : ''), + import.meta.url ); try { @@ -494,5 +491,3 @@ class LandingSession extends Session { } } } - -module.exports = LandingSession; diff --git a/lib/links.js b/lib/links.js index d21cd9b1e..ad498b8aa 100644 --- a/lib/links.js +++ b/lib/links.js @@ -1,16 +1,15 @@ -'use strict'; +import cheerio from 'cheerio'; const FIXES_RE = /(Close[ds]?|Fix(e[ds])?|Resolve[sd]?)\s*:\s*(\S+)/mgi; const FIX_RE = /(Close[ds]?|Fix(e[ds])?|Resolve[sd]?)\s*:\s*(\S+)/i; const REFS_RE = /Refs?\s*:\s*(\S+)/mgi; const REF_RE = /Refs?\s*:\s*(\S+)/i; const PR_RE = /PR-URL\s*:\s*(\S+)/i; -const cheerio = require('cheerio'); /** * Most of this class is ported from node-review */ -class LinkParser { +export class LinkParser { constructor(owner, repo, html) { this.owner = owner; this.repo = repo; @@ -90,7 +89,7 @@ class LinkParser { const GITHUB_PULL_REQUEST_URL = /github.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/; -LinkParser.parsePRFromURL = function(url) { +export function parsePRFromURL(url) { if (typeof url !== 'string') { return undefined; } @@ -105,16 +104,16 @@ LinkParser.parsePRFromURL = function(url) { return undefined; }; -LinkParser.getPrURL = function({ owner, repo, prid }) { +export function getPrURL({ owner, repo, prid }) { return `https://github.com/${owner}/${repo}/pull/${prid}`; }; -LinkParser.getMachineUrl = function(name) { +export function getMachineUrl(name) { return `[${name}](https://ci.nodejs.org/computer/${name}/)`; }; const PR_URL_RE = /PR-URL: https:\/\/github.com\/.+/; -LinkParser.parsePrURL = function(text) { +export function parsePrURL(text) { if (typeof text !== 'string') { return undefined; } @@ -122,7 +121,5 @@ LinkParser.parsePrURL = function(text) { if (!match) { return undefined; } - return LinkParser.parsePRFromURL(match[0]); + return parsePRFromURL(match[0]); }; - -module.exports = LinkParser; diff --git a/lib/mergeable_state.js b/lib/mergeable_state.js index 1c2a11252..8c86a2dd3 100644 --- a/lib/mergeable_state.js +++ b/lib/mergeable_state.js @@ -1,7 +1,3 @@ -'use strict'; - -module.exports = { - CONFLICTING: 'CONFLICTING', - MERGEABLE: 'MERGEABLE', - UNKNOWN: 'UNKNOWN' -}; +export const CONFLICTING = 'CONFLICTING'; +export const MERGEABLE = 'MERGEABLE'; +export const UNKNOWN = 'UNKNOWN'; diff --git a/lib/metadata_gen.js b/lib/metadata_gen.js index 3214adb51..9a100791a 100644 --- a/lib/metadata_gen.js +++ b/lib/metadata_gen.js @@ -1,11 +1,9 @@ -'use strict'; - -const LinkParser = require('./links'); +import { LinkParser } from './links.js'; /** * @typedef {{reviewer: Collaborator}} Reviewer */ -class MetadataGenerator { +export default class MetadataGenerator { /** * @param {PRData} data */ @@ -61,5 +59,3 @@ class MetadataGenerator { return meta.join('\n'); } } - -module.exports = MetadataGenerator; diff --git a/lib/pr_checker.js b/lib/pr_checker.js index 9463f946d..fff21f696 100644 --- a/lib/pr_checker.js +++ b/lib/pr_checker.js @@ -1,4 +1,21 @@ -'use strict'; +import { + REVIEW_SOURCES +} from './reviews.js'; +import { + CONFLICTING +} from './mergeable_state.js'; +import { + shortSha +} from './utils.js'; +import { + JobParser, + CI_TYPES, + CI_PROVIDERS, + isFullCI +} from './ci/ci_type_parser.js'; +import { PRBuild } from './ci/build-types/pr_build.js'; + +const { FROM_COMMENT, FROM_REVIEW_COMMENT } = REVIEW_SOURCES; const SECOND = 1000; const MINUTE = SECOND * 60; @@ -10,28 +27,9 @@ const WAIT_TIME_SINGLE_APPROVAL = 24 * 7; const GITHUB_SUCCESS_CONCLUSIONS = ['SUCCESS', 'NEUTRAL', 'SKIPPED']; const FAST_TRACK_RE = /^Fast-track has been requested by @(.+?)\. Please 👍 to approve\.$/; - -const { - REVIEW_SOURCES: { FROM_COMMENT, FROM_REVIEW_COMMENT } -} = require('./reviews'); -const { - CONFLICTING -} = require('./mergeable_state'); -const { - shortSha -} = require('./utils'); - -const { - JobParser, - CI_TYPES, - CI_PROVIDERS, - isFullCI -} = require('./ci/ci_type_parser'); -const { PRBuild } = require('./ci/build-types/pr_build'); - const GIT_CONFIG_GUIDE_URL = 'https://github.com/nodejs/node/blob/99b1ada/doc/guides/contributing/pull-requests.md#step-1-fork'; -class PRChecker { +export default class PRChecker { /** * @param {{}} cli * @param {PRData} data @@ -580,5 +578,3 @@ class PRChecker { return true; } } - -module.exports = PRChecker; diff --git a/lib/pr_data.js b/lib/pr_data.js index 8468db19a..53379b8ae 100644 --- a/lib/pr_data.js +++ b/lib/pr_data.js @@ -1,11 +1,8 @@ -'use strict'; - -const { getCollaborators } = require('./collaborators'); -const { ReviewAnalyzer } = require('./reviews'); - -const { +import { getCollaborators } from './collaborators.js'; +import { ReviewAnalyzer } from './reviews.js'; +import { FIRST_TIME_CONTRIBUTOR, FIRST_TIMER -} = require('./user_status'); +} from './user_status.js'; // lib/queries/*.gql file names const PR_QUERY = 'PR'; @@ -13,7 +10,7 @@ const REVIEWS_QUERY = 'Reviews'; const COMMENTS_QUERY = 'PRComments'; const COMMITS_QUERY = 'PRCommits'; -class PRData { +export default class PRData { /** * @param {Object} argv * @param {Object} cli @@ -116,5 +113,3 @@ class PRData { return assoc === FIRST_TIME_CONTRIBUTOR || assoc === FIRST_TIMER; } }; - -module.exports = PRData; diff --git a/lib/pr_summary.js b/lib/pr_summary.js index 6fced93f0..fc0fe91e0 100644 --- a/lib/pr_summary.js +++ b/lib/pr_summary.js @@ -1,6 +1,4 @@ -'use strict'; - -class PRSummary { +export default class PRSummary { /** * @param {Object} prid * @param {Object} cli @@ -62,5 +60,3 @@ class PRSummary { } }; } - -module.exports = PRSummary; diff --git a/lib/prepare_release.js b/lib/prepare_release.js index c4a946df9..fc918fc8a 100644 --- a/lib/prepare_release.js +++ b/lib/prepare_release.js @@ -1,26 +1,25 @@ -'use strict'; +import path from 'node:path'; +import { promises as fs } from 'node:fs'; -const path = require('path'); -const { promises: fs } = require('fs'); -const semver = require('semver'); -const replace = require('replace-in-file'); +import semver from 'semver'; +import replace from 'replace-in-file'; -const { getMergedConfig } = require('./config'); -const { runAsync, runSync } = require('./run'); -const { writeJson, readJson } = require('./file'); -const { +import { getMergedConfig } from './config.js'; +import { runAsync, runSync } from './run.js'; +import { writeJson, readJson } from './file.js'; +import { getUnmarkedDeprecations, updateDeprecations -} = require('./deprecations'); -const { +} from './deprecations.js'; +import { getEOLDate, getStartLTSBlurb, updateTestProcessRelease -} = require('./release/utils'); +} from './release/utils.js'; const isWindows = process.platform === 'win32'; -class ReleasePreparation { +export default class ReleasePreparation { constructor(argv, cli, dir) { this.cli = cli; this.dir = dir; @@ -289,9 +288,9 @@ class ReleasePreparation { } getChangelog() { - const changelogMaker = path.join( - __dirname, - '../node_modules/.bin/changelog-maker' + (isWindows ? '.cmd' : '') + const changelogMaker = new URL( + '../node_modules/.bin/changelog-maker' + (isWindows ? '.cmd' : ''), + import.meta.url ); return runSync(changelogMaker, [ @@ -610,9 +609,9 @@ class ReleasePreparation { ]; } - const branchDiff = path.join( - __dirname, - '../node_modules/.bin/branch-diff' + (isWindows ? '.cmd' : '') + const branchDiff = new URL( + '../node_modules/.bin/branch-diff' + (isWindows ? '.cmd' : ''), + import.meta.url ); return runSync(branchDiff, branchDiffOptions); @@ -645,5 +644,3 @@ class ReleasePreparation { return true; } } - -module.exports = ReleasePreparation; diff --git a/lib/proxy.js b/lib/proxy.js index deae20ac3..f01cdc43a 100644 --- a/lib/proxy.js +++ b/lib/proxy.js @@ -1,9 +1,11 @@ -const ProxyAgent = require('proxy-agent'); -const { globalAgent } = require('https'); -const { spawnSync } = require('child_process'); -const { getMergedConfig } = require('./config'); +import { globalAgent } from 'node:https'; +import { spawnSync } from 'child_process'; -function proxy() { +import ProxyAgent from 'proxy-agent'; + +import { getMergedConfig } from './config.js'; + +export default function proxy() { let proxyUrl = getMergedConfig().proxy; if (proxyUrl == null || proxyUrl === '') { proxyUrl = spawnSync( @@ -17,5 +19,3 @@ function proxy() { return new ProxyAgent(proxyUrl); } } - -module.exports = proxy; diff --git a/lib/release/utils.js b/lib/release/utils.js index 75362f2bd..78b316c10 100644 --- a/lib/release/utils.js +++ b/lib/release/utils.js @@ -1,20 +1,18 @@ -'use strict'; - -function getEOLDate(ltsStartDate) { +export function getEOLDate(ltsStartDate) { // Maintenance LTS lasts for 18 months. const result = getLTSMaintenanceStartDate(ltsStartDate); result.setMonth(result.getMonth() + 18); return result; } -function getLTSMaintenanceStartDate(ltsStartDate) { +export function getLTSMaintenanceStartDate(ltsStartDate) { // Active LTS lasts for one year. const result = new Date(ltsStartDate); result.setMonth(result.getMonth() + 12); return result; } -function getStartLTSBlurb({ date, ltsCodename, versionComponents }) { +export function getStartLTSBlurb({ date, ltsCodename, versionComponents }) { const dateFormat = { month: 'long', year: 'numeric' }; // TODO pull these from the schedule.json in the Release repo? const mainDate = getLTSMaintenanceStartDate(date); @@ -32,7 +30,8 @@ function getStartLTSBlurb({ date, ltsCodename, versionComponents }) { ].join('\n'); } -function updateTestProcessRelease(test, { versionComponents, ltsCodename }) { +export function updateTestProcessRelease(test, options) { + const { versionComponents, ltsCodename } = options; if (test.includes(ltsCodename)) { return test; } @@ -52,10 +51,3 @@ function updateTestProcessRelease(test, { versionComponents, ltsCodename }) { } return outLines.join('\n'); } - -module.exports = { - getEOLDate, - getLTSMaintenanceStartDate, - getStartLTSBlurb, - updateTestProcessRelease -}; diff --git a/lib/request.js b/lib/request.js index 8ba878b8e..9e9acfc05 100644 --- a/lib/request.js +++ b/lib/request.js @@ -1,14 +1,13 @@ -'use strict'; +import fs from 'node:fs'; -const fetch = require('node-fetch'); -const fs = require('fs'); -const path = require('path'); -const { CI_DOMAIN } = require('./ci/ci_type_parser'); -const proxy = require('./proxy'); -const { +import fetch from 'node-fetch'; + +import { CI_DOMAIN } from './ci/ci_type_parser.js'; +import proxy from './proxy.js'; +import { isDebugVerbosity, debuglog -} = require('./verbosity'); +} from './verbosity.js'; function wrappedFetch(url, options, ...args) { if (isDebugVerbosity()) { @@ -17,14 +16,14 @@ function wrappedFetch(url, options, ...args) { return fetch(url, options, ...args); } -class Request { +export default class Request { constructor(credentials) { this.credentials = credentials; this.proxyAgent = proxy(); } loadQuery(file) { - const filePath = path.resolve(__dirname, 'queries', `${file}.gql`); + const filePath = new URL(`./queries/${file}.gql`, import.meta.url); return fs.readFileSync(filePath, 'utf8'); } @@ -152,5 +151,3 @@ class Request { return all; } } - -module.exports = Request; diff --git a/lib/review_state.js b/lib/review_state.js index 16410e518..3ae9a8b89 100644 --- a/lib/review_state.js +++ b/lib/review_state.js @@ -1,9 +1,5 @@ -'use strict'; - -module.exports = { - PENDING: 'PENDING', - COMMENTED: 'COMMENTED', - APPROVED: 'APPROVED', - CHANGES_REQUESTED: 'CHANGES_REQUESTED', - DISMISSED: 'DISMISSED' -}; +export const PENDING = 'PENDING'; +export const COMMENTED = 'COMMENTED'; +export const APPROVED = 'APPROVED'; +export const CHANGES_REQUESTED = 'CHANGES_REQUESTED'; +export const DISMISSED = 'DISMISSED'; diff --git a/lib/reviews.js b/lib/reviews.js index acba509c9..ac51a60b9 100644 --- a/lib/reviews.js +++ b/lib/reviews.js @@ -1,15 +1,15 @@ -'use strict'; -const { +import { PENDING, COMMENTED, APPROVED, CHANGES_REQUESTED, DISMISSED -} = require('./review_state'); -const { isCollaborator } = require('./collaborators'); -const { ascending } = require('./utils'); +} from './review_state.js'; +import { isCollaborator } from './collaborators.js'; +import { ascending } from './utils.js'; + const LGTM_RE = /^lgtm\W?$/i; const FROM_REVIEW = 'review'; const FROM_COMMENT = 'comment'; const FROM_REVIEW_COMMENT = 'review_comment'; -class Review { +export class Review { /** * @param {string} state * @param {string} date // ISO date string @@ -38,7 +38,7 @@ class Review { * @property {string} publishedAt * */ -class ReviewAnalyzer { +export class ReviewAnalyzer { /** * @param {PRData} data */ @@ -173,12 +173,6 @@ class ReviewAnalyzer { } } -const REVIEW_SOURCES = { +export const REVIEW_SOURCES = { FROM_COMMENT, FROM_REVIEW, FROM_REVIEW_COMMENT }; - -module.exports = { - ReviewAnalyzer, - Review, - REVIEW_SOURCES -}; diff --git a/lib/run.js b/lib/run.js index 9be14f1d0..2fa3f655b 100644 --- a/lib/run.js +++ b/lib/run.js @@ -1,17 +1,21 @@ -'use strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; -const { spawn, spawnSync } = require('child_process'); -const { +import { isDebugVerbosity, debuglog -} = require('./verbosity'); -const IGNORE = '__ignore__'; +} from './verbosity.js'; + +export const IGNORE = '__ignore__'; function runAsyncBase(cmd, args, { ignoreFailure = true, spawnArgs, captureStdout = false } = {}) { + if (cmd instanceof URL) { + cmd = fileURLToPath(cmd); + } return new Promise((resolve, reject) => { const opt = Object.assign({ cwd: process.cwd(), @@ -46,7 +50,7 @@ function runAsyncBase(cmd, args, { }); } -exports.forceRunAsync = function(cmd, args, options) { +export function forceRunAsync(cmd, args, options) { return runAsyncBase(cmd, args, options).catch((error) => { if (error.message !== IGNORE) { if (!error.messageOnly) { @@ -57,20 +61,23 @@ exports.forceRunAsync = function(cmd, args, options) { }); }; -exports.runPromise = function runAsync(promise) { +export function runPromise(promise) { return promise.catch((error) => { if (error.message !== IGNORE) { console.error(error); } - exports.exit(); + exit(); }); }; -exports.runAsync = function(cmd, args, options) { - return exports.runPromise(runAsyncBase(cmd, args, options)); +export function runAsync(cmd, args, options) { + return runPromise(runAsyncBase(cmd, args, options)); }; -exports.runSync = function(cmd, args, options) { +export function runSync(cmd, args, options) { + if (cmd instanceof URL) { + cmd = fileURLToPath(cmd); + } const opt = Object.assign({ cwd: process.cwd() }, options); @@ -88,8 +95,6 @@ exports.runSync = function(cmd, args, options) { } }; -exports.exit = function() { +export function exit() { process.exit(1); }; - -exports.IGNORE = IGNORE; diff --git a/lib/session.js b/lib/session.js index c424810d2..9200930e4 100644 --- a/lib/session.js +++ b/lib/session.js @@ -1,22 +1,22 @@ -'use strict'; - -const path = require('path'); -const fs = require('fs'); -const { getMergedConfig, getNcuDir } = require('./config'); -const rimraf = require('rimraf'); -const { readJson, writeJson, readFile, writeFile } = require('./file'); -const { +import path from 'node:path'; +import fs from 'node:fs'; + +import rimraf from 'rimraf'; + +import { getMergedConfig, getNcuDir } from './config.js'; +import { readJson, writeJson, readFile, writeFile } from './file.js'; +import { runAsync, runSync, forceRunAsync -} = require('./run'); -const { +} from './run.js'; +import { shortSha -} = require('./utils'); +} from './utils.js'; const APPLYING = 'APPLYING'; const STARTED = 'STARTED'; const AMENDING = 'AMENDING'; -class Session { +export default class Session { constructor(cli, dir, prid) { this.cli = cli; this.dir = dir; @@ -414,5 +414,3 @@ class Session { // TODO warn if backporting onto master branch } } - -module.exports = Session; diff --git a/lib/sync_session.js b/lib/sync_session.js index 5c0920882..7e8f86fe3 100644 --- a/lib/sync_session.js +++ b/lib/sync_session.js @@ -1,8 +1,6 @@ -'use strict'; +import Session from './session.js'; -const Session = require('./session'); - -class SyncSession extends Session { +export default class SyncSession extends Session { // eslint-disable-next-line no-useless-constructor constructor(cli, dir) { super(cli, dir); @@ -15,5 +13,3 @@ class SyncSession extends Session { return this.tryResetHead(); } } - -module.exports = SyncSession; diff --git a/lib/team_info.js b/lib/team_info.js index aaad8c59f..3446ed420 100644 --- a/lib/team_info.js +++ b/lib/team_info.js @@ -1,7 +1,5 @@ -'use strict'; - -const { readFile, writeFile } = require('./file'); -const { ascending } = require('./utils'); +import { readFile, writeFile } from './file.js'; +import { ascending } from './utils.js'; const TEAM_QUERY = 'Team'; @@ -18,7 +16,7 @@ function key(org, team) { return `${org}/${team}`; } -class TeamInfo { +export default class TeamInfo { constructor(cli, request, org, team) { this.cli = cli; this.request = request; @@ -95,5 +93,3 @@ TeamInfo.update = async function(cli, request, content) { return newContent; }; - -module.exports = TeamInfo; diff --git a/lib/update-v8/applyNodeChanges.js b/lib/update-v8/applyNodeChanges.js index 1aace2bcc..806e1d253 100644 --- a/lib/update-v8/applyNodeChanges.js +++ b/lib/update-v8/applyNodeChanges.js @@ -1,15 +1,13 @@ -'use strict'; +import path from 'node:path'; -const path = require('path'); +import { Listr } from 'listr2'; -const { Listr } = require('listr2'); - -const { +import { getNodeV8Version, filterForVersion, replaceGitignore, removeDirectory -} = require('./util'); +} from './util.js'; const nodeChanges = [ { @@ -18,7 +16,7 @@ const nodeChanges = [ } ]; -function applyNodeChanges() { +export default function applyNodeChanges() { return { title: 'Apply Node-specific changes', task: async(ctx) => { @@ -44,5 +42,3 @@ function removeEuStrip() { } }; } - -module.exports = applyNodeChanges; diff --git a/lib/update-v8/backport.js b/lib/update-v8/backport.js index 15c3f75c0..8bc86c5ac 100644 --- a/lib/update-v8/backport.js +++ b/lib/update-v8/backport.js @@ -1,21 +1,16 @@ -'use strict'; +import path from 'node:path'; +import { + promises as fs +} from 'node:fs'; -const path = require('path'); +import inquirer from 'inquirer'; +import { Listr } from 'listr2'; -const { - promises: { - readFile, - writeFile - } -} = require('fs'); -const inquirer = require('inquirer'); -const { Listr } = require('listr2'); - -const { shortSha } = require('../utils'); +import { shortSha } from '../utils.js'; -const common = require('./common'); +import { getCurrentV8Version } from './common.js'; -exports.checkOptions = async function checkOptions(options) { +export async function checkOptions(options) { if (options.sha.length > 1 && options.squash) { const { wantSquash } = await inquirer.prompt([{ type: 'confirm', @@ -32,9 +27,9 @@ exports.checkOptions = async function checkOptions(options) { } }; -exports.doBackport = function doBackport(options) { +export function doBackport(options) { const todo = [ - common.getCurrentV8Version(), + getCurrentV8Version(), generatePatches() ]; @@ -224,12 +219,12 @@ function incrementV8Version() { task: async(ctx) => { const incremented = ++ctx.currentVersion.patch; const versionHPath = `${ctx.nodeDir}/deps/v8/include/v8-version.h`; - let versionH = await readFile(versionHPath, 'utf8'); + let versionH = await fs.readFile(versionHPath, 'utf8'); versionH = versionH.replace( /V8_PATCH_LEVEL (\d+)/, `V8_PATCH_LEVEL ${incremented}` ); - await writeFile(versionHPath, versionH); + await fs.writeFile(versionHPath, versionH); } }; } @@ -240,11 +235,11 @@ function incrementEmbedderVersion() { title: 'Increment embedder version number', task: async(ctx) => { const commonGypiPath = path.join(ctx.nodeDir, 'common.gypi'); - const commonGypi = await readFile(commonGypiPath, 'utf8'); + const commonGypi = await fs.readFile(commonGypiPath, 'utf8'); const embedderValue = parseInt(embedderRegex.exec(commonGypi)[1], 10); const embedderString = `'v8_embedder_string': '-node.${embedderValue + 1}'`; - await writeFile( + await fs.writeFile( commonGypiPath, commonGypi.replace(embedderRegex, embedderString) ); diff --git a/lib/update-v8/commitUpdate.js b/lib/update-v8/commitUpdate.js index b12669ac6..5bed246bf 100644 --- a/lib/update-v8/commitUpdate.js +++ b/lib/update-v8/commitUpdate.js @@ -1,12 +1,10 @@ -'use strict'; +import { getNodeV8Version } from './util.js'; -const util = require('./util'); - -module.exports = function() { +export default function commitUpdate() { return { title: 'Commit V8 update', task: async(ctx) => { - const newV8Version = await util.getNodeV8Version(ctx.nodeDir); + const newV8Version = await getNodeV8Version(ctx.nodeDir); await ctx.execGitNode('add', ['deps/v8']); const moreArgs = []; let message; diff --git a/lib/update-v8/common.js b/lib/update-v8/common.js index 50e7f2c54..ca421b3c3 100644 --- a/lib/update-v8/common.js +++ b/lib/update-v8/common.js @@ -1,28 +1,21 @@ -'use strict'; +import path from 'node:path'; +import { promises as fs } from 'node:fs'; -const path = require('path'); +import { getNodeV8Version } from './util.js'; -const { - promises: { - readFile - } -} = require('fs'); - -const util = require('./util'); - -exports.getCurrentV8Version = function getCurrentV8Version() { +export function getCurrentV8Version() { return { title: 'Get current V8 version', task: async(ctx) => { - ctx.currentVersion = await util.getNodeV8Version(ctx.nodeDir); + ctx.currentVersion = await getNodeV8Version(ctx.nodeDir); } }; }; -exports.checkCwd = async function checkCwd(ctx) { +export async function checkCwd(ctx) { let isNode = false; try { - const nodeVersion = await readFile( + const nodeVersion = await fs.readFile( path.join(ctx.nodeDir, 'src/node_version.h') ); const match = /#define NODE_MAJOR_VERSION (\d+)/.exec(nodeVersion); diff --git a/lib/update-v8/constants.js b/lib/update-v8/constants.js index be9bc0718..6d46541fb 100644 --- a/lib/update-v8/constants.js +++ b/lib/update-v8/constants.js @@ -1,14 +1,13 @@ -'use strict'; +import os from 'node:os'; +import path from 'node:path'; -const homedir = require('os').homedir(); -const path = require('path'); +const homedir = os.homedir(); -const chromiumGit = 'https://chromium.googlesource.com'; +export const chromiumGit = 'https://chromium.googlesource.com'; -exports.defaultBaseDir = path.join(homedir, '.update-v8'); -exports.chromiumGit = chromiumGit; +export const defaultBaseDir = path.join(homedir, '.update-v8'); -exports.v8Git = `${chromiumGit}/v8/v8.git`; +export const v8Git = `${chromiumGit}/v8/v8.git`; const gtestReplace = `/testing/gtest/* !/testing/gtest/include @@ -31,7 +30,7 @@ const zlibIgnore = `!/third_party/zlib /third_party/zlib/contrib/tests /third_party/zlib/google/test`; -exports.v8Deps = [ +export const v8Deps = [ { name: 'trace_event', repo: 'base/trace_event/common', diff --git a/lib/update-v8/index.js b/lib/update-v8/index.js index ab8d1ab3c..cbb528ae0 100644 --- a/lib/update-v8/index.js +++ b/lib/update-v8/index.js @@ -1,15 +1,13 @@ -'use strict'; +import { Listr } from 'listr2'; -const { Listr } = require('listr2'); +import { checkOptions, doBackport } from './backport.js'; +import updateVersionNumbers from './updateVersionNumbers.js'; +import commitUpdate from './commitUpdate.js'; +import majorUpdate from './majorUpdate.js'; +import minorUpdate from './minorUpdate.js'; +import updateV8Clone from './updateV8Clone.js'; -const backport = require('./backport'); -const updateVersionNumbers = require('./updateVersionNumbers'); -const commitUpdate = require('./commitUpdate'); -const majorUpdate = require('./majorUpdate'); -const minorUpdate = require('./minorUpdate'); -const updateV8Clone = require('./updateV8Clone'); - -exports.major = function(options) { +export function major(options) { const tasks = new Listr( [updateV8Clone(), majorUpdate(), commitUpdate(), updateVersionNumbers()], getOptions(options) @@ -17,7 +15,7 @@ exports.major = function(options) { return tasks.run(options); }; -exports.minor = function(options) { +export function minor(options) { const tasks = new Listr( [updateV8Clone(), minorUpdate(), commitUpdate()], getOptions(options) @@ -25,11 +23,11 @@ exports.minor = function(options) { return tasks.run(options); }; -exports.backport = async function(options) { - const shouldStop = await backport.checkOptions(options); +export async function backport(options) { + const shouldStop = await checkOptions(options); if (shouldStop) return; const tasks = new Listr( - [updateV8Clone(), backport.doBackport(options)], + [updateV8Clone(), doBackport(options)], getOptions(options) ); return tasks.run(options); diff --git a/lib/update-v8/majorUpdate.js b/lib/update-v8/majorUpdate.js index 0f2975429..cf376ffd6 100644 --- a/lib/update-v8/majorUpdate.js +++ b/lib/update-v8/majorUpdate.js @@ -1,33 +1,26 @@ -'use strict'; +import path from 'node:path'; +import { promises as fs } from 'node:fs'; -const path = require('path'); +import { execa } from 'execa'; +import { Listr } from 'listr2'; -const execa = require('execa'); -const { - promises: { - readFile, - mkdir - } -} = require('fs'); -const { Listr } = require('listr2'); - -const common = require('./common'); -const { +import { getCurrentV8Version } from './common.js'; +import { getNodeV8Version, filterForVersion, addToGitignore, replaceGitignore, removeDirectory -} = require('./util'); -const applyNodeChanges = require('./applyNodeChanges'); -const { chromiumGit, v8Deps } = require('./constants'); +} from './util.js'; +import applyNodeChanges from './applyNodeChanges.js'; +import { chromiumGit, v8Deps } from './constants.js'; -module.exports = function() { +export default function majorUpdate() { return { title: 'Major V8 update', task: () => { return new Listr([ - common.getCurrentV8Version(), + getCurrentV8Version(), checkoutBranch(), removeDepsV8(), cloneLocalV8(), @@ -145,7 +138,7 @@ function updateV8Deps() { } async function readDeps(nodeDir, depName) { - const depsStr = await readFile(path.join(nodeDir, 'deps/v8/DEPS'), 'utf8'); + const depsStr = await fs.readFile(path.join(nodeDir, 'deps/v8/DEPS'), 'utf8'); const start = depsStr.indexOf('deps = {'); const end = depsStr.indexOf('\n}', start) + 2; const depsDeclaration = depsStr.substring(start, end).replace(/^ *#.*/gm, ''); @@ -160,7 +153,7 @@ async function readDeps(nodeDir, depName) { } async function fetchFromGit(cwd, repo, commit) { - await mkdir(cwd, { recursive: true }); + await fs.mkdir(cwd, { recursive: true }); await exec('init'); await exec('remote', 'add', 'origin', repo); await exec('fetch', 'origin', commit); diff --git a/lib/update-v8/minorUpdate.js b/lib/update-v8/minorUpdate.js index 9202707fe..cb5bc8fcb 100644 --- a/lib/update-v8/minorUpdate.js +++ b/lib/update-v8/minorUpdate.js @@ -1,25 +1,19 @@ -'use strict'; +import path from 'node:path'; +import { promises as fs } from 'node:fs'; -const path = require('path'); +import { execa } from 'execa'; +import { Listr } from 'listr2'; -const execa = require('execa'); -const { - promises: { - writeFile - } -} = require('fs'); -const { Listr } = require('listr2'); - -const common = require('./common'); +import { getCurrentV8Version } from './common.js'; -module.exports = function() { +export default function minorUpdate() { return { title: 'Minor V8 update', task: () => { return new Listr([ - common.getCurrentV8Version(), + getCurrentV8Version(), getLatestV8Version(), - minorUpdate() + doMinorUpdate() ]); } }; @@ -41,7 +35,7 @@ function getLatestV8Version() { }; } -function minorUpdate() { +function doMinorUpdate() { return { title: 'Do minor update', task: (ctx, task) => { @@ -50,7 +44,7 @@ function minorUpdate() { } const latestStr = ctx.latestVersion.join('.'); task.title = `Do minor update to ${latestStr}`; - return doMinorUpdate(ctx, latestStr); + return applyPatch(ctx, latestStr); }, skip: (ctx) => { if (ctx.currentVersion.patch >= ctx.latestVersion[3]) { @@ -62,7 +56,7 @@ function minorUpdate() { }; } -async function doMinorUpdate(ctx, latestStr) { +async function applyPatch(ctx, latestStr) { const { stdout: diff } = await execa( 'git', ['format-patch', '--stdout', `${ctx.currentVersion}...${latestStr}`], @@ -75,7 +69,7 @@ async function doMinorUpdate(ctx, latestStr) { }); } catch (e) { const file = path.join(ctx.nodeDir, `${latestStr}.diff`); - await writeFile(file, diff); + await fs.writeFile(file, diff); throw new Error(`Could not apply patch.\n${e}\nDiff was stored in ${file}`); } } diff --git a/lib/update-v8/updateV8Clone.js b/lib/update-v8/updateV8Clone.js index 45e05b99f..37004af25 100644 --- a/lib/update-v8/updateV8Clone.js +++ b/lib/update-v8/updateV8Clone.js @@ -1,16 +1,11 @@ -'use strict'; +import { promises as fs } from 'node:fs'; -const execa = require('execa'); -const { Listr } = require('listr2'); -const { - promises: { - mkdir - } -} = require('fs'); +import { execa } from 'execa'; +import { Listr } from 'listr2'; -const { v8Git } = require('./constants'); +import { v8Git } from './constants.js'; -module.exports = function() { +export default function updateV8Clone() { return { title: 'Update local V8 clone', task: () => { @@ -41,7 +36,7 @@ function createClone() { return { title: 'Clone V8', task: async(ctx) => { - await mkdir(ctx.baseDir, { recursive: true }); + await fs.mkdir(ctx.baseDir, { recursive: true }); await execa('git', ['clone', v8Git], { cwd: ctx.baseDir }); }, enabled: (ctx) => ctx.shouldClone diff --git a/lib/update-v8/updateVersionNumbers.js b/lib/update-v8/updateVersionNumbers.js index 2fa1b9369..5c832e081 100644 --- a/lib/update-v8/updateVersionNumbers.js +++ b/lib/update-v8/updateVersionNumbers.js @@ -1,18 +1,11 @@ -'use strict'; +import path from 'node:path'; +import { promises as fs } from 'node:fs'; -const path = require('path'); -const { - promises: { - readFile, - writeFile - } -} = require('fs'); +import { Listr } from 'listr2'; -const { Listr } = require('listr2'); +import { getNodeV8Version } from './util.js'; -const util = require('./util'); - -module.exports = function() { +export default function updateVersionNumbers() { return { title: 'Update version numbers', task: () => { @@ -25,7 +18,7 @@ function bumpNodeModule() { return { title: 'Bump NODE_MODULE_VERSION', task: async(ctx) => { - const v8Version = await util.getNodeV8Version(ctx.nodeDir); + const v8Version = await getNodeV8Version(ctx.nodeDir); const newModuleVersion = await updateModuleVersionRegistry( ctx.nodeDir, v8Version, @@ -56,7 +49,7 @@ async function updateModuleVersionRegistry( nodeMajorVersion ) { const registryFile = `${nodeDir}/doc/abi_version_registry.json`; - const registryStr = await readFile(registryFile, 'utf8'); + const registryStr = await fs.readFile(registryFile, 'utf8'); const registry = JSON.parse(registryStr); const newVersion = registry.NODE_MODULE_VERSION[0].modules + 1; const newLine = @@ -68,18 +61,18 @@ async function updateModuleVersionRegistry( registryStr.substring(0, firstLineIndex) + newLine + registryStr.substring(firstLineIndex); - await writeFile(registryFile, newRegistry); + await fs.writeFile(registryFile, newRegistry); return newVersion; } async function updateModuleVersion(nodeDir, newVersion) { const path = `${nodeDir}/src/node_version.h`; - let nodeVersionH = await readFile(path, 'utf8'); + let nodeVersionH = await fs.readFile(path, 'utf8'); nodeVersionH = nodeVersionH.replace( /NODE_MODULE_VERSION \d+/, `NODE_MODULE_VERSION ${newVersion}` ); - await writeFile(path, nodeVersionH); + await fs.writeFile(path, nodeVersionH); } function getCommitTitle(moduleVersion) { @@ -102,10 +95,10 @@ function resetEmbedderString() { title: 'Reset V8 embedder version string', task: async(ctx, task) => { const commonGypiPath = path.join(ctx.nodeDir, 'common.gypi'); - const commonGypi = await readFile(commonGypiPath, 'utf8'); + const commonGypi = await fs.readFile(commonGypiPath, 'utf8'); const embedderValue = embedderRegex.exec(commonGypi)[1]; if (embedderValue !== '0') { - await writeFile( + await fs.writeFile( commonGypiPath, commonGypi.replace(embedderRegex, embedderString) ); diff --git a/lib/update-v8/util.js b/lib/update-v8/util.js index c0849843e..3f929ec25 100644 --- a/lib/update-v8/util.js +++ b/lib/update-v8/util.js @@ -1,19 +1,9 @@ -'use strict'; +import { promises as fs } from 'node:fs'; +import path from 'node:path'; -const { - promises: { - appendFile, - readFile, - writeFile, - rm, - rmdir - } -} = require('fs'); -const path = require('path'); - -async function getNodeV8Version(cwd) { +export async function getNodeV8Version(cwd) { try { - const v8VersionH = await readFile( + const v8VersionH = await fs.readFile( `${cwd}/deps/v8/include/v8-version.h`, 'utf8' ); @@ -38,39 +28,31 @@ async function getNodeV8Version(cwd) { } }; -function filterForVersion(list, version) { +export function filterForVersion(list, version) { return list.filter((dep) => { return dep.since <= version.majorMinor && (dep.until || Infinity) >= version.majorMinor; }); } -async function addToGitignore(nodeDir, value) { +export async function addToGitignore(nodeDir, value) { const gitignorePath = path.join(nodeDir, 'deps/v8/.gitignore'); - await appendFile(gitignorePath, `${value}\n`); + await fs.appendFile(gitignorePath, `${value}\n`); } -async function replaceGitignore(nodeDir, options) { +export async function replaceGitignore(nodeDir, options) { const gitignorePath = path.join(nodeDir, 'deps/v8/.gitignore'); - let gitignore = await readFile(gitignorePath, 'utf8'); + let gitignore = await fs.readFile(gitignorePath, 'utf8'); gitignore = gitignore.replace(options.match, options.replace); - await writeFile(gitignorePath, gitignore); + await fs.writeFile(gitignorePath, gitignore); } -function removeDirectory(path) { - if (typeof rm !== 'undefined') { - return rm(path, { recursive: true, force: true }); +export function removeDirectory(path) { + if (typeof fs.rm !== 'undefined') { + return fs.rm(path, { recursive: true, force: true }); } else { // Node.js 12 doesn't have `rm`, and `rmdir` emits a deprecation warning in // Node.js 16+. - return rmdir(path, { recursive: true }); + return fs.rmdir(path, { recursive: true }); } } - -module.exports = { - getNodeV8Version, - filterForVersion, - addToGitignore, - replaceGitignore, - removeDirectory -}; diff --git a/lib/user.js b/lib/user.js index d92433ec0..b452ccf50 100644 --- a/lib/user.js +++ b/lib/user.js @@ -1,10 +1,4 @@ -'use strict'; - -function isTheSamePerson(actor, b) { +export function isTheSamePerson(actor, b) { if (!actor || !actor.login) return false; // ghost return actor.login.toLowerCase() === b.toLowerCase(); } - -module.exports = { - isTheSamePerson -}; diff --git a/lib/user_status.js b/lib/user_status.js index b8db790b4..9c38d0931 100644 --- a/lib/user_status.js +++ b/lib/user_status.js @@ -1,9 +1,5 @@ -'use strict'; - -module.exports = { - FIRST_TIME_CONTRIBUTOR: 'FIRST_TIME_CONTRIBUTOR', - NONE: 'NONE', - OWNER: 'OWNER', // TSC - FIRST_TIMER: 'FIRST_TIMER', // New to Github - COLLABORATOR: 'COLLABORATOR' -}; +export const FIRST_TIME_CONTRIBUTOR = 'FIRST_TIME_CONTRIBUTOR'; +export const NONE = 'NONE'; +export const OWNER = 'OWNER'; // TSC +export const FIRST_TIMER = 'FIRST_TIMER'; // New to Github +export const COLLABORATOR = 'COLLABORATOR'; diff --git a/lib/utils.js b/lib/utils.js index 532f7760a..985f7c6c1 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,19 +1,18 @@ -'use strict'; +import which from 'which'; -const which = require('which'); -const { forceRunAsync } = require('./run'); +import { forceRunAsync } from './run.js'; -exports.ascending = function(a, b) { +export function ascending(a, b) { if (a === b) return 0; return a < b ? -1 : 1; }; -exports.descending = function(a, b) { +export function descending(a, b) { if (a === b) return 0; return a > b ? -1 : 1; }; -function flatten(arr) { +export function flatten(arr) { let result = []; for (const item of arr) { if (Array.isArray(item)) { @@ -24,14 +23,13 @@ function flatten(arr) { } return result; } -exports.flatten = flatten; -exports.shortSha = function shortSha(sha) { +export function shortSha(sha) { return sha.slice(0, 12); }; let isGhAvailableCache; -exports.isGhAvailable = function isGhAvailable() { +export function isGhAvailable() { if (isGhAvailableCache === undefined) { isGhAvailableCache = which.sync('gh', { nothrow: true }) !== null; } @@ -45,7 +43,7 @@ exports.isGhAvailable = function isGhAvailable() { * variable or `git config`. * @returns {string|null} */ -exports.getEditor = async function getEditor(options = {}) { +export async function getEditor(options = {}) { const { git = false } = options; diff --git a/lib/verbosity.js b/lib/verbosity.js index 37b381d1e..d52b77c8e 100644 --- a/lib/verbosity.js +++ b/lib/verbosity.js @@ -1,29 +1,26 @@ -'use strict'; +import util from 'node:util'; -const chalk = require('chalk'); -const util = require('util'); +import chalk from 'chalk'; const VERBOSITY = { NONE: 0, DEBUG: 2 }; -let verbosity = VERBOSITY.NONE; +export let verbosity = VERBOSITY.NONE; -exports.isDebugVerbosity = function() { +export function isDebugVerbosity() { return verbosity === VERBOSITY.DEBUG; }; -exports.setVerbosityFromEnv = function() { +export function setVerbosityFromEnv() { const env = (process.env.NCU_VERBOSITY || '').toUpperCase(); if (Object.keys(VERBOSITY).includes(env)) { verbosity = VERBOSITY[env]; } }; -exports.debuglog = function(...args) { +export function debuglog(...args) { // Prepend a line break in case it's logged while the spinner is running console.error(chalk.green(util.format('\n[DEBUG]', ...args))); }; - -exports.VERBOSITY = VERBOSITY; diff --git a/lib/wpt/index.js b/lib/wpt/index.js index f35cef274..52d2376b9 100644 --- a/lib/wpt/index.js +++ b/lib/wpt/index.js @@ -1,14 +1,14 @@ -'use strict'; +import path from 'node:path'; -const GitHubTree = require('../github/tree'); -const path = require('path'); -const { writeFile, readJson, writeJson, readFile } = require('../file'); -const _ = require('lodash'); -const { +import _ from 'lodash'; + +import GitHubTree from '../github/tree.js'; +import { writeFile, readJson, writeJson, readFile } from '../file.js'; +import { shortSha -} = require('../utils'); +} from '../utils.js'; -class WPTUpdater { +export class WPTUpdater { constructor(path, cli, request, nodedir, commit) { this.path = path; this.nodedir = nodedir; @@ -27,7 +27,8 @@ class WPTUpdater { } templates(...args) { - return _.template(readFile(path.join(__dirname, 'templates', ...args))); + const file = path.posix.join('templates', ...args); + return _.template(readFile(new URL(file, import.meta.url))); } fixtures(...args) { @@ -168,7 +169,7 @@ class WPTUpdater { } } -class ResourcesUpdater extends WPTUpdater { +export class ResourcesUpdater extends WPTUpdater { constructor(cli, request, nodedir, commit) { super('resources', cli, request, nodedir, commit); } @@ -200,7 +201,7 @@ class ResourcesUpdater extends WPTUpdater { } } -class InterfacesUpdater extends WPTUpdater { +export class InterfacesUpdater extends WPTUpdater { constructor(cli, request, nodedir, commit, supported) { super('interfaces', cli, request, nodedir, commit); this.supported = supported; @@ -235,9 +236,3 @@ class InterfacesUpdater extends WPTUpdater { }); } } - -module.exports = { - WPTUpdater, - ResourcesUpdater, - InterfacesUpdater -}; diff --git a/package.json b/package.json index 6b2d9e222..a18926009 100644 --- a/package.json +++ b/package.json @@ -2,22 +2,22 @@ "name": "node-core-utils", "version": "1.31.0", "description": "Utilities for Node.js core collaborators", + "type": "module", "bin": { - "get-metadata": "./bin/get-metadata", - "git-node": "./bin/git-node", - "ncu-config": "./bin/ncu-config", - "ncu-team": "./bin/ncu-team", - "ncu-ci": "./bin/ncu-ci" + "get-metadata": "./bin/get-metadata.js", + "git-node": "./bin/git-node.js", + "ncu-config": "./bin/ncu-config.js", + "ncu-team": "./bin/ncu-team.js", + "ncu-ci": "./bin/ncu-ci.js" }, "scripts": { "test": "npm run test-unit && npm run lint", "test-unit": "mocha test/unit/*.test.js", "test-all": "mocha test/**/*.test.js", - "coverage": "nyc --reporter=html --reporter=text --reporter=text-summary npm test", - "coverage-all": "nyc --reporter=lcov --reporter=text --reporter=text-summary npm run test-all", - "report-coverage": "nyc report --reporter=lcov > coverage.lcov && codecov", - "lint": "eslint . \"bin/*\" --cache", - "lint-fix": "eslint . \"bin/*\" --fix" + "coverage": "c8 --reporter=html --reporter=text --reporter=text-summary npm test", + "coverage-all": "c8 --reporter=lcov --reporter=text --reporter=text-summary npm run test-all", + "lint": "eslint . --cache", + "lint-fix": "eslint . --fix" }, "author": "Joyee Cheung ", "repository": { @@ -32,38 +32,36 @@ "license": "MIT", "dependencies": { "branch-diff": "^1.10.5", - "chalk": "^4.1.2", - "changelog-maker": "^2.7.3", + "chalk": "^5.0.0", + "changelog-maker": "^2.7.4", "cheerio": "^1.0.0-rc.10", - "clipboardy": "^2.3.0", + "clipboardy": "^3.0.0", "core-validate-commit": "^3.13.4", - "execa": "^5.1.1", - "figures": "^3.2.0", + "execa": "^6.0.0", + "figures": "^4.0.0", "form-data": "^4.0.0", "ghauth": "^4.0.0", "inquirer": "^8.2.0", - "listr2": "^3.13.3", + "listr2": "^3.13.5", "lodash": "^4.17.21", - "log-symbols": "^4.1.0", - "node-fetch": "^2.6.1", - "ora": "^5.4.1", + "log-symbols": "^5.1.0", + "node-fetch": "^3.1.0", + "ora": "^6.0.1", "proxy-agent": "^5.0.0", "replace-in-file": "^6.3.2", "rimraf": "^3.0.2", "which": "^2.0.2", - "yargs": "^17.2.1" + "yargs": "^17.3.0" }, "devDependencies": { + "c8": "^7.10.0", "eslint": "^7.32.0", "eslint-config-standard": "^16.0.3", "eslint-plugin-import": "^2.25.2", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^4.3.1", "eslint-plugin-standard": "^4.1.0", - "intelli-espower-loader": "^1.1.0", "mocha": "^9.1.3", - "nyc": "^15.1.0", - "power-assert": "^1.6.1", "sinon": "^12.0.1" } } diff --git a/test/common.js b/test/common.js index de2171787..464883b8b 100644 --- a/test/common.js +++ b/test/common.js @@ -1,12 +1,14 @@ -'use strict'; +import path from 'node:path'; +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; -const path = require('path'); -const rimraf = require('rimraf'); -const fs = require('fs'); +import rimraf from 'rimraf'; -exports.tmpdir = { +const tmpdirPath = fileURLToPath(new URL('tmp', import.meta.url)); + +export const tmpdir = { get path() { - return path.join(__dirname, 'tmp'); + return tmpdirPath; }, refresh() { rimraf.sync(this.path); @@ -14,14 +16,14 @@ exports.tmpdir = { } }; -exports.copyShallow = function(src, dest) { +export function copyShallow(src, dest) { fs.mkdirSync(dest, { recursive: true }); const list = fs.readdirSync(src); for (const file of list) { fs.copyFileSync(path.join(src, file), path.join(dest, file)); } -}; +} -exports.raw = function(obj) { +export function raw(obj) { return JSON.parse(JSON.stringify(obj)); -}; +} diff --git a/test/fixtures/assert_throws_async.js b/test/fixtures/assert_throws_async.js index ec4daacfb..1a5e6760a 100644 --- a/test/fixtures/assert_throws_async.js +++ b/test/fixtures/assert_throws_async.js @@ -2,9 +2,9 @@ // so assert.throws doesn't work with them. // The next allows us to try async error throws -const assert = require('assert'); +import assert from 'node:assert'; -const assertThrowsAsync = async(fn, regExp) => { +export default async function assertThrowsAsync(fn, regExp) { let throwFn = () => {}; try { await fn(); @@ -14,5 +14,3 @@ const assertThrowsAsync = async(fn, regExp) => { assert.throws(throwFn, regExp); } }; - -module.exports = assertThrowsAsync; diff --git a/test/fixtures/data.js b/test/fixtures/data.js index 5c3328782..f123a9960 100644 --- a/test/fixtures/data.js +++ b/test/fixtures/data.js @@ -1,68 +1,68 @@ -'use strict'; +import { basename } from 'node:path'; +import { readdirSync } from 'node:fs'; -const { basename } = require('path'); -const { readdirSync } = require('fs'); +import { Collaborator } from '../../lib/collaborators.js'; +import { Review } from '../../lib/reviews.js'; +import { readJSON, patchPrototype, readFile, path } from './index.js'; -const { readJSON, patchPrototype, readFile, path } = require('./index'); -const { Collaborator } = require('../../lib/collaborators'); -const { Review } = require('../../lib/reviews'); - -const approved = readJSON('reviewers_approved.json'); -const requestedChanges = readJSON('reviewers_requested_changes.json'); +export const approved = readJSON('reviewers_approved.json'); +export const requestedChanges = readJSON('reviewers_requested_changes.json'); patchPrototype(approved, 'reviewer', Collaborator.prototype); patchPrototype(approved, 'review', Review.prototype); patchPrototype(requestedChanges, 'reviewer', Collaborator.prototype); patchPrototype(requestedChanges, 'review', Review.prototype); -const allGreenReviewers = { +export const allGreenReviewers = { approved, requestedChanges: [] }; -const singleGreenReviewer = { +export const singleGreenReviewer = { approved: [approved[0]], requestedChanges: [] }; -const requestedChangesReviewers = { +export const requestedChangesReviewers = { requestedChanges, approved: [] }; -const noReviewers = { +export const noReviewers = { requestedChanges: [], approved: [] }; -const approvingReviews = readJSON('reviews_approved.json'); -const requestingChangesReviews = readJSON('reviews_requesting_changes.json'); +export const approvingReviews = readJSON('reviews_approved.json'); +export const requestingChangesReviews = + readJSON('reviews_requesting_changes.json'); -const commentsWithFastTrack = readJSON('comments_with_fast_track.json'); -const commentsWithFastTrackInsuffientApprovals = +export const commentsWithFastTrack = readJSON('comments_with_fast_track.json'); +export const commentsWithFastTrackInsuffientApprovals = readJSON('comments_with_fast_track_insufficient_approvals.json'); -const commentsWithCI = readJSON('comments_with_ci.json'); -const commentsWithFailedCI = readJSON('comments_with_failed_ci.json'); -const commentsWithLGTM = readJSON('comments_with_lgtm.json'); -const commentsWithPendingCI = readJSON('comments_with_pending_ci.json'); -const commentsWithSuccessCI = readJSON('comments_with_success_ci.json'); - -const oddCommits = readJSON('odd_commits.json'); -const incorrectGitConfigCommits = readJSON('incorrect_git_config_commits.json'); -const simpleCommits = readJSON('simple_commits.json'); - -const singleCommitAfterReview = { +export const commentsWithCI = readJSON('comments_with_ci.json'); +export const commentsWithFailedCI = readJSON('comments_with_failed_ci.json'); +export const commentsWithLGTM = readJSON('comments_with_lgtm.json'); +export const commentsWithPendingCI = readJSON('comments_with_pending_ci.json'); +export const commentsWithSuccessCI = readJSON('comments_with_success_ci.json'); + +export const oddCommits = readJSON('odd_commits.json'); +export const incorrectGitConfigCommits = + readJSON('incorrect_git_config_commits.json'); +export const simpleCommits = readJSON('simple_commits.json'); + +export const singleCommitAfterReview = { commits: readJSON('single_commit_after_review_commits.json'), reviews: readJSON('single_commit_after_review_reviews.json') }; -const multipleCommitsAfterReview = { +export const multipleCommitsAfterReview = { commits: readJSON('multiple_commits_after_review_commits.json'), reviews: readJSON('multiple_commits_after_review_reviews.json') }; -const moreThanThreeCommitsAfterReview = { +export const moreThanThreeCommitsAfterReview = { commits: readJSON('more_than_three_commits_after_review_commits.json'), reviews: readJSON('more_than_three_commits_after_review_reviews.json') }; -const commitsAfterCi = readJSON('commits_after_ci.json'); -const mulipleCommitsAfterCi = readJSON('multiple_commits_after_ci.json'); +export const commitsAfterCi = readJSON('commits_after_ci.json'); +export const mulipleCommitsAfterCi = readJSON('multiple_commits_after_ci.json'); function makeCollaborators(arr) { arr.forEach((c) => { @@ -73,32 +73,35 @@ function makeCollaborators(arr) { ); } -const collaborators = makeCollaborators(readJSON('collaborators.json')); -const collaboratorsAlternative = makeCollaborators( +export const collaborators = makeCollaborators(readJSON('collaborators.json')); +export const collaboratorsAlternative = makeCollaborators( readJSON('collaborators_alternative.json') ); -const firstTimerPR = readJSON('first_timer_pr.json'); -const firstTimerPrivatePR = readJSON('first_timer_pr_with_private_email.json'); -const semverMajorPR = readJSON('semver_major_pr.json'); -const fixAndRefPR = readJSON('pr_with_fixes_and_refs.json'); -const fixCrossPR = readJSON('pr_with_fixes_cross.json'); -const duplicateRefPR = readJSON('pr_with_duplicate_refs.json'); -const selfRefPR = readJSON('pr_with_self_ref.json'); -const backportPR = readJSON('pr_with_backport.json'); -const conflictingPR = readJSON('conflicting_pr.json'); -const emptyProfilePR = readJSON('empty_profile_pr.json'); -const closedPR = readJSON('./closed_pr.json'); -const mergedPR = readJSON('./merged_pr.json'); -const readme = readFile('./README/README.md'); -const readmeAlternative = readFile('./README/README_alternative.md'); -const readmeNoTsc = readFile('./README/README_no_TSC.md'); -const readmeNoTscE = readFile('./README/README_no_TSCE.md'); -const readmeNoCollaborators = readFile('./README/README_no_collaborators.md'); -const readmeNoCollaboratorE = readFile('./README/README_no_collaboratorE.md'); -const readmeUnordered = readFile('./README/README_unordered.md'); - -const githubCI = {}; +export const firstTimerPR = readJSON('first_timer_pr.json'); +export const firstTimerPrivatePR = + readJSON('first_timer_pr_with_private_email.json'); +export const semverMajorPR = readJSON('semver_major_pr.json'); +export const fixAndRefPR = readJSON('pr_with_fixes_and_refs.json'); +export const fixCrossPR = readJSON('pr_with_fixes_cross.json'); +export const duplicateRefPR = readJSON('pr_with_duplicate_refs.json'); +export const selfRefPR = readJSON('pr_with_self_ref.json'); +export const backportPR = readJSON('pr_with_backport.json'); +export const conflictingPR = readJSON('conflicting_pr.json'); +export const emptyProfilePR = readJSON('empty_profile_pr.json'); +export const closedPR = readJSON('./closed_pr.json'); +export const mergedPR = readJSON('./merged_pr.json'); +export const readme = readFile('./README/README.md'); +export const readmeAlternative = readFile('./README/README_alternative.md'); +export const readmeNoTsc = readFile('./README/README_no_TSC.md'); +export const readmeNoTscE = readFile('./README/README_no_TSCE.md'); +export const readmeNoCollaborators = + readFile('./README/README_no_collaborators.md'); +export const readmeNoCollaboratorE = + readFile('./README/README_no_collaboratorE.md'); +export const readmeUnordered = readFile('./README/README_unordered.md'); + +export const githubCI = {}; for (const item of readdirSync(path('./github-ci'))) { if (!item.endsWith('.json')) { @@ -107,7 +110,7 @@ for (const item of readdirSync(path('./github-ci'))) { githubCI[basename(item, '.json')] = readJSON(`./github-ci/${item}`); }; -const pullRequests = {}; +export const pullRequests = {}; for (const item of readdirSync(path('./pull_requests'))) { if (!item.endsWith('.json')) { @@ -116,7 +119,7 @@ for (const item of readdirSync(path('./pull_requests'))) { pullRequests[basename(item, '.json')] = readJSON(`./pull_requests/${item}`); }; -const jenkinsCI = {}; +export const jenkinsCI = {}; for (const subdir of readdirSync(path('./jenkins'))) { for (const item of readdirSync(path(`./jenkins/${subdir}`))) { @@ -127,53 +130,3 @@ for (const subdir of readdirSync(path('./jenkins'))) { readJSON(`./jenkins/${subdir}/${item}`); } }; - -module.exports = { - approved, - requestedChanges, - allGreenReviewers, - singleGreenReviewer, - noReviewers, - requestedChangesReviewers, - approvingReviews, - requestingChangesReviews, - commentsWithFastTrack, - commentsWithFastTrackInsuffientApprovals, - commentsWithCI, - commentsWithFailedCI, - commentsWithLGTM, - commentsWithSuccessCI, - commentsWithPendingCI, - oddCommits, - jenkinsCI, - githubCI, - incorrectGitConfigCommits, - simpleCommits, - singleCommitAfterReview, - multipleCommitsAfterReview, - moreThanThreeCommitsAfterReview, - commitsAfterCi, - mulipleCommitsAfterCi, - collaborators, - collaboratorsAlternative, - firstTimerPR, - firstTimerPrivatePR, - semverMajorPR, - fixAndRefPR, - fixCrossPR, - backportPR, - conflictingPR, - emptyProfilePR, - readme, - readmeAlternative, - readmeNoTsc, - readmeNoTscE, - readmeNoCollaborators, - readmeNoCollaboratorE, - readmeUnordered, - closedPR, - mergedPR, - selfRefPR, - duplicateRefPR, - pullRequests -}; diff --git a/test/fixtures/index.js b/test/fixtures/index.js index 9d91afbf7..a1dac90b8 100644 --- a/test/fixtures/index.js +++ b/test/fixtures/index.js @@ -1,24 +1,25 @@ -'use strict'; +import fs from 'node:fs'; +import nodePath from 'node:path'; +import { fileURLToPath } from 'node:url'; -const fs = require('fs'); -const path = require('path'); +const __dirname = nodePath.dirname(fileURLToPath(import.meta.url)); -exports.readFile = function(...args) { - const file = path.resolve(__dirname, ...args); +export function readFile(...args) { + const file = nodePath.join(__dirname, ...args); return fs.readFileSync(file, 'utf8'); }; -exports.readJSON = function(...args) { - const file = exports.readFile(...args); +export function readJSON(...args) { + const file = readFile(...args); return JSON.parse(file); }; -exports.patchPrototype = function(arr, key, proto) { +export function patchPrototype(arr, key, proto) { for (const item of arr) { Object.setPrototypeOf(item[key], proto); } }; -exports.path = function(...args) { - return path.resolve(__dirname, ...args); +export function path(...args) { + return nodePath.join(__dirname, ...args); }; diff --git a/test/fixtures/log_stream.js b/test/fixtures/log_stream.js index 09a857d98..f35c8045b 100644 --- a/test/fixtures/log_stream.js +++ b/test/fixtures/log_stream.js @@ -1,9 +1,7 @@ -'use strict'; - -const { Writable } = require('stream'); +import { Writable } from 'node:stream'; const writtenSym = Symbol('written'); -class LogStream extends Writable { +export default class LogStream extends Writable { constructor(options) { super(options); this.isTTY = false; @@ -22,5 +20,3 @@ class LogStream extends Writable { cursorTo() {} } - -module.exports = LogStream; diff --git a/test/fixtures/run-auth-error.js b/test/fixtures/run-auth-error.js index 7a531fd69..a78dac394 100644 --- a/test/fixtures/run-auth-error.js +++ b/test/fixtures/run-auth-error.js @@ -1,10 +1,8 @@ -'use strict'; - async function mockCredentials() { throw new Error('Bad credentials'); } (async function() { - const auth = require('../../lib/auth'); + const { default: auth } = await import('../../lib/auth.js'); await auth({ github: true }, mockCredentials); })(); diff --git a/test/fixtures/run-auth-github.js b/test/fixtures/run-auth-github.js index 8daac4f26..25cd4bb21 100644 --- a/test/fixtures/run-auth-github.js +++ b/test/fixtures/run-auth-github.js @@ -1,6 +1,4 @@ -'use strict'; - -const assert = require('assert'); +import assert from 'assert'; async function mockCredentials(options) { assert.deepStrictEqual(options, { @@ -15,7 +13,7 @@ async function mockCredentials(options) { } (async function() { - const auth = require('../../lib/auth'); + const { default: auth } = await import('../../lib/auth.js'); const authParams = await auth({ github: true }, mockCredentials); process.stdout.write(`${JSON.stringify(authParams)}\n`); })().catch(err => { diff --git a/test/fixtures/test_cli.js b/test/fixtures/test_cli.js index af2c52b8c..77954818c 100644 --- a/test/fixtures/test_cli.js +++ b/test/fixtures/test_cli.js @@ -1,7 +1,7 @@ -'use strict'; +import assert from 'node:assert'; + +import CLI from '../../lib/cli.js'; -const assert = require('assert'); -const CLI = require('../../lib/cli'); const functions = Object.getOwnPropertyNames(CLI.prototype) .filter(func => func !== 'constructor'); @@ -13,7 +13,7 @@ function newCalls() { return calls; } -class TestCLI { +export default class TestCLI { constructor() { this.spinner = {}; this._calls = newCalls(); @@ -48,5 +48,3 @@ for (const func of functions) { for (const key of Object.keys(CLI)) { TestCLI[key] = CLI[key]; // constants } - -module.exports = TestCLI; diff --git a/test/unit/auth.test.js b/test/unit/auth.test.js index c7ef6c9dd..ea68aeaeb 100644 --- a/test/unit/auth.test.js +++ b/test/unit/auth.test.js @@ -1,10 +1,11 @@ -'use strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import assert from 'node:assert'; + +import rimraf from 'rimraf'; -const { spawn } = require('child_process'); -const rimraf = require('rimraf'); -const path = require('path'); -const fs = require('fs'); -const assert = require('assert'); let testCounter = 0; // for tmp directories const FIRST_TIME_MSG = @@ -80,7 +81,8 @@ function runAuthScript( if (ncurc.HOME === undefined) ncurc.HOME = ''; // HOME must always be set. for (const envVar in ncurc) { if (ncurc[envVar] === undefined) continue; - newEnv[envVar] = path.resolve(__dirname, `tmp-${testCounter++}`); + newEnv[envVar] = + fileURLToPath(new URL(`tmp-${testCounter++}`, import.meta.url)); rimraf.sync(newEnv[envVar]); fs.mkdirSync(newEnv[envVar], { recursive: true }); @@ -98,7 +100,7 @@ function runAuthScript( newEnv.USERPROFILE = newEnv.HOME; const proc = spawn(process.execPath, - [require.resolve(`../fixtures/${fixture}`)], + [fileURLToPath(new URL(`../fixtures/${fixture}`, import.meta.url))], { timeout: 1500, env: Object.assign({}, process.env, newEnv) diff --git a/test/unit/cache.test.js b/test/unit/cache.test.js index c7b15b228..4461b6516 100644 --- a/test/unit/cache.test.js +++ b/test/unit/cache.test.js @@ -1,10 +1,10 @@ -'use strict'; +import path from 'node:path'; +import fs from 'node:fs'; +import assert from 'node:assert'; -const Cache = require('../../lib/cache'); -const { tmpdir } = require('../common'); -const path = require('path'); -const fs = require('fs'); -const assert = require('assert'); +import Cache from '../../lib/cache.js'; + +import { tmpdir } from '../common.js'; describe('Cache', () => { const syncResult = 'content in sync'; diff --git a/test/unit/ci_failure_parser.test.js b/test/unit/ci_failure_parser.test.js index a4b476858..906cc2994 100644 --- a/test/unit/ci_failure_parser.test.js +++ b/test/unit/ci_failure_parser.test.js @@ -1,10 +1,9 @@ -'use strict'; +import assert from 'node:assert'; -const CIFailureParser = require('../../lib/ci/ci_failure_parser'); -const fixtures = require('../fixtures'); -const { raw } = require('../common'); +import CIFailureParser from '../../lib/ci/ci_failure_parser.js'; -const assert = require('assert'); +import * as fixtures from '../fixtures/index.js'; +import { raw } from '../common.js'; describe('Jenkins', () => { it('should parse git failure', async() => { diff --git a/test/unit/ci_result_parser.test.js b/test/unit/ci_result_parser.test.js index 274ef0c80..20489c512 100644 --- a/test/unit/ci_result_parser.test.js +++ b/test/unit/ci_result_parser.test.js @@ -1,26 +1,30 @@ -'use strict'; +import assert from 'node:assert'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; -const { +import { CITGMComparisonBuild -} = require('../../lib/ci/build-types/citgm_comparison_build'); -const { PRBuild } = require('../../lib/ci/build-types/pr_build'); -const { CommitBuild } = require('../../lib/ci/build-types/commit_build'); -const { BenchmarkRun } = require('../../lib/ci/build-types/benchmark_run'); -const { CITGMBuild } = require('../../lib/ci/build-types/citgm_build'); -const { jobCache } = require('../../lib/ci/build-types/job'); - -const TestCLI = require('../fixtures/test_cli'); -const { tmpdir, copyShallow } = require('../common'); -const path = require('path'); -const fixtures = require('../fixtures'); - -const assert = require('assert'); +} from '../../lib/ci/build-types/citgm_comparison_build.js'; +import { PRBuild } from '../../lib/ci/build-types/pr_build.js'; +import { CommitBuild } from '../../lib/ci/build-types/commit_build.js'; +import { BenchmarkRun } from '../../lib/ci/build-types/benchmark_run.js'; +import { CITGMBuild } from '../../lib/ci/build-types/citgm_build.js'; +import { jobCache } from '../../lib/ci/build-types/job.js'; + +import TestCLI from '../fixtures/test_cli.js'; +import { tmpdir, copyShallow } from '../common.js'; +import * as fixtures from '../fixtures/index.js'; + +function getFixturesDir(prefix) { + const base = fileURLToPath(new URL('../fixtures', import.meta.url)); + return path.join(base, ...prefix); +} describe('Jenkins', () => { it('should get failures in PR build and commit build', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'js-flake-1']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -65,7 +69,7 @@ describe('Jenkins', () => { it('should get successful PR build and commit build', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'success']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -92,7 +96,7 @@ describe('Jenkins', () => { it('should handle node-test-commit trigger failure', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'trigger-failure']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -115,7 +119,7 @@ describe('Jenkins', () => { it('should handle git failure', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'git-failure-1']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -138,7 +142,7 @@ describe('Jenkins', () => { it('should handle no compiler failure', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'no-compiler-error']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -161,7 +165,7 @@ describe('Jenkins', () => { it('should get benchmark run', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'benchmark-buffer']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -184,7 +188,7 @@ describe('Jenkins', () => { it('should correctly fetch CITGM build results', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'citgm']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -205,7 +209,7 @@ describe('Jenkins', () => { it('should correctly fetch CITGM nobuild job results', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'citgm-nobuild']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -226,7 +230,7 @@ describe('Jenkins', () => { it('should correctly fetch CITGM comparison build results', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'citgm-compare']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); @@ -253,7 +257,7 @@ describe('Jenkins', () => { it('should correctly fetch CITGM comparison noBuild results', async() => { tmpdir.refresh(); const prefix = ['jenkins', 'citgm-compare-nobuild']; - const fixturesDir = path.join(__dirname, '..', 'fixtures', ...prefix); + const fixturesDir = getFixturesDir(prefix); copyShallow(fixturesDir, tmpdir.path); jobCache.dir = tmpdir.path; jobCache.enable(); diff --git a/test/unit/ci_start.test.js b/test/unit/ci_start.test.js index 6c126476e..cac43f629 100644 --- a/test/unit/ci_start.test.js +++ b/test/unit/ci_start.test.js @@ -1,16 +1,15 @@ -'use strict'; +import assert from 'assert'; -const assert = require('assert'); +import sinon from 'sinon'; +import FormData from 'form-data'; -const sinon = require('sinon'); -const FormData = require('form-data'); - -const { +import { RunPRJob, CI_CRUMB_URL, CI_PR_URL -} = require('../../lib/ci/run_ci'); -const TestCLI = require('../fixtures/test_cli'); +} from '../../lib/ci/run_ci.js'; + +import TestCLI from '../fixtures/test_cli.js'; describe('Jenkins', () => { const owner = 'nodejs'; diff --git a/test/unit/ci_type_parser.test.js b/test/unit/ci_type_parser.test.js index 54ce733ab..50c28c53c 100644 --- a/test/unit/ci_type_parser.test.js +++ b/test/unit/ci_type_parser.test.js @@ -1,13 +1,12 @@ -'use strict'; +import assert from 'node:assert'; -const { +import { JobParser -} = require('../../lib/ci/ci_type_parser'); +} from '../../lib/ci/ci_type_parser.js'; -const assert = require('assert'); -const { +import { commentsWithCI -} = require('../fixtures/data'); +} from '../fixtures/data.js'; const expected = new Map([ ['PR', { diff --git a/test/unit/cli.test.js b/test/unit/cli.test.js index fd867f45e..02ca60e08 100644 --- a/test/unit/cli.test.js +++ b/test/unit/cli.test.js @@ -1,10 +1,9 @@ -'use strict'; +import assert from 'node:assert'; -const assert = require('assert'); +import CLI from '../../lib/cli.js'; +import * as figures from '../../lib/figures.js'; -const CLI = require('../../lib/cli'); -const LogStream = require('../fixtures/log_stream'); -const figures = require('../../lib/figures'); +import LogStream from '../fixtures/log_stream.js'; function strip(text) { // eslint-disable-next-line diff --git a/test/unit/collaborators.test.js b/test/unit/collaborators.test.js index 462c81f14..754efe7fc 100644 --- a/test/unit/collaborators.test.js +++ b/test/unit/collaborators.test.js @@ -1,13 +1,12 @@ -'use strict'; +import { fileURLToPath } from 'node:url'; +import assert from 'node:assert'; -const assert = require('assert'); -const path = require('path'); - -const { +import { isCollaborator, getCollaborators -} = require('../../lib/collaborators'); -const { +} from '../../lib/collaborators.js'; + +import { readme, readmeAlternative, readmeNoTsc, @@ -17,9 +16,9 @@ const { readmeUnordered, collaborators, collaboratorsAlternative -} = require('../fixtures/data'); -const TestCLI = require('../fixtures/test_cli'); -const assertThrowsAsync = require('../fixtures/assert_throws_async'); +} from '../fixtures/data.js'; +import TestCLI from '../fixtures/test_cli.js'; +import assertThrowsAsync from '../fixtures/assert_throws_async.js'; describe('collaborators', function() { const collaborator = collaborators.get('bar'); @@ -100,8 +99,8 @@ describe('collaborators', function() { } it('should use specified readme', async function() { - const readmePath = path.resolve( - __dirname, '..', 'fixtures', 'README', 'README.md'); + const readmePath = + fileURLToPath(new URL('../fixtures/README/README.md', import.meta.url)); const argv = { owner: 'nodejs', repo: 'node', readme: readmePath }; const request = { async text() { assert.fail('should not call'); } }; const parsed = await getCollaborators(cli, request, argv); diff --git a/test/unit/comp.test.js b/test/unit/comp.test.js index 051bf644f..cef5373cd 100644 --- a/test/unit/comp.test.js +++ b/test/unit/comp.test.js @@ -1,7 +1,6 @@ -'use strict'; +import assert from 'node:assert'; -const assert = require('assert'); -const { ascending, descending } = require('../../lib/utils'); +import { ascending, descending } from '../../lib/utils.js'; const arr = [ '2017-10-30T15:47:52Z', diff --git a/test/unit/links.test.js b/test/unit/links.test.js index 86709afaf..f95ddcd51 100644 --- a/test/unit/links.test.js +++ b/test/unit/links.test.js @@ -1,8 +1,9 @@ -'use strict'; +import assert from 'node:assert'; + +import { LinkParser, parsePRFromURL } from '../../lib/links.js'; + +import * as fixtures from '../fixtures/index.js'; -const LinkParser = require('../../lib/links'); -const fixtures = require('../fixtures'); -const assert = require('assert'); const htmls = fixtures.readJSON('op_html.json'); describe('LinkParser', () => { @@ -73,7 +74,7 @@ describe('LinkParser', () => { }]; for (const test of tests) { - const actual = LinkParser.parsePRFromURL(test.input); + const actual = parsePRFromURL(test.input); assert.deepStrictEqual(actual, test.output); } }); diff --git a/test/unit/metadata_gen.test.js b/test/unit/metadata_gen.test.js index 07520c549..790db37f3 100644 --- a/test/unit/metadata_gen.test.js +++ b/test/unit/metadata_gen.test.js @@ -1,16 +1,15 @@ -'use strict'; +import assert from 'node:assert'; -const MetadataGenerator = require('../../lib/metadata_gen'); -const { +import MetadataGenerator from '../../lib/metadata_gen.js'; + +import { fixAndRefPR, selfRefPR, duplicateRefPR, fixCrossPR, backportPR, allGreenReviewers -} = require('../fixtures/data'); - -const assert = require('assert'); +} from '../fixtures/data.js'; const data = { owner: 'nodejs', diff --git a/test/unit/pr_checker.test.js b/test/unit/pr_checker.test.js index 7a01d88d5..00f7c222a 100644 --- a/test/unit/pr_checker.test.js +++ b/test/unit/pr_checker.test.js @@ -1,22 +1,13 @@ -'use strict'; +import assert from 'node:assert'; -const assert = require('assert'); -const sinon = require('sinon'); +import sinon from 'sinon'; -const TestCLI = require('../fixtures/test_cli'); +import PRData from '../../lib/pr_data.js'; +import PRChecker from '../../lib/pr_checker.js'; +import { jobCache } from '../../lib/ci/build-types/job.js'; -const PRData = require('../../lib/pr_data'); -const PRChecker = require('../../lib/pr_checker'); -const { jobCache } = require('../../lib/ci/build-types/job'); -jobCache.disable(); - -const GT_7D = '2018-11-23T17:50:44.477Z'; -const LT_7D_GT_48H = '2018-11-27T17:50:44.477Z'; -const LT_48H = '2018-11-30T17:50:44.477Z'; -const LT_48H_GT_47H = '2018-11-29T17:55:44.477Z'; -const NOW = '2018-11-31T17:50:44.477Z'; - -const { +import TestCLI from '../fixtures/test_cli.js'; +import { allGreenReviewers, singleGreenReviewer, requestedChangesReviewers, @@ -48,7 +39,15 @@ const { closedPR, mergedPR, pullRequests -} = require('../fixtures/data'); +} from '../fixtures/data.js'; + +jobCache.disable(); + +const GT_7D = '2018-11-23T17:50:44.477Z'; +const LT_7D_GT_48H = '2018-11-27T17:50:44.477Z'; +const LT_48H = '2018-11-30T17:50:44.477Z'; +const LT_48H_GT_47H = '2018-11-29T17:55:44.477Z'; +const NOW = '2018-11-31T17:50:44.477Z'; const argv = { maxCommits: 3 }; diff --git a/test/unit/pr_data.test.js b/test/unit/pr_data.test.js index 197388e53..638dffe58 100644 --- a/test/unit/pr_data.test.js +++ b/test/unit/pr_data.test.js @@ -1,9 +1,10 @@ -'use strict'; +import assert from 'node:assert'; -const assert = require('assert'); -const sinon = require('sinon'); +import sinon from 'sinon'; -const { +import PRData from '../../lib/pr_data.js'; + +import { approvingReviews, allGreenReviewers, commentsWithLGTM, @@ -11,9 +12,8 @@ const { collaborators, firstTimerPR, readme -} = require('../fixtures/data'); -const TestCLI = require('../fixtures/test_cli'); -const PRData = require('../../lib/pr_data'); +} from '../fixtures/data.js'; +import TestCLI from '../fixtures/test_cli.js'; function toRaw(obj) { return JSON.parse(JSON.stringify(obj)); diff --git a/test/unit/pr_summary.test.js b/test/unit/pr_summary.test.js index 0bdb4e4af..59ec78fe4 100644 --- a/test/unit/pr_summary.test.js +++ b/test/unit/pr_summary.test.js @@ -1,14 +1,13 @@ -'use strict'; +import PRSummary from '../../lib/pr_summary.js'; -const { +import { oddCommits, simpleCommits, firstTimerPR, semverMajorPR, emptyProfilePR -} = require('../fixtures/data'); -const TestCLI = require('../fixtures/test_cli'); -const PRSummary = require('../../lib/pr_summary'); +} from '../fixtures/data.js'; +import TestCLI from '../fixtures/test_cli.js'; describe('PRSummary', () => { const argv = { prid: 16348, owner: 'nodejs', repo: 'node' }; diff --git a/test/unit/prepare_release.test.js b/test/unit/prepare_release.test.js index 6dc665d22..950c1aa76 100644 --- a/test/unit/prepare_release.test.js +++ b/test/unit/prepare_release.test.js @@ -1,9 +1,7 @@ -'use strict'; +import assert from 'node:assert'; +import { readFileSync } from 'node:fs'; -const assert = require('assert'); -const { readFileSync } = require('fs'); -const path = require('path'); -const utils = require('../../lib/release/utils'); +import * as utils from '../../lib/release/utils.js'; describe('prepare_release: utils.getEOLDate', () => { it('calculates the correct EOL date', () => { @@ -50,14 +48,14 @@ describe('prepare_release: utils.getStartLTSBlurb', () => { describe('prepare_release: utils.updateTestProcessRelease', () => { it('inserts test for a new LTS codename', () => { - const expectedPath = path.join( - __dirname, - '../fixtures/release/expected-test-process-release.js' + const expectedPath = new URL( + '../fixtures/release/expected-test-process-release.js', + import.meta.url ); const expected = readFileSync(expectedPath, { encoding: 'utf8' }); - const testPath = path.join( - __dirname, - '../fixtures/release/original-test-process-release.js' + const testPath = new URL( + '../fixtures/release/original-test-process-release.js', + import.meta.url ); const test = readFileSync(testPath, { encoding: 'utf8' }); const context = { diff --git a/test/unit/reviews.test.js b/test/unit/reviews.test.js index 161a62d9c..f72c66866 100644 --- a/test/unit/reviews.test.js +++ b/test/unit/reviews.test.js @@ -1,16 +1,15 @@ -'use strict'; +import assert from 'node:assert'; -const assert = require('assert'); -const { ReviewAnalyzer } = require('../../lib/reviews'); +import { ReviewAnalyzer } from '../../lib/reviews.js'; -const { +import { allGreenReviewers, requestedChangesReviewers, approvingReviews, requestingChangesReviews, commentsWithLGTM, collaborators -} = require('../fixtures/data'); +} from '../fixtures/data.js'; describe('ReviewAnalyzer', () => { it('should parse reviews and comments that all approve', () => { diff --git a/test/unit/team_info.test.js b/test/unit/team_info.test.js index 7cec4a49a..6d1ffbbb7 100644 --- a/test/unit/team_info.test.js +++ b/test/unit/team_info.test.js @@ -1,11 +1,10 @@ -'use strict'; +import assert from 'node:assert'; -const assert = require('assert'); -const sinon = require('sinon'); +import sinon from 'sinon'; -const TestCLI = require('../fixtures/test_cli'); -const TeamInfo = require('../../lib/team_info'); -const { readJSON, readFile, path: getPath } = require('../fixtures'); +import TestCLI from '../fixtures/test_cli.js'; +import TeamInfo from '../../lib/team_info.js'; +import { readJSON, readFile, path as getPath } from '../fixtures/index.js'; const collabList = `- [@Bar](https://github.com/Bar) - Bar Bar