Skip to content

Commit

Permalink
refactor: streamline hidden file handling and improve system flag checks
Browse files Browse the repository at this point in the history
  • Loading branch information
mceachen committed Dec 1, 2024
1 parent 373fe52 commit 9a798da
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions src/hidden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,9 @@ export async function isHidden(
nativeFn: NativeBindingsFn,
): Promise<boolean> {
pathname = normalizePath(pathname);

if (isWindows && isRootDirectory(pathname)) {
// windows `attr` thinks all drive letters don't exist.
return false;
}

// Windows doesn't hide dot-prefixed files or directories:
return (
(LocalSupport.dotPrefix && isPosixHidden(pathname)) ||
(LocalSupport.systemFlag &&
// don't bother the native bindings if the file doesn't exist:
(await canStatAsync(pathname)) &&
(await nativeFn()).isHidden(pathname))
(LocalSupport.systemFlag && isSystemHidden(pathname, nativeFn))
);
}

Expand All @@ -120,7 +110,7 @@ export function createHiddenPosixPath(pathname: string, hidden: boolean) {
return dest;
}

export async function setHiddenPosix(
async function setHiddenPosix(
pathname: string,
hidden: boolean,
): Promise<string> {
Expand All @@ -133,11 +123,31 @@ export async function setHiddenPosix(
throw new Error("Unsupported platform");
}

export function isPosixHidden(pathname: string): boolean {
function isPosixHidden(pathname: string): boolean {
const b = basename(pathname);
return b.startsWith(".") && b !== "." && b !== "..";
}

async function isSystemHidden(
pathname: string,
nativeFn: NativeBindingsFn,
): Promise<boolean> {
if (!LocalSupport.systemFlag) {
// not supported on this platform
return false;
}
if (isWindows && isRootDirectory(pathname)) {
// windows `attr` thinks all drive letters don't exist.
return false;
}

// don't bother the native bindings if the file doesn't exist:
return (
(await canStatAsync(pathname)) &&
(await (await nativeFn()).isHidden(pathname))
);
}

/**
* Gets detailed information about the hidden state of the file or directory
* @returns An object containing detailed hidden state information
Expand All @@ -151,9 +161,7 @@ export async function getHiddenMetadata(

const dotPrefix = LocalSupport.dotPrefix && isPosixHidden(pathname);
const systemFlag =
LocalSupport.systemFlag &&
(await canStatAsync(pathname)) &&
(await (await nativeFn()).isHidden(pathname));
LocalSupport.systemFlag && (await isSystemHidden(pathname, nativeFn));
return {
hidden: dotPrefix || systemFlag,
dotPrefix,
Expand All @@ -178,6 +186,10 @@ export async function setHidden(
throw new WrappedError("setHidden()", err);
}

if (isWindows && isRootDirectory(pathname)) {
throw new Error("Cannot hide root directory on Windows");
}

const actions = {
dotPrefix: false,
systemFlag: false,
Expand Down

0 comments on commit 9a798da

Please sign in to comment.