浏览代码

Merge pull request #202 from javascript-obfuscator/cli-directory-obfuscation-logging

Cli directory obfuscation logging
Timofey Kachalov 7 年之前
父节点
当前提交
2be087f92e

文件差异内容过多而无法显示
+ 0 - 0
dist/index.js


+ 19 - 1
src/cli/utils/SourceCodeReader.ts

@@ -5,7 +5,10 @@ import { TSourceCodeData } from '../../types/cli/TSourceCodeData';
 
 import { IFileData } from '../../interfaces/cli/IFileData';
 
+import { LoggingPrefix } from '../../enums/logger/LoggingPrefix';
+
 import { JavaScriptObfuscatorCLI } from '../JavaScriptObfuscatorCLI';
+import { Logger } from '../../logger/Logger';
 
 export class SourceCodeReader {
     /**
@@ -63,7 +66,7 @@ export class SourceCodeReader {
                         ...SourceCodeReader.readDirectoryRecursive(filePath)
                     );
                 } else if (SourceCodeReader.isFilePath(filePath) && SourceCodeReader.isValidFile(fileName)) {
-                    const content: string = fs.readFileSync(filePath, JavaScriptObfuscatorCLI.encoding);
+                    const content: string = SourceCodeReader.readFile(filePath);
 
                     fileData.push({ filePath, content });
                 }
@@ -81,6 +84,8 @@ export class SourceCodeReader {
             throw new ReferenceError(`Input file must have .js extension`);
         }
 
+        SourceCodeReader.logFilePath(filePath);
+
         return fs.readFileSync(filePath, JavaScriptObfuscatorCLI.encoding);
     }
 
@@ -92,4 +97,17 @@ export class SourceCodeReader {
         return JavaScriptObfuscatorCLI.availableInputExtensions.includes(path.extname(filePath))
             && !filePath.includes(JavaScriptObfuscatorCLI.obfuscatedFilePrefix);
     }
+
+    /**
+     * @param {string} filePath
+     */
+    private static logFilePath (filePath: string): void {
+        const normalizedFilePath: string = path.normalize(filePath);
+
+        Logger.log(
+            Logger.colorInfo,
+            LoggingPrefix.CLI,
+            `Obfuscating file: ${normalizedFilePath}...`
+        );
+    }
 }

+ 4 - 0
src/enums/logger/LoggingPrefix.ts

@@ -0,0 +1,4 @@
+export enum LoggingPrefix {
+    Base = '[javascript-obfuscator]',
+    CLI = '[javascript-obfuscator-cli]'
+}

+ 32 - 36
src/logger/Logger.ts

@@ -1,40 +1,30 @@
-import { inject, injectable, postConstruct } from 'inversify';
+import { inject, injectable } from 'inversify';
 import { ServiceIdentifiers } from '../container/ServiceIdentifiers';
 
 import chalk, { Chalk } from 'chalk';
 
-import { IInitializable } from '../interfaces/IInitializable';
 import { ILogger } from '../interfaces/logger/ILogger';
 import { IOptions } from '../interfaces/options/IOptions';
 
 import { LoggingMessage } from '../enums/logger/LoggingMessage';
-
-import { initializable } from '../decorators/Initializable';
+import { LoggingPrefix } from '../enums/logger/LoggingPrefix';
 
 @injectable()
