node/lib/internal/shell.js
Yagiz Nizipli 128c60d906
cli: implement node --run <script-in-package-json>
Co-authored-by: Daniel Lemire <daniel@lemire.me>
PR-URL: https://github.com/nodejs/node/pull/52190
Reviewed-By: Daniel Lemire <daniel@lemire.me>
Reviewed-By: Vinícius Lourenço Claro Cardoso <contact@viniciusl.com.br>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
Reviewed-By: Tierney Cyren <hello@bnb.im>
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Ruy Adorno <ruy@vlt.sh>
2024-04-08 00:49:14 +00:00

38 lines
1.1 KiB
JavaScript

'use strict';
// There is no need to add primordials to this file.
// `shell.js` is a script only executed when `node run <script>` is called.
const forbiddenCharacters = /[\t\n\r "#$&'()*;<>?\\`|~]/;
/**
* Escapes a string to be used as a shell argument.
*
* Adapted from `promise-spawn` module available under ISC license.
* Ref: https://github.com/npm/promise-spawn/blob/16b36410f9b721dbe190141136432a418869734f/lib/escape.js
* @param {string} input
*/
function escapeShell(input) {
// If the input is an empty string, return a pair of quotes
if (!input.length) {
return '\'\'';
}
// Check if input contains any forbidden characters
// If it doesn't, return the input as is.
if (!forbiddenCharacters.test(input)) {
return input;
}
// Replace single quotes with '\'' and wrap the whole result in a fresh set of quotes
return `'${input.replace(/'/g, '\'\\\'\'')}'`
// If the input string already had single quotes around it, clean those up
.replace(/^(?:'')+(?!$)/, '')
.replace(/\\'''/g, '\\\'');
}
module.exports = {
escapeShell,
};