Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

refactor: use logger #1748

Merged
merged 13 commits into from
Sep 3, 2020
3 changes: 2 additions & 1 deletion packages/generators/src/addon-generator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from 'webpack-cli/lib/utils/logger';
import mkdirp from 'mkdirp';
import path from 'path';
import Generator from 'yeoman-generator';
Expand Down Expand Up @@ -54,7 +55,7 @@ const addonGenerator = (
try {
mkdirp.sync(pathToProjectDir);
} catch (err) {
console.error('Failed to create directory', err);
logger.error('Failed to create directory', err);
}
this.destinationRoot(pathToProjectDir);
}
Expand Down
7 changes: 4 additions & 3 deletions packages/generators/src/init-generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { blue, green, bold } from 'colorette';
import logger from 'webpack-cli/lib/utils/logger';
import logSymbols from 'log-symbols';
import path from 'path';
import { getPackageManager } from '@webpack-cli/package-utils';
Expand Down Expand Up @@ -74,12 +75,12 @@ export default class InitGenerator extends CustomGenerator {

this.usingDefaults = true;

process.stdout.write(
logger.log(
`\n${logSymbols.info}${blue(' INFO ')} ` +
'For more information and a detailed description of each question, have a look at: ' +
`${bold(green('https://github.com/webpack/webpack-cli/blob/master/INIT.md'))}\n`,
`${bold(green('https://github.com/webpack/webpack-cli/blob/master/INIT.md'))}`,
);
process.stdout.write(`${logSymbols.info}${blue(' INFO ')} ` + 'Alternatively, run "webpack(-cli) --help" for usage info\n\n');
logger.log(`${logSymbols.info}${blue(' INFO ')} ` + 'Alternatively, run "webpack(-cli) --help" for usage info\n');

const { multiEntries } = await Confirm(
self,
Expand Down
2 changes: 1 addition & 1 deletion packages/info/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,6 @@ export default async function info(...args): Promise<string[]> {
output = output.replace(/npmGlobalPackages/g, 'Global Packages');

const finalOutput = output;
process.stdout.write(finalOutput + '\n');
logger.raw(finalOutput);
return finalOutput;
}
1 change: 1 addition & 0 deletions packages/migrate/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"p-lazy": "3.0.0"
},
"peerDependencies": {
"webpack-cli": "4.x.x",
"webpack": "4.x.x || 5.x.x"
},
"devDependencies": {
Expand Down
25 changes: 12 additions & 13 deletions packages/migrate/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { green, red } from 'colorette';
import { Change, diffLines } from 'diff';
import fs from 'fs';
import inquirer from 'inquirer';
import logger from 'webpack-cli/lib/utils/logger';
import Listr from 'listr';
import pLazy = require('p-lazy');
import path from 'path';
Expand Down Expand Up @@ -121,7 +122,7 @@ function runMigration(currentConfigPath: string, outputConfigPath: string): Prom
},
]);
} else {
console.error(red('✖ Migration aborted'));
logger.error('✖ Migration aborted');
}
},
)
Expand All @@ -138,24 +139,23 @@ function runMigration(currentConfigPath: string, outputConfigPath: string): Prom
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const webpackOptionsValidationErrors: any = validate(outputConfig);
if (webpackOptionsValidationErrors.length) {
console.error(red("\n✖ Your configuration validation wasn't successful \n"));
logger.error("\n✖ Your configuration validation wasn't successful\n");
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
console.error(new WebpackOptionsValidationError(webpackOptionsValidationErrors));
logger.error(new WebpackOptionsValidationError(webpackOptionsValidationErrors));
}
}

console.info(green(`\n✔︎ New webpack config file is at ${outputConfigPath}.`));
console.info(green('✔︎ Heads up! Updating to the latest version could contain breaking changes.'));
logger.success(`\n✔︎ New webpack config file is at ${outputConfigPath}.`);
logger.success('✔︎ Heads up! Updating to the latest version could contain breaking changes.');