-export class Logger implements ILogger, IInitializable {
-    /**
-     * @type {string}
-     */
-    private static readonly loggingPrefix: string = '[javascript-obfuscator]';
-
+export class Logger implements ILogger {
     /**
      * @type {Chalk}
      */
-    @initializable()
-    private colorInfo!: Chalk;
+    public static readonly colorInfo: Chalk = chalk.cyan;
 
     /**
      * @type {Chalk}
      */
-    @initializable()
-    private colorSuccess!: Chalk;
+    public static readonly colorSuccess: Chalk = chalk.green;
 
     /**
      * @type {Chalk}
      */
-    @initializable()
-    private colorWarn!: Chalk;
+    public static readonly colorWarn: Chalk = chalk.yellow;
 
     /**
      * @type {IOptions}
@@ -50,50 +40,56 @@ export class Logger implements ILogger, IInitializable {
         this.options = options;
     }
 
-    @postConstruct()
-    public initialize (): void {
-        this.colorInfo = chalk.cyan;
-        this.colorSuccess = chalk.green;
-        this.colorWarn = chalk.yellow;
-    }
-
     /**
-     * @param {LoggingMessage} loggingMessage
+     * @param {Chalk} loggingLevelColor
+     * @param {LoggingPrefix} loggingPrefix
+     * @param {string} loggingMessage
      * @param {string | number} value
      */
-    public info (loggingMessage: LoggingMessage, value?: string | number): void {
-        this.log(this.colorInfo, loggingMessage, value);
+    public static log (
+        loggingLevelColor: Chalk,
+        loggingPrefix: LoggingPrefix,
+        loggingMessage: string,
+        value?: string | number,
+    ): void {
+        const processedMessage: string = loggingLevelColor(`\n${loggingPrefix} ${loggingMessage}`);
+
+        !value ? console.log(processedMessage) : console.log(processedMessage, value);
     }
 
     /**
      * @param {LoggingMessage} loggingMessage
      * @param {string | number} value
      */
-    public success (loggingMessage: LoggingMessage, value?: string | number): void {
-        this.log(this.colorSuccess, loggingMessage, value);
+    public info (loggingMessage: LoggingMessage, value?: string | number): void {
+        if (!this.options.log) {
+            return;
+        }
+
+        Logger.log(Logger.colorInfo, LoggingPrefix.Base, loggingMessage, value);
     }
 
     /**
      * @param {LoggingMessage} loggingMessage
      * @param {string | number} value
      */
-    public warn (loggingMessage: LoggingMessage, value?: string | number): void {
-        this.log(this.colorWarn, loggingMessage, value);
+    public success (loggingMessage: LoggingMessage, value?: string | number): void {
+        if (!this.options.log) {
+            return;
+        }
+
+        Logger.log(Logger.colorSuccess, LoggingPrefix.Base, loggingMessage, value);
     }
 
     /**
-     *
-     * @param {Chalk} loggingLevelColor
      * @param {LoggingMessage} loggingMessage
      * @param {string | number} value
      */
-    private log (loggingLevelColor: Chalk, loggingMessage: LoggingMessage, value?: string | number): void {
+    public warn (loggingMessage: LoggingMessage, value?: string | number): void {
         if (!this.options.log) {
             return;
         }
 
-        const processedMessage: string = loggingLevelColor(`\n${Logger.loggingPrefix} ${loggingMessage}`);
-
-        !value ? console.log(processedMessage) : console.log(processedMessage, value);
+        Logger.log(Logger.colorWarn, LoggingPrefix.Base, loggingMessage, value);
     }
 }

+ 38 - 1
test/unit-tests/cli/utils/SourceCodeReader.spec.ts

@@ -3,10 +3,12 @@ import * as mkdirp from 'mkdirp';
 import * as rimraf from 'rimraf';
 
 import { assert } from 'chai';
+import * as sinon from 'sinon';
 
-import { SourceCodeReader } from '../../../../src/cli/utils/SourceCodeReader';
 import { IFileData } from '../../../../src/interfaces/cli/IFileData';
 
+import { SourceCodeReader } from '../../../../src/cli/utils/SourceCodeReader';
+
 describe('SourceCodeReader', () => {
     const fileContent: string = 'test';
     const tmpDirectoryPath: string = 'test/tmp';
@@ -190,6 +192,41 @@ describe('SourceCodeReader', () => {
                 });
             });
         });
+
+        describe('Variant #3: logging', () => {
+            const tmpFileName: string = 'test.js';
+            const inputPath: string = `${tmpDirectoryPath}/${tmpFileName}`;
+            const expectedConsoleLogCallResult: boolean = true;
+            const expectedLoggingMessage: string = `[javascript-obfuscator-cli] Obfuscating file: ${inputPath}...`;
+
+            let consoleLogSpy: sinon.SinonSpy,
+                consoleLogCallResult: boolean,
+                loggingMessageResult: string;
+
+            before(() => {
+                consoleLogSpy = sinon.spy(console, 'log');
+
+                fs.writeFileSync(inputPath, fileContent);
+                SourceCodeReader.readSourceCode(inputPath);
+
+                consoleLogCallResult = consoleLogSpy.called;
+                loggingMessageResult = consoleLogSpy.getCall(0).args[0];
+            });
+
+            it('should call `console.log`', () => {
+                assert.equal(consoleLogCallResult, expectedConsoleLogCallResult);
+            });
+
+            it('should log file name to the console', () => {
+                assert.include(loggingMessageResult, expectedLoggingMessage);
+            });
+
+
+            after(() => {
+                consoleLogSpy.restore();
+                fs.unlinkSync(inputPath);
+            });
+        });
     });
 
     after(() => {

+ 142 - 0
test/unit-tests/logger/Logger.spec.ts

@@ -82,4 +82,146 @@ describe('Logger', () => {
             });
         });
     });
