Skip to content

Commit 416179d

Browse files
refactor(u4): reuse main's errorCode helper and drop a one-line fsync wrapper
Two module-private helpers on this branch reimplemented `src/utils/errorCode.ts`, which main already ships and which `safeWriteJson.ts` already imports: - `safeWriteJson._scopeErrorCode` (2 call sites) -> `getErrorCode` - `safeWriteText.errorCode` (8 call sites) -> `getErrorCode` - `safeWriteText._fsyncFile(fd)` wrapped a single `fsSync.fsyncSync(fd)` call; the 4 call sites now call it directly. Equivalence was checked at the call sites rather than assumed. All 10 uses compare the result against a string code literal (`=== "ENOENT"`, `!== "ENOENT"`, and the ENOTDIR variants), so the one real difference between the bodies - main's helper additionally guards `typeof error.code === "string"`, `_scopeErrorCode` casts, and `errorCode` stringifies - cannot change a decision: an absent or non-string code yields `undefined` from `getErrorCode` and either a coerced string or `undefined` from the private helpers, and both take the same branch against a string literal. This is line-count work for the mutation gate, not a behaviour change: no assertion moved, no expectation weakened, nothing dropped to make a number fit. The gate counts changed executable lines per package against main and fails above 500. With the repository's own counting rules applied locally (scripts/stryker-diff.mjs) at b86511f the `extension` package measured 509, which is the number CI reported for that head; after this commit the same selector reports 499 (safeWriteText +272 -> +266, safeWriteJson +135 -> +131). The removals are the duplicate helper bodies and the wrapper only. Measured with pinned node v22.23.4 on this tree: prettier --check on both files exit 0; eslint --max-warnings=0 on both files exit 0 with src/eslint-suppressions json unmodified; tsc -p src/tsconfig.json --noEmit exit 0; misc shard 119 passed / 1 skipped files and 2118 passed / 17 skipped tests; core shard 197 files and 4280 passed / 9 skipped tests; misc shard restricted to the write-protocol proof files (5 exist in this lane) 81 passed / 4 skipped; knip and knip --production, both with --treat-config-hints-as-errors, exit 0; knip-policy test 8 pass / 0 fail. The services shard is unchanged from the pre-commit baseline: the same 6 failures with and without this commit, classed from the messages themselves - 5 `EPERM: operation not permitted, symlink ...` fixture-creation failures in services/rules (unprivileged symlink creation in %TEMP% on this box) and 1 `DaclRestoreError` in safeWriteText.integration.spec.ts (the saved access rights could not be restored here). The hosted windows leg passes both files at b86511f. Local results describe this tree only: pnpm 10.8.1 ignores the `pnpm` field in package.json (onlyBuiltDependencies, overrides), so a resolution difference is the first candidate if a local shard disagrees with a hosted leg.
1 parent b86511f commit 416179d

2 files changed

Lines changed: 16 additions & 35 deletions

File tree

‎src/services/file-safety/safeWriteText.ts‎

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import * as fsSync from "fs"
33
import * as path from "path"
44
import { execFile } from "child_process"
55

