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 CLI code for easier reuse #3788

Merged
merged 6 commits into from
Sep 24, 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
57 changes: 7 additions & 50 deletions packages/cli/generators/model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const utils = require('../../lib/utils');
const chalk = require('chalk');
const path = require('path');

const {createPropertyTemplateData} = require('./property-definition');

const PROMPT_BASE_MODEL_CLASS = 'Please select the model base class';
const ERROR_NO_MODELS_FOUND = 'Model was not found in';

Expand Down Expand Up @@ -476,56 +478,11 @@ module.exports = class ModelGenerator extends ArtifactGenerator {
this.artifactInfo.modelBaseClass,
);

// Set up types for Templating
const TS_TYPES = ['string', 'number', 'object', 'boolean', 'any'];
const NON_TS_TYPES = ['geopoint', 'date'];
Object.values(this.artifactInfo.properties).forEach(val => {
// Default tsType is the type property
val.tsType = val.type;

// Override tsType based on certain type values
if (val.type === 'array') {
if (TS_TYPES.includes(val.itemType)) {
val.tsType = `${val.itemType}[]`;
} else if (val.type === 'buffer') {
val.tsType = 'Buffer[]';
} else {
val.tsType = 'string[]';
}
} else if (val.type === 'buffer') {
val.tsType = 'Buffer';
}

if (NON_TS_TYPES.includes(val.tsType)) {
val.tsType = 'string';
}

if (
val.defaultValue &&
NON_TS_TYPES.concat(['string', 'any']).includes(val.type)
) {
val.defaultValue = `'${val.defaultValue}'`;
}

// Convert Type to include '' for template
val.type = `'${val.type}'`;
if (val.itemType) {
val.itemType = `'${val.itemType}'`;
}

// If required is false, we can delete it as that's the default assumption
// for this field if not present. This helps to avoid polluting the
// decorator with redundant properties.
if (!val.required) {
delete val.required;
}

// We only care about marking the `id` field as `id` and not fields that
// are not the id so if this is false we delete it similar to `required`.
if (!val.id) {
delete val.id;
}
});
const propDefs = this.artifactInfo.properties;
this.artifactInfo.properties = {};
for (const key in propDefs) {
this.artifactInfo.properties = createPropertyTemplateData(propDefs[key]);
}

