Skip to content

Commit 299f161

Browse files
authored
Merge pull request #129 from microservices-suite/repo-engineering/universal-cli
Repo engineering/universal cli
2 parents 8454814 + b6922a6 commit 299f161

File tree

4 files changed

+66
-81
lines changed

4 files changed

+66
-81
lines changed

.suite-cli/cli/cli.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ program
5151
.command('release [package]')
5252
.description('make a package release and publish simultaneously to npm.If no package is passed then generate:release for changelog is run')
5353
.action(async (package) => await actionHandlers.releasePackage({ package }));
54+
program
55+
.command('test [package]')
56+
.description('run tests')
57+
.action(async (package) => await actionHandlers.test({ package }));
5458
program
5559
.command('start [components...]')
5660
.description('Starts specified components (services or apps), or all services in dev mode if -m is not specified')
@@ -169,7 +173,14 @@ program
169173
// find out if this separater works on windows
170174
// const project_base = `@${answers.repo_name}-${Date.now()}`
171175
const project_base = `@${answers.repo_name}`
172-
actionHandlers.scaffoldNewRepo({ answers: { ...answers, project_base, private: true } });
176+
actionHandlers.scaffoldNewRepo({
177+
answers: {
178+
...answers,
179+
project_base,
180+
private: true,
181+
port: parseFloat(answers.port)
182+
}
183+
});
173184
});
174185
break;
175186
case 'service':
@@ -188,7 +199,13 @@ program
188199
default: getNextAvailablePort({ services: existing_services }),
189200
validate: input => input === '' || !isNaN(input) ? true : 'Port must be a number.'
190201
}
191-
]).then((answers) => actionHandlers.scaffoldNewService({ answers: { ...answers, private: true } }))
202+
]).then((answers) => actionHandlers.scaffoldNewService({
203+
answers: {
204+
...answers,
205+
private: true,
206+
port: parseFloat(answers.port)
207+
}
208+
}))
192209
break;
193210
case 'library':
194211
prompt([
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
const { test } = require('../scripts.module')
3+
4+
module.exports = async ({ package }) => {
5+
test({ package });
6+
};

.suite-cli/cli/scripts/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ module.exports.scaffoldNewRepo = require('./commands/scaffoldNewRepo.cmd');
2222
module.exports.releasePackage = require('./commands/releasePackage.cmd');
2323
module.exports.scaffoldNewService = require('./commands/scaffoldNewService.cmd');
2424
module.exports.scaffoldNewLibrary = require('./commands/scaffoldNewLibrary.cmd');
25+
module.exports.test = require('./commands/test.cmd');

.suite-cli/cli/scripts/scripts.module.js

Lines changed: 40 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -360,56 +360,8 @@ const startAll = async ({ options }) => {
360360
// case -v(--vanilla)
361361
// TODO: run services with nodemon in dev mode otherwise PM2
362362
// runVanillaServices({ services: [], mode: options.mode })
363-
364363
}
365364

366-
// /**
367-
// * Starts services with nodemon in development mode by default, otherwise with PM2.
368-
// * @param {Object} options - Environment settings for running the services.
369-
// * @param {string[]} options.serviceDirectories - List of service directories under `options.microservicesDir`.
370-
// * @param {string} options.microservicesDir - The root directory of the services.
371-
// * @param {string} [options.mode='dev'] - The environment mode for running the services. Defaults to 'dev'.
372-
// * @returns {void} Starts the services and logs their startup status.
373-
// */
374-
// const spinVanillaServices = async ({ serviceDirectories, microservicesDir, mode = 'dev' }) => {
375-
// const spinner = ora('Starting all services in ' + mode + ' mode...').start();
376-
377-
// try {
378-
// // Simulate delay before starting services
379-
// await delay(1);
380-
381-
// await Promise.all(serviceDirectories.map(async (dir) => {
382-
// const serviceSpinner = ora('Starting service concurrently in: ' + dir).start();
383-
// const processes = await exec(`yarn ${mode}`, { cwd: join(microservicesDir, dir) }, async (error, stdout, stderr) => {
384-
// if (error) {
385-
// const errorMessage = getErrorMessage(error, dir, microservicesDir);
386-
// serviceSpinner.fail(errorMessage);
387-
// } else {
388-
// serviceSpinner.succeed(`Service in directory ${dir} started successfully`);
389-
// }
390-
// });
391-
// processes.stdout.on('data', data => {
392-
// const output = data.toString();
393-
// // Check if the output contains the "yarn run" message
394-
// if (!output.includes('yarn run')) {
395-
// // Stop the spinner before printing the output
396-
// serviceSpinner.stop();
397-
// spinner.succeed(output);
398-
// // Restart the spinner after printing the output
399-
// // serviceSpinner.start();
400-
// }
401-
// });
402-
// }));
403-
404-
// spinner.succeed(`service${serviceDirectories.length > 0 ? 's' : ''} started successfully: ${serviceDirectories}`);
405-
// } catch (error) {
406-
// spinner.fail('An error occurred while starting services');
407-
// console.error(error);
408-
// exit(1);
409-
// }
410-
// };
411-
412-
413365
/**
414366
* Starts services with nodemon in development mode by default, otherwise with PM2.
415367
* @param {Object} options - Environment settings for running the services.
@@ -441,9 +393,10 @@ const spinVanillaServices = async ({ serviceDirectories, microservicesDir, mode
441393
});
442394

443395
child.stderr.on('data', (data) => {
444-
const output = data.toString();
396+
let output = data.toString();
397+
output = output.split(':')
445398
// Handle stderr output
446-
spinner.fail(`Error in service ${dir}: ${output.trim()}`);
399+
console.log(`${output[0]}: ${dir}: ${output[1]}`);
447400
});
448401

449402
child.on('close', (code) => {
@@ -465,28 +418,6 @@ const spinVanillaServices = async ({ serviceDirectories, microservicesDir, mode
465418
}
466419
};
467420

468-
const getErrorMessage = (error, dir, microservicesDir) => {
469-
const errorMessageParts = error.message.split('\n');
470-
let errorMessage = '';
471-
if (errorMessageParts[1]) {
472-
if (errorMessageParts[1].startsWith('error Command') && errorMessageParts[1].endsWith('not found.')) {
473-
errorMessage = `Missing script at ${dir}${sep}package.json: ${errorMessageParts[1].match(/"(.*?)"/)[1]}`;
474-
} else if (errorMessageParts[1].startsWith('error There are more than one workspace')) {
475-
errorMessage = errorMessageParts[1].replace('error ', '');
476-
} else if (errorMessageParts[1].includes('Unknown workspace')) {
477-
if (existsSync(`${microservicesDir}/${dir}/package.json`)) {
478-
errorMessage = 'Wrong workspace naming';
479-
} else {
480-
errorMessage = `Missing package.json @microservices-suite${sep}${dir}`;
481-
}
482-
} else {
483-
errorMessage = error.message;
484-
}
485-
}
486-
return errorMessage;
487-
};
488-
489-
490421
/**
491422
*
492423
* @param {Object} options Environment to run the
@@ -1387,12 +1318,9 @@ const addProjectConfigs = ({ project_root, answers }) => {
13871318

13881319
// Function to get the next available port
13891320
const getNextAvailablePort = ({ services }) => {
1390-
const usedPorts = services.map(service => service.port);
1391-
let port = 9001;
1392-
while (usedPorts.includes(port)) {
1393-
port++;
1394-
}
1395-
return port;
1321+
const usedPorts = services.map(service => service.port).sort((a, b) => a - b);
1322+
let last_port = usedPorts[usedPorts.length - 1] || 9000
1323+
return last_port + 1;
13961324
};
13971325

13981326
const getExistingServices = ({ currentDir }) => {
@@ -1411,8 +1339,40 @@ const registerServiceWithSuiteJson = ({ root_dir, name, port }) => {
14111339
config.services = [];
14121340
}
14131341
config.services.push({ name, port });
1342+
1343+
// keep the services ordered by port
1344+
config.services.sort((a, b) => a.port - b.port);
14141345
writeFile(configPath, JSON.stringify(config, null, 2), 'utf8');
14151346
}
1347+
1348+
/**
1349+
* Releases a package or generates a release for the workspace.
1350+
* @async
1351+
* @param {Object} options - Options for releasing the package.
1352+
* @param {string} options.package - The name of the package to release (optional).
1353+
* @returns {Promise<void>} A Promise that resolves when the release process is completed.
1354+
*/
1355+
const test = async ({ package }) => {
1356+
let rootDir = cwd();
1357+
if (!package) {
1358+
rootDir = generatRootPath({ currentDir: cwd() });
1359+
}
1360+
try {
1361+
const package_json_path = join(rootDir, 'package.json');
1362+
1363+
// Read the package.json file
1364+
const { workspace_name } = retrieveWorkSpaceName({ package_json_path });
1365+
if (package) {
1366+
logInfo({ message: `Looking for package: ${workspace_name}/${package}` });
1367+
await executeCommand('yarn', ['workspace', `${workspace_name}/${package}`, 'test'], { stdio: 'inherit', shell: true });
1368+
} else {
1369+
await executeCommand('yarn', ['test'], { cwd: rootDir, stdio: 'inherit', shell: true });
1370+
}
1371+
} catch (error) {
1372+
ora().fail('Command failed to run');
1373+
}
1374+
}
1375+
14161376
const readFileContent = ({ path }) => { }
14171377
module.exports = {
14181378
generateDirectoryPath,
@@ -1441,5 +1401,6 @@ module.exports = {
14411401
scaffoldNewService,
14421402
scaffoldNewLibrary,
14431403
getNextAvailablePort,
1444-
getExistingServices
1404+
getExistingServices,
1405+
test
14451406
}

0 commit comments

Comments
 (0)