Skip to content

Commit

Permalink
refactor: shared constants (#8707)
Browse files Browse the repository at this point in the history
define plugin name and theme name regexs in one location for consistency

define various shared paths in one place for consistency
  • Loading branch information
pitaj committed Oct 2, 2020
1 parent e60357d commit 1aa336d
Show file tree
Hide file tree
Showing 20 changed files with 131 additions and 137 deletions.
18 changes: 9 additions & 9 deletions src/cli/index.js
@@ -1,16 +1,16 @@
'use strict';

var fs = require('fs');
var path = require('path');
const fs = require('fs');
const path = require('path');

require('../../require-main');

var packageInstall = require('./package-install');
var dirname = require('./paths').baseDir;
const packageInstall = require('./package-install');
const { paths } = require('../constants');

// check to make sure dependencies are installed
try {
fs.accessSync(path.join(dirname, 'package.json'), fs.constants.R_OK);
fs.accessSync(paths.currentPackage, fs.constants.R_OK);
} catch (e) {
if (e.code === 'ENOENT') {
console.warn('package.json not found.');
Expand All @@ -20,7 +20,7 @@ try {
packageInstall.preserveExtraneousPlugins();

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');
console.log('OK'.green);
Expand All @@ -33,13 +33,13 @@ 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 defaultPackage = require('../../install/package.json');

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])) {
var e = new TypeError('Incorrect dependency version: ' + packageName);
e.code = 'DEP_WRONG_VERSION';
Expand Down Expand Up @@ -97,7 +97,7 @@ global.env = env;
prestart.setupWinston();

// 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'));

prestart.loadConfig(configFile);
Expand Down
28 changes: 13 additions & 15 deletions src/cli/manage.js
@@ -1,17 +1,18 @@
'use strict';

var async = require('async');
var winston = require('winston');
var childProcess = require('child_process');
var _ = require('lodash');
var CliGraph = require('cli-graph');

var build = require('../meta/build');
var db = require('../database');
var plugins = require('../plugins');
var events = require('../events');
var analytics = require('../analytics');
var reset = require('./reset');
const async = require('async');
const winston = require('winston');
const childProcess = require('child_process');
const _ = require('lodash');
const CliGraph = require('cli-graph');

const build = require('../meta/build');
const db = require('../database');
const plugins = require('../plugins');
const events = require('../events');
const analytics = require('../analytics');
const reset = require('./reset');
const { pluginNamePattern, themeNamePattern } = require('../constants');

function buildTargets() {
var aliases = build.aliases;
Expand All @@ -34,9 +35,6 @@ function buildTargets() {
);
}

var themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
var pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;

function activate(plugin) {
if (themeNamePattern.test(plugin)) {
reset.reset({
Expand Down
30 changes: 13 additions & 17 deletions src/cli/package-install.js
Expand Up @@ -4,28 +4,24 @@ const path = require('path');
const fs = require('fs');
const cproc = require('child_process');

const packageFilePath = path.join(__dirname, '../../package.json');
const packageDefaultFilePath = path.join(__dirname, '../../install/package.json');
const modulesPath = path.join(__dirname, '../../node_modules');

const isPackage = /^(@\w+\/)?nodebb-(plugin|theme|widget|reward)-\w+/;
const { paths, pluginNamePattern } = require('../constants');

function updatePackageFile() {
let oldPackageContents = {};

try {
oldPackageContents = JSON.parse(fs.readFileSync(packageFilePath, 'utf8'));
oldPackageContents = JSON.parse(fs.readFileSync(paths.currentPackage, 'utf8'));
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}

const defaultPackageContents = JSON.parse(fs.readFileSync(packageDefaultFilePath, 'utf8'));
const defaultPackageContents = JSON.parse(fs.readFileSync(paths.installPackage, 'utf8'));

let dependencies = {};
Object.entries(oldPackageContents.dependencies || {}).forEach(([dep, version]) => {
if (isPackage.test(dep)) {
if (pluginNamePattern.test(dep)) {
dependencies[dep] = version;
}
});
Expand All @@ -38,7 +34,7 @@ function updatePackageFile() {

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;
Expand All @@ -54,7 +50,7 @@ function installAll() {
const prod = global.env !== 'development';
let command = 'npm install';
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 packageManager = require('nconf').get('package_manager');
if (supportedPackageManagerList.indexOf(packageManager) >= 0) {
Expand Down Expand Up @@ -94,34 +90,34 @@ exports.installAll = installAll;
function preserveExtraneousPlugins() {
// Skip if `node_modules/` is not found or inaccessible
try {
fs.accessSync(modulesPath, fs.constants.R_OK);
fs.accessSync(paths.nodeModules, fs.constants.R_OK);
} catch (e) {
return;
}

const packages = fs.readdirSync(modulesPath).filter(function (pkgName) {
return isPackage.test(pkgName);
const packages = fs.readdirSync(paths.nodeModules).filter(function (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
// only extraneous plugins (ones not in package.json) which are not links
.filter(function (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;
})
// reduce to a map of package names to package versions
.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;
return map;
}, {});

// Add those packages to package.json
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;
17 changes: 0 additions & 17 deletions src/cli/paths.js

This file was deleted.

8 changes: 2 additions & 6 deletions src/cli/reset.js
Expand Up @@ -11,11 +11,7 @@ const meta = require('../meta');
const plugins = require('../plugins');
const widgets = require('../widgets');
const privileges = require('../privileges');

const dirname = require('./paths').baseDir;

const themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
const pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;
const { paths, pluginNamePattern, themeNamePattern } = require('../constants');

exports.reset = async function (options) {
const map = {
Expand Down Expand Up @@ -97,7 +93,7 @@ async function resetSettings() {

async function resetTheme(themeId) {
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) {
winston.warn('[reset] Theme `%s` is not installed on this forum', themeId);
throw new Error('theme-not-found');
Expand Down
18 changes: 9 additions & 9 deletions src/cli/running.js
@@ -1,12 +1,12 @@
'use strict';

var fs = require('fs');
var childProcess = require('child_process');
const fs = require('fs');
const childProcess = require('child_process');

var fork = require('../meta/debugFork');
var paths = require('./paths');
const fork = require('../meta/debugFork');
const { paths } = require('../constants');

var dirname = paths.baseDir;
const cwd = paths.baseDir;

function getRunningPid(callback) {
fs.readFile(paths.pidfile, {
Expand All @@ -32,8 +32,8 @@ function start(options) {
process.env.NODE_ENV = 'development';
fork(paths.loader, ['--no-daemon', '--no-silent'], {
env: process.env,
cwd: dirname,
stdio: 'inherit',
cwd,
});
return;
}
Expand All @@ -56,12 +56,12 @@ function start(options) {
// Spawn a new NodeBB process
var child = fork(paths.loader, process.argv.slice(3), {
env: process.env,
cwd: dirname,
cwd,
});
if (options.log) {
childProcess.spawn('tail', ['-F', './logs/output.log'], {
cwd: dirname,
stdio: 'inherit',
cwd,
});
}

Expand Down Expand Up @@ -112,8 +112,8 @@ function status() {
function log() {
console.log('\nHit '.red + 'Ctrl-C '.bold + 'to exit\n'.red + '\n'.reset);
childProcess.spawn('tail', ['-F', './logs/output.log'], {
cwd: dirname,
stdio: 'inherit',
cwd,
});
}

Expand Down
20 changes: 10 additions & 10 deletions src/cli/setup.js
@@ -1,18 +1,18 @@
'use strict';

var winston = require('winston');
var async = require('async');
var path = require('path');
var nconf = require('nconf');
const winston = require('winston');
const async = require('async');
const path = require('path');
const nconf = require('nconf');

var install = require('../../install/web').install;
const { install } = require('../../install/web');

function setup(initConfig) {
var paths = require('./paths');
var install = require('../install');
var build = require('../meta/build');
var prestart = require('../prestart');
var pkg = require('../../package.json');
const { paths } = require('../constants');
const install = require('../install');
const build = require('../meta/build');
const prestart = require('../prestart');
const pkg = require('../../package.json');

winston.info('NodeBB Setup Triggered via Command Line');

Expand Down
25 changes: 10 additions & 15 deletions src/cli/upgrade-plugins.js
Expand Up @@ -9,7 +9,7 @@ const fs = require('fs');
const path = require('path');
const nconf = require('nconf');

const paths = require('./paths');
const { paths, pluginNamePattern } = require('../constants');
const packageManager = nconf.get('package_manager');

const supportedPackageManagerList = require('./package-install').supportedPackageManager; // load config from src/cli/package-install.js
Expand All @@ -21,13 +21,11 @@ if (process.platform === 'win32') {
packageManagerExecutable += '.cmd';
}

const dirname = paths.baseDir;

function getModuleVersions(modules, callback) {
const versionHash = {};

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) {
return next(err);
}
Expand All @@ -47,19 +45,16 @@ function getModuleVersions(modules, callback) {

function getInstalledPlugins(callback) {
async.parallel({
files: async.apply(fs.readdir, path.join(dirname, 'node_modules')),
deps: async.apply(fs.readFile, path.join(dirname, 'package.json'), { encoding: 'utf-8' }),
bundled: async.apply(fs.readFile, path.join(dirname, 'install/package.json'), { encoding: 'utf-8' }),
files: async.apply(fs.readdir, paths.nodeModules),
deps: async.apply(fs.readFile, paths.currentPackage, { encoding: 'utf-8' }),
bundled: async.apply(fs.readFile, paths.installPackage, { encoding: 'utf-8' }),
}, function (err, payload) {
if (err) {
return callback(err);
}

const isNbbModule = /^nodebb-(?:plugin|theme|widget|rewards)-[\w-]+$/;


payload.files = payload.files.filter(function (file) {
return isNbbModule.test(file);
return pluginNamePattern.test(file);
});

try {
Expand All @@ -70,10 +65,10 @@ function getInstalledPlugins(callback) {
}

payload.bundled = payload.bundled.filter(function (pkgName) {
return isNbbModule.test(pkgName);
return pluginNamePattern.test(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
Expand All @@ -84,7 +79,7 @@ function getInstalledPlugins(callback) {

// Ignore git repositories
try {
fs.accessSync(path.join(dirname, 'node_modules', pkgName, '.git'));
fs.accessSync(path.join(paths.nodeModules, pkgName, '.git'));
return false;
} catch (e) {
return true;
Expand All @@ -96,7 +91,7 @@ function getInstalledPlugins(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) {
return callback(err);
}
Expand Down

0 comments on commit 1aa336d

Please sign in to comment.