refactor: shared constants (#8707)

define plugin name and theme name regexs in one location for consistency

define various shared paths in one place for consistency
v1.18.x
Peter Jaszkowiak 5 years ago committed by GitHub
parent e60357d20d
commit 1aa336d837
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,16 +1,16 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
require('../../require-main'); require('../../require-main');
var packageInstall = require('./package-install'); const packageInstall = require('./package-install');
var dirname = require('./paths').baseDir; const { paths } = require('../constants');
// check to make sure dependencies are installed // check to make sure dependencies are installed
try { try {
fs.accessSync(path.join(dirname, 'package.json'), fs.constants.R_OK); fs.accessSync(paths.currentPackage, fs.constants.R_OK);
} catch (e) { } catch (e) {
if (e.code === 'ENOENT') { if (e.code === 'ENOENT') {
console.warn('package.json not found.'); console.warn('package.json not found.');
@ -20,7 +20,7 @@ try {
packageInstall.preserveExtraneousPlugins(); packageInstall.preserveExtraneousPlugins();
try { try {
fs.accessSync(path.join(dirname, 'node_modules/colors/package.json'), fs.constants.R_OK); fs.accessSync(path.join(paths.nodeModules, 'colors/package.json'), fs.constants.R_OK);
require('colors'); require('colors');
console.log('OK'.green); console.log('OK'.green);
@ -33,13 +33,13 @@ try {
} }
try { try {
fs.accessSync(path.join(dirname, 'node_modules/semver/package.json'), fs.constants.R_OK); fs.accessSync(path.join(paths.nodeModules, 'semver/package.json'), fs.constants.R_OK);
var semver = require('semver'); var semver = require('semver');
var defaultPackage = require('../../install/package.json'); var defaultPackage = require('../../install/package.json');
var checkVersion = function (packageName) { var checkVersion = function (packageName) {
var version = JSON.parse(fs.readFileSync(path.join(dirname, 'node_modules', packageName, 'package.json'), 'utf8')).version; var version = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, packageName, 'package.json'), 'utf8')).version;
if (!semver.satisfies(version, defaultPackage.dependencies[packageName])) { if (!semver.satisfies(version, defaultPackage.dependencies[packageName])) {
var e = new TypeError('Incorrect dependency version: ' + packageName); var e = new TypeError('Incorrect dependency version: ' + packageName);
e.code = 'DEP_WRONG_VERSION'; e.code = 'DEP_WRONG_VERSION';
@ -97,7 +97,7 @@ global.env = env;
prestart.setupWinston(); prestart.setupWinston();
// Alternate configuration file support // Alternate configuration file support
var configFile = path.resolve(dirname, nconf.get('config') || 'config.json'); var configFile = path.resolve(paths.baseDir, nconf.get('config') || 'config.json');
var configExists = file.existsSync(configFile) || (nconf.get('url') && nconf.get('secret') && nconf.get('database')); var configExists = file.existsSync(configFile) || (nconf.get('url') && nconf.get('secret') && nconf.get('database'));
prestart.loadConfig(configFile); prestart.loadConfig(configFile);

@ -1,17 +1,18 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var winston = require('winston'); const winston = require('winston');
var childProcess = require('child_process'); const childProcess = require('child_process');
var _ = require('lodash'); const _ = require('lodash');
var CliGraph = require('cli-graph'); const CliGraph = require('cli-graph');
var build = require('../meta/build'); const build = require('../meta/build');
var db = require('../database'); const db = require('../database');
var plugins = require('../plugins'); const plugins = require('../plugins');
var events = require('../events'); const events = require('../events');
var analytics = require('../analytics'); const analytics = require('../analytics');
var reset = require('./reset'); const reset = require('./reset');
const { pluginNamePattern, themeNamePattern } = require('../constants');
function buildTargets() { function buildTargets() {
var aliases = build.aliases; var aliases = build.aliases;
@ -34,9 +35,6 @@ function buildTargets() {
); );
} }
var themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
var pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;
function activate(plugin) { function activate(plugin) {
if (themeNamePattern.test(plugin)) { if (themeNamePattern.test(plugin)) {
reset.reset({ reset.reset({

@ -4,28 +4,24 @@ const path = require('path');
const fs = require('fs'); const fs = require('fs');
const cproc = require('child_process'); const cproc = require('child_process');
const packageFilePath = path.join(__dirname, '../../package.json'); const { paths, pluginNamePattern } = require('../constants');
const packageDefaultFilePath = path.join(__dirname, '../../install/package.json');
const modulesPath = path.join(__dirname, '../../node_modules');
const isPackage = /^(@\w+\/)?nodebb-(plugin|theme|widget|reward)-\w+/;
function updatePackageFile() { function updatePackageFile() {
let oldPackageContents = {}; let oldPackageContents = {};
try { try {
oldPackageContents = JSON.parse(fs.readFileSync(packageFilePath, 'utf8')); oldPackageContents = JSON.parse(fs.readFileSync(paths.currentPackage, 'utf8'));
} catch (e) { } catch (e) {
if (e.code !== 'ENOENT') { if (e.code !== 'ENOENT') {
throw e; throw e;
} }
} }
const defaultPackageContents = JSON.parse(fs.readFileSync(packageDefaultFilePath, 'utf8')); const defaultPackageContents = JSON.parse(fs.readFileSync(paths.installPackage, 'utf8'));
let dependencies = {}; let dependencies = {};
Object.entries(oldPackageContents.dependencies || {}).forEach(([dep, version]) => { Object.entries(oldPackageContents.dependencies || {}).forEach(([dep, version]) => {
if (isPackage.test(dep)) { if (pluginNamePattern.test(dep)) {
dependencies[dep] = version; dependencies[dep] = version;
} }
}); });
@ -38,7 +34,7 @@ function updatePackageFile() {
const packageContents = { ...oldPackageContents, ...defaultPackageContents, dependencies: dependencies }; const packageContents = { ...oldPackageContents, ...defaultPackageContents, dependencies: dependencies };
fs.writeFileSync(packageFilePath, JSON.stringify(packageContents, null, 2)); fs.writeFileSync(paths.currentPackage, JSON.stringify(packageContents, null, 2));
} }
exports.updatePackageFile = updatePackageFile; exports.updatePackageFile = updatePackageFile;
@ -54,7 +50,7 @@ function installAll() {
const prod = global.env !== 'development'; const prod = global.env !== 'development';
let command = 'npm install'; let command = 'npm install';
try { try {
fs.accessSync(path.join(modulesPath, 'nconf/package.json'), fs.constants.R_OK); fs.accessSync(path.join(paths.nodeModules, 'nconf/package.json'), fs.constants.R_OK);
const supportedPackageManagerList = exports.supportedPackageManager; // load config from src/cli/package-install.js const supportedPackageManagerList = exports.supportedPackageManager; // load config from src/cli/package-install.js
const packageManager = require('nconf').get('package_manager'); const packageManager = require('nconf').get('package_manager');
if (supportedPackageManagerList.indexOf(packageManager) >= 0) { if (supportedPackageManagerList.indexOf(packageManager) >= 0) {
@ -94,34 +90,34 @@ exports.installAll = installAll;
function preserveExtraneousPlugins() { function preserveExtraneousPlugins() {
// Skip if `node_modules/` is not found or inaccessible // Skip if `node_modules/` is not found or inaccessible
try { try {
fs.accessSync(modulesPath, fs.constants.R_OK); fs.accessSync(paths.nodeModules, fs.constants.R_OK);
} catch (e) { } catch (e) {
return; return;
} }
const packages = fs.readdirSync(modulesPath).filter(function (pkgName) { const packages = fs.readdirSync(paths.nodeModules).filter(function (pkgName) {
return isPackage.test(pkgName); return pluginNamePattern.test(pkgName);
}); });
const packageContents = JSON.parse(fs.readFileSync(packageFilePath, 'utf8')); const packageContents = JSON.parse(fs.readFileSync(paths.currentPackage, 'utf8'));
const extraneous = packages const extraneous = packages
// only extraneous plugins (ones not in package.json) which are not links // only extraneous plugins (ones not in package.json) which are not links
.filter(function (pkgName) { .filter(function (pkgName) {
const extraneous = !packageContents.dependencies.hasOwnProperty(pkgName); const extraneous = !packageContents.dependencies.hasOwnProperty(pkgName);
const isLink = fs.lstatSync(path.join(modulesPath, pkgName)).isSymbolicLink(); const isLink = fs.lstatSync(path.join(paths.nodeModules, pkgName)).isSymbolicLink();
return extraneous && !isLink; return extraneous && !isLink;
}) })
// reduce to a map of package names to package versions // reduce to a map of package names to package versions
.reduce(function (map, pkgName) { .reduce(function (map, pkgName) {
const pkgConfig = JSON.parse(fs.readFileSync(path.join(modulesPath, pkgName, 'package.json'), 'utf8')); const pkgConfig = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, pkgName, 'package.json'), 'utf8'));
map[pkgName] = pkgConfig.version; map[pkgName] = pkgConfig.version;
return map; return map;
}, {}); }, {});
// Add those packages to package.json // Add those packages to package.json
Object.assign(packageContents.dependencies, extraneous); Object.assign(packageContents.dependencies, extraneous);
fs.writeFileSync(packageFilePath, JSON.stringify(packageContents, null, 2)); fs.writeFileSync(paths.currentPackage, JSON.stringify(packageContents, null, 2));
} }
exports.preserveExtraneousPlugins = preserveExtraneousPlugins; exports.preserveExtraneousPlugins = preserveExtraneousPlugins;

@ -1,17 +0,0 @@
'use strict';
var path = require('path');
var baseDir = path.join(__dirname, '../../');
var loader = path.join(baseDir, 'loader.js');
var app = path.join(baseDir, 'app.js');
var pidfile = path.join(baseDir, 'pidfile');
var config = path.join(baseDir, 'config.json');
module.exports = {
baseDir: baseDir,
loader: loader,
app: app,
pidfile: pidfile,
config: config,
};

@ -11,11 +11,7 @@ const meta = require('../meta');
const plugins = require('../plugins'); const plugins = require('../plugins');
const widgets = require('../widgets'); const widgets = require('../widgets');
const privileges = require('../privileges'); const privileges = require('../privileges');
const { paths, pluginNamePattern, themeNamePattern } = require('../constants');
const dirname = require('./paths').baseDir;
const themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
const pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;
exports.reset = async function (options) { exports.reset = async function (options) {
const map = { const map = {
@ -97,7 +93,7 @@ async function resetSettings() {
async function resetTheme(themeId) { async function resetTheme(themeId) {
try { try {
await fs.promises.access(path.join(dirname, 'node_modules', themeId, 'package.json')); await fs.promises.access(path.join(paths.nodeModules, themeId, 'package.json'));
} catch (err) { } catch (err) {
winston.warn('[reset] Theme `%s` is not installed on this forum', themeId); winston.warn('[reset] Theme `%s` is not installed on this forum', themeId);
throw new Error('theme-not-found'); throw new Error('theme-not-found');

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var childProcess = require('child_process'); const childProcess = require('child_process');
var fork = require('../meta/debugFork'); const fork = require('../meta/debugFork');
var paths = require('./paths'); const { paths } = require('../constants');
var dirname = paths.baseDir; const cwd = paths.baseDir;
function getRunningPid(callback) { function getRunningPid(callback) {
fs.readFile(paths.pidfile, { fs.readFile(paths.pidfile, {
@ -32,8 +32,8 @@ function start(options) {
process.env.NODE_ENV = 'development'; process.env.NODE_ENV = 'development';
fork(paths.loader, ['--no-daemon', '--no-silent'], { fork(paths.loader, ['--no-daemon', '--no-silent'], {
env: process.env, env: process.env,
cwd: dirname,
stdio: 'inherit', stdio: 'inherit',
cwd,
}); });
return; return;
} }
@ -56,12 +56,12 @@ function start(options) {
// Spawn a new NodeBB process // Spawn a new NodeBB process
var child = fork(paths.loader, process.argv.slice(3), { var child = fork(paths.loader, process.argv.slice(3), {
env: process.env, env: process.env,
cwd: dirname, cwd,
}); });
if (options.log) { if (options.log) {
childProcess.spawn('tail', ['-F', './logs/output.log'], { childProcess.spawn('tail', ['-F', './logs/output.log'], {
cwd: dirname,
stdio: 'inherit', stdio: 'inherit',
cwd,
}); });
} }
@ -112,8 +112,8 @@ function status() {
function log() { function log() {
console.log('\nHit '.red + 'Ctrl-C '.bold + 'to exit\n'.red + '\n'.reset); console.log('\nHit '.red + 'Ctrl-C '.bold + 'to exit\n'.red + '\n'.reset);
childProcess.spawn('tail', ['-F', './logs/output.log'], { childProcess.spawn('tail', ['-F', './logs/output.log'], {
cwd: dirname,
stdio: 'inherit', stdio: 'inherit',
cwd,
}); });
} }

@ -1,18 +1,18 @@
'use strict'; 'use strict';
var winston = require('winston'); const winston = require('winston');
var async = require('async'); const async = require('async');
var path = require('path'); const path = require('path');
var nconf = require('nconf'); const nconf = require('nconf');
var install = require('../../install/web').install; const { install } = require('../../install/web');
function setup(initConfig) { function setup(initConfig) {
var paths = require('./paths'); const { paths } = require('../constants');
var install = require('../install'); const install = require('../install');
var build = require('../meta/build'); const build = require('../meta/build');
var prestart = require('../prestart'); const prestart = require('../prestart');
var pkg = require('../../package.json'); const pkg = require('../../package.json');
winston.info('NodeBB Setup Triggered via Command Line'); winston.info('NodeBB Setup Triggered via Command Line');

@ -9,7 +9,7 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const nconf = require('nconf'); const nconf = require('nconf');
const paths = require('./paths'); const { paths, pluginNamePattern } = require('../constants');
const packageManager = nconf.get('package_manager'); const packageManager = nconf.get('package_manager');
const supportedPackageManagerList = require('./package-install').supportedPackageManager; // load config from src/cli/package-install.js const supportedPackageManagerList = require('./package-install').supportedPackageManager; // load config from src/cli/package-install.js
@ -21,13 +21,11 @@ if (process.platform === 'win32') {
packageManagerExecutable += '.cmd'; packageManagerExecutable += '.cmd';
} }
const dirname = paths.baseDir;
function getModuleVersions(modules, callback) { function getModuleVersions(modules, callback) {
const versionHash = {}; const versionHash = {};
async.eachLimit(modules, 50, function (module, next) { async.eachLimit(modules, 50, function (module, next) {
fs.readFile(path.join(dirname, 'node_modules', module, 'package.json'), { encoding: 'utf-8' }, function (err, pkg) { fs.readFile(path.join(paths.nodeModules, module, 'package.json'), { encoding: 'utf-8' }, function (err, pkg) {
if (err) { if (err) {
return next(err); return next(err);
} }
@ -47,19 +45,16 @@ function getModuleVersions(modules, callback) {
function getInstalledPlugins(callback) { function getInstalledPlugins(callback) {
async.parallel({ async.parallel({
files: async.apply(fs.readdir, path.join(dirname, 'node_modules')), files: async.apply(fs.readdir, paths.nodeModules),
deps: async.apply(fs.readFile, path.join(dirname, 'package.json'), { encoding: 'utf-8' }), deps: async.apply(fs.readFile, paths.currentPackage, { encoding: 'utf-8' }),
bundled: async.apply(fs.readFile, path.join(dirname, 'install/package.json'), { encoding: 'utf-8' }), bundled: async.apply(fs.readFile, paths.installPackage, { encoding: 'utf-8' }),
}, function (err, payload) { }, function (err, payload) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
const isNbbModule = /^nodebb-(?:plugin|theme|widget|rewards)-[\w-]+$/;
payload.files = payload.files.filter(function (file) { payload.files = payload.files.filter(function (file) {
return isNbbModule.test(file); return pluginNamePattern.test(file);
}); });
try { try {
@ -70,10 +65,10 @@ function getInstalledPlugins(callback) {
} }
payload.bundled = payload.bundled.filter(function (pkgName) { payload.bundled = payload.bundled.filter(function (pkgName) {
return isNbbModule.test(pkgName); return pluginNamePattern.test(pkgName);
}); });
payload.deps = payload.deps.filter(function (pkgName) { payload.deps = payload.deps.filter(function (pkgName) {
return isNbbModule.test(pkgName); return pluginNamePattern.test(pkgName);
}); });
// Whittle down deps to send back only extraneously installed plugins/themes/etc // Whittle down deps to send back only extraneously installed plugins/themes/etc
@ -84,7 +79,7 @@ function getInstalledPlugins(callback) {
// Ignore git repositories // Ignore git repositories
try { try {
fs.accessSync(path.join(dirname, 'node_modules', pkgName, '.git')); fs.accessSync(path.join(paths.nodeModules, pkgName, '.git'));
return false; return false;
} catch (e) { } catch (e) {
return true; return true;
@ -96,7 +91,7 @@ function getInstalledPlugins(callback) {
} }
function getCurrentVersion(callback) { function getCurrentVersion(callback) {
fs.readFile(path.join(dirname, 'install/package.json'), { encoding: 'utf-8' }, function (err, pkg) { fs.readFile(paths.installPackage, { encoding: 'utf-8' }, function (err, pkg) {
if (err) { if (err) {
return callback(err); return callback(err);
} }

@ -0,0 +1,26 @@
'use strict';
const path = require('path');
const baseDir = path.join(__dirname, '../');
const loader = path.join(baseDir, 'loader.js');
const app = path.join(baseDir, 'app.js');
const pidfile = path.join(baseDir, 'pidfile');
const config = path.join(baseDir, 'config.json');
const currentPackage = path.join(baseDir, 'package.json');
const installPackage = path.join(baseDir, 'install/package.json');
const nodeModules = path.join(baseDir, 'node_modules');
exports.paths = {
baseDir,
loader,
app,
pidfile,
config,
currentPackage,
installPackage,
nodeModules,
};
exports.pluginNamePattern = /^(@[\w-]+\/)?nodebb-(theme|plugin|widget|rewards)-[\w-]+$/;
exports.themeNamePattern = /^(@[\w-]+\/)?nodebb-theme-[\w-]+$/;

@ -4,13 +4,14 @@ const path = require('path');
const fs = require('fs'); const fs = require('fs');
const file = require('../../file'); const file = require('../../file');
const { paths } = require('../../constants');
const themesController = module.exports; const themesController = module.exports;
const defaultScreenshotPath = path.join(__dirname, '../../../public/images/themes/default.png'); const defaultScreenshotPath = path.join(__dirname, '../../../public/images/themes/default.png');
themesController.get = async function (req, res, next) { themesController.get = async function (req, res, next) {
const themeDir = path.join(__dirname, '../../../node_modules', req.params.theme); const themeDir = path.join(paths.nodeModules, req.params.theme);
const themeConfigPath = path.join(themeDir, 'theme.json'); const themeConfigPath = path.join(themeDir, 'theme.json');
let themeConfig; let themeConfig;

@ -8,6 +8,7 @@ const winston = require('winston');
require('colors'); require('colors');
const pkg = require('../../package.json'); const pkg = require('../../package.json');
const { paths, pluginNamePattern } = require('../constants');
const Dependencies = module.exports; const Dependencies = module.exports;
@ -28,11 +29,9 @@ Dependencies.check = async function () {
} }
}; };
const pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;
Dependencies.checkModule = async function (moduleName) { Dependencies.checkModule = async function (moduleName) {
try { try {
let pkgData = await fs.promises.readFile(path.join(__dirname, '../../node_modules/', moduleName, 'package.json'), 'utf8'); let pkgData = await fs.promises.readFile(path.join(paths.nodeModules, moduleName, 'package.json'), 'utf8');
pkgData = Dependencies.parseModuleData(moduleName, pkgData); pkgData = Dependencies.parseModuleData(moduleName, pkgData);
const satisfies = Dependencies.doesSatisfy(pkgData, pkg.dependencies[moduleName]); const satisfies = Dependencies.doesSatisfy(pkgData, pkg.dependencies[moduleName]);

@ -12,9 +12,10 @@ const rimrafAsync = util.promisify(rimraf);
const file = require('../file'); const file = require('../file');
const Plugins = require('../plugins'); const Plugins = require('../plugins');
const { paths } = require('../constants');
const buildLanguagesPath = path.join(__dirname, '../../build/public/language'); const buildLanguagesPath = path.join(paths.baseDir, 'build/public/language');
const coreLanguagesPath = path.join(__dirname, '../../public/language'); const coreLanguagesPath = path.join(paths.baseDir, 'public/language');
async function getTranslationMetadata() { async function getTranslationMetadata() {
const paths = await file.walk(coreLanguagesPath); const paths = await file.walk(coreLanguagesPath);
@ -98,7 +99,7 @@ async function buildNamespaceLanguage(lang, namespace, plugins) {
} }
async function addPlugin(translations, pluginData, lang, namespace) { async function addPlugin(translations, pluginData, lang, namespace) {
const pluginLanguages = path.join(__dirname, '../../node_modules/', pluginData.id, pluginData.languages); const pluginLanguages = path.join(paths.nodeModules, pluginData.id, pluginData.languages);
const defaultLang = pluginData.defaultLang || 'en-GB'; const defaultLang = pluginData.defaultLang || 'en-GB';
// for each plugin, fallback in this order: // for each plugin, fallback in this order:

@ -15,6 +15,7 @@ const Benchpress = require('benchpressjs');
const plugins = require('../plugins'); const plugins = require('../plugins');
const file = require('../file'); const file = require('../file');
const db = require('../database'); const db = require('../database');
const { themeNamePattern, paths } = require('../constants');
const viewsPath = nconf.get('views_dir'); const viewsPath = nconf.get('views_dir');
@ -43,8 +44,6 @@ async function processImports(paths, templatePath, source) {
} }
Templates.processImports = processImports; Templates.processImports = processImports;
const themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
async function getTemplateDirs(activePlugins) { async function getTemplateDirs(activePlugins) {
const pluginTemplates = activePlugins.map(function (id) { const pluginTemplates = activePlugins.map(function (id) {
if (themeNamePattern.test(id)) { if (themeNamePattern.test(id)) {
@ -53,7 +52,7 @@ async function getTemplateDirs(activePlugins) {
if (!plugins.pluginsData[id]) { if (!plugins.pluginsData[id]) {
return ''; return '';
} }
return path.join(__dirname, '../../node_modules/', id, plugins.pluginsData[id].templates || 'templates'); return path.join(paths.nodeModules, id, plugins.pluginsData[id].templates || 'templates');
}).filter(Boolean); }).filter(Boolean);
let themeConfig = require(nconf.get('theme_config')); let themeConfig = require(nconf.get('theme_config'));

@ -10,12 +10,11 @@ const file = require('../file');
const db = require('../database'); const db = require('../database');
const Meta = require('./index'); const Meta = require('./index');
const events = require('../events'); const events = require('../events');
const utils = require('../../public/src/utils'); const utils = require('../utils');
const { themeNamePattern } = require('../constants');
const Themes = module.exports; const Themes = module.exports;
const themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
Themes.get = async () => { Themes.get = async () => {
const themePath = nconf.get('themes_path'); const themePath = nconf.get('themes_path');
if (typeof themePath !== 'string') { if (typeof themePath !== 'string') {

@ -6,6 +6,7 @@ const winston = require('winston');
const db = require('../database'); const db = require('../database');
const file = require('../file'); const file = require('../file');
const { paths } = require('../constants');
const Data = module.exports; const Data = module.exports;
@ -14,7 +15,7 @@ const basePath = path.join(__dirname, '../../');
Data.getPluginPaths = async function () { Data.getPluginPaths = async function () {
let plugins = await db.getSortedSetRange('plugins:active', 0, -1); let plugins = await db.getSortedSetRange('plugins:active', 0, -1);
plugins = plugins.filter(plugin => plugin && typeof plugin === 'string') plugins = plugins.filter(plugin => plugin && typeof plugin === 'string')
.map(plugin => path.join(__dirname, '../../node_modules/', plugin)); .map(plugin => path.join(paths.nodeModules, plugin));
const exists = await Promise.all(plugins.map(p => file.exists(p))); const exists = await Promise.all(plugins.map(p => file.exists(p)));
return plugins.filter((p, i) => exists[i]); return plugins.filter((p, i) => exists[i]);
@ -221,13 +222,13 @@ Data.getLanguageData = async function getLanguageData(pluginData) {
return; return;
} }
const pathToFolder = path.join(__dirname, '../../node_modules/', pluginData.id, pluginData.languages); const pathToFolder = path.join(paths.nodeModules, pluginData.id, pluginData.languages);
const paths = await file.walk(pathToFolder); const filepaths = await file.walk(pathToFolder);
const namespaces = []; const namespaces = [];
const languages = []; const languages = [];
paths.forEach(function (p) { filepaths.forEach(function (p) {
const rel = path.relative(pathToFolder, p).split(/[/\\]/); const rel = path.relative(pathToFolder, p).split(/[/\\]/);
const language = rel.shift().replace('_', '-').replace('@', '-x-'); const language = rel.shift().replace('_', '-').replace('@', '-x-');
const namespace = rel.join('/').replace(/\.json$/, ''); const namespace = rel.join('/').replace(/\.json$/, '');
@ -241,7 +242,7 @@ Data.getLanguageData = async function getLanguageData(pluginData) {
}); });
return { return {
languages: languages, languages,
namespaces: namespaces, namespaces,
}; };
}; };

@ -10,6 +10,7 @@ const request = require('request-promise-native');
const user = require('../user'); const user = require('../user');
const posts = require('../posts'); const posts = require('../posts');
const { pluginNamePattern, themeNamePattern, paths } = require('../constants');
var app; var app;
var middleware; var middleware;
@ -176,7 +177,7 @@ Plugins.list = async function (matching) {
if (matching === undefined) { if (matching === undefined) {
matching = true; matching = true;
} }
const version = require(path.join(nconf.get('base_dir'), 'package.json')).version; const version = require(paths.currentPackage).version;
const url = (nconf.get('registry') || 'https://packages.nodebb.org') + '/api/v1/plugins' + (matching !== false ? '?version=' + version : ''); const url = (nconf.get('registry') || 'https://packages.nodebb.org') + '/api/v1/plugins' + (matching !== false ? '?version=' + version : '');
try { try {
const body = await request(url, { const body = await request(url, {
@ -197,9 +198,8 @@ Plugins.listTrending = async () => {
}; };
Plugins.normalise = async function (apiReturn) { Plugins.normalise = async function (apiReturn) {
const themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
const pluginMap = {}; const pluginMap = {};
const dependencies = require(path.join(nconf.get('base_dir'), 'package.json')).dependencies; const dependencies = require(paths.currentPackage).dependencies;
apiReturn = Array.isArray(apiReturn) ? apiReturn : []; apiReturn = Array.isArray(apiReturn) ? apiReturn : [];
apiReturn.forEach(function (packageData) { apiReturn.forEach(function (packageData) {
packageData.id = packageData.name; packageData.id = packageData.name;
@ -263,7 +263,7 @@ Plugins.normalise = async function (apiReturn) {
return pluginArray; return pluginArray;
}; };
Plugins.nodeModulesPath = path.join(__dirname, '../../node_modules'); Plugins.nodeModulesPath = paths.nodeModules;
Plugins.showInstalled = async function () { Plugins.showInstalled = async function () {
const dirs = await fs.promises.readdir(Plugins.nodeModulesPath); const dirs = await fs.promises.readdir(Plugins.nodeModulesPath);
@ -290,7 +290,6 @@ Plugins.showInstalled = async function () {
}; };
async function findNodeBBModules(dirs) { async function findNodeBBModules(dirs) {
const pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;
const pluginPaths = []; const pluginPaths = [];
await async.each(dirs, function (dirname, next) { await async.each(dirs, function (dirname, next) {
var dirPath = path.join(Plugins.nodeModulesPath, dirname); var dirPath = path.join(Plugins.nodeModulesPath, dirname);

@ -12,6 +12,7 @@ const request = require('request-promise-native');
const db = require('../database'); const db = require('../database');
const meta = require('../meta'); const meta = require('../meta');
const pubsub = require('../pubsub'); const pubsub = require('../pubsub');
const { paths } = require('../constants');
const supportedPackageManagerList = require('../cli/package-install').supportedPackageManager; // load config from src/cli/package-install.js const supportedPackageManagerList = require('../cli/package-install').supportedPackageManager; // load config from src/cli/package-install.js
const packageManager = supportedPackageManagerList.indexOf(nconf.get('package_manager')) >= 0 ? nconf.get('package_manager') : 'npm'; const packageManager = supportedPackageManagerList.indexOf(nconf.get('package_manager')) >= 0 ? nconf.get('package_manager') : 'npm';
@ -132,7 +133,7 @@ module.exports = function (Plugins) {
} }
Plugins.isInstalled = async function (id) { Plugins.isInstalled = async function (id) {
const pluginDir = path.join(__dirname, '../../node_modules', id); const pluginDir = path.join(paths.nodeModules, id);
try { try {
const stats = await fs.promises.stat(pluginDir); const stats = await fs.promises.stat(pluginDir);
return stats.isDirectory(); return stats.isDirectory();

@ -7,6 +7,7 @@ const nconf = require('nconf');
const _ = require('lodash'); const _ = require('lodash');
const meta = require('../meta'); const meta = require('../meta');
const { themeNamePattern } = require('../constants');
module.exports = function (Plugins) { module.exports = function (Plugins) {
async function registerPluginAssets(pluginData, fields) { async function registerPluginAssets(pluginData, fields) {
@ -102,8 +103,6 @@ module.exports = function (Plugins) {
await Promise.all(plugins.map(p => registerPluginAssets(p, fields))); await Promise.all(plugins.map(p => registerPluginAssets(p, fields)));
}; };
const themeNamePattern = /(@.*?\/)?nodebb-theme-.*$/;
Plugins.loadPlugin = async function (pluginPath) { Plugins.loadPlugin = async function (pluginPath) {
let pluginData; let pluginData;
try { try {

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const nconf = require('nconf');
var url = require('url'); const url = require('url');
var winston = require('winston'); const winston = require('winston');
var path = require('path'); const path = require('path');
var pkg = require('../package.json'); const pkg = require('../package.json');
var dirname = require('./cli/paths').baseDir; const { paths } = require('./constants');
function setupWinston() { function setupWinston() {
if (!winston.format) { if (!winston.format) {
@ -49,10 +49,10 @@ function loadConfig(configFile) {
}); });
nconf.defaults({ nconf.defaults({
base_dir: dirname, base_dir: paths.baseDir,
themes_path: path.join(dirname, 'node_modules'), themes_path: paths.nodeModules,
upload_path: 'public/uploads', upload_path: 'public/uploads',
views_dir: path.join(dirname, 'build/public/templates'), views_dir: path.join(paths.baseDir, 'build/public/templates'),
version: pkg.version, version: pkg.version,
isCluster: false, isCluster: false,
isPrimary: true, isPrimary: true,
@ -72,8 +72,8 @@ function loadConfig(configFile) {
nconf.set('runJobs', nconf.get('isPrimary') && !nconf.get('jobsDisabled')); nconf.set('runJobs', nconf.get('isPrimary') && !nconf.get('jobsDisabled'));
// Ensure themes_path is a full filepath // Ensure themes_path is a full filepath
nconf.set('themes_path', path.resolve(dirname, nconf.get('themes_path'))); nconf.set('themes_path', path.resolve(paths.baseDir, nconf.get('themes_path')));
nconf.set('core_templates_path', path.join(dirname, 'src/views')); nconf.set('core_templates_path', path.join(paths.baseDir, 'src/views'));
nconf.set('base_templates_path', path.join(nconf.get('themes_path'), 'nodebb-theme-persona/templates')); nconf.set('base_templates_path', path.join(nconf.get('themes_path'), 'nodebb-theme-persona/templates'));
nconf.set('upload_path', path.resolve(nconf.get('base_dir'), nconf.get('upload_path'))); nconf.set('upload_path', path.resolve(nconf.get('base_dir'), nconf.get('upload_path')));

@ -9,6 +9,7 @@ const winston = require('winston');
const db = require('./database'); const db = require('./database');
const file = require('./file'); const file = require('./file');
const { paths } = require('./constants');
/* /*
* Need to write an upgrade script for NodeBB? Cool. * Need to write an upgrade script for NodeBB? Cool.
@ -61,7 +62,7 @@ Upgrade.appendPluginScripts = async function (files) {
// Find all active plugins // Find all active plugins
const plugins = await db.getSortedSetRange('plugins:active', 0, -1); const plugins = await db.getSortedSetRange('plugins:active', 0, -1);
plugins.forEach((plugin) => { plugins.forEach((plugin) => {
const configPath = path.join(__dirname, '../node_modules', plugin, 'plugin.json'); const configPath = path.join(paths.nodeModules, plugin, 'plugin.json');
try { try {
const pluginConfig = require(configPath); const pluginConfig = require(configPath);
if (pluginConfig.hasOwnProperty('upgrades') && Array.isArray(pluginConfig.upgrades)) { if (pluginConfig.hasOwnProperty('upgrades') && Array.isArray(pluginConfig.upgrades)) {

Loading…
Cancel
Save