Skip to content

Commit

Permalink
Add support for bash code blocks in markdown scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Aug 13, 2021
1 parent 8fefed0 commit 479ca79
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 4 deletions.
15 changes: 15 additions & 0 deletions examples/markdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,18 @@ We can use imports here as well:
```js
await import('./basics.mjs')
```

A bash code (with `bash` or `sh` language tags) also will be executed:

```bash
VAR=$(date)
echo "$VAR" | wc -c
```

Other code blocks are ignored:

```css
body .hero {
margin: 42px;
}
```
14 changes: 13 additions & 1 deletion index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,16 @@ export function $(pieces, ...args) {
}
cmd += s + pieces[++i]
}
if (verbose) console.log('$', colorize(cmd))
if (verbose) {
if (/\n/.test(cmd)) {
console.log(cmd
.split('\n')
.map((line, i) => (i === 0 ? '$' : '>') + ' ' + colorize(line))
.join('\n'))
} else {
console.log('$', colorize(cmd))
}
}
let options = {
cwd: $.cwd,
shell: typeof $.shell === 'string' ? $.shell : true,
Expand All @@ -58,16 +67,19 @@ export function $(pieces, ...args) {
process.stdin.pipe(child.stdin)
}
let stdout = '', stderr = '', combined = ''

function onStdout(data) {
if (verbose) process.stdout.write(data)
stdout += data
combined += data
}

function onStderr(data) {
if (verbose) process.stderr.write(data)
stderr += data
combined += data
}

child.stdout.on('data', onStdout)
child.stderr.on('data', onStderr)
promise._stop = () => {
Expand Down
29 changes: 26 additions & 3 deletions zx.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,15 @@ function transformMarkdown(source) {
if (/^( {4}|\t)/.test(line) && prevLineIsEmpty) {
output.push(line)
state = 'tab'
} else if (/^```(js)?$/.test(line)) {
} else if (/^```(js|javascript)$/.test(line)) {
output.push('')
state = 'code'
state = 'js'
} else if (/^```(sh|bash)$/.test(line)) {
output.push('await $`')
state = 'bash'
} else if (/^```.*$/.test(line)) {
output.push('')
state = 'other'
} else {
prevLineIsEmpty = line === ''
output.push('// ' + line)
Expand All @@ -156,16 +162,33 @@ function transformMarkdown(source) {
state = 'root'
}
break
case 'code':
case 'js':
if (/^```$/.test(line)) {
output.push('')
state = 'root'
} else {
output.push(line)
}
break
case 'bash':
if (/^```$/.test(line)) {
output.push('`')
state = 'root'
} else {
output.push(line)
}
break
case 'other':
if (/^```$/.test(line)) {
output.push('')
state = 'root'
} else {
output.push('// ' + line)
}
break
}
}
console.log(output.join('\n'))
return output.join('\n')
}

Expand Down

0 comments on commit 479ca79

Please sign in to comment.