Commit d969840

Anton Golub <antongolub@antongolub.com>
2025-01-07 19:11:53
feat: accept `mode` option for `tmpdir` and `tmpfile` (#1063)
1 parent 022606a
Changed files (3)
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
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
 }
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