Skip to content
This repository has been archived by the owner on Jan 6, 2021. It is now read-only.

Commit

Permalink
Refactored the main parsing loop
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Rey Lopez committed Mar 26, 2017
1 parent 928dbc4 commit 53776d3
Showing 1 changed file with 26 additions and 21 deletions.
47 changes: 26 additions & 21 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ module.exports = crossEnv
const envSetterRegex = /(\w+)=('(.+)'|"(.+)"|(.+))/

function crossEnv(args) {
const [command, commandArgs, env] = getCommandArgsAndEnvVars(args)
const [envSetters, command, commandArgs] = parseCommand(args)
if (command) {
const proc = spawn(command, commandArgs, {
stdio: 'inherit',
shell: true,
env,
})
const proc = spawn(
commandConvert(command),
commandArgs.map(commandConvert),
{
stdio: 'inherit',
shell: true,
env: getEnvVars(envSetters),
},
)
process.on('SIGTERM', () => proc.kill('SIGTERM'))
process.on('SIGINT', () => proc.kill('SIGINT'))
process.on('SIGBREAK', () => proc.kill('SIGBREAK'))
Expand All @@ -24,30 +28,31 @@ function crossEnv(args) {
return null
}

function getCommandArgsAndEnvVars(args) {
const envVars = getEnvVars()
const commandArgs = args.slice()
const command = getCommand(commandArgs, envVars)
return [commandConvert(command), commandArgs.map(commandConvert), envVars]
}

function getCommand(commandArgs, envVars) {
while (commandArgs.length) {
const shifted = commandArgs.shift()
const match = envSetterRegex.exec(shifted)
function parseCommand(args) {
const envSetters = {}
let command = null
let commandArgs = []
for (let i = 0; i < args.length; i++) {
const match = envSetterRegex.exec(args[i])
if (match) {
envVars[match[1]] = varValueConvert(match[3] || match[4] || match[5])
envSetters[match[1]] = match[3] || match[4] || match[5]
} else {
return shifted
// No more env setters, the rest of the line must be the command and args
command = args[i]
commandArgs = args.slice(i + 1)
break
}
}
return null
return [envSetters, command, commandArgs]
}

function getEnvVars() {
function getEnvVars(envSetters) {
const envVars = Object.assign({}, process.env)
if (process.env.APPDATA) {
envVars.APPDATA = process.env.APPDATA
}
Object.keys(envSetters).forEach(varName => {
envVars[varName] = varValueConvert(envSetters[varName])
})
return envVars
}

0 comments on commit 53776d3

Please sign in to comment.