This commit is contained in:
Benjamin Toby 2024-11-03 10:57:44 +01:00
parent 714f50314f
commit f4364524ef
6 changed files with 483 additions and 406 deletions

2
.npmrc Normal file
View File

@ -0,0 +1,2 @@
registry=https://git.tben.me/api/packages/Moduletrace/npm/
//git.tben.me/api/packages/Moduletrace/npm/:_authToken=${GITBEN_NPM_TOKEN}

218
README.md
View File

@ -1,109 +1,109 @@
# Run multiple concurrent processes # Run multiple concurrent processes
Do you run an application that needs multiple processes? Like `npm run dev` and `npm run tailwind`. Typically in a dev environment you would need to have more than one terminal open if you're running more than on processes. But with batch run you only need one terminal to run all processes concurrently. Do you run an application that needs multiple processes? Like `npm run dev` and `npm run tailwind`. Typically in a dev environment you would need to have more than one terminal open if you're running more than on processes. But with batch run you only need one terminal to run all processes concurrently.
## Installation ## Installation
You can install and run this package directly by running: You can install and run this package directly by running:
```bash ```bash
npx batchrun "npm run dev, npm run tailwind" npx batchrun "npm run dev, npm run tailwind"
``` ```
To install this module globally simply run: To install this module globally simply run:
```bash ```bash
npm install -g batchrun npm install -g batchrun
``` ```
To install this module locally(for just the project) run: To install this module locally(for just the project) run:
```bash ```bash
npm install batchrun npm install batchrun
``` ```
_NOTE_: You will have to append `npx` to your command for just a local installation. _NOTE_: You will have to append `npx` to your command for just a local installation.
## Requirements ## Requirements
For this package to work you need an argument of strings in the terminal command, or a `batchrun.config.json` file at the root of your project directory, which is simply an array of strings, each string being the command to run. Example: For this package to work you need an argument of strings in the terminal command, or a `batchrun.config.json` file at the root of your project directory, which is simply an array of strings, each string being the command to run. Example:
```json ```json
["node index.js", "npm run tailwind"] ["node index.js", "npm run tailwind"]
``` ```
More entries mean more processes. More entries mean more processes.
# Usage # Usage
To fire up the process without a `batchrun.config.json` file simply run: To fire up the process without a `batchrun.config.json` file simply run:
```bash ```bash
batchrun "npm run dev, npm run tailwind" batchrun "npm run dev, npm run tailwind"
``` ```
If you did not install the package globally, run: If you did not install the package globally, run:
```bash ```bash
npx batchrun "npm run dev, npm run tailwind" npx batchrun "npm run dev, npm run tailwind"
``` ```
If you already have a `batchrun.config.json` file just run If you already have a `batchrun.config.json` file just run
```bash ```bash
batchrun batchrun
``` ```
# Process actions # Process actions
When your process is up and running, you can perform a few more actions to your running processes. When your process is up and running, you can perform a few more actions to your running processes.
### Reload all processes ### Reload all processes
To reload all processes, while the process is active in your terminal type To reload all processes, while the process is active in your terminal type
```bash ```bash
reload reload
``` ```
Press `Enter` after tyring this. This will reload all the processes you started. Alternatively, you can simply press `Ctrl+R`: this does the same thing. `restart` amd `reboot` commands work also. Press `Enter` after tyring this. This will reload all the processes you started. Alternatively, you can simply press `Ctrl+R`: this does the same thing. `restart` amd `reboot` commands work also.
### Reload processes ### Reload processes
You can also target a single process and reload it. This will need an index appended to the `reload` command. Example: You can also target a single process and reload it. This will need an index appended to the `reload` command. Example:
```bash ```bash
- Processes Started ... - Processes Started ...
... ...
reload 0 reload 0
``` ```
This will reload the first command in your list of commands. You can add more indexes by separating them with a comma(,): Example: This will reload the first command in your list of commands. You can add more indexes by separating them with a comma(,): Example:
```bash ```bash
- Processes Started ... - Processes Started ...
... ...
reload 0,3,4 reload 0,3,4
``` ```
_NOTE_: Do not add a space between the commands or else the `reload` command won't work. _NOTE_: Do not add a space between the commands or else the `reload` command won't work.
### Kill processes ### Kill processes
To kill all processes simply type: To kill all processes simply type:
```bash ```bash
- Processes Started ... - Processes Started ...
... ...
kill kill
``` ```
This is the equivalent of pressing `Ctrl+C`. To kill specific processes just follow the same convention as the `reload` command. Example: This is the equivalent of pressing `Ctrl+C`. To kill specific processes just follow the same convention as the `reload` command. Example:
```bash ```bash
- Processes Started ... - Processes Started ...
... ...
kill 1,2 kill 1,2
``` ```
To restart a killed process simple use the `reload` command again. To restart a killed process simple use the `reload` command again.

