add generators to cli (#10779)

* add generators to cli

* add strapi generate comment

* remove old generators

* rename generator-cli -> generate

* list generators alphabetically

* update package description

* add check for strapi app in cwd
This commit is contained in:
markkaylor 2021-08-23 16:08:20 +02:00 committed by Mark Kaylor
parent 439103e4cf
commit b1ff616fd5
120 changed files with 124 additions and 4560 deletions

View File

@ -40,4 +40,4 @@
"npm": ">=6.0.0"
},
"license": "SEE LICENSE IN LICENSE"
}
}

View File

@ -10,7 +10,6 @@
"dependencies": {
"@sindresorhus/slugify": "1.1.0",
"@strapi/generate": "3.6.7",
"@strapi/generate-api": "3.6.7",
"@strapi/helper-plugin": "3.6.7",
"@strapi/utils": "3.6.7",
"fs-extra": "^9.1.0",

View File

@ -118,68 +118,21 @@ program
.description('Start your Strapi application in development mode')
.action(getLocalScript('develop'));
// `$ strapi generate:api`
// $ strapi generate
program
.command('generate:api <id> [attributes...]')
.option('-a, --api <api>', 'API name to generate the files in')
.option('-p, --plugin <api>', 'Name of the local plugin')
.option('-e, --extend <api>', 'Name of the plugin to extend')
.option('--draft-and-publish', 'Enable draft/publish', false)
.description('Generate a basic API')
.action((id, attributes, cliArguments) => {
cliArguments.attributes = attributes;
getLocalScript('generate')(id, cliArguments);
.command('generate')
.description('Launch interactive API generator')
.action(() => {
checkCwdIsStrapiApp('generate');
require('@strapi/generate')();
});
// `$ strapi generate:controller`
program
.command('generate:controller <id>')
.option('-a, --api <api>', 'API name to generate the files in')
.option('-p, --plugin <api>', 'Name of the local plugin')
.option('-e, --extend <api>', 'Name of the plugin to extend')
.description('Generate a controller for an API')
.action(getLocalScript('generate'));
// `$ strapi generate:model`
program
.command('generate:model <id> [attributes...]')
.option('-a, --api <api>', 'API name to generate a sub API')
.option('-p, --plugin <api>', 'plugin name')
.option('--draft-and-publish', 'Enable draft/publish', false)
.description('Generate a model for an API')
.action((id, attributes, cliArguments) => {
cliArguments.attributes = attributes;
getLocalScript('generate')(id, cliArguments);
});
// `$ strapi generate:policy`
program
.command('generate:policy <id>')
.option('-a, --api <api>', 'API name')
.option('-p, --plugin <api>', 'plugin name')
.description('Generate a policy for an API')
.action(getLocalScript('generate'));
// `$ strapi generate:service`
program
.command('generate:service <id>')
.option('-a, --api <api>', 'API name')
.option('-p, --plugin <api>', 'plugin name')
.description('Generate a service for an API')
.action(getLocalScript('generate'));
// `$ strapi generate:plugin`
program
.command('generate:plugin <id>')
.option('-n, --name <name>', 'Plugin name')
.description('Generate a basic plugin')
.action(getLocalScript('generate'));
// `$ strapi generate:template <directory>`
program
.command('generate:template <directory>')
.description('Generate template from Strapi project')
.action(getLocalScript('generate-template'));
program
.command('build')
.option('--clean', 'Remove the build and .cache folders', false)

View File

@ -1,76 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// FIXME
/* eslint-disable import/extensions */
// Node.js core.
const path = require('path');
// Master of ceremonies for generators.
const generate = require('@strapi/generate');
// Logger.
const { createLogger } = require('@strapi/logger');
// Configuration
const loadConfiguration = require('../core/app-configuration');
// Local Strapi dependencies.
const packageJSON = require('../../package.json');
/**
* `$ strapi generate`
*
* Scaffolding for the application in our working directory.
*/
module.exports = function(id, cliArguments) {
const dir = process.cwd();
const config = loadConfiguration(dir);
const logger = createLogger(config.get('logger', {}));
// Build initial scope.
const scope = {
rootPath: process.cwd(),
strapiRoot: path.resolve(__dirname, '..'),
id: id,
args: cliArguments,
strapiPackageJSON: packageJSON,
};
scope.generatorType = process.argv[2].split(':')[1];
// Show usage if no generator type is defined.
if (!scope.generatorType) {
return logger.error('Write `$ strapi generate:something` instead.');
}
return generate(scope, {
// Log and exit the REPL in case there is an error
// while we were trying to generate the requested generator.
error(msg) {
logger.error(msg);
process.exit(1);
},
// Log and exit the REPL in case of success
// but first make sure we have all the info we need.
success() {
if (!scope.outputPath && scope.filename && scope.destDir) {
scope.outputPath = scope.destDir + scope.filename;
}
if (scope.generatorType !== 'new') {
logger.info(
`Generated a new ${scope.generatorType} \`${scope.name}\` at \`${scope.filePath}\`.`
);
}
process.exit(0);
},
});
};

View File

@ -16,13 +16,7 @@
"@strapi/admin": "3.6.7",
"@strapi/database": "3.6.7",
"@strapi/generate": "3.6.7",
"@strapi/generate-api": "3.6.7",
"@strapi/generate-controller": "3.6.7",
"@strapi/generate-model": "3.6.7",
"@strapi/generate-new": "3.6.7",
"@strapi/generate-plugin": "3.6.7",
"@strapi/generate-policy": "3.6.7",
"@strapi/generate-service": "3.6.7",
"@strapi/logger": "3.6.7",
"@strapi/utils": "3.6.7",
"async": "^2.1.2",
@ -63,6 +57,7 @@
"open": "8.2.1",
"ora": "^5.4.0",
"package-json": "6.5.0",
"plop": "2.7.4",
"qs": "^6.10.1",
"resolve-cwd": "^3.0.0",
"rimraf": "^3.0.2",
@ -138,4 +133,4 @@
"reactjs"
],
"gitHead": "231263a3535658bab1e9492c6aaaed8692d62a53"
}
}

View File

@ -1,16 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -1,102 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
package-lock.json
############################
# Tests
############################
testApp
coverage

View File

@ -1,109 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.editorconfig
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
.snyk
############################
# Tests
############################
test
tests
__tests__
jest.config.js
testApp
coverage

View File

@ -1,9 +0,0 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.12.0
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
shelljs:
- '*':
reason: testing
expires: 2019-01-04T14:35:54.864Z
patch: {}

View File

