diff --git a/package.json b/package.json index 190aa881..5d860c7e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "powership", - "version": "3.2.11", + "version": "3.2.15", "private": true, "scripts": { "pack": "run-s pack:*", diff --git a/packages/accounts/package.json b/packages/accounts/package.json index f47ac261..e88007a3 100644 --- a/packages/accounts/package.json +++ b/packages/accounts/package.json @@ -1,6 +1,6 @@ { "name": "@powership/accounts", - "version": "3.2.11", + "version": "3.2.15", "description": "Powership accounts", "type": "module", "main": "./out/index.cjs", diff --git a/packages/babel-plugins/package.json b/packages/babel-plugins/package.json index f0368ee9..daf759d1 100644 --- a/packages/babel-plugins/package.json +++ b/packages/babel-plugins/package.json @@ -1,6 +1,6 @@ { "name": "@powership/babel-plugins", - "version": "3.2.11", + "version": "3.2.15", "main": "./out/index.js", "sideEffects": false, "typings": "./out/index.d.ts", diff --git a/packages/boilerplate/package.json b/packages/boilerplate/package.json index 4daa78a9..045aa0dd 100644 --- a/packages/boilerplate/package.json +++ b/packages/boilerplate/package.json @@ -1,6 +1,6 @@ { "name": "@powership/boilerplate", - "version": "3.2.11", + "version": "3.2.15", "author": "antoniopresto ", "sideEffects": false, "type": "module", diff --git a/packages/deepstate/package.json b/packages/deepstate/package.json index 310c2f0d..84b5c2af 100644 --- a/packages/deepstate/package.json +++ b/packages/deepstate/package.json @@ -1,6 +1,6 @@ { "name": "@powership/deepstate", - "version": "3.2.11", + "version": "3.2.15", "main": "out/index.cjs", "module": "out/module/index.mjs", "sideEffects": false, diff --git a/packages/entity/package.json b/packages/entity/package.json index bbc0601d..e2ad2d67 100644 --- a/packages/entity/package.json +++ b/packages/entity/package.json @@ -1,6 +1,6 @@ { "name": "@powership/entity", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/helpers/package.json b/packages/helpers/package.json index e7f2e851..a8182d14 100644 --- a/packages/helpers/package.json +++ b/packages/helpers/package.json @@ -1,6 +1,6 @@ { "name": "@powership/helpers", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/logstorm/package.json b/packages/logstorm/package.json index 5dcd9df6..69629478 100644 --- a/packages/logstorm/package.json +++ b/packages/logstorm/package.json @@ -1,6 +1,6 @@ { "name": "logstorm", - "version": "3.2.11", + "version": "3.2.15", "typings": "out", "author": "antoniopresto ", "type": "module", diff --git a/packages/mongo/package.json b/packages/mongo/package.json index c941e745..91023c66 100644 --- a/packages/mongo/package.json +++ b/packages/mongo/package.json @@ -1,6 +1,6 @@ { "name": "@powership/mongo", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/plugin-engine/package.json b/packages/plugin-engine/package.json index 85cbc7da..9b1b2b7b 100644 --- a/packages/plugin-engine/package.json +++ b/packages/plugin-engine/package.json @@ -1,6 +1,6 @@ { "name": "plugin-engine", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/powership/package.json b/packages/powership/package.json index d13f83b3..5bf3bc1e 100644 --- a/packages/powership/package.json +++ b/packages/powership/package.json @@ -1,6 +1,6 @@ { "name": "powership", - "version": "3.2.11", + "version": "3.2.15", "author": "antoniopresto ", "type": "module", "main": "./out/index.cjs", diff --git a/packages/runmate/package.json b/packages/runmate/package.json index b51b2dae..62faaf1f 100644 --- a/packages/runmate/package.json +++ b/packages/runmate/package.json @@ -1,6 +1,6 @@ { "name": "runmate", - "version": "3.2.11", + "version": "3.2.15", "typings": "out", "author": "antoniopresto ", "license": "MIT", @@ -12,6 +12,7 @@ "sideEffects": false, "scripts": { "test": "echo ok", + "link": "pnpm prepublishOnly && pnpm link --global", "build": "run-s clear && run-p build:*", "fix": "run-s fix:*", "fix:prettier": "prettier \"src/**/*.ts\" --write", @@ -28,6 +29,7 @@ }, "description": "run command in each package", "keywords": [], + "workspaces": [], "dependencies": { "@types/glob": "^8.1.0", "@types/lodash": "4.14.191", diff --git a/packages/runmate/src/ICommons.ts b/packages/runmate/src/ICommons.ts index 24f2e2be..93cff731 100644 --- a/packages/runmate/src/ICommons.ts +++ b/packages/runmate/src/ICommons.ts @@ -11,5 +11,6 @@ export interface PackageJson { peerDependencies?: { [dependencyName: string]: string }; optionalDependencies?: { [dependencyName: string]: string }; license?: string; + workspaces?: string[] | { packages?: string[]; nohoist?: string[] }; [key: string]: unknown; } diff --git a/packages/runmate/src/__tests__/depTree.spec.ts b/packages/runmate/src/__tests__/depTree.spec.ts index 474aebf7..9a528716 100644 --- a/packages/runmate/src/__tests__/depTree.spec.ts +++ b/packages/runmate/src/__tests__/depTree.spec.ts @@ -2,7 +2,6 @@ import { DepTree } from '../depTree'; import { packageRunner } from '../packageRunner'; import nodePath from 'path'; import { PackageJson } from '../ICommons'; -import { defaultPackagesGlobPattern } from '../defaultPackagesGlobPattern'; describe('depTree', () => { // afterEach(); @@ -11,7 +10,7 @@ describe('depTree', () => { const packages: PackageJson[] = []; const cwd = nodePath.resolve(__dirname, '../../../../'); - const runner = await packageRunner(defaultPackagesGlobPattern, { cwd }); + const runner = await packageRunner({ cwd }); await runner.run((utils) => { packages.push(utils.json); diff --git a/packages/runmate/src/__tests__/findWorkspacePackages.spec.ts b/packages/runmate/src/__tests__/findWorkspacePackages.spec.ts new file mode 100644 index 00000000..1b91dc2a --- /dev/null +++ b/packages/runmate/src/__tests__/findWorkspacePackages.spec.ts @@ -0,0 +1,21 @@ +import nodePath from 'path'; +import { findWorkspacePackages } from '../findWorkspacePackages'; + +describe('findWorkspacePackages', () => { + test('basic test', () => { + const sut = findWorkspacePackages({ + cwd: nodePath.resolve(__dirname), + }); + + expect(sut).toEqual([ + { + found: [], + pattern: 'apps/*', + }, + { + found: [], + pattern: 'packages/*', + }, + ]); + }); +}); diff --git a/packages/runmate/src/__tests__/pnpm-workspace.yaml b/packages/runmate/src/__tests__/pnpm-workspace.yaml new file mode 100644 index 00000000..e9b0dad6 --- /dev/null +++ b/packages/runmate/src/__tests__/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +packages: + - 'apps/*' + - 'packages/*' diff --git a/packages/runmate/src/__tests__/runInPackages.spec.ts b/packages/runmate/src/__tests__/runInPackages.spec.ts index abd48933..0f980c09 100644 --- a/packages/runmate/src/__tests__/runInPackages.spec.ts +++ b/packages/runmate/src/__tests__/runInPackages.spec.ts @@ -7,7 +7,7 @@ describe('runInPackages', () => { // afterEach(); test('works', async () => { - const runner = await packageRunner('./packages/**/*', { + const runner = await packageRunner({ cwd, }); @@ -19,8 +19,8 @@ describe('runInPackages', () => { expect(utils.slice(0, 3).map((el) => el.json.name)).toEqual([ '@powership/babel-plugins', + '@powership/boilerplate', '@powership/utils', - '@powership/schema', ]); }); }); diff --git a/packages/runmate/src/cli.ts b/packages/runmate/src/cli.ts index a87c8531..97fbb109 100644 --- a/packages/runmate/src/cli.ts +++ b/packages/runmate/src/cli.ts @@ -7,11 +7,9 @@ import { align } from './commands/align'; import { list } from './commands/list'; import { main } from './commands/main'; import { version } from './commands/version'; -import { defaultPackagesGlobPattern } from './defaultPackagesGlobPattern'; import { packageRunner, PackageRunnerUtils } from './packageRunner'; import { packageJSONDependencyKeys } from './packageVersion'; import { runInFiles } from './runInFiles'; -import { runmateLogger } from './runmateLogger'; const program = new Command(); @@ -20,16 +18,15 @@ main(program); program .command('clean') .alias('clear') - .option('-c, --chunk-size', 'Chunk size of parallel executions', '10') - .option('-s, --src', 'Folder pattern', defaultPackagesGlobPattern) + .option( + '-c, --chunk-size ', + 'Chunk size of parallel executions', + '10' + ) + .option('-s, --src ', 'Folder pattern') .action(async function run(options): Promise { const { chunkSize, src } = options || {}; - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify(options, null, 2), - ]); - try { const runner = await packageRunner(src); await runner.run('rm -rf node_modules', { @@ -37,7 +34,7 @@ program failFast: false, }); } catch (e: any) { - console.error(chalk.red(e)); + console.error(chalk.redBright.bgBlack(e)); } }); @@ -45,19 +42,17 @@ program .command('each') .alias('packages') .argument('[command...]') - .option('-s, --src', 'Folder pattern', defaultPackagesGlobPattern) - .option('-c, --chunk-size', 'Chunk size of parallel executions', '1') + .option('-s, --src ', 'Folder pattern') + .option( + '-c, --chunk-size ', + 'Chunk size of parallel executions', + '1' + ) .alias('e') .action(async function run(commands: string[], options): Promise { const { chunkSize, src } = options; const command = commands.join(' '); - // - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify({ src, command, chunkSize, options }, null, 2), - ]); - try { await runInFiles({ chunkSize: +chunkSize, @@ -74,9 +69,9 @@ program .description( 'Executes `link` or any other command in every dependency/dependent package.' ) - .option('-s, --src ', 'Packages glob pattern.') + .option('-s, --src ', 'Packages glob pattern.') .option('--clean', 'Clean node_modules before link.') - .option('-c, --chunkSize ', 'Parallel executions size.', '10') + .option('-c, --chunkSize ', 'Parallel executions size.', '10') .alias('l') .option( '--from ', @@ -85,15 +80,11 @@ program .action(async function run(options): Promise { const { src, chunkSize = 10, clean, from } = options || {}; - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify(options, null, 2), - ]); - const localPackages = new Map(); try { - const runner = await packageRunner(src || defaultPackagesGlobPattern, { + const runner = await packageRunner({ + cwd: src, failFast: false, }); diff --git a/packages/runmate/src/commands/align.ts b/packages/runmate/src/commands/align.ts index 2910776e..dfc8de28 100644 --- a/packages/runmate/src/commands/align.ts +++ b/packages/runmate/src/commands/align.ts @@ -4,23 +4,20 @@ import chalk from 'chalk'; import { Command } from 'commander'; import semver from 'semver/preload'; -import { defaultPackagesGlobPattern } from '../defaultPackagesGlobPattern'; import { packageRunner } from '../packageRunner'; import { packageJSONDependencyKeys } from '../packageVersion'; export function align(program: Command) { program - .command('align') - .option('-s, --src ', 'Packages glob pattern.') + .command('align [cwd]') .description( 'Align dependency versions between all packages in the monorepo.' ) - .action(async function run(_version, options = {}): Promise { - const { src } = options; - + .action(async function run(cwd): Promise { try { - const runner = await packageRunner(src || defaultPackagesGlobPattern, { + const runner = await packageRunner({ failFast: false, + cwd, }); const commons: { [K: string]: string[] } = {}; diff --git a/packages/runmate/src/commands/install.ts b/packages/runmate/src/commands/install.ts index ac2a1335..3d6e10ba 100644 --- a/packages/runmate/src/commands/install.ts +++ b/packages/runmate/src/commands/install.ts @@ -1,27 +1,20 @@ import chalk from 'chalk'; import { Command } from 'commander'; -import { defaultPackagesGlobPattern } from '../defaultPackagesGlobPattern'; import { packageRunner } from '../packageRunner'; import { packageVersion } from '../packageVersion'; -import { runmateLogger } from '../runmateLogger'; export function install(program: Command) { program - .command('install') - .option('-s, --src ', 'Packages glob pattern.') + .command('install [cwd]') .option('--no-scripts', 'Ignores the prepublish scripts.') .option('--dry-run', 'Ignores the publication.') - .action(async function run(_version, options): Promise { - const { src, scripts, dryRun } = options || {}; - - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify(options, null, 2), - ]); + .action(async function run(cwd, options): Promise { + const { scripts, dryRun } = options || {}; try { - const runner = await packageRunner(src || defaultPackagesGlobPattern, { + const runner = await packageRunner({ + cwd, failFast: false, }); @@ -55,12 +48,6 @@ export function install(program: Command) { ) .alias('v') .action(async function run(releaseTypeOrVersion, pattern): Promise { - // - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify({ releaseTypeOrVersion }, null, 2), - ]); - try { await packageVersion(releaseTypeOrVersion, pattern); } catch (e: any) { diff --git a/packages/runmate/src/commands/list.ts b/packages/runmate/src/commands/list.ts index a1ccd093..1de81b82 100644 --- a/packages/runmate/src/commands/list.ts +++ b/packages/runmate/src/commands/list.ts @@ -1,67 +1,31 @@ import chalk from 'chalk'; import { Command } from 'commander'; -import { defaultPackagesGlobPattern } from '../defaultPackagesGlobPattern'; import { packageRunner } from '../packageRunner'; import { printWithScroll } from '../printWithScroll'; -import { runmateLogger } from '../runmateLogger'; export function list(program: Command) { program - .command('list') - .option('-s, --src', 'Folder pattern', defaultPackagesGlobPattern) + .command('list [cwd]') .option( '--delay ', 'Delay between printing lines. Used during development.', '5' ) - .action(async function run(options): Promise { - // - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify(options, null, 2), - ]); + .action(async function run(cwd, options): Promise { + const { delay } = options || {}; - const { src, delay } = options || {}; - - runmateLogger.level = 'silent'; process.env.LOG_LEVEL = 'silent'; const timeout = +delay || 25; try { - const runner = await packageRunner(src); - - await printWithScroll( - JSON.stringify( - runner.utils.map((el) => el.name), - null, - 2 - ) - .split('\n') - .concat('\n'), - timeout - ); - - await printWithScroll( - JSON.stringify( - runner.utils.map((el) => el.basename), - null, - 2 - ) - .split('\n') - .concat('\n'), - timeout - ); + const runner = await packageRunner({ cwd }); await printWithScroll( - JSON.stringify( - runner.utils.map((el) => `packages/${el.basename}`), - null, - 2 - ) - .split('\n') - .concat('\n'), + runner.utils.flatMap(({ version, name, cwd: folder }) => { + return `${name}@${version} ${chalk.bgBlack.grey(folder)}`; + }), timeout ); } catch (e: any) { diff --git a/packages/runmate/src/commands/main.ts b/packages/runmate/src/commands/main.ts index e891117e..f4bc5bf3 100644 --- a/packages/runmate/src/commands/main.ts +++ b/packages/runmate/src/commands/main.ts @@ -1,11 +1,7 @@ -import { inspect } from 'util'; - import chalk from 'chalk'; import { Command } from 'commander'; -import { defaultPackagesGlobPattern } from '../defaultPackagesGlobPattern'; import { packageRunner } from '../packageRunner'; -import { runmateLogger } from '../runmateLogger'; export function main(program: Command) { program @@ -14,12 +10,12 @@ export function main(program: Command) { .description( 'Run command in each package in ./packages folder or in `--src` option folder' ) + .option('-s, --src ', 'Source directory or glob pattern') .option( - '-s, --src ', - 'Source directory or glob pattern', - './packages/*/' + '-c, --chunk-size ', + 'Chunk size of parallel executions', + '1' ) - .option('-c, --chunk-size', 'Chunk size of parallel executions', '1') .option( '-no-ff, --no-fail-fast, --no-ff, --noff', 'Disable exit on first error' @@ -60,18 +56,9 @@ export function main(program: Command) { const ignoreList = ignore?.split(/, ?/); const packagesExclusiveList = packages?.split(/, ?/); - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - inspect({ - commands, - ignoreList, - packagesExclusiveList, - ...options, - }), - ]); - try { - const runner = await packageRunner(src || defaultPackagesGlobPattern, { + const runner = await packageRunner({ + cwd: src, failFast, }); @@ -92,18 +79,6 @@ export function main(program: Command) { } } - const res = await runner.run( - `npm help | awk '/^ / { print $1 }' | tr -d ','` - ); - - const com = res.results[0]?.data.find( - (command) => command === commands[0] - ); - - if (com) { - return runner.run(`npm run ${commands.join(' ')}`); - } - await runner.run( async (utils) => { if (packagesExclusiveList?.length) { @@ -124,3 +99,72 @@ export function main(program: Command) { } }); } + +// const npmCommands = [ +// 'access', +// 'adduser', +// 'audit', +// 'bugs', +// 'cache', +// 'ci', +// 'completion', +// 'config', +// 'dedupe', +// 'deprecate', +// 'diff', +// 'dist-tag', +// 'docs', +// 'doctor', +// 'edit', +// 'exec', +// 'explain', +// 'explore', +// 'find-dupes', +// 'fund', +// 'get', +// 'help', +// 'help-search', +// 'hook', +// 'init', +// 'install', +// 'install-ci-test', +// 'install-test', +// 'link', +// 'll', +// 'login', +// 'logout', +// 'ls', +// 'org', +// 'outdated', +// 'owner', +// 'pack', +// 'ping', +// 'pkg', +// 'prefix', +// 'profile', +// 'prune', +// 'publish', +// 'query', +// 'rebuild', +// 'repo', +// 'restart', +// 'root', +// 'run-script', +// 'search', +// 'set', +// 'shrinkwrap', +// 'star', +// 'stars', +// 'start', +// 'stop', +// 'team', +// 'test', +// 'token', +// 'uninstall', +// 'unpublish', +// 'unstar', +// 'update', +// 'version', +// 'view', +// 'whoami', +// ]; diff --git a/packages/runmate/src/commands/version.ts b/packages/runmate/src/commands/version.ts index e3d00017..3dfbc5cc 100644 --- a/packages/runmate/src/commands/version.ts +++ b/packages/runmate/src/commands/version.ts @@ -1,31 +1,25 @@ import chalk from 'chalk'; import { Command } from 'commander'; -import { defaultPackagesGlobPattern } from '../defaultPackagesGlobPattern'; import { packageRunner } from '../packageRunner'; import { packageVersion } from '../packageVersion'; -import { runmateLogger } from '../runmateLogger'; export function version(program: Command) { program .command('publish [version]') - .option('-s, --src ', 'Packages glob pattern.') + .option('-s, --src ', 'Packages root folder.') .option('--no-scripts', 'Ignores the prepublish scripts.') .option('--dry-run', 'Ignores the publication.') .action(async function run(version, options): Promise { const { src, scripts, dryRun } = options || {}; - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify(options, null, 2), - ]); - try { if (version) { await packageVersion(version, src); } - const runner = await packageRunner(src || defaultPackagesGlobPattern, { + const runner = await packageRunner({ + cwd: src, failFast: false, }); @@ -59,12 +53,6 @@ export function version(program: Command) { ) .alias('v') .action(async function run(releaseTypeOrVersion, pattern): Promise { - // - await runmateLogger.lazyDebug(() => [ - 'Received args: \n', - JSON.stringify({ releaseTypeOrVersion }, null, 2), - ]); - try { await packageVersion(releaseTypeOrVersion, pattern); } catch (e: any) { diff --git a/packages/runmate/src/defaultPackagesGlobPattern.ts b/packages/runmate/src/defaultPackagesGlobPattern.ts deleted file mode 100644 index d83a594e..00000000 --- a/packages/runmate/src/defaultPackagesGlobPattern.ts +++ /dev/null @@ -1 +0,0 @@ -export let defaultPackagesGlobPattern = './packages/*/'; diff --git a/packages/runmate/src/findWorkspacePackages.ts b/packages/runmate/src/findWorkspacePackages.ts new file mode 100644 index 00000000..ae1d15ad --- /dev/null +++ b/packages/runmate/src/findWorkspacePackages.ts @@ -0,0 +1,98 @@ +import nodePath from 'path'; +import * as path from 'path'; +import process from 'process'; + +import fs from 'fs-extra'; +import * as glob from 'glob'; + +import { PackageJson } from './ICommons'; + +export type FindWorkspacePackagesInit = { + cwd?: string; + globCache?: any; +}; + +export type WorkspacePackagesFoundResult = ReturnType< + typeof findWorkspacePackages +>; + +export function findWorkspacePackages(init?: FindWorkspacePackagesInit) { + const { cwd: rootDir = process.cwd(), globCache } = init || {}; + + const pnpmWorkspaces = listPnpmWorkspaces(rootDir); + const packageJsonWorkspaces = listPackageJSONWorkspaces(rootDir); + + const foundPatterns = pnpmWorkspaces?.length + ? pnpmWorkspaces + : packageJsonWorkspaces?.length + ? packageJsonWorkspaces + : null; + + if (!foundPatterns) { + throw new Error('No workspaces config found.'); + } + + return foundPatterns.flatMap((pattern) => { + const found = glob.sync(nodePath.join(pattern, 'package.json'), { + cwd: rootDir, + absolute: true, + cache: globCache, + ignore: ['**/node_modules/**'], + }); + + return { + found, + pattern, + }; + }); +} + +function listPnpmWorkspaces(rootDir: string) { + const pnpmWorkspacePath = path.join(rootDir, 'pnpm-workspace.yaml'); + + if (fs.existsSync(pnpmWorkspacePath)) { + const workspaceFileContent = fs.readFileSync(pnpmWorkspacePath, 'utf-8'); + + if (!workspaceFileContent) { + throw new Error(`empty file ${pnpmWorkspacePath}`); + } + + let res = workspaceFileContent.replace(/packages:\n/, '').split('-'); + + res = res.map((el) => { + return el + .trim() // + .replace(/^['"]|['"]$/gm, ''); + }); + + return res.filter(Boolean); + } + + return null; +} + +function listPackageJSONWorkspaces(rootDir: string) { + const packageJsonPath = path.join(rootDir, 'package.json'); + + if (fs.existsSync(packageJsonPath)) { + const packageJson = fs.readJSONSync(packageJsonPath) as PackageJson; + const found = Array.isArray(packageJson?.workspaces) + ? packageJson.workspaces + : packageJson.workspaces?.packages || null; + + if (!Array.isArray(found)) return null; + + for (let p of found) { + if (typeof p !== 'string') { + throw new Error(`cant handle workspace ${p}`); + } + } + + return found; + } + + return null; +} + +export const listPackages = findWorkspacePackages; +export const findPackages = findWorkspacePackages; diff --git a/packages/runmate/src/index.ts b/packages/runmate/src/index.ts index 8ced9c5d..cbd96379 100644 --- a/packages/runmate/src/index.ts +++ b/packages/runmate/src/index.ts @@ -1,5 +1,5 @@ -export * from './runmateLogger'; export * from './runCommand'; export * from './runInFiles'; export * from './packageRunner'; export * from './ICommons'; +export * from './findWorkspacePackages'; diff --git a/packages/runmate/src/packageRunner.ts b/packages/runmate/src/packageRunner.ts index fe3a1637..7122f160 100644 --- a/packages/runmate/src/packageRunner.ts +++ b/packages/runmate/src/packageRunner.ts @@ -1,14 +1,12 @@ import nodePath from 'path'; import { inspect } from 'util'; -import { existsSync } from 'fs-extra'; -import { glob } from 'glob'; import chunk from 'lodash/chunk'; import { DepTree, PackageItem } from './depTree'; +import { findWorkspacePackages } from './findWorkspacePackages'; import { readPackageJSON, writePackageJSON } from './handleJSON'; import { runCommand, RunCommandResult } from './runCommand'; -import { runmateLogger } from './runmateLogger'; let packageRunnerCache = {}; @@ -45,9 +43,20 @@ export function getPackageRunnerUtils(jsonPath: string) { return await runCommand(command, { cwd }); } catch (e: any) { - const message = `Failed to run command in package "${json.name}": ${ - e.message || inspect(e) - }`; + const message = `Failed to run command in package "${json.name}":\n ${( + e.message || + inspect(e) || + '' + ) + .split('\n') + .map((el) => ` ${el}`) + .join('\n')}`; + + if (e?.stack && e.message) { + e.message = message; + throw e; + } + throw new Error(message); } }, @@ -87,7 +96,6 @@ export interface PackageRunnerRun { } export async function packageRunner( - pattern: string, options: PackageRunnerOptions = {} ): Promise { // @@ -104,55 +112,15 @@ export async function packageRunner( return undefined; })(); - const files: string[] = []; - - try { - glob - .sync(pattern, { - cwd, - noext: true, - absolute: true, - cache, - }) - .forEach((file) => { - if (file.match(/node_modules/)) return; - - const ext = nodePath.extname(file); - - if (ext) return; - - const jsonPath = nodePath.join(file, 'package.json'); - - if (existsSync(jsonPath)) { - files.push(jsonPath); - } - }); - } catch (e: any) { - throw new Error(`Failed to find packages: ${e.message}`); - } + const files = findWorkspacePackages({ globCache: cache, cwd }).flatMap( + (el) => el.found + ); const utils = files.map((file) => getPackageRunnerUtils(file)); const packages = reduceObject(utils, (item) => ({ [item.name]: item })); const depTree = new DepTree(utils.map((el) => el.json)).find(); - runmateLogger.lazyDebug(() => { - return [ - 'Found packages:\n', - depTree - .map((el) => { - let txt = `${el.name}: `; - if (!el.dependents.length) { - txt += `0 dependents.`; - } else { - txt += `dependents: ${el.dependents.join(', ')}.`; - } - return `➜ ${txt}`; - }) - .join('\n'), - ]; - }); - const run: PackageRunner['run'] = async function run(command, runOptions) { let { chunkSize, failFast = failFastRoot, from } = runOptions || {}; chunkSize = chunkSize || 1; diff --git a/packages/runmate/src/packageVersion.ts b/packages/runmate/src/packageVersion.ts index 54904e5e..afd26d5e 100644 --- a/packages/runmate/src/packageVersion.ts +++ b/packages/runmate/src/packageVersion.ts @@ -2,7 +2,6 @@ import nodePath from 'path'; import semver from 'semver/preload'; -import { defaultPackagesGlobPattern } from './defaultPackagesGlobPattern'; import { readPackageJSON, writePackageJSON } from './handleJSON'; import { packageRunner, PackageRunnerUtils } from './packageRunner'; @@ -29,15 +28,14 @@ export const packageJSONDependencyKeys = [ export async function packageVersion( releaseTypeOrVersion: ReleaseType | string, - patternInput?: string + cwd?: string ) { - const pattern = patternInput || defaultPackagesGlobPattern; - const runner = await packageRunner(pattern); + const runner = await packageRunner({ cwd }); const rootJSONPath = nodePath.resolve(process.cwd(), 'package.json'); const rootJSON = (() => { - if (patternInput) return; + if (cwd) return; try { return readPackageJSON(rootJSONPath); } catch (e) { diff --git a/packages/runmate/src/runCommand.ts b/packages/runmate/src/runCommand.ts index 96d7ba48..bde9762e 100644 --- a/packages/runmate/src/runCommand.ts +++ b/packages/runmate/src/runCommand.ts @@ -1,30 +1,29 @@ import { ChildProcess, ExecOptions, spawn } from 'child_process'; import nodePath from 'path'; +import process from 'process'; -import chalk from 'chalk'; import { AsyncPlugin, createAsyncPlugin } from 'plugin-hooks'; import { delayPromise } from './printWithScroll'; -import { runmateLogger } from './runmateLogger'; export interface RunCommandOptions { + silent?: boolean; command: string; plugin?: (hooks: RunCommandHooks) => any; } export interface RunCommandResult { - data: string[]; + data: Buffer[]; code: 0; } export async function runCommand( - options: RunCommandOptions | string, + input: RunCommandOptions | string, execOptions?: ExecOptions ): Promise { let childRef: ChildProcess | null = null; - let started = Date.now(); - const data: string[] = []; + const data: Buffer[] = []; const hooks: RunCommandHooks | undefined = { onStderrData: createAsyncPlugin(), @@ -39,42 +38,12 @@ export async function runCommand( data.push(p.data); }); - options = - typeof options === 'string' + const options: RunCommandOptions = + typeof input === 'string' ? { - command: options, - plugin(hooks) { - const c_command_medium = command.replace(/(.{20})(.+)/, `$1…`); - const description = - typeof execOptions?.cwd === 'string' - ? `${c_command_medium} in ./${nodePath.relative( - process.cwd(), - execOptions.cwd - )}` - : c_command_medium; - - hooks.willStart.pushMiddleware(function data() { - runmateLogger.log(`\n\nrun ${chalk.cyan(description)} started\n`); - }); - - hooks.onStdoutData.pushMiddleware(function data(currentValue) { - runmateLogger.log(currentValue.data); - }); - - hooks.onStderrData.pushMiddleware(function data(currentValue) { - runmateLogger.error(chalk.red(currentValue.data)); - }); - - hooks.onClose.pushMiddleware(function data() { - runmateLogger.log( - chalk.green( - `finished in ${Date.now() - started}ms (${description})\n` - ) - ); - }); - }, + command: input, } - : options; + : input; let { command, plugin } = options; @@ -97,10 +66,15 @@ export async function runCommand( const child = (childRef = spawn(command, { ...execOptions, - stdio: 'inherit', + stdio: 'pipe', shell: true, })); + if (!options?.silent && child.stdout && child.stderr) { + child.stdout.on('data', (data) => process.stdout.write(data)); + child.stderr.on('data', (data) => process.stderr.write(data)); + } + child.stdout?.on('data', async function (data) { await hooks?.onStdoutData.dispatch({ data }, child); }); @@ -119,7 +93,9 @@ export async function runCommand( return resolve({ code, data }); } - reject({ code, data }); + const error: any = new Error(data.map((d) => d.toString()).join('')); + error.code = code; + reject(error); }); }); } catch (e: any) { @@ -142,8 +118,8 @@ async function getConfigFile( export interface RunCommandHooks { willStart: AsyncPlugin<{ command: string }, undefined>; started: AsyncPlugin; - onStdoutData: AsyncPlugin<{ data: string }, ChildProcess>; - onStderrData: AsyncPlugin<{ data: string }, ChildProcess>; + onStdoutData: AsyncPlugin<{ data: Buffer }, ChildProcess>; + onStderrData: AsyncPlugin<{ data: Buffer }, ChildProcess>; onClose: AsyncPlugin<{ code: number | null }, ChildProcess>; onError: AsyncPlugin<{ error: Error }, ChildProcess | null>; } diff --git a/packages/runmate/src/runmateLogger.ts b/packages/runmate/src/runmateLogger.ts deleted file mode 100644 index 50114fed..00000000 --- a/packages/runmate/src/runmateLogger.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { createLogger } from 'logstorm'; - -const level: any = process.env.LOG_LEVEL || 'trace'; - -export const runmateLogger = createLogger('runmate', level, { - color: 'cyan', - time: true, -}); diff --git a/packages/schema/package.json b/packages/schema/package.json index a649f146..c2638016 100644 --- a/packages/schema/package.json +++ b/packages/schema/package.json @@ -1,6 +1,6 @@ { "name": "@powership/schema", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/server/package.json b/packages/server/package.json index f9487eaa..fbfb9e1d 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@powership/server", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/transporter/package.json b/packages/transporter/package.json index e92e665d..d835c157 100644 --- a/packages/transporter/package.json +++ b/packages/transporter/package.json @@ -1,6 +1,6 @@ { "name": "@powership/transporter", - "version": "3.2.11", + "version": "3.2.15", "type": "module", "main": "./out/index.cjs", "module": "./out/module/index.mjs", diff --git a/packages/utils/package.json b/packages/utils/package.json index c11cba0b..df3a26de 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,6 +1,6 @@ { "name": "@powership/utils", - "version": "3.2.11", + "version": "3.2.15", "typings": "out", "author": "antoniopresto ", "license": "MIT",