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

Migrated generator code base to xo + prettier and async/await #401

Merged
merged 3 commits into from
Oct 26, 2018
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

![ngx-rocket logo](https://user-images.githubusercontent.com/593151/28924751-08023b32-7863-11e7-9186-c17d4647d861.png)

> Extensible Angular 6+ enterprise-grade project generator based on
> Extensible Angular 7+ enterprise-grade project generator based on
> [angular-cli](https://github.com/angular/angular-cli) with best practices from the community.
> Includes PWA and Cordova support, coding guides and more!

Expand Down
132 changes: 67 additions & 65 deletions cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ const pkg = require('../package.json');

const addonKey = 'ngx-rocket-addon';
const disabledAddons = 'disabledAddons';
const blacklistedNpmAddons = [
'generator-ngx-rocket',
'generator-ngx-rocket-addon'
];
const blacklistedNpmAddons = ['generator-ngx-rocket', 'generator-ngx-rocket-addon'];
const appName = path.basename(process.argv[1]);
const help = `${chalk.bold(`Usage:`)} ${appName} ${chalk.blue(`[new|update|config|list|<script>]`)} [options]\n`;
const detailedHelp = `
Expand Down Expand Up @@ -99,7 +96,7 @@ class NgxCli {
fuzzyRun(args, packageManager);
}

generate(update, args, addon) {
async generate(update, args, addon) {
if (!update) {
console.log(asciiLogo(pkg.version));
} else if (fs.existsSync('.yo-rc.json')) {
Expand All @@ -110,74 +107,78 @@ class NgxCli {
}
if (addon) {
args = args.filter(arg => arg !== '--addon' && arg !== '-a');
env.lookup(() => env.run(['ngx-rocket:addon'].concat(args), {
update,
packageManager: this._packageManager(),
'skip-welcome': true
}));
env.lookup(() =>
env.run(['ngx-rocket:addon'].concat(args), {
update,
packageManager: this._packageManager(),
'skip-welcome': true
})
);
} else {
const disabled = this._config.get(disabledAddons);
return this._findAddons()
.then(addons => addons.filter(addon => !disabled[addon]))
.then(addons => {
return new Promise(resolve => env.lookup(() => env.run(['ngx-rocket'].concat(args), {
update,
packageManager: this._packageManager(),
addons: addons.join(' '),
'skip-welcome': true
}, resolve)));
})
.then(() => console.log());
let addons = await this._findAddons();
addons = addons.filter(addon => !disabled[addon]);

await new Promise(resolve =>
env.lookup(() =>
env.run(
['ngx-rocket'].concat(args),
{
update,
packageManager: this._packageManager(),
addons: addons.join(' '),
'skip-welcome': true
},
resolve
)
)
);
console.log();
}
}

configure() {
this._findAddons().then(addons => {
const disabled = this._config.get(disabledAddons);
inquirer
.prompt({
type: 'checkbox',
name: 'addons',
message: 'Choose add-ons to use for new apps',
choices: addons.map(addon => ({
name: addon,
checked: !disabled[addon]
}))
})
.then(answers => {
this._config.set(disabledAddons, addons
.filter(addon => !answers.addons.includes(addon))
.reduce((r, addon) => {
r[addon] = true;
return r;
}, {}));
console.log('Configuration saved.');
});
async configure() {
const addons = await this._findAddons();
const disabled = this._config.get(disabledAddons);
const answers = await inquirer.prompt({
type: 'checkbox',
name: 'addons',
message: 'Choose add-ons to use for new apps',
choices: addons.map(addon => ({
name: addon,
checked: !disabled[addon]
}))
});

this._config.set(
disabledAddons,
addons.filter(addon => !answers.addons.includes(addon)).reduce((r, addon) => {
r[addon] = true;
return r;
}, {})
);
console.log('Configuration saved.');
}

list(npm) {
let promise;
async list(npm) {
let addons;
if (npm) {
promise = Promise
.resolve(child.execSync(`npm search ${addonKey} --json`, {stdio: [0, null, 2]}))
.then(addons => addons ? JSON.parse(addons) : [])
.then(addons => addons.filter(addon => blacklistedNpmAddons.indexOf(addon.name) === -1));
addons = await Promise.resolve(child.execSync(`npm search ${addonKey} --json`, {stdio: [0, null, 2]}));
addons = addons ? JSON.parse(addons) : [];
addons = addons.filter(addon => blacklistedNpmAddons.indexOf(addon.name) === -1);
} else {
promise = this._findAddons();
addons = await this._findAddons();
}
const disabled = this._config.get(disabledAddons);
console.log(chalk.blue(`Available add-ons${npm ? ' on NPM' : ''}:`));

if (addons.length === 0) {
console.log(' No add-ons found.');
} else if (npm) {
addons.forEach(addon => console.log(` ${addon.name}@${addon.version} - ${addon.description}`));
} else {
addons.forEach(addon => console.log(`${chalk.green(disabled[addon] ? ' ' : figures.tick)} ${addon}`));
}
promise.then(addons => {
const disabled = this._config.get(disabledAddons);
console.log(chalk.blue(`Available add-ons${npm ? ' on NPM' : ''}:`));

if (!addons.length) {
console.log(' No add-ons found.');
} else if (npm) {
addons.forEach(addon => console.log(` ${addon.name}@${addon.version} - ${addon.description}`));
} else {
addons.forEach(addon => console.log(`${chalk.green(disabled[addon] ? ' ' : figures.tick)} ${addon}`));
}
});
}

_findAddons() {
Expand All @@ -199,7 +200,7 @@ class NgxCli {

_findPackageJson(basePath) {
const find = components => {
if (!components.length) {
if (components.length === 0) {
return null;
}
const dir = path.join(...components);
Expand All @@ -208,7 +209,7 @@ class NgxCli {
};

const components = basePath.split(/[/\\]/);
if (components.length && !components[0].length) {
if (components.length !== 0 && components[0].length === 0) {
// When path starts with a slash, the first path component is empty string
components[0] = path.sep;
}
Expand All @@ -223,7 +224,7 @@ class NgxCli {
try {
const rc = require(path.join(process.cwd(), '.yo-rc.json'));
pm = rc['generator-ngx-rocket'].props.packageManager;
} catch (err) {
} catch (error) {
// Do nothing
}
return pm || process.env.NGX_PACKAGE_MANAGER || 'npm';
Expand All @@ -236,6 +237,7 @@ class NgxCli {

_exit(error, code = 1) {
console.error(error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(code);
}
}
Expand Down
13 changes: 9 additions & 4 deletions generators/addon/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ const upperFirst = require('lodash.upperfirst');
const Generator = require('@ngx-rocket/core');
const asciiLogo = require('@ngx-rocket/ascii-logo');

const pkg = require('../../package.json');
const options = require('./options.json');
const prompts = require('./prompts');
const pkg = require('../../package.json');

class NgxAddonGenerator extends Generator {
initializing() {
Expand All @@ -34,13 +34,18 @@ class NgxAddonGenerator extends Generator {

if (fromVersion) {
if (fromVersion >= this.version) {
this.log(chalk.green('\nNothing to update, it\'s all good!\n'));
this.log(chalk.green("\nNothing to update, it's all good!\n"));
// eslint-disable-next-line unicorn/no-process-exit
process.exit(0);
}

this.updating = true;
this.log(`\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(this.version)})\n`);
this.log(`${chalk.yellow('Make sure you don\'t have uncommitted changes before overwriting files!')}`);
this.log(
`\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(
this.version
)})\n`
);
this.log(`${chalk.yellow("Make sure you don't have uncommitted changes before overwriting files!")}`);
this.insight.track('update', fromVersion, 'to', this.version);
} else if (!this.options['skip-welcome']) {
this.log(asciiLogo(pkg.version));
Expand Down
6 changes: 3 additions & 3 deletions generators/addon/prompts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ module.exports = [
{
type: 'input',
name: 'appName',
message: 'What\'s the name of your add-on?'
message: 'What is the name of your add-on?'
},
{
type: 'input',
name: 'description',
message: 'What\'s the add-on description?',
message: 'What is the add-on description?',
default: 'An awesome ngX-Rocket add-on'
},
{
type: 'input',
name: 'author',
message: 'Who\'s the author?',
message: 'Who is the author?',
default: 'Your name'
},
{
Expand Down
28 changes: 17 additions & 11 deletions generators/app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const semver = require('semver');
const Generator = require('@ngx-rocket/core');
const asciiLogo = require('@ngx-rocket/ascii-logo');

const pkg = require('../../package.json');
const prompts = require('./prompts');
const options = require('./options');
const pkg = require('../../package.json');

class NgxGenerator extends Generator {
initializing() {
Expand All @@ -19,6 +19,7 @@ class NgxGenerator extends Generator {
if (semver.lt(process.version, '8.9.0')) {
this.log(chalk.yellow('Angular CLI v6 needs NodeJS v8.9 or greater.'));
this.log(chalk.yellow(`You are using ${process.version} which is unsupported, please upgrade.\n`));
// eslint-disable-next-line unicorn/no-process-exit
process.exit(-1);
}

Expand Down Expand Up @@ -48,13 +49,18 @@ class NgxGenerator extends Generator {

if (fromVersion) {
if (fromVersion >= this.version) {
this.log(chalk.green('\nNothing to update, it\'s all good!\n'));
this.log(chalk.green("\nNothing to update, it's all good!\n"));
// eslint-disable-next-line unicorn/no-process-exit
process.exit(0);
}

this.updating = true;
this.log(`\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(this.version)})\n`);
this.log(`${chalk.yellow('Make sure you don\'t have uncommitted changes before overwriting files!')}`);
this.log(
`\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(
this.version
)})\n`
);
this.log(`${chalk.yellow("Make sure you don't have uncommitted changes before overwriting files!")}`);
this.insight.track('update', fromVersion, 'to', this.version);
} else if (!this.options['skip-welcome']) {
this.log(asciiLogo(pkg.version));
Expand All @@ -71,12 +77,10 @@ class NgxGenerator extends Generator {
this.insight.track('addons', addonsOption);
}

prompting() {
return super.prompting()
.then(() => {
this.props.mobile = this.props.mobile || [];
this.shareProps(this.props);
});
async prompting() {
await super.prompting();
this.props.mobile = this.props.mobile || [];
this.shareProps(this.props);
}

configuring() {
Expand Down Expand Up @@ -119,7 +123,9 @@ class NgxGenerator extends Generator {
}

this.log('\nAll done! Get started with these tasks:');
this.log(`- $ ${chalk.green(`${this.packageManager} start`)}: start dev server with live reload on http://localhost:4200`);
this.log(
`- $ ${chalk.green(`${this.packageManager} start`)}: start dev server with live reload on http://localhost:4200`
);

