Skip to content

Commit fc8702c

Browse files
committed
refactor: extract package fetching logic into shared utility
1 parent fc7359b commit fc8702c

3 files changed

Lines changed: 95 additions & 83 deletions

File tree

src/commands/build.js

Lines changed: 5 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const path = require('path');
21
const webpack = require('webpack');
32
const { terminal } = require('terminal-kit');
43
// eslint-disable-next-line import/no-extraneous-dependencies
@@ -7,11 +6,9 @@ const webpackConfig = require('./build/webpack');
76

87
const spinner = ora();
98

10-
const { findAllProjectPaths, validateProject } = require('./../utils/projectpaths');
11-
const { getPackage } = require('./../utils/get-package');
129
const { getFilteredEntryPoints } = require('./../utils/get-filtered-entrypoints');
13-
const dirsExist = require('../utils/dirs-exist');
1410
const getProjectConfig = require('../utils/get-project-config');
11+
const getPackagesForCommand = require('../utils/get-packages-for-command');
1512

1613
global.buildCount = 0;
1714

@@ -56,66 +53,16 @@ exports.handler = async ({
5653
once = false,
5754
quiet = false,
5855
}) => {
59-
const currentLocation = path.basename(process.cwd());
60-
6156
const mode = production ? 'production' : 'development';
62-
// Use env variables if working on Webpack >=5.
63-
const projectsList = projects.split(',').map((item) => item.split('@')[0]).filter((item) => item.length > 0);
64-
const hasTargetDirs = dirsExist(targetDirs);
65-
const isAllProjects = (site || hasTargetDirs) && (!projects || projectsList.length === 0);
66-
67-
let packages = [];
68-
69-
try {
70-
if (projectsList.length === 0 && !isAllProjects) {
71-
// Is project root - a standalone build.
72-
terminal(`\x1b[1mCompiling \x1b[4msingle\x1b[0m\x1b[1m project in ${mode} mode.\x1b[0m\n`);
73-
packages.push(getPackage(path.resolve('./')));
74-
} else if (isAllProjects) {
75-
// Find all projects through-out the site.
76-
terminal(`\x1b[1mCompiling \x1b[4mall\x1b[0m\x1b[1m projects in ${mode} mode.\x1b[0m\n`);
77-
packages = findAllProjectPaths(targetDirs).map((path) => getPackage(path));
78-
} else {
79-
// List of projects.
80-
terminal(`\x1b[1mCompiling \x1b[4mlist\x1b[0m\x1b[1m of projects in ${mode} mode.\x1b[0m\n`);
81-
packages = findAllProjectPaths(targetDirs, projectsList).map((path) => getPackage(path));
82-
83-
const packageNames = packages.map((pkg) => pkg.name);
84-
projectsList.map((projectName) => {
85-
if (!packageNames.includes(projectName)) {
86-
terminal.red(`Error: Project ${projectName} does not exist.\n`);
87-
}
88-
packageNames.includes(projectName);
89-
});
90-
}
91-
} catch (e) {
92-
terminal.red(e);
93-
process.exit(1);
94-
}
95-
96-
const validProjects = packages.filter((pkg) => validateProject(pkg));
97-
98-
if (!quiet) {
99-
const invalidProjects = packages.filter((pkg) => !validateProject(pkg));
100-
invalidProjects.map((invalidProject) =>
101-
terminal.red(`[${invalidProject.relativePath}] no entrypoints\n`),
102-
);
103-
}
104-
105-
if (validProjects.length === 0) {
106-
terminal.red(`Error: No projects found\n`);
107-
process.exit(1);
108-
}
10957

110-
terminal('Processing the following projects:\n');
111-
validProjects.forEach((pkg) => {
112-
terminal.defaultColor(` * %s `, pkg.name).dim(`[%s]\n`, pkg.relativePath);
58+
const packages = await getPackagesForCommand({
59+
projects,
60+
site,
11361
});
114-
terminal('\n');
11562

11663
spinner.start('Building webpack configs.\n');
11764

118-
const configMap = validProjects.map((packageObject) => {
65+
const configMap = packages.map((packageObject) => {
11966
// Empty array means all entrypoints.
12067
let filteredEntrypoints = [];
12168

src/commands/installer/installer.js

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,16 @@ const { execSync } = require('child_process');
33
const yargs = require('yargs');
44
const args = yargs.argv._;
55

6-
const { findAllProjectPaths } = require('./../../utils/projectpaths');
7-
const { getPackage } = require('./../../utils/get-package');
8-
const dirsExist = require('./../../utils/dirs-exist');
6+
const getPackagesForCommand = require('./../../utils/get-packages-for-command');
97

10-
module.exports = (commandType) => {
8+
module.exports = async (commandType) => {
119
if (!['ci', 'install'].includes(commandType)) {
1210
throw new Error('Not a valid comment type.');
1311
}
1412

15-
const hasTargetDirs = dirsExist(targetDirs);
16-
17-
if (!hasTargetDirs) {
18-
throw new Error('Recursive install only works from the site root directory.');
19-
}
20-
21-
let paths = findAllProjectPaths(targetDirs);
22-
23-
let packages = [];
24-
25-
try {
26-
packages = paths.map((item) => getPackage(item, false)).filter((item) => item);
27-
} catch (e) {
28-
terminal.red(e);
29-
process.exit(1);
30-
}
31-
32-
terminal('Installing packages for the following projects:\n');
33-
packages.forEach((pkg) => {
34-
terminal.defaultColor(` * %s `, pkg.name).dim(`[%s]\n`, pkg.relativePath);
13+
const packages = await getPackagesForCommand({
14+
requireSiteRoot: true,
3515
});
36-
terminal('\n');
3716

3817
const gluedArgs = args.join(' ');
3918

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// src/utils/command-handler.js
2+
const { terminal } = require('terminal-kit');
3+
const { findAllProjectPaths, validateProject } = require('./projectpaths');
4+
const { getPackage } = require('./get-package');
5+
const dirsExist = require('./dirs-exist');
6+
const path = require('path');
7+
8+
/**
9+
* Get valid packages to run a command against.
10+
*
11+
* Bases results on the following logic:
12+
* - If the `site` flag is set, or the command was ran from within wp-content, all projects are targeted.
13+
* - If the `projects` flag is set, only those projects are targeted.
14+
* - If neither the `site` or `projects` flags are set, only the current project is targeted.
15+
*
16+
* @param {Object} args
17+
* @param {string} [args.projects] Comma separated list of projects to target.
18+
* @param {boolean} [args.site] Run the process from the root of a site, such as from wp-content.
19+
* @param {boolean} [args.requireSiteRoot] Require the process to be run from the site
20+
*
21+
* @return {Array} An array of valid projects to run the command against.
22+
*/
23+
const getPackagesForCommand = ({ projects = '', site = false, requireSiteRoot = true }) => {
24+
const projectsList = projects
25+
.split(',')
26+
.map((item) => item.split('@')[0])
27+
.filter((item) => item.length > 0);
28+
29+
const hasTargetDirs = dirsExist(targetDirs);
30+
31+
if (requireSiteRoot && !hasTargetDirs) {
32+
terminal.red(`Command only works from the site root directory.\n`);
33+
}
34+
35+
const isAllProjects = (site || hasTargetDirs) && (!projects || projectsList.length === 0);
36+
37+
let validProjects = [];
38+
39+
try {
40+
let packages = [];
41+
42+
if (projectsList.length === 0 && !isAllProjects) {
43+
// Single project
44+
packages.push(getPackage(path.resolve('./')));
45+
} else if (isAllProjects) {
46+
// All projects
47+
packages = findAllProjectPaths(targetDirs).map((path) => getPackage(path));
48+
} else {
49+
// Specific projects
50+
packages = findAllProjectPaths(targetDirs, projectsList).map((path) => getPackage(path));
51+
const packageNames = packages.map((pkg) => pkg.name);
52+
projectsList.map((projectName) => {
53+
if (!packageNames.includes(projectName)) {
54+
terminal.red(`Error: Project ${projectName} does not exist.\n`);
55+
}
56+
packageNames.includes(projectName);
57+
});
58+
}
59+
60+
packages.map((pkg) => {
61+
if (validateProject(pkg)) {
62+
validProjects.push(pkg);
63+
} else {
64+
terminal.yellow(`Warning: Project [${pkg.relativePath}] has no entrypoints\n`);
65+
}
66+
});
67+
68+
if (validProjects.length === 0) {
69+
terminal.red(`Error: No projects found\n`);
70+
process.exit(1);
71+
}
72+
73+
terminal('Processing the following projects:\n');
74+
validProjects.forEach((pkg) => {
75+
terminal.defaultColor(` * %s `, pkg.name).dim(`[%s]\n`, pkg.relativePath);
76+
});
77+
terminal('\n');
78+
} catch (e) {
79+
terminal.red(e);
80+
process.exit(1);
81+
}
82+
83+
return validProjects;
84+
};
85+
86+
module.exports = getPackagesForCommand;

0 commit comments

Comments
 (0)