Skip to content

chore: merge release into master #4685

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

Merged
merged 11 commits into from
Jun 6, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
37 changes: 23 additions & 14 deletions lib/common/logger/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,31 +154,40 @@ export class Logger implements ILogger {
}

private getLogOptionsForMessage(data: any[]): { data: any[], [key: string]: any } {
const opts = _.keys(LoggerConfigData);
const loggerOptionKeys = _.keys(LoggerConfigData);
const dataToCheck = data.filter(el => {
// objects created with Object.create(null) do not have `hasOwnProperty` function
if (!!el && typeof el === "object" && el.hasOwnProperty && typeof el.hasOwnProperty === "function") {
for (const key of loggerOptionKeys) {
if (el.hasOwnProperty(key)) {
// include only the elements which have one of the keys we've specified as logger options
return true;
}
}
}

const result: any = {};
const cleanedData = _.cloneDeep(data);
return false;
});

// objects created with Object.create(null) do not have `hasOwnProperty` function
const dataToCheck = data.filter(el => typeof el === "object" && el.hasOwnProperty && typeof el.hasOwnProperty === "function");
const result: any = {
data: _.difference(data, dataToCheck)
};

for (const element of dataToCheck) {
if (opts.length === 0) {
if (loggerOptionKeys.length === 0) {
break;
}

const remainingOpts = _.cloneDeep(opts);
const remainingOpts = _.cloneDeep(loggerOptionKeys);
for (const prop of remainingOpts) {
const hasProp = element && element.hasOwnProperty(prop);
if (hasProp) {
opts.splice(opts.indexOf(prop), 1);
loggerOptionKeys.splice(loggerOptionKeys.indexOf(prop), 1);
result[prop] = element[prop];
cleanedData.splice(cleanedData.indexOf(element), 1);
}
}
}

result.data = cleanedData;
return result;
}

Expand All @@ -195,19 +204,19 @@ export class Logger implements ILogger {
/*******************************************************************************************
* Metods below are deprecated. Delete them in 6.0.0 release: *
* Present only for backwards compatibility as some plugins (nativescript-plugin-firebase) *
* use these methods in their hooks *
* use these methods in their hooks *
*******************************************************************************************/

out(...args: any[]): void {
this.info(args);
this.info(...args);
}

write(...args: any[]): void {
this.info(args, { [LoggerConfigData.skipNewLine]: true });
this.info(...args, { [LoggerConfigData.skipNewLine]: true });
}

printOnStderr(...args: string[]): void {
this.error(args);
this.error(...args);
}

printInfoMessageOnSameLine(message: string): void {
Expand Down
22 changes: 11 additions & 11 deletions lib/common/services/commands-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,6 @@ export class CommandsService implements ICommandsService {
private $extensibilityService: IExtensibilityService,
private $optionsTracker: IOptionsTracker,
private $projectDataService: IProjectDataService) {
let projectData = null;
try {
projectData = this.$projectDataService.getProjectData();
} catch (err) {
this.$logger.trace(`Error while trying to get project data. More info: ${err}`);
}

this.$options.setupOptions(projectData);
this.$options.printMessagesForDeprecatedOptions(this.$logger);
}

public allCommands(opts: { includeDevCommands: boolean }): string[] {
Expand Down Expand Up @@ -114,8 +105,17 @@ export class CommandsService implements ICommandsService {

private async tryExecuteCommandAction(commandName: string, commandArguments: string[]): Promise<boolean | ICanExecuteCommandOutput> {
const command = this.$injector.resolveCommand(commandName);
if (!command || (command && !command.isHierarchicalCommand)) {
this.$options.validateOptions(command ? command.dashedOptions : null);
if (!command || !command.isHierarchicalCommand) {
let projectData = null;
try {
projectData = this.$projectDataService.getProjectData();
} catch (err) {
this.$logger.trace(`Error while trying to get project data. More info: ${err}`);
}

const dashedOptions = command ? command.dashedOptions : null;
this.$options.validateOptions(dashedOptions, projectData);
this.$options.printMessagesForDeprecatedOptions(this.$logger);
}

return this.canExecuteCommand(commandName, commandArguments);
Expand Down
83 changes: 82 additions & 1 deletion lib/common/test/unit-tests/logger.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Yok } from "../../yok";
import { Logger } from "../../logger/logger";
import * as path from "path";
import * as util from "util";
import { assert } from "chai";
import * as fileSystemFile from "../../file-system";
import { LoggerConfigData } from "../../../constants";

const passwordReplacement = "*******";
const debugTrace = ["debug", "trace"];
Expand Down Expand Up @@ -33,7 +35,11 @@ describe("logger", () => {
fs = testInjector.resolve("fs");
outputs = {
debug: "",
trace: ""
trace: "",
info: "",
error: "",
context: {},
removedContext: {}
};

const log4jsLogger = {
Expand All @@ -42,6 +48,18 @@ describe("logger", () => {
},
trace: (...args: string[]) => {
outputs.trace += args.join("");
},
info: (...args: string[]) => {
outputs.info += util.format.apply(null, args);
},
error: (...args: string[]) => {
outputs.error += util.format.apply(null, args);
},
addContext(key: string, value: any): void {
outputs.context[key] = value;
},
removeContext(key: string): void {
outputs.removedContext[key] = true;
}
};

Expand Down Expand Up @@ -139,4 +157,67 @@ describe("logger", () => {
assert.deepEqual(outputs.trace, `${request}${requestBody}`, "logger.trace should not obfuscate body of request unless it is towards api/itmstransporter");
});
});

describe("info", () => {
[undefined, null, false, "string value", 42, { obj: 1 }, ["string value 1", "string value 2"]].forEach(value => {
it(`handles formatted message with '${value}' value in one of the args`, () => {
logger.info("test %s", value);
assert.equal(outputs.info, `test ${value}`);
assert.deepEqual(outputs.context, {}, "Nothing should be added to logger context.");
assert.deepEqual(outputs.removedContext, {}, "Removed context should be empty.");
});

it(`handles formatted message with '${value}' value in one of the args and additional values passed to context`, () => {
logger.info("test %s", value, { [LoggerConfigData.skipNewLine]: true });
assert.equal(outputs.info, `test ${value}`);
assert.deepEqual(outputs.context, { [LoggerConfigData.skipNewLine]: true }, `${LoggerConfigData.skipNewLine} should be set with value true.`);
assert.deepEqual(outputs.removedContext, { [LoggerConfigData.skipNewLine]: true }, `Removed context should contain ${LoggerConfigData.skipNewLine}`);
});
});

it("sets correct context when multiple logger options are passed in one object", () => {
logger.info("test", { [LoggerConfigData.skipNewLine]: true, [LoggerConfigData.useStderr]: true });
assert.equal(outputs.info, "test");
assert.deepEqual(outputs.context, { [LoggerConfigData.skipNewLine]: true, [LoggerConfigData.useStderr]: true });
assert.deepEqual(outputs.removedContext, { [LoggerConfigData.skipNewLine]: true, [LoggerConfigData.useStderr]: true });
});

it("sets correct context when multiple logger options are passed in multiple objects", () => {
logger.info({ [LoggerConfigData.useStderr]: true }, "test", { [LoggerConfigData.skipNewLine]: true });
assert.equal(outputs.info, "test");
assert.deepEqual(outputs.context, { [LoggerConfigData.skipNewLine]: true, [LoggerConfigData.useStderr]: true });
assert.deepEqual(outputs.removedContext, { [LoggerConfigData.skipNewLine]: true, [LoggerConfigData.useStderr]: true });
});
});

describe("printMarkdown", () => {
it(`passes markdown formatted text to log4js.info method`, () => {
logger.printMarkdown("header text\n==");
assert.isTrue(outputs.info.indexOf("# header text") !== -1);
});

it(`passes skipNewLine to log4js context`, () => {
logger.printMarkdown("`coloured` text");
assert.isTrue(outputs.info.indexOf("coloured") !== -1);
assert.deepEqual(outputs.context, { [LoggerConfigData.skipNewLine]: true }, `${LoggerConfigData.skipNewLine} should be set with value true.`);
assert.deepEqual(outputs.removedContext, { [LoggerConfigData.skipNewLine]: true }, `Removed context should contain ${LoggerConfigData.skipNewLine}`);
});
});

describe("error", () => {
const errorMessage = "this is error message";
it(`passes useStderr to log4js context`, () => {
logger.error(errorMessage);
assert.equal(outputs.error, errorMessage);
assert.deepEqual(outputs.context, { [LoggerConfigData.useStderr]: true }, `${LoggerConfigData.useStderr} should be set with value true.`);
assert.deepEqual(outputs.removedContext, { [LoggerConfigData.useStderr]: true }, `Removed context should contain ${LoggerConfigData.useStderr}`);
});

it(`allows overwrite of useStderr`, () => {
logger.error(errorMessage, { [LoggerConfigData.useStderr]: false });
assert.equal(outputs.error, errorMessage);
assert.deepEqual(outputs.context, { [LoggerConfigData.useStderr]: false }, `${LoggerConfigData.useStderr} should be set with value false.`);
assert.deepEqual(outputs.removedContext, { [LoggerConfigData.useStderr]: true }, `Removed context should contain ${LoggerConfigData.useStderr}`);
});
});
});
2 changes: 1 addition & 1 deletion lib/common/verify-node-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function verifyNodeVersion(): void {

var nodeWarning = getNodeWarning();
if (nodeWarning && nodeWarning.message) {
console.warn((`${os.EOL}${nodeWarning.message}${os.EOL}`).yellow.bold);
console.warn((os.EOL + nodeWarning.message + os.EOL).yellow.bold);
}
}

Expand Down
3 changes: 1 addition & 2 deletions lib/declarations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ interface IAndroidBundleOptions {

interface IOptions extends IRelease, IDeviceIdentifier, IJustLaunch, IAvd, IAvailableDevices, IProfileDir, IHasEmulatorOption, IBundleString, IPlatformTemplate, IHasEmulatorOption, IClean, IProvision, ITeamIdentifier, IAndroidReleaseOptions, IAndroidBundleOptions, INpmInstallConfigurationOptions, IPort, IEnvOptions, IPluginSeedOptions, IGenerateOptions {
argv: IYargArgv;
validateOptions(commandSpecificDashedOptions?: IDictionary<IDashedOption>): void;
validateOptions(commandSpecificDashedOptions?: IDictionary<IDashedOption>, projectData?: IProjectData): void;
options: IDictionary<IDashedOption>;
shorthands: string[];
/**
Expand Down Expand Up @@ -573,7 +573,6 @@ interface IOptions extends IRelease, IDeviceIdentifier, IJustLaunch, IAvd, IAvai
performance: Object;
cleanupLogFile: string;
workflow: any;
setupOptions(projectData: IProjectData): void;
printMessagesForDeprecatedOptions(logger: ILogger): void;
}

Expand Down
1 change: 1 addition & 0 deletions lib/definitions/project.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ interface IAssetItem {
idiom: string;
resizeOperation?: string;
overlayImageScale?: number;
rgba?: boolean;
}

interface IAssetSubGroup {
Expand Down
15 changes: 8 additions & 7 deletions lib/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ export class Options {

public options: IDictionary<IDashedOption>;

public setupOptions(projectData: IProjectData): void {
public setupOptions(projectData: IProjectData, commandSpecificDashedOptions?: IDictionary<IDashedOption>): void {
if (commandSpecificDashedOptions) {
_.extend(this.options, commandSpecificDashedOptions);
this.setArgv();
}

if (this.argv.release && this.argv.hmr) {
this.$errors.failWithoutHelp("The options --release and --hmr cannot be used simultaneously.");
}
Expand Down Expand Up @@ -173,12 +178,8 @@ export class Options {
return this.argv[optionName];
}

public validateOptions(commandSpecificDashedOptions?: IDictionary<IDashedOption>): void {
if (commandSpecificDashedOptions) {
_.extend(this.options, commandSpecificDashedOptions);
this.setArgv();
}

public validateOptions(commandSpecificDashedOptions?: IDictionary<IDashedOption>, projectData?: IProjectData): void {
this.setupOptions(projectData, commandSpecificDashedOptions);
const parsed = Object.create(null);
// DO NOT REMOVE { } as when they are missing and some of the option values is false, the each stops as it thinks we have set "return false".
_.each(_.keys(this.argv), optionName => {
Expand Down
22 changes: 14 additions & 8 deletions lib/services/assets-generation/assets-generation-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,30 @@ export class AssetsGenerationService implements IAssetsGenerationService {
const outputPath = assetItem.path;
const width = assetItem.width * scale;
const height = assetItem.height * scale;

let image: Jimp;
switch (operation) {
case Operations.OverlayWith:
const overlayImageScale = assetItem.overlayImageScale || AssetConstants.defaultOverlayImageScale;
const imageResize = Math.round(Math.min(width, height) * overlayImageScale);
const image = await this.resize(generationData.imagePath, imageResize, imageResize);
await this.generateImage(generationData.background, width, height, outputPath, image);
image = await this.resize(generationData.imagePath, imageResize, imageResize);
image = this.generateImage(generationData.background, width, height, outputPath, image);
break;
case Operations.Blank:
await this.generateImage(generationData.background, width, height, outputPath);
image = this.generateImage(generationData.background, width, height, outputPath);
break;
case Operations.Resize:
const resizedImage = await this.resize(generationData.imagePath, width, height);
resizedImage.write(outputPath);
image = await this.resize(generationData.imagePath, width, height);
break;
default:
throw new Error(`Invalid image generation operation: ${operation}`);
}

// This code disables the alpha chanel, as some images for the Apple App Store must not have transparency.
if (assetItem.rgba === false) {
image = image.rgba(false);
}

image.write(outputPath);
}
}

Expand All @@ -97,7 +103,7 @@ export class AssetsGenerationService implements IAssetsGenerationService {
return image.scaleToFit(width, height);
}

private generateImage(background: string, width: number, height: number, outputPath: string, overlayImage?: Jimp): void {
private generateImage(background: string, width: number, height: number, outputPath: string, overlayImage?: Jimp): Jimp {
// Typescript declarations for Jimp are not updated to define the constructor with backgroundColor so we workaround it by casting it to <any> for this case only.
const J = <any>Jimp;
const backgroundColor = this.getRgbaNumber(background);
Expand All @@ -109,7 +115,7 @@ export class AssetsGenerationService implements IAssetsGenerationService {
image = image.composite(overlayImage, centeredWidth, centeredHeight);
}

image.write(outputPath);
return image;
}

private getRgbaNumber(colorString: string): number {
Expand Down
1 change: 1 addition & 0 deletions lib/services/project-data-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ export class ProjectDataService implements IProjectDataService {
image.resizeOperation = image.resizeOperation || assetItem.resizeOperation;
image.overlayImageScale = image.overlayImageScale || assetItem.overlayImageScale;
image.scale = image.scale || assetItem.scale;
image.rgba = assetItem.rgba;
// break each
return false;
}
Expand Down
3 changes: 2 additions & 1 deletion resources/assets/image-definitions.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@
"height": 1024,
"directory": "Assets.xcassets/AppIcon.appiconset",
"filename": "icon-1024.png",
"scale": "1x"
"scale": "1x",
"rgba": false
}
],
"splashBackgrounds": [
Expand Down
4 changes: 2 additions & 2 deletions test/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ describe("options", () => {
it(`should pass correctly when ${testCase.name} and useLegacyWorkflow is ${useLegacyWorkflow}`, () => {
(testCase.args || []).forEach(arg => process.argv.push(arg));

const options = createOptions(testInjector);
const options: any = createOptions(testInjector);
const projectData = <IProjectData>{ useLegacyWorkflow };
options.setupOptions(projectData);

Expand Down Expand Up @@ -359,7 +359,7 @@ describe("options", () => {
errors.failWithoutHelp = (error: string) => actualError = error;
(testCase.args || []).forEach(arg => process.argv.push(arg));

const options = createOptions(testInjector);
const options: any = createOptions(testInjector);
options.setupOptions(null);

(testCase.args || []).forEach(arg => process.argv.pop());
Expand Down