if (this.props.target.includes('web')) {
this.log(`- $ ${chalk.green(`${this.packageManager} run build`)}: build web app for production`);
Expand Down
3 changes: 2 additions & 1 deletion generators/app/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module.exports = [
name: 'skip-welcome',
type: 'Boolean',
required: false,
description: 'Skip Yeoman\'s welcome message',
description: "Skip Yeoman's welcome message",
defaults: false
},
{
Expand Down Expand Up @@ -41,6 +41,7 @@ module.exports = [
type: value => {
if (value !== 'hash' && value !== 'path') {
console.error('Invalid location strategy: can be either "hash" or "path"');
// eslint-disable-next-line unicorn/no-process-exit
process.exit(-1);
}
return value;
Expand Down
7 changes: 3 additions & 4 deletions generators/app/prompts.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module.exports = [
{
type: 'input',
name: 'appName',
message: 'What\'s the name of your app?'
message: 'What is the name of your app?'
},
{
type: 'checkbox',
Expand Down Expand Up @@ -73,7 +73,7 @@ module.exports = [
name: 'Ionic (more mobile-oriented)'
}
],
default: props => props.target && props.target.includes('cordova') ? 'ionic' : 'bootstrap'
default: props => (props.target && props.target.includes('cordova') ? 'ionic' : 'bootstrap')
},
{
type: 'list',
Expand All @@ -96,8 +96,7 @@ module.exports = [
name: 'Tabs menu (more app-oriented)',
when: props.ui === 'ionic'
}
]
.filter(choice => choice.when);
].filter(choice => choice.when);
},
when: props => props.ui === 'material' || props.ui === 'ionic',
default: 'side-menu'
Expand Down
Loading