Skip to content
This repository was archived by the owner on Apr 8, 2026. It is now read-only.

Commit df254e3

Browse files
authored
Exclude non file paths to avoid reading a directory (#64)
1 parent 2852eea commit df254e3

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

src/lib/file/readGit.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,24 @@
11
import { exec } from '../util/exec';
22
import { readGit } from './readGit';
3+
import fs from 'fs';
34

45
jest.mock('../util/exec');
6+
jest.mock('fs');
7+
const fsMocked = jest.mocked<any>(fs);
58
const execFileMock = exec as jest.Mock;
69

710
describe('readGit', () => {
11+
beforeEach(() => {
12+
fsMocked.statSync.mockImplementation((path: any) => {
13+
return {
14+
isFile() {
15+
if (!path) { return false; }
16+
return true;
17+
},
18+
};
19+
});
20+
});
21+
822
it('should return the expected list of files when called', async () => {
923
execFileMock.mockResolvedValue({ stdout: 'foo\nbar\n', stderr: '' });
1024

@@ -25,4 +39,20 @@ describe('readGit', () => {
2539
}),
2640
);
2741
});
42+
43+
it('should not return non-files', async () => {
44+
execFileMock.mockResolvedValue({ stdout: 'foo\nbar\nbaz\n', stderr: '' });
45+
fsMocked.statSync.mockImplementation((path: any) => {
46+
return {
47+
isFile() {
48+
if (!path || path === 'baz') { return false; }
49+
return true;
50+
},
51+
};
52+
});
53+
54+
const result = await readGit('some/dir');
55+
56+
expect(result).toStrictEqual(['foo', 'bar']);
57+
});
2858
});

src/lib/file/readGit.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,21 @@
1+
import fs, { Stats } from 'fs';
12
import { exec } from '../util/exec';
23

34
export const readGit = async (dir: string): Promise<string[]> => {
45
const { stdout } = await exec('git ls-files', { cwd: dir });
5-
return stdout.split('\n').filter(x => !!x);
6+
return stdout.split('\n').filter((filePath) => {
7+
let stats: Stats | undefined = undefined;
8+
try {
9+
stats = fs.statSync(filePath);
10+
} catch (e) {
11+
return false; // Ignore missing files and symlinks
12+
}
13+
14+
// Ignore if path is not a file
15+
if (!stats.isFile()){
16+
return false;
17+
}
18+
19+
return true;
20+
});
621
};

0 commit comments

Comments
 (0)