6+
import { getErrorCode } from "../../utils/errorCode"
7+
68
export interface SafeWriteTextOptions {
79
/**
810
* When true, keep the old-file semantics without ever removing the target: the
@@ -142,10 +144,6 @@ function _stagingDir(dir: string): string {
142144
return sd
143145
}
144146

145-
function _fsyncFile(fd: number): void {
146-
fsSync.fsyncSync(fd)
147-
}
148-
149147
/** Save the DACL of *srcPath* to a dump file on Windows.
150148
* Returns true when the dump was written successfully; false otherwise.
151149
* Never throws — callers treat failure as "skip DACL handling". */
@@ -196,31 +194,20 @@ async function _restoreDaclWindows(
196194
*/
197195
export async function resolvePublishTarget(absoluteFilePath: string): Promise<string> {
198196
return fs.realpath(absoluteFilePath).catch(async (error: unknown) => {
199-
if (errorCode(error) !== "ENOENT") throw error
197+
if (getErrorCode(error) !== "ENOENT") throw error
200198
// ENOENT also covers a dangling symlink, which must never be written through.
201199
// Only a lstat that also reports the path as absent may fall back to the
202200
// given path; a real lstat failure (EACCES, EIO) says nothing about whether
203201
// the path is a link, so falling back would write through a link we were
204202
// simply not allowed to inspect.
205203
const linkStat = await fs.lstat(absoluteFilePath).catch((lstatError: unknown) => {
206-
if (errorCode(lstatError) === "ENOENT") return undefined
204+
if (getErrorCode(lstatError) === "ENOENT") return undefined
207205
throw lstatError
208206
})
209207
if (linkStat?.isSymbolicLink()) throw error
210208
return absoluteFilePath
211209
})
212210
}
213-
/**
214-
* Distinguish "the target does not exist" from a real I/O failure (EACCES,
215-
* EIO, ...). The mode-preservation path may only fall back to the fresh-file
216-
* default on ENOENT; any other failure is propagated, otherwise a restrictive
217-
* target (0o600) would be published with the default 0o644 through the rename.
218-
*/
219-
function errorCode(error: unknown): string | undefined {
220-
return typeof error === "object" && error !== null && "code" in error
221-
? String((error as { code: unknown }).code)
222-
: undefined
223-
}
224211

225212
/**
226213
* Canonicalize the parent directory and re-join the basename. fs.realpath
@@ -245,7 +232,7 @@ async function canonicalDirKey(absoluteFilePath: string): Promise<string> {
245232
const missing: string[] = []
246233
for (;;) {
247234
const canonical = await fs.realpath(cursor).catch((error: unknown) => {
248-
if (errorCode(error) === "ENOENT") return undefined
235+
if (getErrorCode(error) === "ENOENT") return undefined
249236
throw error
250237
})
251238
if (canonical !== undefined) {
@@ -352,7 +339,7 @@ export async function safeWriteText(
352339
// staging alias reach the commit and let cleanup delete the file it was meant to
353340
// protect.
354341
const targetStat = await fs.lstat(targetPath, { bigint: true }).catch((error: unknown) => {
355-
if (errorCode(error) !== "ENOENT") {
342+
if (getErrorCode(error) !== "ENOENT") {
356343
throw new StagingPathError("Staging file could not be compared with the target", supplied)
357344
}
358345
return null
@@ -426,7 +413,7 @@ export async function safeWriteText(
426413
targetMode = fsSync.statSync(targetPath).mode & 0o777
427414
targetExists = true
428415
} catch (error: unknown) {
429-
if (errorCode(error) !== "ENOENT") throw error
416+
if (getErrorCode(error) !== "ENOENT") throw error
430417
// target does not exist yet - keep the default
431418
}
432419
// openSync's creation mode is narrowed by the process umask, so an
@@ -445,7 +432,7 @@ export async function safeWriteText(
445432
while (offset < buffer.length) {
446433
offset += fsSync.writeSync(fd, buffer, offset, buffer.length - offset)
447434
}
448-
_fsyncFile(fd)
435+
fsSync.fsyncSync(fd)
449436
} finally {
450437
fsSync.closeSync(fd)
451438
}
@@ -460,15 +447,15 @@ export async function safeWriteText(
460447
try {
461448
targetMode = fsSync.statSync(targetPath).mode & 0o777
462449
} catch (error: unknown) {
463-
if (errorCode(error) !== "ENOENT") throw error
450+
if (getErrorCode(error) !== "ENOENT") throw error
464451
// target does not exist yet - keep the temp's default mode
465452
}
466453
const fd = fsSync.openSync(tempPath, "r+")
467454
try {
468455
if (targetMode !== null) {
469456
fsSync.fchmodSync(fd, targetMode)
470457
}
471-
_fsyncFile(fd)
458+
fsSync.fsyncSync(fd)
472459
} finally {
473460
fsSync.closeSync(fd)
474461
}
@@ -505,7 +492,7 @@ export async function safeWriteText(
505492
// staging directory - so a refused publish strands neither.
506493
throw new DaclInspectionError(targetPath, "save", null)
507494
}
508-
} else if (errorCode(accessError) !== "ENOENT") {
495+
} else if (getErrorCode(accessError) !== "ENOENT") {
509496
// Not "absent": the target is there but its access rights could not be read
510497
// (EACCES, ...), so publishing would replace a file whose rights this call never
511498
// learned. Same rule as the failed save above: refuse before anything is committed.
@@ -541,7 +528,7 @@ export async function safeWriteText(
541528
// flag the staged temp file uses above.
542529
const backupFd = fsSync.openSync(backupPath, "r+")
543530
try {
544-
_fsyncFile(backupFd)
531+
fsSync.fsyncSync(backupFd)
545532
} finally {
546533
fsSync.closeSync(backupFd)
547534
}
@@ -554,7 +541,7 @@ export async function safeWriteText(
554541
}
555542
releaseBackupOnSuccess = true
556543
} catch (err: unknown) {
557-
if (errorCode(err) !== "ENOENT") throw err
544+
if (getErrorCode(err) !== "ENOENT") throw err
558545
}
559546
}
560547

@@ -567,7 +554,7 @@ export async function safeWriteText(
567554
try {
568555
const dirFd = fsSync.openSync(dirPath, "r")
569556
try {
570-
_fsyncFile(dirFd)
557+
fsSync.fsyncSync(dirFd)
571558
} finally {
572559
fsSync.closeSync(dirFd)
573560
}

‎src/utils/safeWriteJson.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ async function _resolveScopeRoot(confineTo: string): Promise<string> {
118118
// scope cannot be canonicalized at all, and continuing would build a partly
119119
// lexical root that can disagree with the canonical target - the failure has to
120120
// surface rather than decide the scope from a guess.
121-
if (_scopeErrorCode(error) !== "ENOENT") {
121+
if (getErrorCode(error) !== "ENOENT") {
122122
throw error
123123
}
124124
const missing: string[] = []
@@ -134,7 +134,7 @@ async function _resolveScopeRoot(confineTo: string): Promise<string> {
134134
const real = await fs.realpath(ancestor)
135135
return path.join(real, ...missing.reverse())
136136
} catch (innerError: unknown) {
137-
if (_scopeErrorCode(innerError) !== "ENOENT") {
137+
if (getErrorCode(innerError) !== "ENOENT") {
138138
throw innerError
139139
}
140140
}
@@ -155,12 +155,6 @@ function _assertWithinScope(requestedPath: string, candidatePath: string, scopeR
155155
}
156156
}
157157

158-
function _scopeErrorCode(error: unknown): string | undefined {
159-
return typeof error === "object" && error !== null && "code" in error
160-
? (error as { code?: string }).code
161-
: undefined
162-
}
163-
164158
/**
165159
* The scope root a caller declared, or undefined when no scope was declared.
166160
* Confinement is active whenever confineTo is DEFINED: a declared root that is

0 commit comments

Comments
 (0)