Skip to content

Commit 7e33313

Browse files
unhappychoiceclaude
andcommitted
refactor(server): extract shared errno predicates into utils
Deduplicate the permission-error handling introduced for inaccessible directories: - Move the near-identical `isUnreadableDirectoryError` (filetree) and `isPermissionError` (watcher) predicates into `src/utils/errors.ts`, built on a shared `hasErrnoCode` helper. - Extract the copy-pasted permission branch of both chokidar `error` handlers into `logSkippedWatchTarget`. - Add unit tests for the new helpers. No behavior change. Co-Authored-By: Claude Opus 5 <[email protected]>
1 parent 1953b77 commit 7e33313

4 files changed

Lines changed: 78 additions & 38 deletions

File tree

‎src/server/routes/filetree.ts‎

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import simpleGit, { SimpleGit, StatusResult, FileStatusResult } from 'simple-git
55
import { EXCLUDED_DIRECTORIES } from '../../constants';
66
import { ServerContext } from '../context';
77
import { logger } from '../../utils/logger';
8+
import { isUnreadableDirectoryError } from '../../utils/errors';
89
import { resolveGlobPatterns } from '../../utils/glob';
910

1011
type FileTreeItem = { path: string, status: string, isDirectory?: boolean } | { [key: string]: FileTree };
@@ -40,20 +41,6 @@ const shouldIncludeEntry = (entry: Dirent): boolean => {
4041
return !isDotFileOrDirectory(entry.name) && !EXCLUDED_DIRECTORIES.includes(entry.name);
4142
};
4243

43-
// Errors that mean "this directory can't be enumerated" — skip it and keep going
44-
// rather than failing the whole file tree. EACCES/EPERM cover permission denials;
45-
// ENOENT/ENOTDIR cover races where the entry vanishes or isn't a directory.
46-
const UNREADABLE_DIRECTORY_ERROR_CODES = ['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR'];
47-
48-
const isUnreadableDirectoryError = (error: unknown): boolean => {
49-
return Boolean(
50-
error &&
51-
typeof error === 'object' &&
52-
'code' in error &&
53-
UNREADABLE_DIRECTORY_ERROR_CODES.includes((error as NodeJS.ErrnoException).code as string),
54-
);
55-
};
56-
5744
const buildFileTreeFromPatterns = (
5845
filePatterns: string[],
5946
gitStatus: StatusResult | null,

‎src/server/watcher.ts‎

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as http from 'http';
44
import path from 'path';
55
import { WebSocket, WebSocketServer } from 'ws';
66
import { logger } from '../utils/logger';
7+
import { isPermissionError } from '../utils/errors';
78
import { EXCLUDED_DIRECTORIES } from '../constants';
89
import { ServerContext } from './context';
910

@@ -67,14 +68,11 @@ const attachTreeReloadHandlers = (watcher: FSWatcher, wss: WebSocketServer): voi
6768
});
6869
};
6970

