The bashToOne
function maps Bash shell script code to a single executable command, handling platform-specific line endings and command separators. It does this by splitting, modifying, and joining the input code according to the detected platform (Windows or Unix-like).
npm run import -- "convert bash to one liner"
// read cmd template and execute each line?
var multiline = process.platform === 'win32' ? '^\n ' : '\\\n ';
var multicmd = process.platform === 'win32' ? ' ^\n; ' : ' \\\n&& ';
function bashToOne(code) {
return code
.split(/\n/ig)
.map(l => '{EXEC} ' + l)
.join('\n')
.replace(/\\((\s*\n)+\{EXEC\})+\s*&&/ig, multicmd)
.replace(/\\((\s*\n)+\{EXEC\})+/ig, multiline)
.split(/\s*\{EXEC\}\s*/ig)
.filter(r => r.trim() !== '')
.join(multicmd);
}
module.exports = bashToOne;
// Import required modules
const { EOL } = require('os');
/**
* Formats bash code to run each line sequentially.
*
* @param {string} code - The bash code to format.
* @returns {string} The formatted bash code.
*/
function bashToOne(code) {
// Split the code into individual lines
const lines = code.split(EOL);
// Map over the lines to wrap each with the EXEC placeholder
const wrappedLines = lines.map(line => ` {EXEC} ${line.trim()}`).join(EOL);
// Replace newline characters with multiline placeholders
const multilinePlaceholder = EOL === '\r\n'? '^' + EOL +'' : '\\\n ';
const wrappedLinesWithMultiline = wrappedLines.replace(/\n/g, multilinePlaceholder);
// Replace `&&` with the multicmd placeholder
const multicmd = EOL === '\r\n'?'^' + EOL + ';':'\\\n&& ';
const formattedCode = wrappedLinesWithMultiline.replace(/(\s*\n)+&&/g, multicmd);
// Split the code on the EXEC placeholder and filter out empty lines
const commands = formattedCode.split(' {EXEC} ').filter(command => command.trim()!== '');
// Join the commands with the multicmd placeholder and return the result
return commands.join(multicmd);
}
module.exports = bashToOne;
Function: bashToOne
Maps Bash shell script code to a single executable command.
code
: The Bash shell script code to be converted.The converted code as a single executable command.
\n
).{EXEC}
to indicate where the command should be executed.\n
) or a Windows-style command separator (;
) depending on the platform.{EXEC}
with either a Windows-style newline or a Unix-style command separator, depending on the platform.&&
).Uses the process.platform
property to determine whether to use Windows-style or Unix-style line endings and command separators.
process.platform === 'win32'
: Windows platformprocess.platform!== 'win32'
: Unix-like platform