Skip to content

Commit

Permalink
feat: accept mode option for tmpdir and tmpfile
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Jan 7, 2025
1 parent 022606a commit 5826319
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
5 changes: 3 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,9 @@ Temp file factory.

```js
f1 = tmpfile() // /os/based/tmp/zx-1ra1iofojgg
f2 = tmpfile('f.txt') // /os/based/tmp/zx-1ra1iofojgg/foo.txt
f3 = tmpfile('f.txt', 'string or buffer')
f2 = tmpfile('f2.txt') // /os/based/tmp/zx-1ra1iofojgg/foo.txt
f3 = tmpfile('f3.txt', 'string or buffer')
f4 = tmpfile('f4.sh', 'echo "foo"', 0o744) // executable
```

## minimist
Expand Down
19 changes: 13 additions & 6 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,33 @@

import os from 'node:os'
import path from 'node:path'
import fs from 'node:fs'
import fs, { type Mode } from 'node:fs'
import { chalk, type RequestInfo, type RequestInit } from './vendor-core.js'
import { inspect } from 'node:util'

export { isStringLiteral } from './vendor-core.js'

export function tempdir(prefix: string = `zx-${randomId()}`): string {
export function tempdir(
prefix: string = `zx-${randomId()}`,
mode?: Mode
): string {
const dirpath = path.join(os.tmpdir(), prefix)
fs.mkdirSync(dirpath, { recursive: true })
fs.mkdirSync(dirpath, { recursive: true, mode })

return dirpath
}

export function tempfile(name?: string, data?: string | Buffer): string {
export function tempfile(
name?: string,
data?: string | Buffer,
mode?: Mode
): string {
const filepath = name
? path.join(tempdir(), name)
: path.join(os.tmpdir(), `zx-${randomId()}`)

if (data === undefined) fs.closeSync(fs.openSync(filepath, 'w'))
else fs.writeFileSync(filepath, data)
if (data === undefined) fs.closeSync(fs.openSync(filepath, 'w', mode))
else fs.writeFileSync(filepath, data, { mode })

return filepath
}
Expand Down
3 changes: 1 addition & 2 deletions test/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,9 +272,8 @@ describe('cli', () => {
const zxLocation = isWindows ? toPOSIXPath(zxPath) : zxPath
const scriptCode = `#!/usr/bin/env ${zxLocation}\nconsole.log('The script from path runs.')`
const scriptName = 'script-from-path'
const scriptFile = tmpfile(scriptName, scriptCode)
const scriptFile = tmpfile(scriptName, scriptCode, 0o744)
const scriptDir = path.dirname(scriptFile)
fs.chmodSync(scriptFile, 0o744)

const envPathSeparator = isWindows ? ';' : ':'
process.env.PATH += envPathSeparator + scriptDir
Expand Down

0 comments on commit 5826319

Please sign in to comment.