Files
Netcatty/electron/bridges/localFsBridge.test.cjs
T
陈大猫andClaude Opus 4.7 e0302e5f34 Batch Windows hidden-attribute detection in local FS listing (#766) (#767)
* Batch Windows hidden-attribute detection in local FS listing (#766)

Symptom: opening a local directory with ~800 files in the SFTP panel
hangs for ~30 s on Windows. Reported on netcatty 1.0.93.

Root cause: listLocalDir spawns attrib.exe once per entry inside the
worker pool to detect the Windows hidden flag. 800 subprocess spawns
× ~40 ms each is precisely the reported 30 s. fs.promises.stat and
readdir on their own are nearly free; the subprocess flood dominates.

Fix: replace the per-entry attrib call with a single
`attrib.exe "<dir>\*"` invocation up front, parse its output into a
Set<basename>, and have the workers do an O(1) set lookup. One
subprocess per directory listing instead of one per entry.

Expected speedup for the #766 case: ~30 s → <1 s. Behavior is
unchanged — hidden files keep their hidden flag, non-hidden files
stay not-hidden; only the mechanism is different. Broken-symlink
handling (lstat fallback) also uses the same set.

Tests:
- parseAttribOutput is extracted as a pure function and unit-tested
  against real attrib output shapes: drive-letter paths, UNC paths,
  the trailing [DIR] marker that some Windows versions emit, mixed
  flag columns (A/H/R), malformed "Parameter format not correct"
  lines, empty input.
- listWindowsHiddenBasenames short-circuits on non-Windows without
  spawning anything.
- Parser uses path.win32.basename explicitly so the tests pass under
  non-Windows CI.

I cannot reproduce or test on Windows directly. The diagnosis is
mechanical (we can count subprocess calls) and the fix is a local
rewrite that preserves behavior, but Windows verification is still
desirable before release.

Closes #766

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Address codex review on #767: pass /d so batched attrib includes hidden directories

Codex flagged that attrib.exe treats `<dir>\*` as file-centric by
default — without `/d`, hidden directories (node_modules, .git, etc.)
never appear in the output, so listWindowsHiddenBasenames misses them
and the SFTP browser shows those folders as not-hidden. This is a
behavior regression from the per-file path, which passed each entry's
full path directly and therefore covered both files and directories.

Added `/d` to the execFileAsync argv and a regression test that
module-mocks child_process.execFile to capture the argv and assert
`/d` is present. The parser-level [DIR] marker test is also still
there, so both the attrib call shape and the parser behavior are
locked down.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Address codex round 2 on #767: tighten [DIR] strip to the literal marker

Codex flagged that /\s+\[[^\]]+\]\s*$/ also swallows legitimate trailing
bracketed text, so a hidden file named "Notes [old]" gets stored as
"Notes" in hiddenSet and hiddenSet.has("Notes [old]") returns false —
the entry is misclassified as not-hidden, a regression from the old
per-entry attrib path which never saw a "[DIR]" marker to strip.

Narrowed the regex to /\s+\[DIR\]\s*$/ — only the literal attrib/d
marker. Added a regression test covering "Notes [old]", "Draft [v2].md",
"archived [2024]" alongside the existing [DIR] case to lock down both
behaviors together.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 22:32:33 +08:00

140 lines
4.9 KiB
JavaScript

const test = require("node:test");
const assert = require("node:assert/strict");
const { parseAttribOutput, listWindowsHiddenBasenames } = require("./localFsBridge.cjs");
test("parseAttribOutput returns an empty set for empty input", () => {
assert.equal(parseAttribOutput("").size, 0);
assert.equal(parseAttribOutput("\r\n\r\n").size, 0);
});
test("parseAttribOutput captures basenames of files with the H flag", () => {
const stdout = [
"A C:\\Users\\foo\\public.txt",
" H C:\\Users\\foo\\.secret",
"A H R C:\\Users\\foo\\hidden-readonly.exe",
"A C:\\Users\\foo\\another.log",
].join("\r\n");
const hidden = parseAttribOutput(stdout);
assert.deepEqual(
[...hidden].sort(),
[".secret", "hidden-readonly.exe"].sort(),
);
});
test("parseAttribOutput ignores the trailing [DIR] marker on some Windows versions", () => {
const stdout = [
" H C:\\data\\node_modules [DIR]",
" H C:\\data\\.git [DIR]",
"A C:\\data\\README.md",
].join("\r\n");
const hidden = parseAttribOutput(stdout);
assert.deepEqual([...hidden].sort(), [".git", "node_modules"].sort());
});
test("parseAttribOutput preserves filenames that legitimately end with bracketed suffixes", () => {
// Regression: a prior version stripped ANY trailing bracketed suffix
// via /\s+\[[^\]]+\]\s*$/, truncating "Notes [old]" to "Notes".
// Only the literal [DIR] marker that attrib emits with /d is a parser
// artifact; user-facing filenames with brackets must survive intact so
// hiddenSet.has(entry.name) still matches the actual readdir entry.
const stdout = [
" H C:\\data\\Notes [old]",
" H C:\\data\\Draft [v2].md",
" H C:\\data\\archived [2024]",
" H C:\\data\\node_modules [DIR]",
].join("\r\n");
const hidden = parseAttribOutput(stdout);
assert.deepEqual(
[...hidden].sort(),
["Draft [v2].md", "Notes [old]", "archived [2024]", "node_modules"].sort(),
);
});
test("parseAttribOutput handles UNC paths", () => {
const stdout = [
" H \\\\fileserver\\share\\secret.cfg",
"A \\\\fileserver\\share\\public.cfg",
].join("\r\n");
const hidden = parseAttribOutput(stdout);
assert.deepEqual([...hidden], ["secret.cfg"]);
});
test("parseAttribOutput skips malformed lines", () => {
const stdout = [
"Parameter format not correct",
"",
" H C:\\good\\hidden.txt",
"File not found",
" H not-a-windows-path.txt",
].join("\r\n");
const hidden = parseAttribOutput(stdout);
assert.deepEqual([...hidden], ["hidden.txt"]);
});
test("listWindowsHiddenBasenames returns an empty set on non-Windows without spawning anything", async () => {
// Running this test file is only meaningful on a non-Windows host for this
// assertion. On Windows CI we skip the subprocess-free guarantee.
if (process.platform === "win32") return;
const result = await listWindowsHiddenBasenames("/tmp");
assert.ok(result instanceof Set);
assert.equal(result.size, 0);
});
test("listWindowsHiddenBasenames invokes attrib.exe with /d so hidden directories aren't omitted", async () => {
// Regression: without `/d`, `attrib <dir>\*` treats the wildcard as
// file-centric and hidden directories (node_modules, .git, …) never
// reach parseAttribOutput — the SFTP browser then shows them as
// not-hidden, a behavior regression from the per-file implementation.
const Module = require("node:module");
const realChildProcess = require("node:child_process");
const originalLoad = Module._load;
const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
let capturedArgs = null;
let capturedExecutable = null;
Module._load = function patchedLoad(request, parent, isMain) {
if (request === "node:child_process") {
return {
...realChildProcess,
execFile: (executable, args, _options, cb) => {
capturedExecutable = executable;
capturedArgs = args;
cb(null, { stdout: "", stderr: "" });
},
};
}
return originalLoad.call(this, request, parent, isMain);
};
Object.defineProperty(process, "platform", {
value: "win32",
writable: true,
configurable: true,
});
const bridgePath = require.resolve("./localFsBridge.cjs");
delete require.cache[bridgePath];
try {
const { listWindowsHiddenBasenames: fn } = require("./localFsBridge.cjs");
await fn("C:\\fixture");
} finally {
Module._load = originalLoad;
Object.defineProperty(process, "platform", originalPlatform);
delete require.cache[bridgePath];
}
assert.equal(capturedExecutable, "attrib.exe");
assert.ok(
Array.isArray(capturedArgs) && capturedArgs.includes("/d"),
`expected /d in attrib args so hidden directories are included, got ${JSON.stringify(capturedArgs)}`,
);
});