diff --git a/docs/api.md b/docs/api.md index 250261a500..cfc3c88c92 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 diff --git a/src/util.ts b/src/util.ts index 0743324184..9d7207f2b7 100644 --- a/src/util.ts +++ b/src/util.ts @@ -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 } diff --git a/test/cli.test.js b/test/cli.test.js index 418302e668..649fac33b4 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -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