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: Unify logging #146

Merged
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions packages/cli/src/generator/copyProjectTemplateAndReplace.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const path = require('path');
const copyAndReplace = require('../util/copyAndReplace');
const prompt = require('./promptSync')();
const walk = require('../util/walk');
const logger = require('../util/logger');

/**
* Util for creating a new React Native project.
Expand Down Expand Up @@ -135,11 +136,11 @@ function upgradeFileContentChangedCallback(
contentChanged
) {
if (contentChanged === 'new') {
console.log(`${chalk.bold('new')} ${relativeDestPath}`);
logger.info(`${chalk.bold('new')} ${relativeDestPath}`);
return 'overwrite';
}
if (contentChanged === 'changed') {
console.log(
logger.info(
`${chalk.bold(relativeDestPath)} ` +
`has changed in the new version.\nDo you want to keep your ${relativeDestPath} or replace it with the ` +
`latest version?\nIf you ever made any changes ` +
Expand All @@ -150,10 +151,10 @@ function upgradeFileContentChangedCallback(
);
const answer = prompt();
if (answer === 'y') {
console.log(`Replacing ${relativeDestPath}`);
logger.info(`Replacing ${relativeDestPath}`);
return 'overwrite';
}
console.log(`Keeping your ${relativeDestPath}`);
logger.info(`Keeping your ${relativeDestPath}`);
return 'keep';
}
if (contentChanged === 'identical') {
Expand Down
24 changes: 11 additions & 13 deletions packages/cli/src/generator/printRunInstructions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
* @format
*/

const chalk = require('chalk');
const path = require('path');
const logger = require('../util/logger');

function printRunInstructions(projectDir, projectName) {
const absoluteProjectDir = path.resolve(projectDir);
Expand All @@ -22,19 +22,17 @@ function printRunInstructions(projectDir, projectName) {
process.cwd(),
xcodeProjectPath
);
console.log(chalk.white.bold('To run your app on iOS:'));
console.log(` cd ${absoluteProjectDir}`);
console.log(' react-native run-ios');
console.log(' - or -');
console.log(` Open ${relativeXcodeProjectPath} in Xcode`);
console.log(' Hit the Run button');
logger.info(`To run your app on iOS:
cd ${absoluteProjectDir}
react-native run-ios');
- or -
Open ${relativeXcodeProjectPath} in Xcode
Hit the Run button
// Android
console.log(chalk.white.bold('To run your app on Android:'));
console.log(` cd ${absoluteProjectDir}`);
console.log(
' Have an Android emulator running (quickest way to get started), or a device connected'
);
console.log(' react-native run-android');
To run your app on Android:
cd ${absoluteProjectDir}
Have an Android emulator running (quickest way to get started), or a device connected
react-native run-android`);
}

module.exports = printRunInstructions;
19 changes: 10 additions & 9 deletions packages/cli/src/generator/templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const copyProjectTemplateAndReplace = require('./copyProjectTemplateAndReplace');
const logger = require('../util/logger');