console.info(green('✔︎ Plugin and loader dependencies may need to be updated.'));
logger.success('✔︎ Plugin and loader dependencies may need to be updated.');
},
);
})
.catch((err: object): void => {
const errMsg = '\n ✖ ︎Migration aborted due to some errors: \n';
console.error(red(errMsg));
console.error(err);
logger.error('\n ✖ ︎Migration aborted due to some errors:\n');
logger.error(err);
process.exitCode = 1;
});
}
Expand All @@ -174,8 +174,7 @@ function runMigration(currentConfigPath: string, outputConfigPath: string): Prom
export default function migrate(...args: string[]): void | Promise<void> {
const filePaths = args;
if (!filePaths.length) {
const errMsg = '\n ✖ Please specify a path to your webpack config \n ';
console.error(red(errMsg));
logger.error('\n ✖ Please specify a path to your webpack config\n');
return;
}

Expand All @@ -194,14 +193,14 @@ export default function migrate(...args: string[]): void | Promise<void> {
])
.then((ans: { confirmPath: boolean }): void | Promise<void> => {
if (!ans.confirmPath) {
console.error(red('✖ ︎Migration aborted due to no output path'));
logger.error('✖ ︎Migration aborted due to no output path');
return;
}
outputConfigPath = path.resolve(process.cwd(), filePaths[0]);
return runMigration(currentConfigPath, outputConfigPath);
})
.catch((err: object): void => {
console.error(err);
logger.error(err);
});
}
jamesgeorge007 marked this conversation as resolved.
Show resolved Hide resolved
outputConfigPath = path.resolve(process.cwd(), filePaths[1]);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { red, underline } from 'colorette';

import logger from 'webpack-cli/lib/utils/logger';

import { findPluginsByName, isType, safeTraverse } from '@webpack-cli/utils';