+
+    describe('success (loggingMessage: LoggingMessage, value?: string | number): void', () => {
+        describe('`log` option is enabled', () => {
+            const loggingMessage: string = '[javascript-obfuscator] Obfuscation started...';
+            const expectedConsoleLogCallResult: boolean = true;
+
+            let consoleLogSpy: sinon.SinonSpy,
+                consoleLogCallResult: boolean,
+                inversifyContainerFacade: IInversifyContainerFacade,
+                loggingMessageResult: string;
+
+            before(() => {
+                inversifyContainerFacade = new InversifyContainerFacade();
+                inversifyContainerFacade.load('', {
+                    log: true
+                });
+
+                const logger: ILogger = inversifyContainerFacade.get<ILogger>(ServiceIdentifiers.ILogger);
+
+                consoleLogSpy = sinon.spy(console, 'log');
+                logger.success(LoggingMessage.ObfuscationStarted);
+
+                consoleLogCallResult = consoleLogSpy.called;
+                loggingMessageResult = consoleLogSpy.getCall(0).args[0];
+            });
+
+            it('should call `console.log`', () => {
+                assert.equal(consoleLogCallResult, expectedConsoleLogCallResult);
+            });
+
+            it('should log `success` message to the console', () => {
+                assert.include(loggingMessageResult, loggingMessage);
+            });
+
+            after(() => {
+                consoleLogSpy.restore();
+                inversifyContainerFacade.unload();
+            });
+        });
+
+        describe('`log` option is disabled', () => {
+            const expectedConsoleLogCallResult: boolean = false;
+
+            let consoleLogSpy: sinon.SinonSpy,
+                consoleLogCallResult: boolean,
+                inversifyContainerFacade: IInversifyContainerFacade;
+
+            before(() => {
+                inversifyContainerFacade = new InversifyContainerFacade();
+                inversifyContainerFacade.load('', {
+                    log: false
+                });
+
+                const logger: ILogger = inversifyContainerFacade.get<ILogger>(ServiceIdentifiers.ILogger);
+
+                consoleLogSpy = sinon.spy(console, 'log');
+                logger.success(LoggingMessage.ObfuscationStarted);
+
+                consoleLogCallResult = consoleLogSpy.called;
+            });
+
+            it('shouldn\'t call `console.log`', () => {
+                assert.equal(consoleLogCallResult, expectedConsoleLogCallResult);
+            });
+
+            after(() => {
+                consoleLogSpy.restore();
+                inversifyContainerFacade.unload();
+            });
+        });
+    });
+
+    describe('warn (loggingMessage: LoggingMessage, value?: string | number): void', () => {
+        describe('`log` option is enabled', () => {
+            const loggingMessage: string = '[javascript-obfuscator] Obfuscation started...';
+            const expectedConsoleLogCallResult: boolean = true;
+
+            let consoleLogSpy: sinon.SinonSpy,
+                consoleLogCallResult: boolean,
+                inversifyContainerFacade: IInversifyContainerFacade,
+                loggingMessageResult: string;
+
+            before(() => {
+                inversifyContainerFacade = new InversifyContainerFacade();
+                inversifyContainerFacade.load('', {
+                    log: true
+                });
+
+                const logger: ILogger = inversifyContainerFacade.get<ILogger>(ServiceIdentifiers.ILogger);
+
+                consoleLogSpy = sinon.spy(console, 'log');
+                logger.warn(LoggingMessage.ObfuscationStarted);
+
+                consoleLogCallResult = consoleLogSpy.called;
+                loggingMessageResult = consoleLogSpy.getCall(0).args[0];
+            });
+
+            it('should call `console.log`', () => {
+                assert.equal(consoleLogCallResult, expectedConsoleLogCallResult);
+            });
+
+            it('should log `warn` message to the console', () => {
+                assert.include(loggingMessageResult, loggingMessage);
+            });
+
+            after(() => {
+                consoleLogSpy.restore();
+                inversifyContainerFacade.unload();
+            });
+        });
+
+        describe('`log` option is disabled', () => {
+            const expectedConsoleLogCallResult: boolean = false;
+
+            let consoleLogSpy: sinon.SinonSpy,
+                consoleLogCallResult: boolean,
+                inversifyContainerFacade: IInversifyContainerFacade;
+
+            before(() => {
+                inversifyContainerFacade = new InversifyContainerFacade();
+                inversifyContainerFacade.load('', {
+                    log: false
+                });
+
+                const logger: ILogger = inversifyContainerFacade.get<ILogger>(ServiceIdentifiers.ILogger);
+
+                consoleLogSpy = sinon.spy(console, 'log');
+                logger.warn(LoggingMessage.ObfuscationStarted);
+
+                consoleLogCallResult = consoleLogSpy.called;
+            });
+
+            it('shouldn\'t call `console.log`', () => {
+                assert.equal(consoleLogCallResult, expectedConsoleLogCallResult);
+            });
+
+            after(() => {
+                consoleLogSpy.restore();
+                inversifyContainerFacade.unload();
+            });
+        });
+    });
 });

部分文件因为文件数量过多而无法显示