/**
* @param destPath Create the new project at this path.
Expand Down Expand Up @@ -68,7 +69,7 @@ function createFromRemoteTemplate(
}

// Check if the template exists
console.log(`Fetching template ${installPackage}...`);
logger.info(`Fetching template ${installPackage}...`);
try {
if (yarnVersion) {
execSync(`yarn add ${installPackage} --ignore-scripts`, {
Expand Down Expand Up @@ -105,7 +106,7 @@ function createFromRemoteTemplate(
} catch (err) {
// Not critical but we still want people to know and report
// if this the clean up fails.
console.warn(
logger.warn(
`Failed to clean up template temp files in node_modules/${templateName}. ` +
'This is not a critical error, you can work on your app.'
);
Expand All @@ -117,9 +118,9 @@ function installTemplateDependencies(templatePath, yarnVersion) {
// dependencies.json is a special file that lists additional dependencies
// that are required by this template
const dependenciesJsonPath = path.resolve(templatePath, 'dependencies.json');
console.log('Adding dependencies for the project...');
logger.info('Adding dependencies for the project...');
if (!fs.existsSync(dependenciesJsonPath)) {
console.log('No additional dependencies.');
logger.info('No additional dependencies.');
return;
}

Expand All @@ -134,7 +135,7 @@ function installTemplateDependencies(templatePath, yarnVersion) {
for (const depName of Object.keys(dependencies)) {
const depVersion = dependencies[depName];
const depToInstall = `${depName}@${depVersion}`;
console.log(`Adding ${depToInstall}...`);
logger.info(`Adding ${depToInstall}...`);
if (yarnVersion) {
execSync(`yarn add ${depToInstall}`, { stdio: 'inherit' });
} else {
Expand All @@ -143,7 +144,7 @@ function installTemplateDependencies(templatePath, yarnVersion) {
});
}
}
console.log("Linking native dependencies into the project's build files...");
logger.info("Linking native dependencies into the project's build files...");
execSync('react-native link', { stdio: 'inherit' });
}

Expand All @@ -154,9 +155,9 @@ function installTemplateDevDependencies(templatePath, yarnVersion) {
templatePath,
'devDependencies.json'
);
console.log('Adding develop dependencies for the project...');
logger.info('Adding develop dependencies for the project...');
if (!fs.existsSync(devDependenciesJsonPath)) {
console.log('No additional develop dependencies.');
logger.info('No additional develop dependencies.');
return;
}

Expand All @@ -171,7 +172,7 @@ function installTemplateDevDependencies(templatePath, yarnVersion) {
for (const depName of Object.keys(dependencies)) {
const depVersion = dependencies[depName];
const depToInstall = `${depName}@${depVersion}`;
console.log(`Adding ${depToInstall}...`);
logger.info(`Adding ${depToInstall}...`);
if (yarnVersion) {
execSync(`yarn add ${depToInstall} -D`, { stdio: 'inherit' });
} else {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/init/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function init(projectDir, argsOrName) {

// args array is e.g. ['AwesomeApp', '--verbose', '--template', 'navigation']
if (!args || args.length === 0) {
console.error('react-native init requires a project name.');
logger.error('react-native init requires a project name.');
return;
}

Expand All @@ -54,15 +54,15 @@ function generateProject(destinationRoot, newProjectName, options) {
const reactNativePackageJson = require('react-native/package.json');
const { peerDependencies } = reactNativePackageJson;
if (!peerDependencies) {
console.error(
logger.error(
"Missing React peer dependency in React Native's package.json. Aborting."
);
return;
}

const reactVersion = peerDependencies.react;
if (!reactVersion) {
console.error(
logger.error(
"Missing React peer dependency in React Native's package.json. Aborting."
);
return;
Expand Down
6 changes: 2 additions & 4 deletions packages/cli/src/logAndroid/logAndroid.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* LICENSE file in the root directory of this source tree.
*/

const chalk = require('chalk');
const { spawnSync } = require('child_process');
const logger = require('../util/logger');

/**
* Starts adb logcat
Expand All @@ -18,9 +18,7 @@ async function logAndroid() {

const adbArgs = ['logcat', '*:S', 'ReactNative:V', 'ReactNativeJS:V'];

console.log(
chalk.bold(`Starting the logger (${adbPath} ${adbArgs.join(' ')})...`)
);
logger.info(`Starting the logger (${adbPath} ${adbArgs.join(' ')})...`);

const log = spawnSync(adbPath, adbArgs, { stdio: 'inherit' });

Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/logIOS/logIOS.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
* @format
*/

const chalk = require('chalk');
const { execFileSync, spawnSync } = require('child_process');
const os = require('os');
const path = require('path');
const logger = require('../util/logger');

