refactor(lint): Don't allow console.log

Enable tslint check for `console.log` as a follow-up to
https://github.com/angular/angular/issues/13018
This commit is contained in:
Bowen Ni 2016-11-22 13:29:53 -08:00 committed by vsavkin
parent 6c2d931744
commit 2c02d34c05
32 changed files with 38 additions and 31 deletions

View File

@ -27,9 +27,7 @@ describe('firefox extension', function() {
browser.driver.get(TEST_URL); browser.driver.get(TEST_URL);
browser.executeScript('window.startProfiler()').then(function() { browser.executeScript('window.startProfiler()');
console.log('started measuring perf');
});
browser.executeAsyncScript('setTimeout(arguments[0], 1000);'); browser.executeAsyncScript('setTimeout(arguments[0], 1000);');
browser.executeScript('window.forceGC()'); browser.executeScript('window.forceGC()');

View File

@ -44,7 +44,7 @@ export class CodeGenerator {
let root = this.options.basePath; let root = this.options.basePath;
for (const eachRootDir of this.options.rootDirs || []) { for (const eachRootDir of this.options.rootDirs || []) {
if (this.options.trace) { if (this.options.trace) {
console.log(`Check if ${filePath} is under rootDirs element ${eachRootDir}`); console.error(`Check if ${filePath} is under rootDirs element ${eachRootDir}`);
} }
if (path.relative(eachRootDir, filePath).indexOf('.') !== 0) { if (path.relative(eachRootDir, filePath).indexOf('.') !== 0) {
root = eachRootDir; root = eachRootDir;

View File

@ -56,7 +56,7 @@ export class PathMappedCompilerHost extends CompilerHost {
ts.resolveModuleName(m, rootedContainingFile, this.options, this.context).resolvedModule; ts.resolveModuleName(m, rootedContainingFile, this.options, this.context).resolvedModule;
if (resolved) { if (resolved) {
if (this.options.traceResolution) { if (this.options.traceResolution) {
console.log('resolve', m, containingFile, '=>', resolved.resolvedFileName); console.error('resolve', m, containingFile, '=>', resolved.resolvedFileName);
} }
return this.getCanonicalFileName(resolved.resolvedFileName); return this.getCanonicalFileName(resolved.resolvedFileName);
} }
@ -71,7 +71,7 @@ export class PathMappedCompilerHost extends CompilerHost {
*/ */
fileNameToModuleName(importedFile: string, containingFile: string): string { fileNameToModuleName(importedFile: string, containingFile: string): string {
if (this.options.traceResolution) { if (this.options.traceResolution) {
console.log( console.error(
'getImportPath from containingFile', containingFile, 'to importedFile', importedFile); 'getImportPath from containingFile', containingFile, 'to importedFile', importedFile);
} }

View File

@ -369,7 +369,7 @@ export function extractProgramSymbols(
files.filter(fileName => _filterFileByPatterns(fileName, options)).forEach(sourceFile => { files.filter(fileName => _filterFileByPatterns(fileName, options)).forEach(sourceFile => {
const moduleMetadata = staticReflector.getModuleMetadata(sourceFile); const moduleMetadata = staticReflector.getModuleMetadata(sourceFile);
if (!moduleMetadata) { if (!moduleMetadata) {
console.log(`WARNING: no metadata found for ${sourceFile}`); console.error(`WARNING: no metadata found for ${sourceFile}`);
return; return;
} }

View File

@ -163,7 +163,7 @@ export class StaticReflector implements ReflectorReader {
} }
return parameters; return parameters;
} catch (e) { } catch (e) {
console.log(`Failed on type ${JSON.stringify(type)} with error ${e}`); console.error(`Failed on type ${JSON.stringify(type)} with error ${e}`);
throw e; throw e;
} }
} }

View File

@ -15,7 +15,6 @@ export function verifyNoBrowserErrors() {
const errors: any[] = []; const errors: any[] = [];
browserLog.filter(logEntry => { browserLog.filter(logEntry => {
const msg = logEntry.message; const msg = logEntry.message;
console.log('>> ' + msg);
if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { if (logEntry.level.value >= webdriver.logging.Level.INFO.value) {
errors.push(msg); errors.push(msg);
} }

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Observable // #docregion Observable
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber'; import {Subscriber} from 'rxjs/Subscriber';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Observable // #docregion Observable
import 'rxjs/add/operator/map'; import 'rxjs/add/operator/map';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Observable // #docregion Observable
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber'; import {Subscriber} from 'rxjs/Subscriber';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Component // #docregion Component
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {FormArray, FormControl, FormGroup} from '@angular/forms'; import {FormArray, FormControl, FormGroup} from '@angular/forms';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Component // #docregion Component
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms'; import {FormControl, FormGroup, Validators} from '@angular/forms';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Component // #docregion Component
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {NgForm} from '@angular/forms'; import {NgForm} from '@angular/forms';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Component // #docregion Component
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {NgForm} from '@angular/forms'; import {NgForm} from '@angular/forms';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
// #docregion Component // #docregion Component
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms'; import {FormControl, FormGroup, Validators} from '@angular/forms';

View File

@ -129,6 +129,7 @@ export function isJsObject(o: any): boolean {
} }
export function print(obj: Error | Object) { export function print(obj: Error | Object) {
// tslint:disable-next-line:no-console
console.log(obj); console.log(obj);
} }

View File

@ -85,6 +85,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
log(error: string): void { log(error: string): void {
if (window.console) { if (window.console) {
// tslint:disable-next-line:no-console
window.console.log && window.console.log(error); window.console.log && window.console.log(error);
} }
} }

View File

@ -75,7 +75,9 @@ export class AngularProfiler {
(<any>window.console.profileEnd)(profileName); (<any>window.console.profileEnd)(profileName);
} }
const msPerTick = (end - start) / numTicks; const msPerTick = (end - start) / numTicks;
// tslint:disable-next-line:no-console
window.console.log(`ran ${numTicks} change detection cycles`); window.console.log(`ran ${numTicks} change detection cycles`);
// tslint:disable-next-line:no-console
window.console.log(`${msPerTick.toFixed(2)} ms per check`); window.console.log(`${msPerTick.toFixed(2)} ms per check`);
return new ChangeDetectionPerfRecord(msPerTick, numTicks); return new ChangeDetectionPerfRecord(msPerTick, numTicks);

View File

@ -63,6 +63,7 @@ export class Parse5DomAdapter extends DomAdapter {
logError(error: string) { console.error(error); } logError(error: string) { console.error(error); }
// tslint:disable-next-line:no-console
log(error: string) { console.log(error); } log(error: string) { console.log(error); }
logGroup(error: string) { console.error(error); } logGroup(error: string) { console.error(error); }

View File

@ -22,10 +22,12 @@ export class WorkerDomAdapter extends DomAdapter {
if (console.error) { if (console.error) {
console.error(error); console.error(error);
} else { } else {
// tslint:disable-next-line:no-console
console.log(error); console.log(error);
} }
} }
// tslint:disable-next-line:no-console
log(error: any /** TODO #9100 */) { console.log(error); } log(error: any /** TODO #9100 */) { console.log(error); }
logGroup(error: any /** TODO #9100 */) { logGroup(error: any /** TODO #9100 */) {
@ -33,6 +35,7 @@ export class WorkerDomAdapter extends DomAdapter {
console.group(error); console.group(error);
this.logError(error); this.logError(error);
} else { } else {
// tslint:disable-next-line:no-console
console.log(error); console.log(error);
} }
} }

View File

@ -15,7 +15,7 @@ export function stringify(obj: any): string {
export function onError(e: any) { export function onError(e: any) {
// TODO: (misko): We seem to not have a stack trace here! // TODO: (misko): We seem to not have a stack trace here!
console.log(e, e.stack); console.error(e, e.stack);
throw e; throw e;
} }

View File

@ -41,7 +41,7 @@ export function main() {
it('should throw an uncaught error', fakeAsync(() => { it('should throw an uncaught error', fakeAsync(() => {
const resolveSpy = jasmine.createSpy('resolveSpy'); const resolveSpy = jasmine.createSpy('resolveSpy');
spyOn(console, 'log'); spyOn(console, 'error');
expect(() => { expect(() => {
adapter.bootstrap(html('<ng2></ng2>'), ['ng1']).ready(resolveSpy); adapter.bootstrap(html('<ng2></ng2>'), ['ng1']).ready(resolveSpy);
@ -50,14 +50,14 @@ export function main() {
expect(resolveSpy).not.toHaveBeenCalled(); expect(resolveSpy).not.toHaveBeenCalled();
})); }));
it('should properly log to the console and re-throw', fakeAsync(() => { it('should output an error message to the console and re-throw', fakeAsync(() => {
spyOn(console, 'log'); spyOn(console, 'error');
expect(() => { expect(() => {
adapter.bootstrap(html('<ng2></ng2>'), ['ng1']); adapter.bootstrap(html('<ng2></ng2>'), ['ng1']);
flushMicrotasks(); flushMicrotasks();
}).toThrowError(); }).toThrowError();
expect(console.log).toHaveBeenCalled(); expect(console.error).toHaveBeenCalled();
expect(console.log).toHaveBeenCalledWith(jasmine.any(Error), jasmine.any(String)); expect(console.error).toHaveBeenCalledWith(jasmine.any(Error), jasmine.any(String));
})); }));
}); });

View File

@ -24,7 +24,6 @@ describe('ng2 largetable benchmark', function() {
['interpolation', 'interpolationAttr', 'interpolationFn'].forEach(function(benchmarkType) { ['interpolation', 'interpolationAttr', 'interpolationFn'].forEach(function(benchmarkType) {
it('should log the ng stats with: ' + benchmarkType, function(done) { it('should log the ng stats with: ' + benchmarkType, function(done) {
console.log('executing for type', benchmarkType);
runClickBenchmark({ runClickBenchmark({
url: URL, url: URL,
buttons: ['#ng2DestroyDom', '#ng2CreateDom'], buttons: ['#ng2DestroyDom', '#ng2CreateDom'],

View File

@ -51,7 +51,6 @@ export function profile(create: () => void, destroy: () => void, name: string) {
destroy(); destroy();
} }
window.console.profileEnd(); window.console.profileEnd();
window.console.log(`Iterations: ${count}; time: ${duration / count} ms / iteration`);
window.console.profile(name + ' w/o GC'); window.console.profile(name + ' w/o GC');
duration = 0; duration = 0;
@ -63,7 +62,6 @@ export function profile(create: () => void, destroy: () => void, name: string) {
destroy(); destroy();
} }
window.console.profileEnd(); window.console.profileEnd();
window.console.log(`Iterations: ${count}; time: ${duration / count} ms / iteration`);
}; };
} }

View File

@ -59,7 +59,7 @@ export function verifyNoBrowserErrors() {
browser.manage().logs().get('browser').then(function(browserLog: any) { browser.manage().logs().get('browser').then(function(browserLog: any) {
const filteredLog = browserLog.filter(function(logEntry: any) { const filteredLog = browserLog.filter(function(logEntry: any) {
if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { if (logEntry.level.value >= webdriver.logging.Level.INFO.value) {
console.log('>> ' + logEntry.message); console.error('>> ' + logEntry.message);
} }
return logEntry.level.value > webdriver.logging.Level.WARNING.value; return logEntry.level.value > webdriver.logging.Level.WARNING.value;
}); });

View File

@ -67,7 +67,7 @@ describe('WebWorkers Animations', function() {
browser.wait(protractor.until.elementLocated(by.css(selector + ' .box')), 5000) browser.wait(protractor.until.elementLocated(by.css(selector + ' .box')), 5000)
.then(() => {}, () => { .then(() => {}, () => {
// jasmine will timeout if this gets called too many times // jasmine will timeout if this gets called too many times
console.log('>> unexpected timeout -> browser.refresh()'); console.error('>> unexpected timeout -> browser.refresh()');
browser.refresh(); browser.refresh();
waitForBootstrap(); waitForBootstrap();
}); });

View File

@ -67,7 +67,7 @@ describe('WebWorkers Input', function() {
}, },
() => { () => {
// jasmine will timeout if this gets called too many times // jasmine will timeout if this gets called too many times
console.log('>> unexpected timeout -> browser.refresh()'); console.error('>> unexpected timeout -> browser.refresh()');
browser.refresh(); browser.refresh();
waitForBootstrap(); waitForBootstrap();
}); });

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
import {Component, Host, NgModule} from '@angular/core'; import {Component, Host, NgModule} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, FormGroupDirective, ReactiveFormsModule, Validators} from '@angular/forms'; import {AbstractControl, FormBuilder, FormGroup, FormGroupDirective, ReactiveFormsModule, Validators} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser'; import {BrowserModule} from '@angular/platform-browser';

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
/* tslint:disable:no-console */
import {Component, Directive, Host, NgModule} from '@angular/core'; import {Component, Directive, Host, NgModule} from '@angular/core';
import {FormControl, FormGroup, FormsModule, NG_VALIDATORS, NgForm} from '@angular/forms'; import {FormControl, FormGroup, FormsModule, NG_VALIDATORS, NgForm} from '@angular/forms';

View File

@ -27,6 +27,7 @@ export interface CompilerInterface {
const DEBUG = false; const DEBUG = false;
function debug(msg: string, ...o: any[]) { function debug(msg: string, ...o: any[]) {
// tslint:disable-next-line:no-console
if (DEBUG) console.log(msg, ...o); if (DEBUG) console.log(msg, ...o);
} }

View File

@ -21,11 +21,9 @@ function processOutputEmitterCodeGen(): Promise<number> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const outDir = 'dist/all/@angular/compiler/test/'; const outDir = 'dist/all/@angular/compiler/test/';
const promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
console.log('Processing codegen...');
OFFLINE_COMPILE.forEach((file: string) => { OFFLINE_COMPILE.forEach((file: string) => {
const codegen = require('../../all/@angular/compiler/test/' + file + '.js'); const codegen = require('../../all/@angular/compiler/test/' + file + '.js');
if (codegen.emit) { if (codegen.emit) {
console.log(` ${file} has changed, regenerating...`);
promises.push(Promise.resolve(codegen.emit()).then((code) => { promises.push(Promise.resolve(codegen.emit()).then((code) => {
writeFileSync(outDir + file + '.ts', code); writeFileSync(outDir + file + '.ts', code);
})); }));
@ -36,7 +34,6 @@ function processOutputEmitterCodeGen(): Promise<number> {
.then(() => { .then(() => {
const args = const args =
['--project', 'tools/cjs-jasmine/tsconfig-output_emitter_codegen.json']; ['--project', 'tools/cjs-jasmine/tsconfig-output_emitter_codegen.json'];
console.log(' compiling changes: tsc ' + args.join(' '));
const tsc = spawn(TSC, args, {stdio: 'pipe'}); const tsc = spawn(TSC, args, {stdio: 'pipe'});
tsc.stdout.on('data', (data: any) => process.stdout.write(data)); tsc.stdout.on('data', (data: any) => process.stdout.write(data));
tsc.stderr.on('data', (data: any) => process.stderr.write(data)); tsc.stderr.on('data', (data: any) => process.stderr.write(data));

View File

@ -37,7 +37,6 @@ export class TscWatch {
start: string, start: string,
complete: string, onStartCmds?: Array<string[]|Command>, onChangeCmds?: Array<string[]|Command> complete: string, onStartCmds?: Array<string[]|Command>, onChangeCmds?: Array<string[]|Command>
}) { }) {
console.log('Watching:', tsconfig, 'in', process.cwd());
this.tsconfig = tsconfig; this.tsconfig = tsconfig;
this.start = start; this.start = start;
this.error = error; this.error = error;
@ -67,14 +66,12 @@ export class TscWatch {
const args = argsOrCmd as Array<string>; const args = argsOrCmd as Array<string>;
return <any>new Promise((resolve, reject) => { return <any>new Promise((resolve, reject) => {
const [cmd, ...options] = args; const [cmd, ...options] = args;
console.log('=====>', cmd, options.join(' '));
const childProcess = spawn(cmd, options, {stdio: 'pipe'}); const childProcess = spawn(cmd, options, {stdio: 'pipe'});
childProcess.stdout.on('data', stdOut); childProcess.stdout.on('data', stdOut);
childProcess.stderr.on('data', stdErr); childProcess.stderr.on('data', stdErr);
const onExit = () => childProcess.kill(); const onExit = () => childProcess.kill();
childProcess.on('close', (code: number) => { childProcess.on('close', (code: number) => {
process.removeListener('exit', onExit); process.removeListener('exit', onExit);
console.log('EXIT:', code, '<=====', args.join(' '));
code ? reject(code) : resolve(code); code ? reject(code) : resolve(code);
}); });
process.on('exit', onExit); process.on('exit', onExit);
@ -98,7 +95,6 @@ export class TscWatch {
consumeLine(buffer: Buffer, isStdError: boolean) { consumeLine(buffer: Buffer, isStdError: boolean) {
const line = '' + buffer; const line = '' + buffer;
if (contains(line, this.start)) { if (contains(line, this.start)) {
console.log('==============================================================================');
stdOut(buffer, isStdError); stdOut(buffer, isStdError);
this.state = State.waiting; this.state = State.waiting;
} else if (contains(line, this.error)) { } else if (contains(line, this.error)) {
@ -106,15 +102,15 @@ export class TscWatch {
this.state = State.error; this.state = State.error;
} else if (contains(line, this.complete)) { } else if (contains(line, this.complete)) {
stdOut(buffer, isStdError); stdOut(buffer, isStdError);
console.log('------------------------------------------------------------------------------');
if (this.state == State.error) { if (this.state == State.error) {
console.log('Errors found.... (response not triggered)'); console.error('Errors found.... (response not triggered)');
if (this.runOnce) process.exit(1); if (this.runOnce) process.exit(1);
this.state = State.idle; this.state = State.idle;
} else { } else {
if (this.triggered) { if (this.triggered) {
this.triggered.then( this.triggered.then(
() => this.triggerCmds(), (e) => console.log('Error while running commands....', e)); () => this.triggerCmds(),
(e) => console.error('Error while running commands....', e));
} else { } else {
this.triggerCmds(); this.triggerCmds();
} }

View File

@ -5,6 +5,7 @@
], ],
"rules": { "rules": {
"file-header": [true, "Copyright Google Inc\\."], "file-header": [true, "Copyright Google Inc\\."],
"no-console": [true, "log"],
"no-duplicate-imports": true, "no-duplicate-imports": true,
"no-duplicate-variable": true, "no-duplicate-variable": true,
"no-jasmine-focus": true, "no-jasmine-focus": true,