Skip to content

Commit

Permalink
Fix bug where running script without extension removes existing `.mjs…
Browse files Browse the repository at this point in the history
…` files (#276)

* Adds test to verify no-ext doesn't overwrite similarly named files

* Changes importPath to use tmpFilename for no-ext case

* Changes tmpFilename in importPath to be more readable

Co-authored-by: Anton Medvedev <anton@medv.io>
  • Loading branch information
Ivraj and antonmedv committed Feb 16, 2022
1 parent 5db11c6 commit f8bb1c7
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
3 changes: 2 additions & 1 deletion test.mjs
Expand Up @@ -80,8 +80,9 @@ import {strict as assert} from 'assert'
}
}

{ // Scripts with no extension are working
{ // Scripts with no extension work and do not overwrite similarly named files.
await $`node zx.mjs tests/no-extension`
assert.match((await fs.readFile('tests/no-extension.mjs')).toString(), /Test file to verify no-extension didn't overwrite similarly name .mjs file./);
}

{ // require() is working from stdin
Expand Down
1 change: 1 addition & 0 deletions tests/no-extension.mjs
@@ -0,0 +1 @@
// Test file to verify no-extension didn't overwrite similarly name .mjs file.
7 changes: 6 additions & 1 deletion zx.mjs
Expand Up @@ -101,10 +101,15 @@ async function writeAndImport(script, filepath, origin = filepath) {

async function importPath(filepath, origin = filepath) {
let ext = extname(filepath)

if (ext === '') {
let tmpFilename = fs.existsSync(`${filepath}.mjs`) ?
`${basename(filepath)}-${Math.random().toString(36).substr(2)}.mjs` :
`${basename(filepath)}.mjs`

return await writeAndImport(
await fs.readFile(filepath),
join(dirname(filepath), basename(filepath) + '.mjs'),
join(dirname(filepath), tmpFilename),
origin,
)
}
Expand Down

0 comments on commit f8bb1c7

Please sign in to comment.