@ -1,22 +0,0 @@
Copyright (c) 2015-present Strapi Solutions SAS
Portions of the Strapi software are licensed as follows:
* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE".
* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below.
MIT Expat License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,25 +0,0 @@
# strapi-generate-api
[![npm version](https://img.shields.io/npm/v/strapi-generate-api.svg)](https://www.npmjs.org/package/strapi-generate-api)
[![npm downloads](https://img.shields.io/npm/dm/strapi-generate-api.svg)](https://www.npmjs.org/package/strapi-generate-api)
[![npm dependencies](https://david-dm.org/strapi/strapi-generate-api.svg)](https://david-dm.org/strapi/strapi-generate-api)
[![Build status](https://travis-ci.org/strapi/strapi-generate-api.svg?branch=master)](https://travis-ci.org/strapi/strapi-generate-api)
[![Slack status](https://slack.strapi.io/badge.svg)](https://slack.strapi.io)
This Strapi generator contains all the default files for a new API.
This generator can be called with:
```bash
$ strapi generate:api apiName
```
## Resources
- [License](LICENSE)
## Links
- [Strapi website](https://strapi.io/)
- [Strapi community on Slack](https://slack.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)

View File

@ -1,7 +0,0 @@
'use strict';
module.exports = {
name: 'generate-api',
displayName: 'Generated API',
testMatch: ['**/test/?(*.)+(spec|test).js'],
};

View File

@ -1,108 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
// Public node modules.
const _ = require('lodash');
function generateSingleTypeRoutes({ route, name }) {
return [
{
method: 'GET',
path: '/' + route,
handler: name + '.find',
config: {
policies: [],
},
},
{
method: 'PUT',
path: '/' + route,
handler: name + '.update',
config: {
policies: [],
},
},
{
method: 'DELETE',
path: '/' + route,
handler: name + '.delete',
config: {
policies: [],
},
},
];
}
function generateCollectionTypeRoutes({ route, name }) {
return [
{
method: 'GET',
path: '/' + route,
handler: name + '.find',
config: {
policies: [],
},
},
{
method: 'GET',
path: '/' + route + '/:id',
handler: name + '.findOne',
config: {
policies: [],
},
},
{
method: 'POST',
path: '/' + route,
handler: name + '.create',
config: {
policies: [],
},
},
{
method: 'PUT',
path: '/' + route + '/:id',
handler: name + '.update',
config: {
policies: [],
},
},
{
method: 'DELETE',
path: '/' + route + '/:id',
handler: name + '.delete',
config: {
policies: [],
},
},
];
}
/**
* Expose main routes of the generated API
*/
module.exports = scope => {
let routes = [];
if (!scope.args.plugin) {
routes =
scope.contentTypeKind === 'singleType'
? generateSingleTypeRoutes({ route: scope.route, name: scope.name })
: generateCollectionTypeRoutes({ route: scope.route, name: scope.name });
}
// if routes.json already exists, then merge
if (fs.existsSync(scope.rootPath)) {
let current = require(scope.rootPath);
fs.unlinkSync(scope.rootPath);
routes = _.concat(routes, _.differenceWith(current.routes, routes, _.isEqual));
}
return { routes };
};

View File

@ -1,138 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const pluralize = require('pluralize');
const { nameToSlug } = require('@strapi/utils');
/**
* This `before` function is run before generating targets.
* Validate, configure defaults, get extra dependencies, etc.
*
* @param {Object} scope
* @param {Function} cb
*/
module.exports = (scope, cb) => {
if (!scope.rootPath || !scope.id) {
return cb.invalid('Usage: `$ strapi generate:api apiName`');
}
// Format `id`.
const name = scope.name || nameToSlug(scope.id);
scope.contentTypeKind = scope.args.kind || 'collectionType';
// `scope.args` are the raw command line arguments.
_.defaults(scope, {
name,
route:
scope.contentTypeKind === 'singleType'
? _.kebabCase(scope.id)
: _.kebabCase(pluralize(scope.id)),
});
let filePath;
if (scope.args.api) {
filePath = `./api/${scope.args.api}`;
} else if (scope.args.plugin) {
filePath = `./plugins/${scope.args.plugin}`;
} else if (scope.args.extend) {
filePath = `./extensions/${scope.args.extend}`;
} else {
filePath = `./api/${name}`;
}
// Take another pass to take advantage of the defaults absorbed in previous passes.
_.defaults(scope, {
filename: `${name}.js`,
filenameSettings: `${name}.settings.json`,
filePath,
});
// Validate optional attribute arguments.
const invalidAttributes = [];
if (_.isPlainObject(scope.args.attributes)) {
scope.attributes = scope.args.attributes;
} else {
// Map attributes and split them for CLI.
scope.attributes = scope.args.attributes.map(attribute => {
if (_.isString(attribute)) {
const parts = attribute.split(':');
parts[1] = parts[1] || 'string';
// Handle invalid attributes.
if (!parts[1] || !parts[0]) {
invalidAttributes.push('Error: Invalid attribute notation `' + attribute + '`.');
return;
}
return {
name: _.trim(_.deburr(parts[0].toLowerCase())),
params: {
type: _.trim(_.deburr(parts[1].toLowerCase())),
},
};
} else {
return _.has(attribute, 'params.type') ? attribute : undefined;
}
});
scope.attributes = _.compact(scope.attributes);
// Handle invalid action arguments.
// Send back invalidActions.
if (invalidAttributes.length) {
return cb.invalid(invalidAttributes);
}
// Make sure there aren't duplicates.
if (
_(scope.attributes.map(attribute => attribute.name))
.uniq()
.valueOf().length !== scope.attributes.length
) {
return cb.invalid('Duplicate attributes not allowed!');
}
// Render some stringified code from the action template
// and make it available in our scope for use later on.
scope.attributes = scope.attributes.reduce((acc, attribute) => {
acc[attribute.name] = attribute.params;
return acc;
}, {});
}
// Set collectionName
scope.collectionName = _.has(scope.args, 'collectionName')
? scope.args.collectionName
: _.snakeCase(pluralize(name));
// Set description
scope.description = _.has(scope.args, 'description') ? scope.args.description : '';
scope.schema = JSON.stringify(
{
collectionName: scope.collectionName,
info: {
name: scope.args.displayName || scope.id,
description: scope.description,
},
options: {
draftAndPublish: scope.args.draftAndPublish === 'true',
comment: '',
},
attributes: scope.attributes,
},
null,
2
);
// Trigger callback with no error to proceed.
return cb.success();
};

View File

@ -1,51 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// FIXME
/* eslint-disable import/extensions */
// Local dependencies.
const routesJSON = require('../json/routes.json.js');
/**
* Generate a core API
*/
module.exports = {
templatesDirectory: path.resolve(__dirname, '..', 'templates'),
before: require('./before'),
targets: {
// Use the default `controller` file as a template for
// every generated controller.
':filePath/controllers/:filename': {
template: 'controller.template',
},
// every generated controller.
':filePath/services/:filename': {
template: 'service.template',
},
// Copy an empty JavaScript model where every functions will be.
':filePath/models/:filename': {
template: 'model.template',
},
// Copy the generated JSON model for the connection,
// schema and attributes.
':filePath/models/:filenameSettings': {
template: 'model.settings.template',
},
// Generate routes.
':filePath/config/routes.json': {
jsonfile: routesJSON,
},
},
};

View File

@ -1,8 +0,0 @@
'use strict';
/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-controllers)
* to customize this controller
*/
module.exports = {};

View File

@ -1 +0,0 @@
<%= schema %>

View File

@ -1,8 +0,0 @@
'use strict';
/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#lifecycle-hooks)
* to customize this model
*/
module.exports = {};

View File

@ -1,8 +0,0 @@
'use strict';
/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-services)
* to customize this service
*/
module.exports = {};

View File

@ -1,16 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -1,104 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
package-lock.json
############################
# Tests
############################
testApp
coverage

View File

@ -1,109 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.editorconfig
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
.snyk
############################
# Tests
############################
test
tests
__tests__
jest.config.js
testApp
coverage

View File

@ -1,9 +0,0 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.12.0
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
shelljs:
- '*':
reason: testing
expires: 2019-01-04T14:35:57.351Z
patch: {}

View File

@ -1,22 +0,0 @@
Copyright (c) 2015-present Strapi Solutions SAS
Portions of the Strapi software are licensed as follows:
* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE".
* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below.
MIT Expat License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,31 +0,0 @@
# strapi-generate-controller
[![npm version](https://img.shields.io/npm/v/strapi-generate-controller.svg)](https://www.npmjs.org/package/strapi-generate-controller)
[![npm downloads](https://img.shields.io/npm/dm/strapi-generate-controller.svg)](https://www.npmjs.org/package/strapi-generate-controller)
[![npm dependencies](https://david-dm.org/strapi/strapi-generate-controller.svg)](https://david-dm.org/strapi/strapi-generate-controller)
[![Build status](https://travis-ci.org/strapi/strapi-generate-controller.svg?branch=master)](https://travis-ci.org/strapi/strapi-generate-controller)
[![Slack status](https://slack.strapi.io/badge.svg)](https://slack.strapi.io)
This Strapi generator contains the default files for a controller.
This generator can be called with:
```bash
$ strapi generate:controller controllerName apiName
```
For example if you want to generate a `group` controller for the `user` API:
```bash
$ strapi generate:controller group user
```
## Resources
- [License](LICENSE)
## Links
- [Strapi website](https://strapi.io/)
- [Strapi community on Slack](https://slack.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)

View File

@ -1,56 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const { nameToSlug } = require('@strapi/utils');
/* eslint-disable prefer-template */
/**
* This `before` function is run before generating targets.
* Validate, configure defaults, get extra dependencies, etc.
*
* @param {Object} scope
* @param {Function} cb
*/
module.exports = (scope, cb) => {
if (!scope.rootPath || !scope.id) {
return cb.invalid(
'Usage: `$ strapi generate:controller controllerName --api apiName --plugin pluginName`'
);
}
// Format `id`.
const name = scope.name || nameToSlug(scope.id);
// `scope.args` are the raw command line arguments.
_.defaults(scope, {
name,
api: scope.id,
});
// Determine the destination path.
let filePath;
if (scope.args.api) {
filePath = `./api/${scope.args.api}/controllers`;
} else if (scope.args.plugin) {
filePath = `./plugins/${scope.args.plugin}/controllers`;
} else if (scope.args.extend) {
filePath = `./extensions/${scope.args.extend}/controllers`;
} else {
filePath = `./api/${name}/controllers`;
}
// Take another pass to take advantage of the defaults absorbed in previous passes.
_.defaults(scope, {
rootPath: scope.rootPath,
filePath,
filename: `${name}.js`,
});
// Trigger callback with no error to proceed.
return cb();
};

View File

@ -1,22 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
/**
* Generate a core API
*/
module.exports = {
templatesDirectory: path.resolve(__dirname, '..', 'templates'),
before: require('./before'),
targets: {
':filePath/:filename': {
template: 'controller.template',
},
},
};

View File

@ -1,15 +0,0 @@
'use strict';
/**
* A set of functions called "actions" for `<%= name %>`
*/
module.exports = {
// exampleAction: async (ctx, next) => {
// try {
// ctx.body = 'ok';
// } catch (err) {
// ctx.body = err;
// }
// }
};

View File

@ -1,12 +0,0 @@
{
"name": "service-plop",
"version": "3.6.6",
"description": "Generate a service for a Strapi API.",
"main": "index.js",
"license": "MIT",
"dependencies": {
"fs-extra": "10.0.0",
"plop": "2.7.4",
"pluralize": "8.0.0"
}
}

View File

@ -1,16 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -1,104 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
package-lock.json
############################
# Tests
############################
testApp
coverage

View File

@ -1,109 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.editorconfig
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
.snyk
############################
# Tests
############################
test
tests
__tests__
jest.config.js
testApp
coverage

View File

@ -1,9 +0,0 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.12.0
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
shelljs:
- '*':
reason: testing
expires: 2019-01-04T14:35:22.585Z
patch: {}

View File

@ -1,22 +0,0 @@
Copyright (c) 2015-present Strapi Solutions SAS
Portions of the Strapi software are licensed as follows:
* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE".
* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below.
MIT Expat License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,25 +0,0 @@
# strapi-generate
[![npm version](https://img.shields.io/npm/v/strapi-generate.svg)](https://www.npmjs.org/package/strapi-generate)
[![npm downloads](https://img.shields.io/npm/dm/strapi-generate.svg)](https://www.npmjs.org/package/strapi-generate)
[![npm dependencies](https://david-dm.org/strapi/strapi-generate.svg)](https://david-dm.org/strapi/strapi-generate)
[![Build status](https://travis-ci.org/strapi/strapi-generate.svg?branch=master)](https://travis-ci.org/strapi/strapi-generate)
[![Slack status](https://slack.strapi.io/badge.svg)](https://slack.strapi.io)
Master of ceremonies for generators in the Strapi CLI.
Usage:
```bash
$ strapi generate:something
```
## Resources
- [License](LICENSE)
## Links
- [Strapi website](https://strapi.io/)
- [Strapi community on Slack](https://slack.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)

View File

@ -0,0 +1,10 @@
'use strict';
process.argv.splice(2, 1);
const { join } = require('path');
const { Plop, run } = require('plop');
module.exports = () => {
Plop.launch({ configPath: join(__dirname, 'plopfile.js') }, run);
};

View File

@ -1,188 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
const util = require('util');
// Public node modules.
const _ = require('lodash');
const async = require('async');
const reportback = require('reportback')();
// Local dependencies.
const pathRegexp = require('./util').pathRegexp;
const generateTarget = require('./target');
/**
* Run a generator given an existing scope
*
* @param {Object} generator
* @param {Object} scope
* @param {Switchback} cb
*/
/* eslint-disable prefer-template */
function generate(generator, scope, cb) {
const sb = reportback.extend(cb, {
error: cb.error,
invalid: cb.invalid,
alreadyExists: 'error',
});
// Resolve string shorthand for generator defs
// to `{ generator: 'originalDef' }`.
if (typeof generator === 'string') {
const generatorName = generator;
generator = {
generator: generatorName,
};
}
// Run the generator's `before()` method proceeding.
generator.before(
scope,
reportback.extend({
error: sb.error,
invalid: sb.invalid,
success: () => {
// Process all of the generator's targets concurrently.
async.each(
Object.keys(generator.targets),
(keyPath, asyncEachCb) => {
const asyncEachSb = reportback.extend(asyncEachCb);
// Create a new scope object for this target,
// with references to the important bits of the original
// (depth will be passed-by-value, but that's what we want).
// Then generate the target, passing along a reference to
// the base `generate` method to allow for recursive generators.
const target = generator.targets[keyPath];
if (!target) {
return asyncEachSb(
new Error(
'Error: Invalid target: {"' + keyPath + '": ' + util.inspect(target) + '}'
)
);
}
// Input tolerance.
if (keyPath === '') {
keyPath = '.';
}
// Interpret `keyPath` using Express's parameterized route conventions,
// first parsing params, then replacing them with their proper values from scope.
const params = [];
pathRegexp(keyPath, params);
let err;
const parsedKeyPath = _.reduce(
params,
(memoKeyPath, param) => {
if (err) {
return false;
}
try {
const paramMatchExpr = ':' + param.name;
let actualParamValue = scope[param.name];
if (!actualParamValue) {
err = new Error(
'generator error:\n' +
'A scope variable (`' +
param.name +
'`) was referenced in target: `' +
memoKeyPath +
'`,\n' +
'but `' +
param.name +
"` does not exist in the generator's scope."
);
return false;
}
actualParamValue = String(actualParamValue);
return memoKeyPath.replace(paramMatchExpr, actualParamValue);
} catch (e) {
err = new Error('Error: Could not parse target key ' + memoKeyPath);
err.message = e;
return false;
}
},
keyPath
);
if (!parsedKeyPath) {
return asyncEachSb(err);
}
// Create path from `rootPath` to `keyPath` to use as the `rootPath`
// for any generators or helpers in this target
// (use a copy so that child generators don't mutate the scope).
const targetScope = _.merge({}, scope, {
rootPath: path.resolve(scope.rootPath, parsedKeyPath),
// Include reference to original keypath for error reporting.
keyPath,
});
// If `target` is an array, run each item.
if (_.isArray(target)) {
async.eachSeries(
target,
(targetItem, asyncEachSeriesCb) => {
generateTarget(
{
target: targetItem,
parent: generator,
scope: _.cloneDeep(targetScope),
recursiveGenerate: generate,
},
asyncEachSeriesCb
);
},
asyncEachSb
);
return;
}
// Otherwise, just run the single target generator/helper.
generateTarget(
{
target,
parent: generator,
scope: targetScope,
recursiveGenerate: generate,
},
asyncEachSb
);
},
err => {
// Expose a `error` handler in generators.
if (err) {
const errorFn =
generator.error ||
function defaultError(err, scope, _cb) {
return _cb(err);
};
return errorFn(err, scope, sb);
}
// Expose a `after` handler in generators (on success only).
const afterFn =
generator.after ||
function defaultAfter(scope, _cb) {
return _cb();
};
return afterFn(scope, sb);
}
);
},
})
);
}
module.exports = generate;

View File

@ -1,45 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const fs = require('fs-extra');
const reportback = require('reportback')();
// Local dependencies.
const fileHelper = require('../file');
/**
* Copy file from one place to another
*/
module.exports = function(options, cb) {
cb = reportback.extend(cb, {
alreadyExists: 'error',
invalid: 'error',
});
// Compute the canonical path to copy from
// given its relative path from its source generator's
// `templates` directory.
const absSrcPath = path.resolve(options.templatesDirectory, options.templatePath);
fs.readFile(absSrcPath, 'utf8', (err, contents) => {
if (err) {
return cb.error(err);
}
return fileHelper(
_.merge(options, {
contents,
}),
cb
);
});
};

View File

@ -1,68 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const async = require('async');
const fs = require('fs-extra');
const reportback = require('reportback')();
/**
* Generate a file using the specified string
*/
/* eslint-disable prefer-template */
module.exports = function(options, cb) {
// Provide default values for switchback.
cb = reportback.extend(cb, {
alreadyExists: 'error',
});
// Provide defaults and validate required options.
_.defaults(options, {
force: false,
});
const missingOpts = _.difference(['contents', 'rootPath'], Object.keys(options));
if (missingOpts.length) {
return cb.invalid(missingOpts);
}
// In case we ended up here with a relative path,
// resolve it using the process's CWD
const rootPath = path.resolve(process.cwd(), options.rootPath);
// Only override an existing file if `options.force` is true.
fs.exists(rootPath, exists => {
if (exists && !options.force) {
return cb.alreadyExists('Something else already exists at `' + rootPath + '`.');
}
// Don't actually write the file if this is a dry run.
if (options.dry) {
return cb.success();
}
async.series(
[
function deleteExistingFileIfNecessary(cb) {
if (!exists) {
return cb();
}
return fs.remove(rootPath, cb);
},
function writeToDisk(cb) {
fs.outputFile(rootPath, options.contents, cb);
},
],
cb
);
});
};

View File

@ -1,77 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const fs = require('fs-extra');
const reportback = require('reportback')();
/**
* Generate a folder
*/
/* eslint-disable prefer-template */
module.exports = function(options, cb) {
// Provide default values for cb.
cb = reportback.extend(cb, {
alreadyExists: 'error',
invalid: 'error',
});
// Provide defaults and validate required options.
_.defaults(options, {
force: false,
gitkeep: false,
});
const missingOpts = _.difference(['rootPath'], Object.keys(options));
if (missingOpts.length) {
return cb.invalid(missingOpts);
}
const rootPath = path.resolve(process.cwd(), options.rootPath);
// Only override an existing folder if `options.force` is true.
fs.lstat(rootPath, err => {
const exists = !(err && err.code === 'ENOENT');
if (exists && err) {
return cb.error(err);
}
if (exists && !options.force) {
return cb.alreadyExists('Something else already exists at `' + rootPath + '`.');
}
if (exists) {
fs.remove(rootPath, err => {
if (err) {
return cb.error(err);
}
_afterwards_();
});
} else {
_afterwards_();
}
function _afterwards_() {
// Don't actually write the directory if this is a dry run.
if (options.dry) {
return cb.success();
}
// Create the directory.
fs.mkdirs(rootPath, err => {
if (err) {
return cb.error(err);
}
return cb.success();
});
}
});
};

View File

@ -1,66 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const fs = require('fs-extra');
const reportback = require('reportback')();
/**
* Generate a JSON file
*/
/* eslint-disable prefer-template */
module.exports = function(options, handlers) {
// Provide default values for handlers.
handlers = reportback.extend(handlers, {
alreadyExists: 'error',
});
// Provide defaults and validate required options.
_.defaults(options, {
force: false,
});
const missingOpts = _.difference(['rootPath', 'data'], Object.keys(options));
if (missingOpts.length) {
return handlers.invalid(missingOpts);
}
const rootPath = path.resolve(process.cwd(), options.rootPath);
// Only override an existing file if `options.force` is true.
fs.exists(rootPath, exists => {
if (exists && !options.force) {
return handlers.alreadyExists('Something else already exists at `' + rootPath + '`.');
}
if (exists) {
fs.remove(rootPath, err => {
if (err) {
return handlers.error(err);
}
_afterwards_();
});
} else {
_afterwards_();
}
function _afterwards_() {
fs.outputJSON(rootPath, options.data, { spaces: 2 }, err => {
if (err) {
return handlers.error(err);
} else {
handlers.success();
}
});
}
});
};

View File

@ -1,72 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const fs = require('fs-extra');
const reportback = require('reportback')();
// Local dependencies.
const fileHelper = require('../file');
/**
* Read a dynamic template, compile it using scope.
* Then use `file` helper to write it to its destination.
*/
module.exports = function(options, cb) {
cb = reportback.extend(cb, {
noTemplate: 'error',
alreadyExists: 'error',
});
// Compute the canonical path to a template
// given its relative path from its source generator's
// `templates` directory.
if (_.isFunction(options.templatesDirectory)) {
options.templatesDirectory = options.templatesDirectory(options);
}
const absTemplatePath = path.resolve(options.templatesDirectory, options.templatePath);
fs.readFile(absTemplatePath, 'utf8', (err, contents) => {
if (err) {
err = err instanceof Error ? err : new Error(err);
err.message = `Template error: ${err.message}`;
err.path = absTemplatePath;
if (err.code === 'ENOENT') {
return cb.noTemplate(err);
} else {
return cb(err);
}
}
try {
const compiled = _.template(contents, {
interpolate: /<%=([\s\S]+?)%>/g,
});
contents = compiled(options);
// With Lodash templates, HTML entities are escaped by default.
// Default assumption is we don't want that, so we'll reverse it.
if (!options.escapeHTMLEntities) {
contents = _.unescape(contents);
}
} catch (e) {
return cb(e);
}
return fileHelper(
_.merge(options, {
contents,
}),
cb
);
});
};

View File

@ -1,67 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const reportback = require('reportback')();
// Logger.
const logger = require('@strapi/utils').logger;
// Local dependencies.
const generate = require('./generate');
const generateTarget = require('./target');
/* eslint-disable prefer-template */
/**
* Generate module(s)
*
* @param {Object} scope
* @param {Function} cb
*
* @return {[Type]}
*/
module.exports = (scope, cb) => {
cb = cb || {};
cb = reportback.extend(cb, {
error: cb.error,
success: () => {},
notStrapiApp: () => {},
alreadyExists: () => {
return cb.error();
},
});
// Use configured module name for this `generatorType` if applicable.
const module = '@strapi/generate-' + scope.generatorType;
let generator;
function throwIfModuleNotFoundError(error, module) {
const isModuleNotFoundError =
error && error.code === 'MODULE_NOT_FOUND' && error.message.match(new RegExp(module));
if (!isModuleNotFoundError) {
logger.error('Invalid `' + scope.generatorType + '` generator.');
throw error;
} else {
return error;
}
}
// Try to require the module or throw if error.
try {
generator = require(module);
} catch (error) {
throwIfModuleNotFoundError(error, module);
}
if (!generator) {
return logger.error('No generator called `' + scope.generatorType + '` found.');
}
generate(generator, scope, cb);
};
module.exports.generateTarget = generateTarget;

View File

@ -1,318 +0,0 @@
'use strict';
/**
* Module dependencies
*/
/* eslint-disable prefer-template */
// Node.js core.
const path = require('path');
const util = require('util');
// Public node modules.
const _ = require('lodash');
const async = require('async');
const report = require('reportback')();
// Local dependencies.
const folderHelper = require('./helpers/folder');
const templateHelper = require('./helpers/template');
const jsonFileHelper = require('./helpers/jsonfile');
const copyHelper = require('./helpers/copy');
/**
* generateTarget()
*
* @param {Object} options
*/
function generateTarget(options, cb) {
const sb = report.extend(cb);
// Options.
let target = options.target;
let scope = options.scope;
const parentGenerator = options.parent;
const recursiveGenerate = options.recursiveGenerate;
const maxResolves = 5;
let _resolves = 0;
async.until(
() => {
return isValidTarget(target) || ++_resolves > maxResolves;
},
asyncCb => {
parseTarget(target, scope, (err, resolvedTarget) => {
if (err) {
return asyncCb(err);
}
target = resolvedTarget;
return asyncCb();
});
},
err => {
if (err) {
return sb(err);
}
if (!isValidTarget(target)) {
return sb(
new Error(
'Generator Error :: Could not resolve target `' +
scope.rootPath +
'` (probably a recursive loop)'
)
);
}
// Pass down parent Generator's template directory abs path.
scope.templatesDirectory = parentGenerator.templatesDirectory;
if (target.copy) {
scope = mergeSubtargetScope(
scope,
typeof target.copy === 'string'
? {
templatePath: target.copy,
}
: target.copy
);
return copyHelper(scope, sb);
}
if (target.folder) {
scope = mergeSubtargetScope(scope, target.folder);
return folderHelper(scope, sb);
}
if (target.template) {
scope = mergeSubtargetScope(
scope,
typeof target.template === 'string'
? {
templatePath: target.template,
}
: target.template
);
return templateHelper(scope, sb);
}
if (target.jsonfile) {
if (typeof target.jsonfile === 'object') {
scope = mergeSubtargetScope(scope, target.jsonfile);
} else if (typeof target.jsonfile === 'function') {
scope = _.merge(scope, {
data: target.jsonfile(scope),
});
}
return jsonFileHelper(scope, sb);
}
// If we made it here, this must be a recursive generator.
// Now that the generator definition has been resolved,
// call this method recursively on it, passing along our
// callback.
if (++scope._depth > scope.maxHops) {
return sb(
new Error(
'`maxHops` (' +
scope.maxHops +
') exceeded! There is probably a recursive loop in one of your generators.'
)
);
}
return recursiveGenerate(target, scope, sb);
}
);
}
module.exports = generateTarget;
/**
* @param {[Type]} scope Description
* @param {[Type]} subtarget Description
* @return {[Type]} Description
*/
function mergeSubtargetScope(scope, subtarget) {
return _.merge(scope, _.isObject(subtarget) ? subtarget : {});
}
/**
* Known helpers
*
* @type {Array}
*/
const knownHelpers = ['folder', 'template', 'jsonfile', 'file', 'copy'];
function targetIsHelper(target) {
return _.some(target, (subTarget, key) => {
return _.includes(knownHelpers, key);
});
}
/**
* @param {String|Object} target Description
* @param {Object} scope Description
* @param {Function} cb Description
* @return {[type]} Description
*/
function parseTarget(target, scope, cb) {
if (typeof target === 'string') {
target = {
generator: target,
};
}
// Interpret generator definition.
if (targetIsHelper(target)) {
return cb(null, target);
}
if (target.generator) {
// Normalize the subgenerator reference.
let subGeneratorRef;
if (typeof target.generator === 'string') {
subGeneratorRef = {
module: target.generator,
};
} else if (typeof target.generator === 'object') {
subGeneratorRef = target.generator;
}
if (!subGeneratorRef) {
return cb(
new Error(
'Generator Error :: Invalid subgenerator referenced for target `' + scope.rootPath + '`'
)
);
}
// Now normalize the sub-generator.
let subGenerator;
// No `module` means we'll treat this subgenerator as an inline generator definition.
if (!subGeneratorRef.module) {
subGenerator = subGeneratorRef;
if (subGenerator) {
return cb(null, subGenerator);
}
}
// Otherwise, we'll attempt to load this subgenerator.
if (typeof subGeneratorRef.module === 'string') {
// Lookup the generator by name if a `module` was specified
// This allows the module for a given generator to be
// overridden.
const configuredReference = scope.modules && scope.modules[subGeneratorRef.module];
// Refers to a configured module.
// If this generator type is explicitly set to `false`,
// disable the generator.
if (configuredReference) {
return cb(null, configuredReference);
} else if (configuredReference === false) {
return cb(null);
}
// If `configuredReference` is undefined, continue on
// and try to require the module.
}
// At this point, `subGeneratorRef.module` should be a string,
// and the best guess at the generator module we're going
// to get.
const module = subGeneratorRef.module;
let requireError;
// Try requiring it directly as a path.
try {
subGenerator = require(module);
} catch (e0) {
requireError = e0;
}
// Try the scope's `rootPath`.
if (!subGenerator) {
try {
const asDependencyInRootPath = path.resolve(scope.rootPath, 'node_modules', module);
subGenerator = require(asDependencyInRootPath);
} catch (e1) {
requireError = e1;
}
}
// Try the current working directory.
if (!subGenerator) {
try {
subGenerator = require(path.resolve(process.cwd(), 'node_modules', module));
} catch (e1) {
requireError = e1;
}
}
// If we couldn't find a generator using the configured module,
// try requiring `@strapi/generate-<module>` to get the core generator.
if (!subGenerator && !module.match(/^@strapi\/generate-/)) {
try {
if (process.mainModule.filename.indexOf('yarn') !== -1) {
subGenerator = require(path.resolve(
process.mainModule.paths[2],
'@strapi/generate-' + module
));
} else {
subGenerator = require(path.resolve(
process.mainModule.paths[1],
'@strapi/generate-' + module
));
}
} catch (e1) {
requireError = e1;
}
}
// If we were able to find it, send it back!
if (subGenerator) {
return cb(null, subGenerator);
}
// But if we still can't find it, give up.
return cb(
new Error(
'Error: Failed to load `' +
subGeneratorRef.module +
'`...' +
(requireError ? ' (' + requireError + ')' : '') +
''
)
);
}
return cb(
new Error(
'Unrecognized generator syntax in `targets["' +
scope.keyPath +
'"]` ::\n' +
util.inspect(target)
)
);
}
/**
*
* @param {[Type]} target Description
* @return {Boolean} Description
*/
function isValidTarget(target) {
let ok = typeof target === 'object';
// Is using a helper.
// Or is another generator def.
ok = ok && (targetIsHelper(target) || _.has(target, 'targets'));
return ok;
}

View File

@ -1,62 +0,0 @@
'use strict';
/**
* From Express core: (MIT License)
*
* Normalize the given path string,
* returning a regular expression.
*
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String|RegExp|Array} path
* @param {Array} keys
* @param {Boolean} sensitive
* @param {Boolean} strict
* @return {RegExp}
* @api private
*/
/* eslint-disable prefer-template */
/* eslint-disable no-useless-escape */
const pathRegexp = (path, keys, sensitive, strict) => {
if (toString.call(path) === '[object RegExp]') {
return path;
}
if (Array.isArray(path)) {
path = '(' + path.join('|') + ')';
}
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(
/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g,
(_, slash, format, key, capture, optional, star) => {
keys.push({
name: key,
optional: !!optional,
});
slash = slash || '';
return (
'' +
(optional ? '' : slash) +
'(?:' +
(optional ? slash : '') +
(format || '') +
(capture || (format && '([^/.]+?)') || '([^/]+?)') +
')' +
(optional || '') +
(star ? '(/*)?' : '')
);
}
)
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
};
module.exports = {
pathRegexp,
};

View File

@ -1,50 +1,12 @@
{
"name": "@strapi/generate",
"version": "3.6.7",
"description": "Master of ceremonies for the Strapi generators.",
"homepage": "https://strapi.io",
"keywords": [
"generate",
"generator",
"strapi"
],
"main": "./lib/index.js",
"directories": {
"lib": "./lib"
},
"scripts": {
"test": "echo \"no tests yet\""
},
"version": "3.6.6",
"description": "Interactive API generator.",
"main": "index.js",
"license": "MIT",
"dependencies": {
"async": "^2.6.2",
"fs-extra": "^9.1.0",
"lodash": "4.17.21",
"reportback": "^2.0.2",
"@strapi/utils": "3.6.7"
},
"author": {
"name": "Strapi team",
"email": "hi@strapi.io",
"url": "https://strapi.io"
},
"maintainers": [
{
"name": "Strapi team",
"email": "hi@strapi.io",
"url": "https://strapi.io"
}
],
"repository": {
"type": "git",
"url": "git://github.com/strapi/strapi.git"
},
"bugs": {
"url": "https://github.com/strapi/strapi/issues"
},
"engines": {
"node": ">=12.x.x <=16.x.x",
"npm": ">=6.0.0"
},
"license": "SEE LICENSE IN LICENSE",
"gitHead": "231263a3535658bab1e9492c6aaaed8692d62a53"
"fs-extra": "10.0.0",
"plop": "2.7.4",
"pluralize": "8.0.0"
}
}

View File

@ -10,92 +10,6 @@ module.exports = function(plop) {
plop.addHelper('pluralize', text => pluralize(text));
// Service generator
plop.setGenerator('service', {
description: 'Generate a service for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Service name',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'api/{{id}}/services/{{id}}.js'),
templateFile: 'templates/service.js.hbs',
},
],
});
// Model generator
plop.setGenerator('model', {
description: 'Generate a model for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Model name',
},
{
type: 'confirm',
name: 'useDraftAndPublish',
message: 'Use draft and publish?',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'api/{{id}}/models/{{id}}.js'),
templateFile: 'templates/model.js.hbs',
},
{
type: 'add',
path: join(rootDir, 'api/{{id}}/models/{{id}}.settings.json'),
templateFile: 'templates/model.settings.json.hbs',
},
],
});
// Controller generator
plop.setGenerator('controller', {
description: 'Generate a controller for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Controller name',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'api/{{id}}/controllers/{{id}}.js'),
templateFile: 'templates/controller.js.hbs',
},
],
});
// Policy generator
plop.setGenerator('policy', {
description: 'Generate a policy for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Policy name',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'config/policies/{{id}}.js'),
templateFile: 'templates/policy.js.hbs',
},
],
});
// API generator
plop.setGenerator('api', {
description: 'Generate a basic API',
@ -140,6 +54,54 @@ module.exports = function(plop) {
],
});
// Controller generator
plop.setGenerator('controller', {
description: 'Generate a controller for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Controller name',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'api/{{id}}/controllers/{{id}}.js'),
templateFile: 'templates/controller.js.hbs',
},
],
});
// Model generator
plop.setGenerator('model', {
description: 'Generate a model for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Model name',
},
{
type: 'confirm',
name: 'useDraftAndPublish',
message: 'Use draft and publish?',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'api/{{id}}/models/{{id}}.js'),
templateFile: 'templates/model.js.hbs',
},
{
type: 'add',
path: join(rootDir, 'api/{{id}}/models/{{id}}.settings.json'),
templateFile: 'templates/model.settings.json.hbs',
},
],
});
// Plugin generator
plop.setGenerator('plugin', {
description: 'Generate a basic plugin',
@ -181,4 +143,42 @@ module.exports = function(plop) {
];
},
});
// Policy generator
plop.setGenerator('policy', {
description: 'Generate a policy for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Policy name',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'config/policies/{{id}}.js'),
templateFile: 'templates/policy.js.hbs',
},
],
});
// Service generator
plop.setGenerator('service', {
description: 'Generate a service for an API',
prompts: [
{
type: 'input',
name: 'id',
message: 'Service name',
},
],
actions: [
{
type: 'add',
path: join(rootDir, 'api/{{id}}/services/{{id}}.js'),
templateFile: 'templates/service.js.hbs',
},
],
});
};

View File

@ -1,16 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -1,104 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
package-lock.json
############################
# Tests
############################
testApp
coverage

View File

@ -1,109 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.editorconfig
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
.snyk
############################
# Tests
############################
test
tests
__tests__
jest.config.js
testApp
coverage

View File

@ -1,9 +0,0 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.12.0
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
shelljs:
- '*':
reason: testing
expires: 2019-01-04T14:35:59.679Z
patch: {}

View File

@ -1,22 +0,0 @@
Copyright (c) 2015-present Strapi Solutions SAS
Portions of the Strapi software are licensed as follows:
* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE".
* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below.
MIT Expat License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,31 +0,0 @@
# strapi-generate-model
[![npm version](https://img.shields.io/npm/v/strapi-generate-model.svg)](https://www.npmjs.org/package/strapi-generate-model)
[![npm downloads](https://img.shields.io/npm/dm/strapi-generate-model.svg)](https://www.npmjs.org/package/strapi-generate-model)
[![npm dependencies](https://david-dm.org/strapi/strapi-generate-model.svg)](https://david-dm.org/strapi/strapi-generate-model)
[![Build status](https://travis-ci.org/strapi/strapi-generate-model.svg?branch=master)](https://travis-ci.org/strapi/strapi-generate-model)
[![Slack status](https://slack.strapi.io/badge.svg)](https://slack.strapi.io)
This Strapi generator contains the default files for a model.
This generator can be called with:
```bash
$ strapi generate:model modelName apiName
```
For example if you want to generate a `group` model for the `user` API:
```bash
$ strapi generate:model group user
```
## Resources
- [License](LICENSE)
## Links
- [Strapi website](https://strapi.io/)
- [Strapi community on Slack](https://slack.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)

View File

@ -1,139 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const pluralize = require('pluralize');
const { nameToSlug, nameToCollectionName } = require('@strapi/utils');
/* eslint-disable prefer-template */
/**
* This `before` function is run before generating targets.
* Validate, configure defaults, get extra dependencies, etc.
*
* @param {Object} scope
* @param {Function} cb
*/
module.exports = (scope, cb) => {
if (!scope.rootPath || !scope.id) {
return cb.invalid(
'Usage: `$ strapi generate:model modelName --api apiName --plugin pluginName`'
);
}
// Format `id`.
const name = scope.name || nameToSlug(scope.id);
// `scope.args` are the raw command line arguments.
_.defaults(scope, {
name,
environment: process.env.NODE_ENV || 'development',
});
// Determine the destination path.
let filePath;
if (scope.args.api) {
filePath = `./api/${scope.args.api}/models`;
} else if (scope.args.plugin) {
filePath = `./plugins/${scope.args.plugin}/models`;
} else {
filePath = `./api/${name}/models`;
}
// Take another pass to take advantage of the defaults absorbed in previous passes.
_.defaults(scope, {
rootPath: scope.rootPath,
filePath,
filename: `${name}.js`,
filenameSettings: `${name}.settings.json`,
});
// Validate optional attribute arguments.
const invalidAttributes = [];
if (_.isPlainObject(scope.args.attributes)) {
scope.attributes = scope.args.attributes;
} else {
// Map attributes and split them for CLI.
scope.attributes = scope.args.attributes.map(attribute => {
if (_.isString(attribute)) {
const parts = attribute.split(':');
parts[1] = parts[1] || 'string';
// Handle invalid attributes.
if (!parts[1] || !parts[0]) {
invalidAttributes.push('Error: Invalid attribute notation `' + attribute + '`.');
return;
}
return {
name: _.trim(_.deburr(parts[0].toLowerCase())),
params: {
type: _.trim(_.deburr(parts[1].toLowerCase())),
},
};
} else {
return _.has(attribute, 'params.type') ? attribute : undefined;
}
});
scope.attributes = _.compact(scope.attributes);
// Handle invalid action arguments.
// Send back invalidActions.
if (invalidAttributes.length) {
return cb.invalid(invalidAttributes);
}
// Make sure there aren't duplicates.
if (
_(scope.attributes.map(attribute => attribute.name))
.uniq()
.valueOf().length !== scope.attributes.length
) {
return cb.invalid('Duplicate attributes not allowed!');
}
// Render some stringified code from the action template
// and make it available in our scope for use later on.
scope.attributes = scope.attributes.reduce((acc, attribute) => {
acc[attribute.name] = attribute.params;
return acc;
}, {});
}
// Set collectionName
scope.collectionName = _.has(scope.args, 'collectionName')
? scope.args.collectionName
: nameToCollectionName(pluralize(scope.id));
// Set description
scope.description = _.has(scope.args, 'description') ? scope.args.description : undefined;
scope.schema = JSON.stringify(
{
kind: 'collectionType',
collectionName: scope.collectionName,
info: {
name: scope.id,
description: scope.description,
},
options: {
draftAndPublish: scope.args.draftAndPublish === 'true',
comment: '',
},
attributes: scope.attributes,
},
null,
2
);
// Trigger callback with no error to proceed.
return cb();
};

View File

@ -1,25 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
/**
* Generate a core API
*/
module.exports = {
templatesDirectory: path.resolve(__dirname, '..', 'templates'),
before: require('./before'),
targets: {
':filePath/:filename': {
template: 'model.template',
},
':filePath/:filenameSettings': {
template: 'model.settings.template',
},
},
};

View File

@ -1 +0,0 @@
<%= schema %>

View File

@ -1,8 +0,0 @@
'use strict';
/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/concepts/models.html#lifecycle-hooks)
* to customize this model
*/
module.exports = {};

View File

@ -1,16 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -1,104 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
package-lock.json
############################
# Tests
############################
testApp
coverage

View File

@ -1,109 +0,0 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
ssl
.editorconfig
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
.snyk
############################
# Tests
############################
test
tests
__tests__
jest.config.js
testApp
coverage

View File

@ -1,9 +0,0 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.12.0
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
shelljs:
- '*':
reason: testing
expires: 2019-01-04T14:36:06.569Z
patch: {}

View File

@ -1,22 +0,0 @@
Copyright (c) 2015-present Strapi Solutions SAS
Portions of the Strapi software are licensed as follows:
* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE".
* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below.
MIT Expat License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,25 +0,0 @@
# strapi-generate-plugin
[![npm version](https://img.shields.io/npm/v/strapi-generate-plugin.svg)](https://www.npmjs.org/package/strapi-generate-plugin)
[![npm downloads](https://img.shields.io/npm/dm/strapi-generate-plugin.svg)](https://www.npmjs.org/package/strapi-generate-plugin)
[![npm dependencies](https://david-dm.org/strapi/strapi-generate-plugin.svg)](https://david-dm.org/strapi/strapi-generate-plugin)
[![Build status](https://travis-ci.org/strapi/strapi-generate-plugin.svg?branch=master)](https://travis-ci.org/strapi/strapi-generate-plugin)
[![Slack status](https://slack.strapi.io/badge.svg)](https://slack.strapi.io)
This Strapi generator contains all the default files for a new plugin.
This generator can be called with:
```bash
$ strapi generate:plugin pluginName
```
## Resources
- [License](LICENSE)
## Links
- [Strapi website](https://strapi.io/)
- [Strapi community on Slack](https://slack.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)

View File

@ -1,25 +0,0 @@
/**
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
*/
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { NotFound } from '@strapi/helper-plugin';
import pluginId from '../../pluginId';
import HomePage from '../HomePage';
const App = () => {
return (
<div>
<Switch>
<Route path={`/plugins/${pluginId}`} component={HomePage} exact />
<Route component={NotFound} />
</Switch>
</div>
);
};
export default App;

View File

@ -1,20 +0,0 @@
/*
*
* HomePage
*
*/
import React, { memo } from 'react';
// import PropTypes from 'prop-types';
import pluginId from '../../pluginId';
const HomePage = () => {
return (
<div>
<h1>{pluginId}&apos;s HomePage</h1>
<p>Happy coding</p>
</div>
);
};
export default memo(HomePage);

View File

@ -1,26 +0,0 @@
/**
*
* Initializer
*
*/
import { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import pluginId from '../../pluginId';
const Initializer = ({ setPlugin }) => {
const ref = useRef();
ref.current = setPlugin;
useEffect(() => {
ref.current(pluginId);
}, []);
return null;
};
Initializer.propTypes = {
setPlugin: PropTypes.func.isRequired,
};
export default Initializer;

View File

@ -1,61 +0,0 @@
import { prefixPluginTranslations } from '@strapi/helper-plugin';
import pluginPkg from '../../package.json';
import pluginId from './pluginId';
import App from './containers/App';
import Initializer from './containers/Initializer';
const pluginDescription = pluginPkg.strapi.description || pluginPkg.description;
const icon = pluginPkg.strapi.icon;
const name = pluginPkg.strapi.name;
export default {
register(app) {
app.addMenuLink({
to: `/plugins/${pluginId}`,
icon,
intlLabel: {
id: `${pluginId}.plugin.name`,
defaultMessage: name,
},
Component: App,
permissions: [
// Uncomment to set the permissions of the plugin here
// {
// action: '', // the action name should be plugins::plugin-name.actionType
// subject: null,
// },
],
});
app.registerPlugin({
description: pluginDescription,
icon,
id: pluginId,
initializer: Initializer,
isReady: false,
isRequired: pluginPkg.strapi.required || false,
name,
});
},
bootstrap(app) {},
async registerTrads({ locales }) {
const importedTrads = await Promise.all(
locales.map(locale => {
return import(`./translations/${locale}.json`)
.then(({ default: data }) => {
return {
data: prefixPluginTranslations(data, pluginId),
locale,
};
})
.catch(() => {
return {
data: {},
locale,
};
});
})
);
return Promise.resolve(importedTrads);
},
};

View File

@ -1,5 +0,0 @@
const pluginPkg = require('../../package.json');
const pluginId = pluginPkg.name.replace(/^@strapi\/plugin-/i, '');
module.exports = pluginId;

View File

@ -1,5 +0,0 @@
import pluginId from '../pluginId';
const getTrad = id => `${pluginId}.${id}`;
export default getTrad;

View File

@ -1,45 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
/**
* Expose main package JSON of the application
* with basic info, dependencies, etc.
*/
module.exports = scope => {
// Finally, return the JSON.
return _.merge(scope.appPackageJSON || {}, {
name: `strapi-plugin-${scope.id}`,
version: '0.0.0',
description: 'This is the description of the plugin.',
strapi: {
name: scope.id,
icon: 'plug',
description: `Description of ${scope.id} plugin.`,
},
dependencies: {},
author: {
name: scope.author || 'A Strapi developer',
email: scope.email || '',
url: scope.website || '',
},
maintainers: [
{
name: scope.author || 'A Strapi developer',
email: scope.email || '',
url: scope.website || '',
},
],
engines: {
node: '>=12.x. <=14.x.x',
npm: '>=6.0.0',
},
license: scope.license || 'MIT',
});
};

View File

@ -1,24 +0,0 @@
'use strict';
/**
* Expose main routes of the generated plugin
*/
module.exports = scope => {
function generateRoutes() {
return {
routes: [
{
method: 'GET',
path: '/',
handler: scope.name + '.index',
config: {
policies: [],
},
},
],
};
}
return generateRoutes();
};

View File

@ -1,52 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const path = require('path');
const fs = require('fs-extra');
const _ = require('lodash');
const { nameToSlug } = require('@strapi/utils');
/**
* This `before` function is run before generating targets.
* Validate, configure defaults, get extra dependencies, etc.
*
* @param {Object} scope
* @param {Function} cb
*/
module.exports = (scope, cb) => {
if (!scope.rootPath || !scope.id) {
return cb.invalid('Usage: `$ strapi generate:plugin pluginName`');
}
// Format `id`.
const name = scope.name || nameToSlug(scope.id);
// Plugin info.
_.defaults(scope, {
name,
author: scope.author || 'A Strapi developer',
email: scope.email || '',
year: new Date().getFullYear(),
license: 'MIT',
});
// Take another pass to take advantage of the defaults absorbed in previous passes.
_.defaults(scope, {
filename: `${name}.js`,
filePath: './plugins',
});
const pluginDir = path.resolve(scope.rootPath, 'plugins');
fs.ensureDirSync(pluginDir);
// Copy the admin files.
fs.copySync(path.resolve(__dirname, '..', 'files'), path.resolve(pluginDir, name));
// Trigger callback with no error to proceed.
return cb.success();
};

View File

@ -1,63 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// FIXME
/* eslint-disable import/extensions */
// Local dependencies.
const packageJSON = require('../json/package.json.js');
const routesJSON = require('../json/routes.json.js');
/**
* Generate a core API
*/
module.exports = {
templatesDirectory: path.resolve(__dirname, '..', 'templates'),
before: require('./before'),
targets: {
'plugins/:name/.gitignore': {
copy: 'gitignore',
},
// Use the default `controller` file as a template for
// every generated controller.
'plugins/:name/controllers/:filename': {
template: 'controller.template',
},
// every generated controller.
'plugins/:name/services/:filename': {
template: 'service.template',
},
// Generate routes.
'plugins/:name/config/routes.json': {
jsonfile: routesJSON,
},
// Main package.
'plugins/:name/package.json': {
jsonfile: packageJSON,
},
// Copy dot files.
'plugins/:name/.editorconfig': {
copy: 'editorconfig',
},
'plugins/:name/.gitattributes': {
copy: 'gitattributes',
},
// Copy Markdown files with some information.
'plugins/:name/README.md': {
template: 'README.md',
},
},
};

View File

@ -1,3 +0,0 @@
# Strapi plugin <%= id %>
A quick description of <%= id %>.

View File

@ -1,25 +0,0 @@
'use strict';
/**
* <%= filename %> controller
*
* @description: A set of functions called "actions" of the `<%= name %>` plugin.
*/
module.exports = {
/**
* Default action.
*
* @return {Object}
*/
index: async (ctx) => {
// Add your own logic here.
// Send 200 `ok`
ctx.send({
message: 'ok'
});
}
};

View File

@ -1,7 +0,0 @@
root = true
[*]
end_of_line = lf
insert_final_newline = false
indent_style = space
indent_size = 2

View File

@ -1,103 +0,0 @@
# From https://github.com/Danimoth/gitattributes/blob/master/Web.gitattributes
# Handle line endings automatically for files detected as text
# and leave all files detected as binary untouched.
* text=auto
#
# The above will handle all files NOT found below
#
#
## These files are text and should be normalized (Convert crlf => lf)
#
# source code
*.php text
*.css text
*.sass text
*.scss text
*.less text
*.styl text
*.js text eol=lf
*.coffee text
*.json text
*.htm text
*.html text
*.xml text
*.svg text
*.txt text
*.ini text
*.inc text
*.pl text
*.rb text
*.py text
*.scm text
*.sql text
*.sh text
*.bat text
# templates
*.ejs text
*.hbt text
*.jade text
*.haml text
*.hbs text
*.dot text
*.tmpl text
*.phtml text
# git config
.gitattributes text
.gitignore text
.gitconfig text
# code analysis config
.jshintrc text
.jscsrc text
.jshintignore text
.csslintrc text
# misc config
*.yaml text
*.yml text
.editorconfig text
# build config
*.npmignore text
*.bowerrc text
# Heroku
Procfile text
.slugignore text
# Documentation
*.md text
LICENSE text
AUTHORS text
#
## These files are binary and should be left untouched
#
# (binary is a macro for -text -diff)
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.mov binary
*.mp4 binary
*.mp3 binary
*.flv binary
*.fla binary
*.swf binary
*.gz binary
*.zip binary
*.7z binary
*.ttf binary
*.eot binary
*.woff binary
*.pyc binary
*.pdf binary

View File

@ -1,10 +0,0 @@
# Don't check auto-generated stuff into git
coverage
node_modules
stats.json
package-lock.json
# Cruft
.DS_Store
npm-debug.log
.idea

Some files were not shown because too many files have changed in this diff Show More