function findAvailableDevice(devices) {
for (const key of Object.keys(devices)) {
Expand All @@ -37,7 +37,7 @@ async function logIOS() {

const device = findAvailableDevice(devices);
if (device === undefined) {
console.log(chalk.red('No active iOS device found'));
logger.error('No active iOS device found');
return;
}

Expand Down
54 changes: 24 additions & 30 deletions packages/cli/src/runAndroid/runAndroid.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@

import type { ContextT } from '../core/types.flow';

const chalk = require('chalk');
const { spawnSync, spawn, execFileSync } = require('child_process');
const fs = require('fs');
const isString = require('lodash/isString');
const path = require('path');
const isPackagerRunning = require('../util/isPackagerRunning');
const logger = require('../util/logger');
const adb = require('./adb');
const runOnAllDevices = require('./runOnAllDevices');
const tryRunAdbReverse = require('./tryRunAdbReverse');
Expand All @@ -33,10 +33,8 @@ function checkAndroid(root) {
*/
function runAndroid(argv: Array<string>, ctx: ContextT, args: Object) {
if (!checkAndroid(args.root)) {
console.log(
chalk.red(
'Android project not found. Are you sure this is a React Native project?'
)
logger.error(
'Android project not found. Are you sure this is a React Native project?'
);
return;
}
Expand All @@ -47,14 +45,12 @@ function runAndroid(argv: Array<string>, ctx: ContextT, args: Object) {

return isPackagerRunning(args.port).then(result => {
if (result === 'running') {
console.log(chalk.bold('JS server already running.'));
logger.info('JS server already running.');
} else if (result === 'unrecognized') {
console.warn(
chalk.yellow('JS server not recognized, continuing with build...')
);
logger.warn('JS server not recognized, continuing with build...');
} else {
// result == 'not_running'
console.log(chalk.bold('Starting JS server...'));
logger.info('Starting JS server...');
startServerInNewWindow(args.port, args.terminal, ctx.reactNativePath);
}
return buildAndRun(args);
Expand Down Expand Up @@ -101,7 +97,7 @@ function buildAndRun(args) {
adbPath
);
}
console.log(chalk.red('Argument missing for parameter --deviceId'));
logger.error('Argument missing for parameter --deviceId');
} else {
return runOnAllDevices(
args,
Expand Down Expand Up @@ -132,27 +128,28 @@ function runOnSpecificDevice(
adbPath
);
} else {
console.log(`Could not find device with the id: "${args.deviceId}".`);
console.log('Choose one of the following:');
console.log(devices);
logger.error(
`Could not find device with the id: "${
args.deviceId
}". Choose one of the following:`,
...devices
);
}
} else {
console.log('No Android devices connected.');
logger.error('No Android devices connected.');
}
}

function buildApk(gradlew) {
try {
console.log(chalk.bold('Building the app...'));
logger.info('Building the app...');

// using '-x lint' in order to ignore linting errors while building the apk
execFileSync(gradlew, ['build', '-x', 'lint'], {
stdio: [process.stdin, process.stdout, process.stderr],
});
} catch (e) {
console.log(
chalk.red('Could not build the app, read the error above for details.\n')
);
logger.error('Could not build the app, read the error above for details.');
}
}

Expand All @@ -163,20 +160,17 @@ function tryInstallAppOnDevice(args, device) {
const pathToApk = `${appFolder}/build/outputs/apk/${appFolder}-debug.apk`;
const adbPath = getAdbPath();
const adbArgs = ['-s', device, 'install', pathToApk];
console.log(
chalk.bold(
`Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`
)
logger.info(
`Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`
);
execFileSync(adbPath, adbArgs, {
stdio: [process.stdin, process.stdout, process.stderr],
});
} catch (e) {
console.log(e.message);
console.log(
chalk.red(
'Could not install the app on the device, read the error above for details.\n'
)
logger.error(
`${
e.message
}\nCould not install the app on the device, read the error above for details.`
);
}
}
Expand Down Expand Up @@ -264,8 +258,8 @@ function startServerInNewWindow(
procConfig.stdio = 'ignore';
return spawn('cmd.exe', ['/C', launchPackagerScript], procConfig);
}
console.log(
chalk.red(`Cannot start the packager. Unknown platform ${process.platform}`)
logger.error(
`Cannot start the packager. Unknown platform ${process.platform}`
);
}

Expand Down
Loading