import { JSCodeshift, Node } from '../types/NodePath';
Expand Down Expand Up @@ -34,7 +36,7 @@ export default function (j: JSCodeshift, ast: Node): Node {
j(path).remove();
}
} else {
process.stderr.write(`
logger.log(`
${red('Please remove deprecated plugins manually. ')}
See ${underline('https://webpack.js.org/guides/migrating/')} for more information.`);
}
Expand Down
9 changes: 4 additions & 5 deletions packages/utils/__tests__/run-prettier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@ import { runPrettier } from '../src/run-prettier';

const outputPath = path.join(__dirname, 'test-assets');
const outputFile = path.join(outputPath, 'test.js');
const stdoutSpy = jest.spyOn(process.stdout, 'write');
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();

describe('runPrettier', () => {
beforeEach(() => {
rimraf.sync(outputPath);
fs.mkdirSync(outputPath);
stdoutSpy.mockClear();
});

afterAll(() => {
Expand All @@ -27,7 +26,7 @@ describe('runPrettier', () => {
const data = fs.readFileSync(outputFile, 'utf8');
expect(data).toContain("console.log('1');\n");

expect(stdoutSpy.mock.calls.length).toEqual(0);
expect(consoleSpy).toHaveBeenCalledTimes(0);
});

it('prettier should fail on invalid JS, with file still written', () => {
Expand All @@ -36,7 +35,7 @@ describe('runPrettier', () => {
const data = fs.readFileSync(outputFile, 'utf8');
expect(data).toContain('"');

expect(stdoutSpy.mock.calls.length).toEqual(1);
expect(stdoutSpy.mock.calls[0][0]).toContain('WARNING: Could not apply prettier');
expect(consoleSpy).toHaveBeenCalledTimes(1);
expect(consoleSpy.mock.calls[0][0]).toContain('WARNING: Could not apply prettier');
});
});
3 changes: 2 additions & 1 deletion packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"yeoman-generator": "4.7.2"
},
"peerDependencies": {
"webpack": "4.x.x || 5.x.x"
"webpack": "4.x.x || 5.x.x",
"webpack-cli": "4.x.x || 5.x.x"
},
"devDependencies": {
"@types/got": "9.6.9",
Expand Down
30 changes: 13 additions & 17 deletions packages/utils/src/modify-config-helper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { red, green } from 'colorette';
import { green } from 'colorette';
import fs from 'fs';
import logger from 'webpack-cli/lib/utils/logger';
import path from 'path';
import yeoman from 'yeoman-environment';
import Generator from 'yeoman-generator';
Expand Down Expand Up @@ -84,7 +85,7 @@ export function modifyHelperUtil(
}
}
} catch (err) {
console.error(red('\nYour package.json was incorrectly formatted.\n'));
logger.error('\nYour package.json was incorrectly formatted.\n');
Error.stackTraceLimit = 0;
process.exitCode = 2;
}
Expand All @@ -103,9 +104,9 @@ export function modifyHelperUtil(
const confPath = path.resolve(process.cwd(), '.yo-rc.json');
configModule = require(confPath);
} catch (err) {
console.error(red('\nCould not find a yeoman configuration file (.yo-rc.json).\n'));
console.error(
red("\nPlease make sure to use 'this.config.set('configuration', this.configuration);' at the end of the generator.\n"),
logger.error('\nCould not find a yeoman configuration file (.yo-rc.json).\n');
logger.error(
"\nPlease make sure to use 'this.config.set('configuration', this.configuration);' at the end of the generator.\n",
);
Error.stackTraceLimit = 0;
process.exitCode = 2;
Expand All @@ -120,11 +121,9 @@ export function modifyHelperUtil(
finalConfig = configModule[packageName].configuration;
}
} catch (err) {
console.error(err);
console.error(err.stack);
console.error(
red('\nYour yeoman configuration file (.yo-rc.json) was incorrectly formatted. Deleting it may fix the problem.\n'),
);
logger.error(err);
logger.error(`${err.stack}\n`);
logger.error('Your yeoman configuration file (.yo-rc.json) was incorrectly formatted. Deleting it may fix the problem.\n');
Error.stackTraceLimit = 0;
process.exitCode = 2;
}
Expand All @@ -139,22 +138,19 @@ export function modifyHelperUtil(
if (finalConfig.usingDefaults && finalConfig.usingDefaults === true) {
const runCommand = getPackageManager() === 'yarn' ? 'yarn build' : 'npm run build';

const successMessage = `\nYou can now run ${green(runCommand)} to bundle your application!\n\n`;
process.stdout.write(`\n${successMessage}`);
logger.log(`\nYou can now run ${green(runCommand)} to bundle your application!\n`);
}

// scaffold webpack config file from using .yo-rc.json
return runTransform(transformConfig, 'init', generateConfig);
})
.catch((err): void => {
console.error(
red(
`
logger.error(
`
Unexpected Error
please file an issue here https://github.com/webpack/webpack-cli/issues/new?template=Bug_report.md
`,
),
);
console.error(err);
logger.error(err);
});
}
4 changes: 3 additions & 1 deletion packages/utils/src/recursive-parser.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { parseTopScope, findRootNodesByName, addProperty, removeProperty, parseMerge, safeTraverse } from './ast-utils';
import { JSCodeshift, Node, valueType } from './types/NodePath';

import logger from 'webpack-cli/lib/utils/logger';

