Skip to content

Commit ca8540d

Browse files
committed
feat: add getSafeCwd() helper for deleted directory handling
Add utility to safely get current working directory with fallbacks. Handles cases where cwd has been deleted or is inaccessible. Falls back to home directory or temp directory as last resort.
1 parent 64c60ac commit ca8540d

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/utils/fs.mts

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
* - Safely deleting files and directories
2121
*/
2222

23-
import { promises as fs } from 'node:fs'
23+
import { accessSync, promises as fs, constants as fsConstants } from 'node:fs'
24+
import os from 'node:os'
2425
import path from 'node:path'
2526

2627
import { remove } from '@socketsecurity/registry/lib/fs'
@@ -29,6 +30,37 @@ import constants from '../constants.mts'
2930

3031
import type { RemoveOptions } from '@socketsecurity/registry/lib/fs'
3132

33+
/**
34+
* Safely get the current working directory.
35+
* If the current directory has been deleted or is inaccessible,
36+
* falls back to the home directory or temp directory.
37+
*/
38+
export function getSafeCwd(): string {
39+
try {
40+
const cwd = process.cwd()
41+
// Verify the directory still exists
42+
try {
43+
accessSync(cwd, fsConstants.F_OK)
44+
return cwd
45+
} catch {
46+
// Directory no longer exists
47+
}
48+
} catch {
49+
// process.cwd() itself failed
50+
}
51+
52+
// Fallback to home directory
53+
try {
54+
const home = constants.homePath
55+
if (home) {return home}
56+
} catch {
57+
// homePath might not be available
58+
}
59+
60+
// Last resort: temp directory
61+
return os.tmpdir()
62+
}
63+
3264
export type FindUpOptions = {
3365
cwd?: string | undefined
3466
onlyDirectories?: boolean | undefined

0 commit comments

Comments
 (0)