Merge pull request #3287 from strapi/tech/clean-cmds

Clean up commands
This commit is contained in:
Jim LAURIE 2019-05-17 16:05:35 +02:00 committed by GitHub
commit c15d58c26e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 76 additions and 146 deletions

View File

@ -1,29 +1,44 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash'); const _ = require('lodash');
// Strapi utilities.
const program = require('strapi-utils').commander;
const resolveCwd = require('resolve-cwd'); const resolveCwd = require('resolve-cwd');
const { yellow } = require('chalk');
// Local Strapi dependencies. const program = require('strapi-utils').commander;
const packageJSON = require('../package.json'); const packageJSON = require('../package.json');
/* eslint-disable no-console */ const checkCwdIsStrapiApp = name => {
let logErrorAndExit = () => {
console.log(
`You need to run ${yellow(
`strapi ${name}`
)} in a Strapi project. Make sure you are in the right directory`
);
process.exit(1);
};
try {
const pkgJSON = require(process.cwd() + '/package.json');
if (!_.has(pkgJSON, 'dependencies.strapi')) {
logErrorAndExit(name);
}
} catch (err) {
logErrorAndExit(name);
}
};
const getLocalScript = name => (...args) => { const getLocalScript = name => (...args) => {
checkCwdIsStrapiApp(name);
const cmdPath = resolveCwd.silent(`strapi/lib/commands/${name}`); const cmdPath = resolveCwd.silent(`strapi/lib/commands/${name}`);
if (!cmdPath) { if (!cmdPath) {
console.log( console.log(
`> Error loading the local ${name} command. Strapi might not be installed in your "node_modules". You may need to run "npm install"` `Error loading the local ${yellow(
name
)} command. Strapi might not be installed in your "node_modules". You may need to run "npm install"`
); );
process.exit(1);
} }
return require(cmdPath)(...args); return require(cmdPath)(...args);

View File

@ -32,7 +32,7 @@ const defaultQueries = require('./core-api/queries');
*/ */
class Strapi extends EventEmitter { class Strapi extends EventEmitter {
constructor({ appPath, autoReload = false } = {}) { constructor({ dir, autoReload = false } = {}) {
super(); super();
this.setMaxListeners(100); this.setMaxListeners(100);
@ -62,7 +62,7 @@ class Strapi extends EventEmitter {
// Expose `plugin`. // Expose `plugin`.
this.plugins = {}; this.plugins = {};
this.dir = appPath || process.cwd(); this.dir = dir || process.cwd();
const pkgJSON = require(path.resolve(this.dir, 'package.json')); const pkgJSON = require(path.resolve(this.dir, 'package.json'));
// Default configurations. // Default configurations.

View File

@ -3,20 +3,14 @@
const path = require('path'); const path = require('path');
const fs = require('fs-extra'); const fs = require('fs-extra');
const _ = require('lodash'); const _ = require('lodash');
const { green, cyan, yellow } = require('chalk'); const { green, yellow } = require('chalk');
const strapiAdmin = require('strapi-admin'); const strapiAdmin = require('strapi-admin');
const { cli } = require('strapi-utils');
const loadConfigFile = require('../load/load-config-files'); const loadConfigFile = require('../load/load-config-files');
// build script shoul only run in production mode /**
* `$ strapi build`
*/
module.exports = async () => { module.exports = async () => {
// Check that we're in a valid Strapi project.
if (!cli.isStrapiApp()) {
return console.log(
`⛔️ ${cyan('strapi start')} can only be used inside a Strapi project.`
);
}
const dir = process.cwd(); const dir = process.cwd();
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
@ -36,7 +30,6 @@ module.exports = async () => {
const serverConfig = await loadConfigFile(envConfigDir, 'server.+(js|json)'); const serverConfig = await loadConfigFile(envConfigDir, 'server.+(js|json)');
const adminPath = _.get(serverConfig, 'admin.path', '/admin'); const adminPath = _.get(serverConfig, 'admin.path', '/admin');
// const adminHost = _.get(serverConfig, 'admin.build.host', '/admin');
const adminBackend = _.get(serverConfig, 'admin.build.backend', '/'); const adminBackend = _.get(serverConfig, 'admin.build.backend', '/');
console.log(`Building your admin UI with ${green(env)} configuration ...`); console.log(`Building your admin UI with ${green(env)} configuration ...`);

View File

@ -1,56 +1,26 @@
// Node.js core. 'use strict';
const REPL = require('repl'); const REPL = require('repl');
const cluster = require('cluster');
const strapi = require('../index'); const strapi = require('../index');
// Public node modules. /**
const _ = require('lodash'); * `$ strapi console`
const { cli, logger } = require('strapi-utils'); */
module.exports = () => {
module.exports = function() {
if (!cli.isStrapiApp()) {
return console.log(
`⛔️ ${cyan('strapi start')} can only be used inside a Strapi project.`
);
}
try {
// Now load up the Strapi framework for real. // Now load up the Strapi framework for real.
const app = strapi(); const app = strapi();
// Only log if the process is a master.
if (cluster.isMaster) {
app.log.info('Starting the application in interactive mode...');
}
app.start(function(err) { app.start(() => {
// Log and exit the REPL in case there is an error
// while we were trying to start the server.
if (err) {
app.log.error('Could not load the Strapi framework.');
app.log.error('Are you using the latest stable version?');
process.exit(1);
}
// Open the Node.js REPL.
if (
(cluster.isMaster && _.isEmpty(cluster.workers)) ||
cluster.worker.id === 1
) {
const repl = REPL.start(app.config.info.name + ' > ' || 'strapi > '); // eslint-disable-line prefer-template const repl = REPL.start(app.config.info.name + ' > ' || 'strapi > '); // eslint-disable-line prefer-template
repl.on('exit', function(err) { repl.on('exit', function(err) {
// Log and exit the REPL in case there is an error
// while we were trying to open the REPL.
if (err) { if (err) {
app.log.error(err); app.log.error(err);
process.exit(1); process.exit(1);
} }
app.stop(); app.server.destroy();
process.exit(0);
}); });
}
}); });
} catch (e) {
logger.error(e);
}
}; };

View File

@ -1,42 +1,21 @@
#!/usr/bin/env node
'use strict'; 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path'); const path = require('path');
const cluster = require('cluster'); const cluster = require('cluster');
const strapi = require('../index');
// Public dependencies
const _ = require('lodash'); const _ = require('lodash');
const fs = require('fs-extra'); const fs = require('fs-extra');
const { cyan } = require('chalk'); const { cyan } = require('chalk');
const chokidar = require('chokidar'); const chokidar = require('chokidar');
const execa = require('execa'); const execa = require('execa');
const loadConfigFile = require('../load/load-config-files');
// Logger. const { logger } = require('strapi-utils');
const { cli, logger } = require('strapi-utils'); const strapi = require('../index');
/** /**
* `$ strapi develop` * `$ strapi develop`
* *
* Expose method which starts the appropriate instance of Strapi
* (fire up the application in our working directory).
*/ */
module.exports = async function({ build }) { module.exports = async function({ build }) {
// Check that we're in a valid Strapi project.
if (!cli.isStrapiApp()) {
return console.log(
`⛔️ ${cyan('strapi start')} can only be used inside a Strapi project.`
);
}
const dir = process.cwd(); const dir = process.cwd();
if (build && !fs.existsSync(path.join(dir, 'build'))) { if (build && !fs.existsSync(path.join(dir, 'build'))) {
@ -51,7 +30,7 @@ module.exports = async function({ build }) {
} }
try { try {
const strapiInstance = strapi({ appPath: dir, autoReload: true }); const strapiInstance = strapi({ dir, autoReload: true });
if (cluster.isMaster) { if (cluster.isMaster) {
cluster.on('message', (worker, message) => { cluster.on('message', (worker, message) => {
@ -77,7 +56,7 @@ module.exports = async function({ build }) {
} }
if (cluster.isWorker) { if (cluster.isWorker) {
watchFileChanges({ appPath: dir, strapiInstance }); watchFileChanges({ dir, strapiInstance });
process.on('message', message => { process.on('message', message => {
switch (message) { switch (message) {
@ -102,10 +81,10 @@ module.exports = async function({ build }) {
/** /**
* Init file watching to auto restart strapi app * Init file watching to auto restart strapi app
* @param {Object} options - Options object * @param {Object} options - Options object
* @param {string} options.appPath - This is the path where the app is located, the watcher will watch the files under this folder * @param {string} options.dir - This is the path where the app is located, the watcher will watch the files under this folder
* @param {Strapi} options.strapi - Strapi instance * @param {Strapi} options.strapi - Strapi instance
*/ */
function watchFileChanges({ appPath, strapiInstance }) { function watchFileChanges({ dir, strapiInstance }) {
const restart = () => { const restart = () => {
if ( if (
strapiInstance.reload.isWatching && strapiInstance.reload.isWatching &&
@ -116,7 +95,7 @@ function watchFileChanges({ appPath, strapiInstance }) {
} }
}; };
const watcher = chokidar.watch(appPath, { const watcher = chokidar.watch(dir, {
ignoreInitial: true, ignoreInitial: true,
ignored: [ ignored: [
/(^|[/\\])\../, /(^|[/\\])\../,

View File

@ -1,35 +1,8 @@
#!/usr/bin/env node
'use strict'; 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
const strapi = require('../index'); const strapi = require('../index');
// Public dependencies
const _ = require('lodash');
const { cyan } = require('chalk');
// Logger.
const { cli } = require('strapi-utils');
/** /**
* `$ strapi start` * `$ strapi start`
*
* Expose method which starts the appropriate instance of Strapi
* (fire up the application in our working directory).
*/ */
module.exports = function() { module.exports = () => strapi().start();
// Check that we're in a valid Strapi project.
if (!cli.isStrapiApp()) {
return console.log(
`⛔️ ${cyan('strapi start')} can only be used inside a Strapi project.`
);
}
strapi().start();
};

View File

@ -16,7 +16,7 @@ module.exports = async function({ appPath }) {
if (!existsSync(extensionsDir)) { if (!existsSync(extensionsDir)) {
throw new Error( throw new Error(
`Missing extension folder. Please create one in your app root directory` `Missing extensions folder. Please create one in your app root directory`
); );
} }

View File

@ -22,6 +22,12 @@ module.exports = strapi => {
*/ */
initialize: function(cb) { initialize: function(cb) {
const staticDir = path.resolve(
strapi.dir,
strapi.config.middleware.settings.public.path ||
strapi.config.paths.static
);
// Serve /public index page. // Serve /public index page.
strapi.router.route({ strapi.router.route({
method: 'GET', method: 'GET',
@ -32,14 +38,10 @@ module.exports = strapi => {
await next(); await next();
}, },
strapi.koaMiddlewares.static( strapi.koaMiddlewares.static(staticDir, {
strapi.config.middleware.settings.public.path ||
strapi.config.paths.static,
{
maxage: strapi.config.middleware.settings.public.maxAge, maxage: strapi.config.middleware.settings.public.maxAge,
defer: true, defer: true,
} }),
),
], ],
}); });
@ -57,14 +59,10 @@ module.exports = strapi => {
await next(); await next();
}, },
strapi.koaMiddlewares.static( strapi.koaMiddlewares.static(staticDir, {
strapi.config.middleware.settings.public.path ||
strapi.config.paths.static,
{
maxage: strapi.config.middleware.settings.public.maxAge, maxage: strapi.config.middleware.settings.public.maxAge,
defer: true, defer: true,
} }),
),
], ],
}); });
@ -75,6 +73,8 @@ module.exports = strapi => {
? strapi.config.currentEnvironment.server.admin.path ? strapi.config.currentEnvironment.server.admin.path
: '/admin'; : '/admin';
const buildDir = path.resolve(strapi.dir, 'build');
// Serve /admin index page. // Serve /admin index page.
strapi.router.route({ strapi.router.route({
method: 'GET', method: 'GET',
@ -85,7 +85,7 @@ module.exports = strapi => {
await next(); await next();
}, },
strapi.koaMiddlewares.static('./build', { strapi.koaMiddlewares.static(buildDir, {
maxage: strapi.config.middleware.settings.public.maxAge, maxage: strapi.config.middleware.settings.public.maxAge,
defer: true, defer: true,
}), }),
@ -106,7 +106,7 @@ module.exports = strapi => {
await next(); await next();
}, },
strapi.koaMiddlewares.static('./build', { strapi.koaMiddlewares.static(buildDir, {
maxage: strapi.config.middleware.settings.public.maxAge, maxage: strapi.config.middleware.settings.public.maxAge,
defer: true, defer: true,
}), }),
@ -123,7 +123,7 @@ module.exports = strapi => {
await next(); await next();
}, },
strapi.koaMiddlewares.static('./build', { strapi.koaMiddlewares.static(buildDir, {
maxage: strapi.config.middleware.settings.public.maxAge, maxage: strapi.config.middleware.settings.public.maxAge,
defer: true, defer: true,
}), }),