export function recursiveTransform(j: JSCodeshift, ast: Node, key: string, value: valueType, action: string): boolean | Node {
if (key === 'topScope') {
if (Array.isArray(value)) {
return parseTopScope(j, ast, value, action);
}
console.error('Error in parsing top scope, Array required');
logger.error('Error in parsing top scope, Array required');
return false;
} else if (key === 'merge') {
if (Array.isArray(value)) {
Expand Down
23 changes: 12 additions & 11 deletions packages/utils/src/resolve-packages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { red, bold } from 'colorette';
import { bold } from 'colorette';
import logger from 'webpack-cli/lib/utils/logger';
import path from 'path';
import { modifyHelperUtil } from './modify-config-helper';
import { getPathToGlobalPackages, spawnChild } from '@webpack-cli/package-utils';
Expand Down Expand Up @@ -57,9 +58,9 @@ export function resolvePackages(pkg: string[]): Function | void {
require.resolve(absolutePath);
packageLocations.push(absolutePath);
} catch (err) {
console.error(`Cannot find a generator at ${absolutePath}.`);
console.error('\nReason:\n');
console.error(bold(red(err)));
logger.error(`Cannot find a generator at ${absolutePath}.\n`);
jamesgeorge007 marked this conversation as resolved.
Show resolved Hide resolved
logger.error('Reason:\n');
jamesgeorge007 marked this conversation as resolved.
Show resolved Hide resolved
logger.error(bold(err));
process.exitCode = 1;
}

Expand All @@ -74,17 +75,17 @@ export function resolvePackages(pkg: string[]): Function | void {
const globalPath: string = getPathToGlobalPackages();
packageLocations.push(path.resolve(globalPath, scaffold));
} catch (err) {
console.error("Package wasn't validated correctly..");
console.error('Submit an issue for', pkg, 'if this persists');
console.error('\nReason: \n');
console.error(bold(red(err)));
logger.error("Package wasn't validated correctly...");
logger.error(`Submit an issue for ${pkg} if this persists\n`);
logger.error('Reason:\n');
logger.error(bold(err));
process.exitCode = 1;
}
})
.catch((err: string): void => {
console.error("Package couldn't be installed, aborting..");
console.error('\nReason: \n');
console.error(bold(red(err)));
logger.error("Package couldn't be installed, aborting...\n");
logger.error('Reason:\n');
logger.error(bold(err));
process.exitCode = 1;
})
.then(invokeGeneratorIfReady);
Expand Down
6 changes: 2 additions & 4 deletions packages/utils/src/run-prettier.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { yellow } from 'colorette';
import fs from 'fs';
import prettier from 'prettier';
import logger from 'webpack-cli/lib/utils/logger';

/**
*
Expand All @@ -22,9 +22,7 @@ export function runPrettier(outputPath: string, source: string): void {
useTabs: true,
});
} catch (err) {
process.stdout.write(
`\n${yellow(`WARNING: Could not apply prettier to ${outputPath}` + ' due validation error, but the file has been created\n')}`,
);
logger.warn(`\nWARNING: Could not apply prettier to ${outputPath} due to validation error, but the file has been created`);
prettySource = source;
}

Expand Down
5 changes: 3 additions & 2 deletions packages/utils/src/scaffold.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { green } from 'colorette';
import j from 'jscodeshift';
import logger from 'webpack-cli/lib/utils/logger';
import pEachSeries = require('p-each-series');
import path from 'path';
import { getPackageManager } from '@webpack-cli/package-utils';
Expand Down Expand Up @@ -88,7 +89,7 @@ export function runTransform(transformConfig: TransformConfig, action: string, g
runPrettier(outputPath, source);
})
.catch((err: Error): void => {
console.error(err.message ? err.message : err);
logger.error(err);
});
},
);
Expand All @@ -102,5 +103,5 @@ export function runTransform(transformConfig: TransformConfig, action: string, g
if (initActionNotDefined && transformConfig.config.item) {
successMessage = green(`Congratulations! ${transformConfig.config.item} has been ${action}ed!\n`);
}
process.stdout.write(`\n${successMessage}`);
logger.log(`\n${successMessage}`);
}
3 changes: 1 addition & 2 deletions packages/webpack-cli/lib/bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,7 @@ async function runCLI(cliArgs) {
cliArgs = newArgKeys;
args = argParser('', core, cliArgs);
await cli.run(args.opts, core);
process.stdout.write('\n');
logger.warn('Duplicate flags found, defaulting to last set value');
logger.warn('\nDuplicate flags found, defaulting to last set value');
} else {
logger.error(err);
return;
Expand Down
4 changes: 2 additions & 2 deletions packages/webpack-cli/lib/groups/BasicGroup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const GroupHelper = require('../utils/GroupHelper');
const { red } = require('colorette');
const logger = require('../utils/logger');
const { core, groups } = require('../utils/cli-flags');

class BasicGroup extends GroupHelper {
Expand Down Expand Up @@ -39,7 +39,7 @@ class BasicGroup extends GroupHelper {
if (arg === 'entry') {
options[arg] = this.resolveFilePath(args[arg], 'index.js');
if (options[arg].length === 0) {
process.stdout.write(red('\nError: you provided an invalid entry point.\n'));
logger.error('\nError: you provided an invalid entry point.');
}
}
});
Expand Down
Loading