70-
// A permission error on a single path is non-fatal: chokidar keeps watching
71-
// everything else, so we just skip that path instead of tearing down the watcher.
72-
const isPermissionError = (error: unknown): boolean => {
73-
return Boolean(
74-
error &&
75-
typeof error === 'object' &&
76-
'code' in error &&
77-
['EACCES', 'EPERM'].includes((error as NodeJS.ErrnoException).code as string),
71+
const logSkippedWatchTarget = (error: unknown, directory: string): void => {
72+
const target = describeWatchTarget(error, directory);
73+
logger.log(
74+
'Livereload',
75+
`🔒 Can't watch "${target}" (permission denied); live-reload skipped for it, others still watched.`,
7876
);
7977
};
8078

@@ -108,14 +106,7 @@ const setupDirectoryWatcher = (directory: string, wss: WebSocketServer): FSWatch
108106
attachTreeReloadHandlers(watcher, wss);
109107

110108
watcher.on('error', (error) => {
111-
if (isPermissionError(error)) {
112-
const target = describeWatchTarget(error, directory);
113-
logger.log(
114-
'Livereload',
115-
`🔒 Can't watch "${target}" (permission denied); live-reload skipped for it, others still watched.`,
116-
);
117-
return;
118-
}
109+
if (isPermissionError(error)) return logSkippedWatchTarget(error, directory);
119110

120111
watcher.unwatch(directory);
121112
watcher.close()
@@ -147,14 +138,8 @@ const setupFilePatternWatcher = (context: ServerContext, wss: WebSocketServer):
147138
attachTreeReloadHandlers(watcher, wss);
148139

149140
watcher.on('error', (error) => {
150-
if (isPermissionError(error)) {
151-
const target = describeWatchTarget(error, directory);
152-
logger.log(
153-
'Livereload',
154-
`🔒 Can't watch "${target}" (permission denied); live-reload skipped for it, others still watched.`,
155-
);
156-
return;
157-
}
141+
if (isPermissionError(error)) return logSkippedWatchTarget(error, directory);
142+
158143
watcher.close()
159144
.then(() => logger.log('Livereload', 'File pattern watcher closed'));
160145
logger.error('🚫 Error watching files:', error);

‎src/utils/errors.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const PERMISSION_ERROR_CODES = ['EACCES', 'EPERM'];
2+
3+
// ENOENT/ENOTDIR cover races where the entry vanishes or isn't a directory anymore.
4+
const UNREADABLE_DIRECTORY_ERROR_CODES = [...PERMISSION_ERROR_CODES, 'ENOENT', 'ENOTDIR'];
5+
6+
export const hasErrnoCode = (error: unknown, codes: string[]): boolean => {
7+
return typeof error === 'object'
8+
&& error !== null
9+
&& 'code' in error
10+
&& codes.includes((error as NodeJS.ErrnoException).code ?? '');
11+
};
12+
13+
// A permission error on a single path is non-fatal: chokidar keeps watching
14+
// everything else, so we just skip that path instead of tearing down the watcher.
15+
export const isPermissionError = (error: unknown): boolean =>
16+
hasErrnoCode(error, PERMISSION_ERROR_CODES);
17+
18+
// Errors that mean "this directory can't be enumerated" - skip it and keep going
19+
// rather than failing the whole file tree.
20+
export const isUnreadableDirectoryError = (error: unknown): boolean =>
21+
hasErrnoCode(error, UNREADABLE_DIRECTORY_ERROR_CODES);

‎test/unit/utils/errors.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { hasErrnoCode, isPermissionError, isUnreadableDirectoryError } from '../../../src/utils/errors';
2+
3+
const errorWithCode = (code: string): NodeJS.ErrnoException =>
4+
Object.assign(new Error(code), { code });
5+
6+
describe('hasErrnoCode', () => {
7+
it('should return true when the error carries one of the given codes', () => {
8+
expect(hasErrnoCode(errorWithCode('EMFILE'), ['EMFILE', 'EACCES'])).toBe(true);
9+
});
10+
11+
it('should return false for a different code', () => {
12+
expect(hasErrnoCode(errorWithCode('EMFILE'), ['EACCES'])).toBe(false);
13+
});
14+
15+
it('should return false for an error without a code', () => {
16+
expect(hasErrnoCode(new Error('boom'), ['EACCES'])).toBe(false);
17+
});
18+
19+
it('should return false when the code property is undefined', () => {
20+
expect(hasErrnoCode(Object.assign(new Error('boom'), { code: undefined }), ['EACCES'])).toBe(false);
21+
});
22+
23+
it('should return false for non-error values', () => {
24+
expect(hasErrnoCode(null, ['EACCES'])).toBe(false);
25+
expect(hasErrnoCode('EACCES', ['EACCES'])).toBe(false);
26+
});
27+
});
28+
29+
describe('isPermissionError', () => {
30+
it.each(['EACCES', 'EPERM'])('should return true for %s', (code) => {
31+
expect(isPermissionError(errorWithCode(code))).toBe(true);
32+
});
33+
34+
it.each(['ENOENT', 'ENOTDIR', 'EMFILE'])('should return false for %s', (code) => {
35+
expect(isPermissionError(errorWithCode(code))).toBe(false);
36+
});
37+
});
38+
39+
describe('isUnreadableDirectoryError', () => {
40+
it.each(['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR'])('should return true for %s', (code) => {
41+
expect(isUnreadableDirectoryError(errorWithCode(code))).toBe(true);
42+
});
43+
44+
it('should return false for an unrelated code', () => {
45+
expect(isUnreadableDirectoryError(errorWithCode('EMFILE'))).toBe(false);
46+
});
47+
});

0 commit comments

Comments
 (0)