Skip to content

Commit

Permalink
✨ ♻️ provide script.posix and script.powershell template tags
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdd committed Aug 18, 2023
1 parent bf0be7b commit c33dcec
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 32 deletions.
62 changes: 31 additions & 31 deletions src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,39 +133,39 @@ export class CommandBuilder {
}
}


export const command = (executable: string, ...args: string[]) =>
new CommandBuilder({ type: 'spawn', executable, args })

export const script = (template: TemplateStringsArray, ...args: unknown[]) => {
const source = template
.map((s: string, i: number) => {
const arg = args[i]

if (arg === null || arg === undefined) {
return s
}
else if (typeof arg === 'string') {
return `${s}${quote(arg)}`
}
else if (typeof arg === 'number' || typeof arg === 'boolean') {
return `${s}${arg}`
}
else {
throw new TypeError(
`Unexpected template argument of type ${typeof arg}`
)
}
})
.join('')

const commands = source
.split(';')
.flatMap(s => s.split('\n'))
.map(s => s.trim())
.filter(s => s.length > 0)

return commands.reduce(
(builder, cmd) => builder.and(command(cmd)),
command('true')
)
const makeSource = (template: TemplateStringsArray, args: unknown[]): string =>
template.map((s: string, i: number) => {
const arg = args[i]

if (arg === null || arg === undefined) {
return s
}
else if (typeof arg === 'string') {
return `${s}${quote(arg)}`
}
else if (typeof arg === 'number' || typeof arg === 'boolean') {
return `${s}${arg}`
}
else {
throw new TypeError(
`Unexpected template argument of type ${typeof arg}`
)
}
}).join('')


export const script = {
posix: (template: TemplateStringsArray, ...args: unknown[]) => {
const src = makeSource(template, args)
return command('sh', '-').writeStdin(Buffer.from(src))
},
powershell: (template: TemplateStringsArray, ...args: unknown[]) => {
const src = makeSource(template, args)
return command('PowerShell', '-Command', '-').writeStdin(Buffer.from(src))
},
}
2 changes: 1 addition & 1 deletion tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ describe('command runner', () => {
})

it('should execute a script', async() => {
const res = await script`
const res = await script.posix`
echo hello
echo world
`.run()
Expand Down

0 comments on commit c33dcec

Please sign in to comment.