Merge pull request #10982 from strapi/v4/migrate-src

Change project structure to use src/ folder
This commit is contained in:
Alexandre BODIN 2021-09-21 13:21:08 +02:00 committed by GitHub
commit 6276e77984
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
83 changed files with 76 additions and 64 deletions

View File

@ -15,7 +15,7 @@ module.exports = ({ env }) => ({
},
myplugin: {
enabled: true,
resolve: `./plugins/myplugin`, // From the root of the project
resolve: `./src/plugins/myplugin`, // From the root of the project
config: {
testConf: 3,
},

View File

@ -10,7 +10,7 @@ const fse = require('fs-extra');
async function clear(uid) {
const { apiName, modelName } = strapi.contentTypes[uid];
const apiFolder = path.join(strapi.dir, 'api', apiName);
const apiFolder = path.join(strapi.dirs.api, apiName);
await recursiveRemoveFiles(apiFolder, createDeleteApiFunction(modelName));
await deleteBackup(uid);
@ -23,8 +23,8 @@ async function clear(uid) {
async function backup(uid) {
const { apiName } = strapi.contentTypes[uid];
const apiFolder = path.join(strapi.dir, 'api', apiName);
const backupFolder = path.join(strapi.dir, 'api', '.backup', apiName);
const apiFolder = path.join(strapi.dirs.api, apiName);
const backupFolder = path.join(strapi.dirs.api, '.backup', apiName);
// backup the api folder
await fse.copy(apiFolder, backupFolder);
@ -37,8 +37,8 @@ async function backup(uid) {
async function deleteBackup(uid) {
const { apiName } = strapi.contentTypes[uid];
const backupFolder = path.join(strapi.dir, 'api', '.backup');
const apiBackupFolder = path.join(strapi.dir, 'api', '.backup', apiName);
const backupFolder = path.join(strapi.dirs.api, '.backup');
const apiBackupFolder = path.join(strapi.dirs.api, '.backup', apiName);
await fse.remove(apiBackupFolder);
@ -55,8 +55,8 @@ async function deleteBackup(uid) {
async function rollback(uid) {
const { apiName } = strapi.contentTypes[uid];
const apiFolder = path.join(strapi.dir, 'api', apiName);
const backupFolder = path.join(strapi.dir, 'api', '.backup', apiName);
const apiFolder = path.join(strapi.dirs.api, apiName);
const backupFolder = path.join(strapi.dirs.api, '.backup', apiName);
const exists = await fse.exists(backupFolder);

View File

@ -11,7 +11,6 @@ const createBuilder = require('./schema-builder');
* @param {Object} infos new category data
*/
const editCategory = async (name, infos) => {
const componentsDir = join(strapi.dir, 'components');
const newName = nameToSlug(infos.name);
// don't do anything the name doesn't change
@ -34,7 +33,7 @@ const editCategory = async (name, infos) => {
// only edit the components in this specific category
if (component.category !== name) return;
component.setUID(newUID).setDir(join(componentsDir, newName));
component.setUID(newUID).setDir(join(strapi.dirs.components, newName));
builder.components.forEach(compo => {
compo.updateComponent(oldUID, newUID);

View File

@ -127,7 +127,7 @@ const createContentType = async ({ contentType, components = [] }, options = {})
*/
const generateAPI = ({ name, kind = 'collectionType' }) => {
const strapiGenerators = require('@strapi/generators');
return strapiGenerators.generate('api', { id: nameToSlug(name), kind }, { dir: strapi.dir });
return strapiGenerators.generate('api', { id: nameToSlug(name), kind }, { dir: strapi.dirs.src });
};
/**

View File

@ -38,7 +38,7 @@ module.exports = function createComponentBuilder() {
}
const handler = createSchemaHandler({
dir: path.join(strapi.dir, 'components', nameToSlug(infos.category)),
dir: path.join(strapi.dirs.components, nameToSlug(infos.category)),
filename: `${nameToSlug(infos.name)}.json`,
});
@ -87,7 +87,7 @@ module.exports = function createComponentBuilder() {
throw new Error('component.edit.alreadyExists');
}
const newDir = path.join(strapi.dir, 'components', newCategory);
const newDir = path.join(strapi.dirs.components, newCategory);
const oldAttributes = component.schema.attributes;

View File

@ -80,7 +80,7 @@ module.exports = function createComponentBuilder() {
const modelName = nameToSlug(infos.name);
const contentType = createSchemaHandler({
modelName: modelName,
dir: path.join(strapi.dir, 'api', modelName, 'content-types', modelName),
dir: path.join(strapi.dirs.api, modelName, 'content-types', modelName),
filename: `schema.json`,
});

View File

@ -1,6 +1,6 @@
'use strict';
const path = require('path');
const { join } = require('path');
const _ = require('lodash');
const createSchemaHandler = require('./schema-handler');
@ -22,7 +22,7 @@ module.exports = function createBuilder() {
plugin: compo.modelName,
uid: compo.uid,
filename: compo.__filename__,
dir: path.join(strapi.dir, 'components', compo.category),
dir: join(strapi.dirs.components, compo.category),
schema: compo.__schema__,
};
});
@ -30,22 +30,21 @@ module.exports = function createBuilder() {
const contentTypes = Object.keys(strapi.contentTypes).map(key => {
const contentType = strapi.contentTypes[key];
let dir;
let filename;
if (contentType.plugin) {
dir = `./extensions/${contentType.plugin}/content-types/${contentType.info.singularName}`;
filename = 'schema.json';
} else {
dir = `./api/${contentType.apiName}/content-types/${contentType.info.singularName}`;
filename = 'schema.json';
}
const dir = contentType.plugin
? join(
strapi.dirs.extensions,
contentType.plugin,
'content-types',
contentType.info.singularName
)
: join(strapi.dirs.api, contentType.apiName, 'content-types', contentType.info.singularName);
return {
modelName: contentType.modelName,
plugin: contentType.plugin,
uid: contentType.uid,
filename,
dir: path.join(strapi.dir, dir),
filename: 'schema.json',
dir,
schema: contentType.__schema__,
};
});

View File

@ -41,8 +41,8 @@ const LIFECYCLES = {
class Strapi {
constructor(opts = {}) {
this.dir = opts.dir || process.cwd();
const appConfig = loadConfiguration(this.dir, opts);
this.dirs = utils.getDirs(opts.dir || process.cwd());
const appConfig = loadConfiguration(this.dirs.root, opts);
this.container = createContainer(this);
this.container.register('config', createConfigProvider(appConfig));
this.container.register('content-types', contentTypesRegistry(this));
@ -72,7 +72,7 @@ class Strapi {
}
get EE() {
return ee({ dir: this.dir, logger: this.log });
return ee({ dir: this.dirs.root, logger: this.log });
}
service(uid) {

View File

@ -124,8 +124,8 @@ function watchFileChanges({ dir, strapiInstance, watchIgnoreFiles, polling }) {
/tmp/,
'**/admin',
'**/admin/**',
'extensions/**/admin',
'extensions/**/admin/**',
'src/extensions/**/admin',
'src/extensions/**/admin/**',
'**/documentation',
'**/documentation/**',
'**/node_modules',

View File

@ -14,20 +14,18 @@ const DEFAULT_CONTENT_TYPE = {
};
module.exports = async strapi => {
const apisDir = join(strapi.dir, 'api');
if (!existsSync(apisDir)) {
throw new Error(`Missing api folder. Please create one in your app root directory`);
if (!existsSync(strapi.dirs.api)) {
throw new Error('Missing api folder. Please create one at `./src/api`');
}
const apisFDs = await fse.readdir(apisDir, { withFileTypes: true });
const apisFDs = await fse.readdir(strapi.dirs.api, { withFileTypes: true });
const apis = {};
// only load folders
for (const apiFD of apisFDs) {
if (apiFD.isDirectory()) {
const apiName = normalizeName(apiFD.name);
const api = await loadAPI(join(apisDir, apiFD.name));
const api = await loadAPI(join(strapi.dirs.api, apiFD.name));
apis[apiName] = api;
}

View File

@ -6,19 +6,17 @@ const { pathExists } = require('fs-extra');
const loadFiles = require('../../load/load-files');
module.exports = async strapi => {
const componentsDir = join(strapi.dir, 'components');
if (!(await pathExists(componentsDir))) {
if (!(await pathExists(strapi.dirs.components))) {
return {};
}
const map = await loadFiles(componentsDir, '*/*.*(js|json)');
const map = await loadFiles(strapi.dirs.components, '*/*.*(js|json)');
return Object.keys(map).reduce((acc, category) => {
Object.keys(map[category]).forEach(key => {
const schema = map[category][key];
const filePath = join(componentsDir, category, schema.__filename__);
const filePath = join(strapi.dirs.components, category, schema.__filename__);
if (!schema.collectionName) {
return strapi.stopWithError(

View File

@ -45,7 +45,7 @@ const createLoaders = strapi => {
loadMiddlewaresInDir(path.resolve(__dirname, '..', '..', 'middlewares'), middlewares);
const loadLocalMiddlewares = (appPath, middlewares) =>
loadMiddlewaresInDir(path.resolve(appPath, 'middlewares'), middlewares);
loadMiddlewaresInDir(path.resolve(appPath, 'src', 'middlewares'), middlewares);
const loadMiddlewareDependencies = async (packages, middlewares) => {
for (let packageName of packages) {

View File

@ -32,7 +32,7 @@ const toDetailedDeclaration = declaration => {
try {
pathToPlugin = dirname(require.resolve(declaration.resolve));
} catch (e) {
pathToPlugin = resolve(strapi.dir, declaration.resolve);
pathToPlugin = resolve(strapi.dirs.root, declaration.resolve);
if (!existsSync(pathToPlugin) || !statSync(pathToPlugin).isDirectory()) {
throw new Error(`${declaration.resolve} couldn't be resolved`);
@ -72,7 +72,7 @@ const getEnabledPlugins = async strapi => {
}
const declaredPlugins = {};
const userPluginConfigPath = join(strapi.dir, 'config', 'plugins.js');
const userPluginConfigPath = join(strapi.dirs.config, 'plugins.js');
const userPluginsConfig = existsSync(userPluginConfigPath)
? loadConfigFile(userPluginConfigPath)
: {};

View File

@ -1,6 +1,6 @@
'use strict';
const { join, resolve } = require('path');
const { join } = require('path');
const { existsSync } = require('fs');
const { defaultsDeep, getOr, get } = require('lodash/fp');
const { env } = require('@strapi/utils');
@ -25,7 +25,7 @@ const defaultPlugin = {
};
const applyUserExtension = async plugins => {
const extensionsDir = resolve(strapi.dir, 'extensions');
const extensionsDir = strapi.dirs.extensions;
if (!existsSync(extensionsDir)) {
return;
}
@ -62,7 +62,7 @@ const formatContentTypes = plugins => {
};
const applyUserConfig = plugins => {
const userPluginConfigPath = join(strapi.dir, 'config', 'plugins.js');
const userPluginConfigPath = join(strapi.dirs.config, 'plugins.js');
const userPluginsConfig = existsSync(userPluginConfigPath)
? loadConfigFile(userPluginConfigPath)
: {};

View File

@ -5,7 +5,7 @@ const fse = require('fs-extra');
// TODO:: allow folders with index.js inside for bigger policies
module.exports = async function loadPolicies(strapi) {
const dir = join(strapi.dir, 'policies');
const dir = strapi.dirs.policies;
if (!(await fse.pathExists(dir))) {
return;

View File

@ -19,11 +19,10 @@ module.exports = strapi => {
*/
initialize() {
const { dir } = strapi;
const { maxAge, path: faviconPath } = strapi.config.middleware.settings.favicon;
strapi.server.use(
favicon(resolve(dir, faviconPath), {
favicon(resolve(strapi.dirs.root, faviconPath), {
maxAge,
})
);

View File

@ -25,7 +25,7 @@ module.exports = strapi => {
async initialize() {
const { defaultIndex, maxAge, path: publicPath } = strapi.config.middleware.settings.public;
const staticDir = path.resolve(strapi.dir, publicPath || strapi.config.paths.static);
const staticDir = path.resolve(strapi.dirs.root, publicPath || strapi.config.paths.static);
if (defaultIndex === true) {
const index = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8');
@ -98,7 +98,7 @@ module.exports = strapi => {
if (!strapi.config.serveAdminPanel) return;
const buildDir = path.resolve(strapi.dir, 'build');
const buildDir = path.resolve(strapi.dirs.root, 'build');
const serveAdmin = async (ctx, next) => {
await next();

View File

@ -11,7 +11,7 @@ const fs = require('../fs');
describe('Strapi fs utils', () => {
const strapi = {
dir: '/tmp',
dirs: { root: '/tmp' },
};
test('Provides new functions', () => {

View File

@ -12,7 +12,7 @@ module.exports = strapi => {
const normalizedPath = path.normalize(filePath).replace(/^\/?(\.\/|\.\.\/)+/, '');
return path.join(strapi.dir, normalizedPath);
return path.join(strapi.dirs.root, normalizedPath);
}
const strapiFS = {

View File

@ -88,7 +88,7 @@ const hashProject = strapi =>
const hashDep = strapi => {
const depStr = JSON.stringify(strapi.config.info.dependencies);
const readmePath = path.join(strapi.dir, 'README.md');
const readmePath = path.join(strapi.dirs.root, 'README.md');
try {
if (fs.existsSync(readmePath)) {

View File

@ -0,0 +1,15 @@
'use strict';
const { join } = require('path');
const getDirs = root => ({
root,
src: join(root, 'src'),
api: join(root, 'src', 'api'),
components: join(root, 'src', 'components'),
extensions: join(root, 'src', 'extensions'),
policies: join(root, 'src', 'policies'),
config: join(root, 'config'),
});
module.exports = getDirs;

View File

@ -2,8 +2,10 @@
const openBrowser = require('./open-browser');
const isInitialized = require('./is-initialized');
const getDirs = require('./get-dirs');
module.exports = {
isInitialized,
openBrowser,
getDirs,
};

View File

@ -38,7 +38,7 @@ const createUpdateNotifier = strapi => {
config = new Configstore(
pkg.name,
{},
{ configPath: path.join(strapi.dir, '.strapi-updater.json') }
{ configPath: path.join(strapi.dirs.root, '.strapi-updater.json') }
);
} catch {
// we don't have write access to the file system

View File

@ -8,7 +8,7 @@ describe('Upload plugin bootstrap function', () => {
const registerMany = jest.fn(() => {});
global.strapi = {
dir: process.cwd(),
dirs: { root: process.cwd() },
admin: {
services: { permission: { actionProvider: { registerMany } } },
},

View File

@ -12,7 +12,7 @@ module.exports = {
'middleware.settings.public.path',
strapi.config.paths.static
);
const staticDir = resolve(strapi.dir, configPublicPath);
const staticDir = resolve(strapi.dirs.root, configPublicPath);
strapi.server.app.on('error', err => {
if (err.code === 'EPIPE') {

View File

@ -13,13 +13,15 @@ const allowChildren = '*';
const allowedTemplateContents = {
'README.md': true,
'.env.example': true,
api: allowChildren,
components: allowChildren,
src: {
api: allowChildren,
components: allowChildren,
plugins: allowChildren,
},
config: {
functions: allowChildren,
},
data: allowChildren,
plugins: allowChildren,
public: allowChildren,
scripts: allowChildren,
};

View File

@ -21,7 +21,7 @@ module.exports = {
strapi.config.paths.static
);
const uploadDir = path.resolve(strapi.dir, configPublicPath);
const uploadDir = path.resolve(strapi.dirs.root, configPublicPath);
return {
upload(file) {