View File

@ -1,31 +1,31 @@
const colors = { const colors = {
Reset: "\x1b[0m", Reset: "\x1b[0m",
Bright: "\x1b[1m", Bright: "\x1b[1m",
Dim: "\x1b[2m", Dim: "\x1b[2m",
Underscore: "\x1b[4m", Underscore: "\x1b[4m",
Blink: "\x1b[5m", Blink: "\x1b[5m",
Reverse: "\x1b[7m", Reverse: "\x1b[7m",
Hidden: "\x1b[8m", Hidden: "\x1b[8m",
FgBlack: "\x1b[30m", FgBlack: "\x1b[30m",
FgRed: "\x1b[31m", FgRed: "\x1b[31m",
FgGreen: "\x1b[32m", FgGreen: "\x1b[32m",
FgYellow: "\x1b[33m", FgYellow: "\x1b[33m",
FgBlue: "\x1b[34m", FgBlue: "\x1b[34m",
FgMagenta: "\x1b[35m", FgMagenta: "\x1b[35m",
FgCyan: "\x1b[36m", FgCyan: "\x1b[36m",
FgWhite: "\x1b[37m", FgWhite: "\x1b[37m",
FgGray: "\x1b[90m", FgGray: "\x1b[90m",
BgBlack: "\x1b[40m", BgBlack: "\x1b[40m",
BgRed: "\x1b[41m", BgRed: "\x1b[41m",
BgGreen: "\x1b[42m", BgGreen: "\x1b[42m",
BgYellow: "\x1b[43m", BgYellow: "\x1b[43m",
BgBlue: "\x1b[44m", BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m", BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m", BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m", BgWhite: "\x1b[47m",
BgGray: "\x1b[100m", BgGray: "\x1b[100m",
}; };
module.exports = colors; module.exports = colors;

565
index.js
View File

@ -1,265 +1,300 @@
#! /usr/bin/env node #! /usr/bin/env node
// @ts-check // @ts-check
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const { spawn, ChildProcess, execSync } = require("child_process"); const { spawn, ChildProcess, execSync } = require("child_process");
const readline = require("readline"); const readline = require("readline");
const colors = require("./console-colors"); const colors = require("./console-colors");
//////////////////////////////////////////// ////////////////////////////////////////////
//////////////////////////////////////////// ////////////////////////////////////////////
//////////////////////////////////////////// ////////////////////////////////////////////
/** @type {string[]} */ /** @type {string[]} */
const processesStrings = []; const processesStrings = [];
/** @type {ChildProcess[]} */ /** @type {ChildProcess[]} */
let processes = []; let processes = [];
//////////////////////////////////////////// ////////////////////////////////////////////
//////////////////////////////////////////// ////////////////////////////////////////////
//////////////////////////////////////////// ////////////////////////////////////////////
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
}); });
rl.on("line", (input) => { rl.on("line", (input) => {
readCommands(input); readCommands(input);
}); });
/** /**
* Read Lines and execute commands * Read Lines and execute commands
* @param {string} input * @param {string} input
* @returns * @returns
*/ */
function readCommands(input) { function readCommands(input) {
if (input?.match(/^(reload|restart|reboot)$/i)) { if (input?.match(/^(reload|restart|reboot)$/i)) {
console.log(` - ${colors.FgBlue}Reloading processes ...${colors.Reset}`); console.log(
restartAll(); ` - ${colors.FgBlue}Reloading processes ...${colors.Reset}`
} else if (input?.match(/^(reload|restart|reboot) \d/i)) { );
const processedIndexesString = input.split(" ")[1]; restartAll();
const processedIndexes = processedIndexesString ? processedIndexesString.split(",") : null; } else if (input?.match(/^(reload|restart|reboot) \d/i)) {
const processedIndexesString = input.split(" ")[1];
if (!processedIndexes?.length) { const processedIndexes = processedIndexesString
console.log(` - ${colors.FgRed}Error:${colors.Reset} No processes to reload`); ? processedIndexesString.split(",")
return; : null;
} else {
console.log(` - ${colors.FgBlue}Reloading processes ${processedIndexesString} ...${colors.Reset}`); if (!processedIndexes?.length) {
processedIndexes.forEach((index) => { console.log(
restartOne(index); ` - ${colors.FgRed}Error:${colors.Reset} No processes to reload`
}); );
console.log(` - ${colors.FgGreen}Processes Restarted Successfully ${processedIndexesString} ...${colors.Reset}`); return;
} } else {
} console.log(
` - ${colors.FgBlue}Reloading processes ${processedIndexesString} ...${colors.Reset}`
if (input?.match(/^kill$/i)) { );
console.log(` - ${colors.FgYellow}Killing processes ...${colors.Reset}`); processedIndexes.forEach((index) => {
process.exit(); restartOne(index);
} else if (input?.match(/^kill \d/i)) { });
const processedIndexesString = input.split(" ")[1]; console.log(
const processedIndexes = processedIndexesString ? processedIndexesString.split(",") : null; ` - ${colors.FgGreen}Processes Restarted Successfully ${processedIndexesString} ...${colors.Reset}`
);
if (!processedIndexes?.length) { }
console.log(` - ${colors.FgRed}Error:${colors.Reset} No processes to reload`); }
return;
} else { if (input?.match(/^kill$/i)) {
console.log(` - ${colors.FgYellow}Killing processes ${processedIndexesString} ...${colors.Reset}`); console.log(
processedIndexes.forEach((index) => { ` - ${colors.FgYellow}Killing processes ...${colors.Reset}`
killOne(index); );
}); process.exit();
} else if (input?.match(/^kill \d/i)) {
console.log(` - ${colors.FgGreen}Processes Killed ${processedIndexesString} ...${colors.Reset}`); const processedIndexesString = input.split(" ")[1];
} const processedIndexes = processedIndexesString
} ? processedIndexesString.split(",")
} : null;
process.stdin.on("keypress", (character, key) => { if (!processedIndexes?.length) {
if (key.ctrl && key.name === "r") { console.log(
console.log(` - ${colors.FgBlue}Reloading processes ...${colors.Reset}`); ` - ${colors.FgRed}Error:${colors.Reset} No processes to reload`
restartAll(); );
} return;
}); } else {
console.log(
process.on("exit", (code) => { ` - ${colors.FgYellow}Killing processes ${processedIndexesString} ...${colors.Reset}`
console.log(` - ${colors.FgBlue}Process exited with code ${code}${colors.Reset}`); );
rl.close(); processedIndexes.forEach((index) => {
}); killOne(index);
});
////////////////////////////////////////////
//////////////////////////////////////////// console.log(
//////////////////////////////////////////// ` - ${colors.FgGreen}Processes Killed ${processedIndexesString} ...${colors.Reset}`
);
const argvProcessListIndex = process.argv.indexOf("batch-run") + 1; }
const argvProcessList = process.argv.at(-1); }
const processesFilePath = path.resolve(process.cwd(), "batchrun.config.json"); }
if (argvProcessList?.match(/batchrun/i) && !fs.existsSync(processesFilePath)) { process.stdin.on("keypress", (character, key) => {
console.error(` - ${colors.FgRed}Error:${colors.Reset} No arguments to run`); if (key.ctrl && key.name === "r") {
process.exit(1); console.log(
} ` - ${colors.FgBlue}Reloading processes ...${colors.Reset}`
);
if (fs.existsSync(processesFilePath)) { restartAll();
const processesFile = fs.readFileSync(processesFilePath, "utf8"); }
const processesArray = JSON.parse(processesFile); });
for (let i = 0; i < processesArray.length; i++) {
const processString = processesArray[i]; process.on("exit", (code) => {
const strippedProcessString = processString.trim(); console.log(
processesStrings.push(strippedProcessString); ` - ${colors.FgBlue}Process exited with code ${code}${colors.Reset}`
} );
} else if (argvProcessList) { rl.close();
const processesArray = argvProcessList.split(","); });
for (let i = 0; i < processesArray.length; i++) {
const processString = processesArray[i]; ////////////////////////////////////////////
const strippedProcessString = processString.trim(); ////////////////////////////////////////////
processesStrings.push(strippedProcessString); ////////////////////////////////////////////
}
} else { const argvProcessListIndex = process.argv.indexOf("batch-run") + 1;
console.error(` - ${colors.FgRed}Error:${colors.Reset} No arguments to run or \`batchrun.config.json\` file present`); const argvProcessList = process.argv.at(-1);
process.exit(1); const processesFilePath = path.resolve(process.cwd(), "batchrun.config.json");
}
if (argvProcessList?.match(/batchrun/i) && !fs.existsSync(processesFilePath)) {
if (!processesStrings?.[0]) { console.error(
console.error(` - ${colors.FgRed}Error:${colors.Reset} No processes to run`); ` - ${colors.FgRed}Error:${colors.Reset} No arguments to run`
process.exit(1); );
} process.exit(1);
}
/** @type {import("child_process").SpawnOptions} */
const spawnOptions = { if (fs.existsSync(processesFilePath)) {
cwd: process.cwd(), const processesFile = fs.readFileSync(processesFilePath, "utf8");
shell: process.platform.match(/win/i) ? "bash.exe" : undefined, const processesArray = JSON.parse(processesFile);
stdio: ["pipe", "inherit", "inherit"], for (let i = 0; i < processesArray.length; i++) {
}; const processString = processesArray[i];
const strippedProcessString = processString.trim();
/** processesStrings.push(strippedProcessString);
* Start all processes }
*/ } else if (argvProcessList) {
function startProcesses() { const processesArray = argvProcessList.split(",");
for (let i = 0; i < processesStrings.length; i++) { for (let i = 0; i < processesArray.length; i++) {
const processString = processesStrings[i]; const processString = processesArray[i];
const processStringArray = processString.split(" "); const strippedProcessString = processString.trim();
const targetProcess = processStringArray.shift(); processesStrings.push(strippedProcessString);
if (targetProcess) { }
const childProcess = spawn(targetProcess, processStringArray, spawnOptions); } else {
if (childProcess) { console.error(
processes.push(childProcess); ` - ${colors.FgRed}Error:${colors.Reset} No arguments to run or \`batchrun.config.json\` file present`
);
// childProcess.stdin?.on("keypress", (character, key) => { process.exit(1);
// if (key.ctrl && key.name === "r") { }
// console.log(` - ${colors.FgBlue}Reloading processes ...${colors.Reset}`);
// restartAll(); if (!processesStrings?.[0]) {
// } console.error(
// }); ` - ${colors.FgRed}Error:${colors.Reset} No processes to run`
);
// childProcess.on("error", (error) => { process.exit(1);
// console.log(` - ${colors.FgRed}Error:${colors.Reset} ${error.message}`); }
// killOne(i.toString());
// }); /** @type {import("child_process").SpawnOptions} */
const spawnOptions = {
// childProcess.on("exit", (code, signal) => { cwd: process.cwd(),
// console.log(` - ${colors.FgRed}Error:${colors.Reset} Process ${i} exited with code ${code} and signal ${signal}`); shell: process.platform.match(/win/i) ? "bash.exe" : undefined,
// killOne(i.toString()); stdio: ["pipe", "inherit", "inherit"],
// }); detached: false,
};
// childProcess.on("message", (code, signal) => {
// console.log(` - ${colors.FgRed}Error:${colors.Reset} Process ${i} exited with code ${code} and signal ${signal}`); /**
// killOne(i.toString()); * Start all processes
// }); */
function startProcesses() {
// childProcess.stdin?.pipe(process.stdin); for (let i = 0; i < processesStrings.length; i++) {
} else { const processString = processesStrings[i];
console.error(` - ${colors.FgRed}Error:${colors.Reset} Failed to start process ${i}`); const processStringArray = processString.split(" ");
process.exit(1); const targetProcess = processStringArray.shift();
} if (targetProcess) {
} else { const childProcess = spawn(
console.error(` - ${colors.FgRed}Error:${colors.Reset} A target process is not defined in \`${processString}\``); targetProcess,
process.exit(1); processStringArray,
} spawnOptions
} );
} if (childProcess) {
processes.push(childProcess);
/** } else {
* Restart All Processes console.error(
*/ ` - ${colors.FgRed}Error:${colors.Reset} Failed to start process ${i}`
function restartAll() { );
for (let i = 0; i < processes.length; i++) { process.exit(1);
const childProcess = processes[i]; }
} else {
try { console.error(
if (childProcess.pid) killProcessForce(childProcess.pid); ` - ${colors.FgRed}Error:${colors.Reset} A target process is not defined in \`${processString}\``
childProcess.kill(); );
// processes.splice(i, 1); process.exit(1);
} catch (error) { }
console.log(` - ${colors.FgRed}Error:${colors.Reset} Failed to kill process ${childProcess.pid}`); }
process.exit(); }
}
} /**
* Restart All Processes
console.log(` - ${colors.FgGreen}Restarted ${processes.length} processes${colors.Reset}`); */
function restartAll() {
processes = []; for (let i = 0; i < processes.length; i++) {
const childProcess = processes[i];
setTimeout(() => {
startProcesses(); try {
}, 500); if (childProcess.pid) killProcessForce(childProcess.pid);
} childProcess.kill();
// processes.splice(i, 1);
/** } catch (error) {
* Restart a single process console.log(
* @param {string} index ` - ${colors.FgRed}Error:${colors.Reset} Failed to kill process ${childProcess.pid}`
*/ );
function restartOne(index) { process.exit();
const childProcess = processes[parseInt(index)]; }
}
try {
if (childProcess.pid) killProcessForce(childProcess.pid); console.log(
childProcess.kill(); ` - ${colors.FgGreen}Restarted ${processes.length} processes${colors.Reset}`
} catch (error) { );
console.log(` - ${colors.FgRed}Error:${colors.Reset} Failed to kill process ${childProcess.pid}`);
process.exit(); processes = [];
}
setTimeout(() => {
const processString = processesStrings[index]; startProcesses();
const processStringArray = processString.split(" "); }, 500);
const targetProcess = processStringArray.shift(); }
const newChildProcess = spawn(targetProcess, processStringArray, spawnOptions);
processes.splice(parseInt(index), 1, newChildProcess); /**
} * Restart a single process
* @param {string} index
/** */
* Kill a single process function restartOne(index) {
* @param {string} index const childProcess = processes[parseInt(index)];
*/
function killOne(index) { try {
const childProcess = processes[parseInt(index)]; if (childProcess.pid) killProcessForce(childProcess.pid);
if (childProcess.pid) killProcessForce(childProcess.pid); childProcess.kill();
childProcess.kill(); } catch (error) {
console.log(
try { ` - ${colors.FgRed}Error:${colors.Reset} Failed to kill process ${childProcess.pid}`
} catch (error) { );
console.log(` - ${colors.FgRed}Error:${colors.Reset} Failed to kill process ${childProcess.pid}`); process.exit();
process.exit(); }
}
} const processString = processesStrings[index];
const processStringArray = processString.split(" ");
/** const targetProcess = processStringArray.shift();
* Kill a process by PID const newChildProcess = spawn(
* @param {number} pid targetProcess,
*/ processStringArray,
function killProcessForce(pid) { spawnOptions
if (typeof pid !== "number") { );
return; processes.splice(parseInt(index), 1, newChildProcess);
} }
try {
if (process.platform.match(/win/i)) { /**
execSync(`taskkill /F /PID ${pid} /T`); * Kill a single process
} else { * @param {string} index
execSync(`kill -9 ${pid}`); */
} function killOne(index) {
} catch (error) {} const childProcess = processes[parseInt(index)];
} if (childProcess.pid) killProcessForce(childProcess.pid);
childProcess.kill();
console.log(` - ${colors.FgGreen}Started ${processesStrings.length} processes${colors.Reset}`);
startProcesses(); try {
} catch (error) {
console.log(
` - ${colors.FgRed}Error:${colors.Reset} Failed to kill process ${childProcess.pid}`
);
process.exit();
}
}
/**
* Kill a process by PID
* @param {number} pid
*/
function killProcessForce(pid) {
if (typeof pid !== "number") {
return;
}
try {
if (process.platform.match(/win/i)) {
execSync(`taskkill /F /PID ${pid} /T`);
} else {
execSync(`kill -9 ${pid}`);
}
} catch (error) {}
}
console.log(
` - ${colors.FgGreen}Started ${processesStrings.length} processes${colors.Reset}`
);
startProcesses();
setInterval(() => {
console.log(
`Turbo Sync Running for ${process.uptime().toLocaleString()}s ...`
);
}, 60000);

37
package-lock.json generated Normal file
View File

@ -0,0 +1,37 @@
{
"name": "batchrun",
"version": "1.0.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "batchrun",
"version": "1.0.7",
"license": "MIT",
"bin": {
"batch-run": "index.js",
"batchrun": "index.js"
},
"devDependencies": {
"@types/node": "^22.8.7"
}
},
"node_modules/@types/node": {
"version": "22.8.7",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.8.7.tgz",
"integrity": "sha512-LidcG+2UeYIWcMuMUpBKOnryBWG/rnmOHQR5apjn8myTQcx3rinFRn7DcIFhMnS0PPFSC6OafdIKEad0lj6U0Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.19.8"
}
},
"node_modules/undici-types": {
"version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"dev": true,
"license": "MIT"
}
}
}

View File

@ -21,5 +21,8 @@
"monitor" "monitor"
], ],
"author": "Benjamin Toby", "author": "Benjamin Toby",
"license": "MIT" "license": "MIT",
"devDependencies": {
"@types/node": "^22.8.7"
}
} }