if (this.artifactInfo.modelSettings) {
this.artifactInfo.modelSettings = utils.stringifyModelSettings(
Expand Down
73 changes: 73 additions & 0 deletions packages/cli/generators/model/property-definition.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/cli
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict';

const TS_TYPES = ['string', 'number', 'object', 'boolean', 'any'];
const NON_TS_TYPES = ['geopoint', 'date'];
const BUILTIN_TYPES = [...TS_TYPES, ...NON_TS_TYPES];

module.exports = {
createPropertyTemplateData,
BUILTIN_TYPES,
};

/**
* Convert property definition in LB4 style to data needed by model template
* @param {object} val The property definition
* @returns {object} Data for model-property template
*/
function createPropertyTemplateData(val) {
// shallow clone the object - don't modify original data!
val = {...val};

// Default tsType is the type property
val.tsType = val.type;

// Override tsType based on certain type values
if (val.type === 'array') {
if (TS_TYPES.includes(val.itemType)) {
val.tsType = `${val.itemType}[]`;
} else if (val.type === 'buffer') {
val.tsType = 'Buffer[]';
} else {
val.tsType = 'string[]';
}
} else if (val.type === 'buffer') {
val.tsType = 'Buffer';
}

if (NON_TS_TYPES.includes(val.tsType)) {
val.tsType = 'string';
}

if (
val.defaultValue &&
NON_TS_TYPES.concat(['string', 'any']).includes(val.type)
) {
val.defaultValue = `'${val.defaultValue}'`;
}

// Convert Type to include '' for template
val.type = `'${val.type}'`;
if (val.itemType) {
val.itemType = `'${val.itemType}'`;
}

// If required is false, we can delete it as that's the default assumption
// for this field if not present. This helps to avoid polluting the
// decorator with redundant properties.
if (!val.required) {
delete val.required;
}

// We only care about marking the `id` field as `id` and not fields that
// are not the id so if this is false we delete it similar to `required`.
if (!val.id) {
delete val.id;
}

return val;
}
49 changes: 4 additions & 45 deletions packages/cli/lib/artifact-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
const BaseGenerator = require('./base-generator');
const debug = require('./debug')('artifact-generator');
const utils = require('./utils');
const updateIndex = require('./update-index');
const path = require('path');
const chalk = require('chalk');

Expand Down Expand Up @@ -69,18 +68,7 @@ module.exports = class ArtifactGenerator extends BaseGenerator {
* remind user the input might get changed if it contains _ or accented char
**/
promptWarningMsgForName() {
if (this.artifactInfo.name.includes('_')) {
this.log(
chalk.red('>>> ') +
`Underscores _ in the class name will get removed: ${this.artifactInfo.name}`,
);
}
if (this.artifactInfo.name.match(/[\u00C0-\u024F\u1E00-\u1EFF]/)) {
this.log(
chalk.red('>>> ') +
`Accented chars in the class name will get replaced: ${this.artifactInfo.name}`,
);
}
utils.logNamingIssues(this.artifactInfo.name, this.log.bind(this));
}

/**
Expand All @@ -90,14 +78,7 @@ module.exports = class ArtifactGenerator extends BaseGenerator {
* >> Model MyModel will be created in src/models/my-model.model.ts
**/
promptClassFileName(type, typePlural, name) {
this.log(
`${utils.toClassName(type)} ${chalk.yellow(
name,
)} will be created in src/${typePlural}/${chalk.yellow(
utils.toFileName(name) + '.' + `${type}.ts`,
)}`,
);
this.log();
utils.logClassCreation(type, typePlural, name, this.log.bind(this));
}

scaffold() {
Expand All @@ -121,16 +102,7 @@ module.exports = class ArtifactGenerator extends BaseGenerator {
return;
}

// Check all files being generated to ensure they succeeded
const generationStatus = !!Object.entries(
this.conflicter.generationStatus,
).find(([key, val]) => {
// If a file was modified, update the indexes and say stuff about it
return val !== 'skip' && val !== 'identical';
});
debug(`Generation status: ${generationStatus}`);

if (generationStatus) {
if (this._isGenerationSuccessful()) {
await this._updateIndexFiles();

const classes = this.artifactInfo.name
Expand Down Expand Up @@ -189,20 +161,7 @@ module.exports = class ArtifactGenerator extends BaseGenerator {
}

for (const idx of this.artifactInfo.indexesToBeUpdated) {
await updateIndex(idx.dir, idx.file);
// Output for users
const updateDirRelPath = path.relative(
this.artifactInfo.relPath,
idx.dir,
);

const outPath = path.join(
this.artifactInfo.relPath,
updateDirRelPath,
'index.ts',
);

this.log(chalk.green(' update'), `${outPath}`);
await this._updateIndexFile(idx.dir, idx.file);
}
}
};
31 changes: 31 additions & 0 deletions packages/cli/lib/base-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const path = require('path');
const fs = require('fs');
const debug = require('./debug')('base-generator');
const semver = require('semver');
const updateIndex = require('./update-index');

/**
* Base Generator for LoopBack 4
Expand Down Expand Up @@ -444,4 +445,34 @@ module.exports = class BaseGenerator extends Generator {
}
await this._runLintFix();
}

// Check all files being generated to ensure they succeeded
_isGenerationSuccessful() {
const generationStatus = !!Object.entries(
this.conflicter.generationStatus,
).find(([key, val]) => {
// If a file was modified, update the indexes and say stuff about it
return val !== 'skip' && val !== 'identical';
});
debug(`Generation status: ${generationStatus}`);
return generationStatus;
}

async _updateIndexFile(dir, file) {
await updateIndex(dir, file);

// Output for users
const updateDirRelPath = path.relative(
this.artifactInfo.relPath,
this.artifactInfo.outDir,
);

const outPath = path.join(
this.artifactInfo.relPath,
updateDirRelPath,
'index.ts',
);

this.log(chalk.green(' update'), `${outPath}`);
}
};
2 changes: 1 addition & 1 deletion packages/cli/lib/update-index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const exists = util.promisify(fs.exists);
* @param {*} file The new file to be exported from index.ts
*/
module.exports = async function(dir, file) {
debug(`Updating index ${path.join(dir, file)}`);
debug(`Updating index with ${path.join(dir, file)}`);
const indexFile = path.join(dir, 'index.ts');
if (!file.endsWith('.ts')) {
throw new Error(`${file} must be a TypeScript (.ts) file`);
Expand Down
27 changes: 27 additions & 0 deletions packages/cli/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

'use strict';

const chalk = require('chalk');
const debug = require('../lib/debug')('utils');
const fs = require('fs');
const path = require('path');
Expand Down Expand Up @@ -103,6 +104,32 @@ exports.validateClassName = function(name) {
return util.format('Class name is invalid: %s', name);
};

exports.logNamingIssues = function(name, log) {
if (name.includes('_')) {
log(
chalk.red('>>> ') +
`Underscores _ in the class name will get removed: ${name}`,
);
}
if (name.match(/[\u00C0-\u024F\u1E00-\u1EFF]/)) {
log(
chalk.red('>>> ') +
`Accented chars in the class name will get replaced: ${name}`,
);
}
};

exports.logClassCreation = function(type, typePlural, name, log) {
log(
`${exports.toClassName(type)} ${chalk.yellow(
name,
)} will be created in src/${typePlural}/${chalk.yellow(
exports.toFileName(name) + '.' + `${type}.ts`,
)}`,
);
log();
};

/**
* Validate project directory to not exist
*/
Expand Down
Loading