Changed file log messages

This commit is contained in:
sanex3339
2020-02-20 23:33:13 +03:00
parent ae111ead95
commit ed09424df5
18 changed files with 141 additions and 153 deletions
+4 -4
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+9 -18
View File
@@ -3,8 +3,6 @@ import acornImportMeta from 'acorn-import-meta';
import * as ESTree from 'estree';
import chalk, { Chalk } from 'chalk';
import { IASTParserFacadeInputData } from './interfaces/IASTParserFacadeInputData';
/**
* Facade over AST parser `acorn`
*/
@@ -28,23 +26,23 @@ export class ASTParserFacade {
];
/**
* @param {string} inputData
* @param {string} sourceCode
* @param {Options} config
* @returns {Program}
*/
public static parse (inputData: IASTParserFacadeInputData, config: acorn.Options): ESTree.Program | never {
public static parse (sourceCode: string, config: acorn.Options): ESTree.Program | never {
const sourceTypeLength: number = ASTParserFacade.sourceTypes.length;
for (let i: number = 0; i < sourceTypeLength; i++) {
try {
return ASTParserFacade.parseType(inputData, config, ASTParserFacade.sourceTypes[i]);
return ASTParserFacade.parseType(sourceCode, config, ASTParserFacade.sourceTypes[i]);
} catch (error) {
if (i < sourceTypeLength - 1) {
continue;
}
throw new Error(ASTParserFacade.processParsingError(
inputData,
sourceCode,
error.message,
error.loc
));
@@ -55,17 +53,16 @@ export class ASTParserFacade {
}
/**
* @param {IASTParserFacadeInputData} inputData
* @param {string} sourceCode
* @param {acorn.Options} inputConfig
* @param {acorn.Options["sourceType"]} sourceType
* @returns {Program}
*/
private static parseType (
inputData: IASTParserFacadeInputData,
sourceCode: string,
inputConfig: acorn.Options,
sourceType: acorn.Options['sourceType']
): ESTree.Program {
const { sourceCode } = inputData;
const comments: ESTree.Comment[] = [];
const config: acorn.Options = {
...inputConfig,
@@ -85,13 +82,13 @@ export class ASTParserFacade {
}
/**
* @param {IASTParserFacadeInputData} inputData
* @param {string} sourceCode
* @param {string} errorMessage
* @param {Position | null} position
* @returns {never}
*/
private static processParsingError (
inputData: IASTParserFacadeInputData,
sourceCode: string,
errorMessage: string,
position: ESTree.Position | null
): never {
@@ -99,8 +96,6 @@ export class ASTParserFacade {
throw new Error(errorMessage);
}
const { sourceCode, inputFilePath } = inputData;
const sourceCodeLines: string[] = sourceCode.split(/\r?\n/);
const errorLine: string | undefined = sourceCodeLines[position.line - 1];
@@ -108,10 +103,6 @@ export class ASTParserFacade {
throw new Error(errorMessage);
}
const formattedInputFilePath: string = inputFilePath
? `${inputFilePath}, `
: '';
const startErrorIndex: number = Math.max(0, position.column - ASTParserFacade.nearestSymbolsCount);
const endErrorIndex: number = Math.min(errorLine.length, position.column + ASTParserFacade.nearestSymbolsCount);
@@ -121,7 +112,7 @@ export class ASTParserFacade {
}...`;
throw new Error(
`ERROR in ${formattedInputFilePath}line ${position.line}: ${errorMessage}\n${formattedPointer} ${formattedCodeSlice}`
`ERROR at line ${position.line}: ${errorMessage}\n${formattedPointer} ${formattedCodeSlice}`
);
}
}
+1 -7
View File
@@ -7,7 +7,6 @@ import * as ESTree from 'estree';
import { TObfuscatedCodeFactory } from './types/container/source-code/TObfuscatedCodeFactory';
import { IASTParserFacadeInputData } from './interfaces/IASTParserFacadeInputData';
import { IGeneratorOutput } from './interfaces/IGeneratorOutput';
import { IJavaScriptObfuscator } from './interfaces/IJavaScriptObfsucator';
import { ILogger } from './interfaces/logger/ILogger';
@@ -150,12 +149,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator {
* @returns {Program}
*/
private parseCode (sourceCode: string): ESTree.Program {
const inputData: IASTParserFacadeInputData = {
sourceCode,
inputFilePath: this.options.inputFilePath
};
return ASTParserFacade.parse(inputData, JavaScriptObfuscator.parseOptions);
return ASTParserFacade.parse(sourceCode, JavaScriptObfuscator.parseOptions);
}
/**
+20 -4
View File
@@ -21,9 +21,11 @@ import { StringArrayEncodingSanitizer } from './sanitizers/StringArrayEncodingSa
import { CLIUtils } from './utils/CLIUtils';
import { JavaScriptObfuscator } from '../JavaScriptObfuscatorFacade';
import { Logger } from '../logger/Logger';
import { ObfuscatedCodeWriter } from './utils/ObfuscatedCodeWriter';
import { SourceCodeReader } from './utils/SourceCodeReader';
import { Utils } from '../utils/Utils';
import { LoggingPrefix } from '../enums/logger/LoggingPrefix';
export class JavaScriptObfuscatorCLI implements IInitializable {
/**
@@ -103,14 +105,12 @@ export class JavaScriptObfuscatorCLI implements IInitializable {
const configFileLocation: string = configFilePath ? path.resolve(configFilePath, '.') : '';
const configFileOptions: TInputOptions = configFileLocation ? CLIUtils.getUserConfig(configFileLocation) : {};
const inputFileName: string = path.basename(inputCodePath);
const inputFilePath: string = inputCodePath;
return {
...DEFAULT_PRESET,
...configFileOptions,
...inputCLIOptions,
inputFileName,
inputFilePath
inputFileName
};
}
@@ -367,7 +367,23 @@ export class JavaScriptObfuscatorCLI implements IInitializable {
sourceCodeData.forEach(({ filePath, content }: IFileData, index: number) => {
const outputCodePath: string = this.obfuscatedCodeWriter.getOutputCodePath(filePath);
this.processSourceCode(content, filePath, outputCodePath, index);
try {
Logger.log(
Logger.colorInfo,
LoggingPrefix.CLI,
`Obfuscating file: ${filePath}...`
);
this.processSourceCode(content, filePath, outputCodePath, index);
} catch (error) {
Logger.log(
Logger.colorInfo,
LoggingPrefix.CLI,
`Error in file: ${filePath}...`
);
throw error;
}
});
}
+1 -19
View File
@@ -6,10 +6,7 @@ import { TInputCLIOptions } from '../../types/options/TInputCLIOptions';
import { IFileData } from '../../interfaces/cli/IFileData';
import { LoggingPrefix } from '../../enums/logger/LoggingPrefix';
import { JavaScriptObfuscatorCLI } from '../JavaScriptObfuscatorCLI';
import { Logger } from '../../logger/Logger';
export class SourceCodeReader {
/**
@@ -104,28 +101,13 @@ export class SourceCodeReader {
&& !SourceCodeReader.isExcludedPath(filePath, excludePatterns);
}
/**
* @param {string} filePath
*/
private static logFilePath (filePath: string): void {
const normalizedFilePath: string = path.normalize(filePath);
Logger.log(
Logger.colorInfo,
LoggingPrefix.CLI,
`Obfuscating file: ${normalizedFilePath}...`
);
}
/**
* @param {string} filePath
* @returns {string}
*/
private static readFile (filePath: string): IFileData {
SourceCodeReader.logFilePath(filePath);
return {
filePath,
filePath: path.normalize(filePath),
content: fs.readFileSync(filePath, JavaScriptObfuscatorCLI.encoding)
};
}
@@ -1,11 +0,0 @@
export interface IASTParserFacadeInputData {
/**
* @type {string}
*/
sourceCode: string;
/**
* @type {string}
*/
inputFilePath?: string;
}
-1
View File
@@ -20,7 +20,6 @@ export interface IOptions {
readonly identifiersDictionary: string[];
readonly identifiersPrefix: string;
readonly inputFileName: string;
readonly inputFilePath: string;
readonly log: boolean;
readonly renameGlobals: boolean;
readonly reservedNames: string[];
+1 -1
View File
@@ -36,7 +36,7 @@ export class NodeUtils {
*/
public static convertCodeToStructure (code: string): ESTree.Statement[] {
const structure: ESTree.Program = ASTParserFacade.parse(
{ sourceCode: code },
code,
{
ecmaVersion,
sourceType: 'script'
-6
View File
@@ -144,12 +144,6 @@ export class Options implements IOptions {
@IsString()
public readonly inputFileName!: string;
/**
* @type {string}
*/
@IsString()
public readonly inputFilePath!: string;
/**
* @type {boolean}
*/
-1
View File
@@ -20,7 +20,6 @@ export const DEFAULT_PRESET: TInputOptions = Object.freeze({
identifiersPrefix: '',
identifiersDictionary: [],
inputFileName: '',
inputFilePath: '',
log: false,
renameGlobals: false,
reservedNames: [],
-1
View File
@@ -19,7 +19,6 @@ export const NO_ADDITIONAL_NODES_PRESET: TInputOptions = Object.freeze({
identifiersPrefix: '',
identifiersDictionary: [],
inputFileName: '',
inputFilePath: '',
log: false,
renameGlobals: false,
reservedNames: [],
+8 -4
View File
@@ -7,13 +7,17 @@ import { NO_ADDITIONAL_NODES_PRESET } from '../../src/options/presets/NoCustomNo
let obfuscatedCode: string = JavaScriptObfuscator.obfuscate(
`
(function () {
return 1;
})();
var s = function () {};
class Foo {
bar (baz, bark) {
return s;
}
}
`,
{
...NO_ADDITIONAL_NODES_PRESET,
selfDefending: true
renameGlobals: true,
identifierNamesGenerator: 'mangled'
}
).getObfuscatedCode();
+1
View File
@@ -0,0 +1 @@
error error
@@ -852,6 +852,94 @@ describe('JavaScriptObfuscatorCLI', function (): void {
});
});
describe('Logging', () => {
describe('Obfuscating file message', () => {
const directoryPath: string = `${fixturesDirName}/directory-obfuscation`;
const inputFileName1: string = 'foo.js';
const inputFileName2: string = 'bar.js';
const inputFilePath1: string = `${directoryPath}/${inputFileName1}`;
const inputFilePath2: string = `${directoryPath}/${inputFileName2}`;
const outputFileName1: string = 'foo-obfuscated.js';
const outputFileName2: string = 'bar-obfuscated.js';
const outputFilePath1: string = `${directoryPath}/${outputFileName1}`;
const outputFilePath2: string = `${directoryPath}/${outputFileName2}`;
const expectedLoggingMessage1: string = `[javascript-obfuscator-cli] Obfuscating file: ${inputFilePath1}...`;
const expectedLoggingMessage2: string = `[javascript-obfuscator-cli] Obfuscating file: ${inputFilePath2}...`;
let consoleLogSpy: sinon.SinonSpy<any, void>,
loggingMessageResult1: string,
loggingMessageResult2: string;
before(() => {
consoleLogSpy = sinon.spy(console, 'log');
JavaScriptObfuscatorCLI.obfuscate([
'node',
'javascript-obfuscator',
directoryPath,
'--rename-globals',
'true'
]);
loggingMessageResult1 = consoleLogSpy.getCall(1).args[0];
loggingMessageResult2 = consoleLogSpy.getCall(0).args[0];
});
it('Variant #1: should log file name to the console', () => {
assert.include(loggingMessageResult1, expectedLoggingMessage1);
});
it('Variant #2: should log file name to the console', () => {
assert.include(loggingMessageResult2, expectedLoggingMessage2);
});
after(() => {
rimraf.sync(outputFilePath1);
rimraf.sync(outputFilePath2);
consoleLogSpy.restore();
});
});
describe('Error message', () => {
const directoryPath: string = `${fixturesDirName}/directory-obfuscation-error`;
const inputFileName: string = 'foo.js';
const inputFilePath: string = `${directoryPath}/${inputFileName}`;
const expectedLoggingMessage1: string = `[javascript-obfuscator-cli] Error in file: ${inputFilePath}...`;
let consoleLogSpy: sinon.SinonSpy<any, void>,
loggingMessageResult: string
before(() => {
consoleLogSpy = sinon.spy(console, 'log');
try {
JavaScriptObfuscatorCLI.obfuscate([
'node',
'javascript-obfuscator',
directoryPath,
'--rename-globals',
'true'
]);
} catch {}
loggingMessageResult = consoleLogSpy.getCall(1).args[0];
});
it('Should log file name to the console', () => {
assert.include(loggingMessageResult, expectedLoggingMessage1);
});
after(() => {
consoleLogSpy.restore();
});
});
});
after(() => {
rimraf.sync(outputDirName);
});
@@ -3,7 +3,6 @@ import * as mkdirp from 'mkdirp';
import * as rimraf from 'rimraf';
import { assert } from 'chai';
import * as sinon from 'sinon';
import { IFileData } from '../../../../src/interfaces/cli/IFileData';
@@ -547,41 +546,6 @@ 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<any, void>,
consoleLogCallResult: boolean,
loggingMessageResult: string;
before(() => {
consoleLogSpy = sinon.spy(console, 'log');
fs.writeFileSync(inputPath, fileContent);
new SourceCodeReader(inputPath, {}).readSourceCode();
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(() => {
@@ -1,7 +1,5 @@
import { assert } from 'chai';
import { IASTParserFacadeInputData } from '../../../src/interfaces/IASTParserFacadeInputData';
import { ecmaVersion } from '../../../src/constants/EcmaVersion';
import { ASTParserFacade } from '../../../src/ASTParserFacade';
@@ -20,13 +18,11 @@ describe('ASTParserFacade', () => {
let testFunc: () => void;
before(() => {
const inputData: IASTParserFacadeInputData = {sourceCode};
testFunc = () => ASTParserFacade.parse(inputData, { ecmaVersion });
testFunc = () => ASTParserFacade.parse(sourceCode, { ecmaVersion });
});
it('should output code preview when AST parser throws a parse error', () => {
assert.throws(testFunc, /ERROR in line 3: Unexpected token \(3:28\)\n.*\.\.\.var baz = 3;,\.\.\./);
assert.throws(testFunc, /ERROR at line 3: Unexpected token \(3:28\)\n.*\.\.\.var baz = 3;,\.\.\./);
});
});
@@ -51,13 +47,11 @@ describe('ASTParserFacade', () => {
let testFunc: () => void;
before(() => {
const inputData: IASTParserFacadeInputData = {sourceCode};
testFunc = () => ASTParserFacade.parse(inputData, { ecmaVersion });
testFunc = () => ASTParserFacade.parse(sourceCode, { ecmaVersion });
});
it('should output code preview when AST parser throws a parse error', () => {
assert.throws(testFunc, /ERROR in line 13: Unexpected token \(13:28\)\n.*\.\.\.var baz = 3;,\.\.\./);
assert.throws(testFunc, /ERROR at line 13: Unexpected token \(13:28\)\n.*\.\.\.var baz = 3;,\.\.\./);
});
});
@@ -76,37 +70,11 @@ describe('ASTParserFacade', () => {
let testFunc: () => void;
before(() => {
const inputData: IASTParserFacadeInputData = {sourceCode};
testFunc = () => ASTParserFacade.parse(inputData, { ecmaVersion });
testFunc = () => ASTParserFacade.parse(sourceCode, { ecmaVersion });
});
it('should output code preview when AST parser throws a parse error', () => {
assert.throws(testFunc, /ERROR in line 4: Unexpected token \(4:28\)\n.*\.\.\.functin baz \(\) {\.\.\./);
});
});
describe('Variant #4: input file path is set', () => {
const sourceCode: string = `` +
`var foo = 1;
var bar = 2;
var baz = 3;,
var bark = 4;
var hawk = 5;`;
let testFunc: () => void;
before(() => {
const inputData: IASTParserFacadeInputData = {
sourceCode,
inputFilePath: '/src/foo.js'
};
testFunc = () => ASTParserFacade.parse(inputData, { ecmaVersion });
});
it('should output code preview when AST parser throws a parse error', () => {
assert.throws(testFunc, /ERROR in \/src\/foo\.js, line 3: Unexpected token \(3:32\)\n.*\.\.\.var baz = 3;,\.\.\./);
assert.throws(testFunc, /ERROR at line 4: Unexpected token \(4:28\)\n.*\.\.\.functin baz \(\) {\.\.\./);
});
});
});