|
| 1 | +import { existsSync, readdirSync, rmSync } from 'node:fs' |
| 2 | +import path from 'node:path' |
| 3 | +import { fileURLToPath } from 'node:url' |
| 4 | + |
| 5 | +import mockFs from 'mock-fs' |
| 6 | +import { afterEach, describe, expect, it } from 'vitest' |
| 7 | + |
| 8 | +import { normalizePath } from '@socketsecurity/registry/lib/path' |
| 9 | + |
| 10 | +import { NODE_MODULES } from '../constants.mjs' |
| 11 | +import { |
| 12 | + createSupportedFilesFilter, |
| 13 | + globWithGitIgnore, |
| 14 | + pathsToGlobPatterns, |
| 15 | +} from './glob.mts' |
| 16 | + |
| 17 | +import type FileSystem from 'mock-fs/lib/filesystem' |
| 18 | + |
| 19 | +// Filter functions defined at module scope to satisfy linting rules. |
| 20 | +function filterJsonFiles(filepath: string): boolean { |
| 21 | + return filepath.endsWith('.json') |
| 22 | +} |
| 23 | + |
| 24 | +function filterTsFiles(filepath: string): boolean { |
| 25 | + return filepath.endsWith('.ts') |
| 26 | +} |
| 27 | + |
| 28 | +const __filename = fileURLToPath(import.meta.url) |
| 29 | +const __dirname = path.dirname(__filename) |
| 30 | + |
| 31 | +const rootNmPath = path.join(__dirname, '../..', NODE_MODULES) |
| 32 | +const mockFixturePath = normalizePath(path.join(__dirname, 'glob-mock')) |
| 33 | +const mockNmPath = normalizePath(rootNmPath) |
| 34 | + |
| 35 | +// Remove broken symlinks in node_modules before loading to prevent mock-fs errors. |
| 36 | +function cleanupBrokenSymlinks(dirPath: string): void { |
| 37 | + try { |
| 38 | + if (!existsSync(dirPath)) { |
| 39 | + return |
| 40 | + } |
| 41 | + const entries = readdirSync(dirPath, { withFileTypes: true }) |
| 42 | + for (const entry of entries) { |
| 43 | + const fullPath = path.join(dirPath, entry.name) |
| 44 | + try { |
| 45 | + if (entry.isSymbolicLink() && !existsSync(fullPath)) { |
| 46 | + // Symlink exists but target does not, remove it. |
| 47 | + rmSync(fullPath, { force: true }) |
| 48 | + } else if (entry.isDirectory()) { |
| 49 | + // Recursively check subdirectories. |
| 50 | + cleanupBrokenSymlinks(fullPath) |
| 51 | + } |
| 52 | + } catch { |
| 53 | + // Ignore errors for individual entries. |
| 54 | + } |
| 55 | + } |
| 56 | + } catch { |
| 57 | + // If we cannot read the directory, skip cleanup. |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// Clean up broken symlinks before loading node_modules. |
| 62 | +cleanupBrokenSymlinks(rootNmPath) |
| 63 | + |
| 64 | +// Load node_modules with error handling for any remaining issues. |
| 65 | +const mockedNmCallback = (() => { |
| 66 | + try { |
| 67 | + return mockFs.load(rootNmPath) |
| 68 | + } catch (e) { |
| 69 | + // If loading fails due to broken symlinks or missing files, return empty mock. |
| 70 | + console.warn( |
| 71 | + `Warning: Failed to load node_modules for mock-fs: ${e instanceof Error ? e.message : String(e)}`, |
| 72 | + ) |
| 73 | + return {} |
| 74 | + } |
| 75 | +})() |
| 76 | + |
| 77 | +function mockTestFs(config: FileSystem.DirectoryItems) { |
| 78 | + return mockFs({ |
| 79 | + ...config, |
| 80 | + [mockNmPath]: mockedNmCallback, |
| 81 | + }) |
| 82 | +} |
| 83 | + |
| 84 | +describe('glob utilities', () => { |
| 85 | + afterEach(() => { |
| 86 | + mockFs.restore() |
| 87 | + }) |
| 88 | + |
| 89 | + describe('globWithGitIgnore()', () => { |
| 90 | + it('should find files matching glob patterns', async () => { |
| 91 | + mockTestFs({ |
| 92 | + [`${mockFixturePath}/package.json`]: '{}', |
| 93 | + [`${mockFixturePath}/src/index.ts`]: '', |
| 94 | + }) |
| 95 | + |
| 96 | + const results = await globWithGitIgnore(['**/*.json'], { |
| 97 | + cwd: mockFixturePath, |
| 98 | + }) |
| 99 | + |
| 100 | + expect(results.map(normalizePath)).toEqual([ |
| 101 | + `${mockFixturePath}/package.json`, |
| 102 | + ]) |
| 103 | + }) |
| 104 | + |
| 105 | + it('should respect .gitignore files', async () => { |
| 106 | + mockTestFs({ |
| 107 | + [`${mockFixturePath}/.gitignore`]: 'ignored/**', |
| 108 | + [`${mockFixturePath}/package.json`]: '{}', |
| 109 | + [`${mockFixturePath}/ignored/package.json`]: '{}', |
| 110 | + [`${mockFixturePath}/included/package.json`]: '{}', |
| 111 | + }) |
| 112 | + |
| 113 | + const results = await globWithGitIgnore(['**/*.json'], { |
| 114 | + cwd: mockFixturePath, |
| 115 | + }) |
| 116 | + |
| 117 | + expect(results.map(normalizePath).sort()).toEqual([ |
| 118 | + `${mockFixturePath}/included/package.json`, |
| 119 | + `${mockFixturePath}/package.json`, |
| 120 | + ]) |
| 121 | + }) |
| 122 | + |
| 123 | + it('should handle negated patterns in .gitignore', async () => { |
| 124 | + mockTestFs({ |
| 125 | + [`${mockFixturePath}/.gitignore`]: 'ignored/**\n!ignored/keep.json', |
| 126 | + [`${mockFixturePath}/package.json`]: '{}', |
| 127 | + [`${mockFixturePath}/ignored/excluded.json`]: '{}', |
| 128 | + [`${mockFixturePath}/ignored/keep.json`]: '{}', |
| 129 | + }) |
| 130 | + |
| 131 | + const results = await globWithGitIgnore(['**/*.json'], { |
| 132 | + cwd: mockFixturePath, |
| 133 | + }) |
| 134 | + |
| 135 | + // The negated pattern should allow keep.json to be included. |
| 136 | + expect(results.map(normalizePath).sort()).toEqual([ |
| 137 | + `${mockFixturePath}/ignored/keep.json`, |
| 138 | + `${mockFixturePath}/package.json`, |
| 139 | + ]) |
| 140 | + }) |
| 141 | + |
| 142 | + it('should apply filter function during streaming to reduce memory', async () => { |
| 143 | + // Create a mock filesystem with many files. |
| 144 | + const files: FileSystem.DirectoryItems = {} |
| 145 | + const fileCount = 100 |
| 146 | + for (let i = 0; i < fileCount; i += 1) { |
| 147 | + files[`${mockFixturePath}/file${i}.txt`] = 'content' |
| 148 | + files[`${mockFixturePath}/file${i}.json`] = '{}' |
| 149 | + } |
| 150 | + // Add a gitignore with negated pattern to trigger the streaming path. |
| 151 | + files[`${mockFixturePath}/.gitignore`] = 'temp/\n!temp/keep.json' |
| 152 | + mockTestFs(files) |
| 153 | + |
| 154 | + const results = await globWithGitIgnore(['**/*'], { |
| 155 | + cwd: mockFixturePath, |
| 156 | + filter: filterJsonFiles, |
| 157 | + }) |
| 158 | + |
| 159 | + // Should only include .json files (100 files). |
| 160 | + expect(results).toHaveLength(fileCount) |
| 161 | + for (const result of results) { |
| 162 | + expect(result.endsWith('.json')).toBe(true) |
| 163 | + } |
| 164 | + }) |
| 165 | + |
| 166 | + it('should apply filter without negated patterns', async () => { |
| 167 | + mockTestFs({ |
| 168 | + [`${mockFixturePath}/package.json`]: '{}', |
| 169 | + [`${mockFixturePath}/src/index.ts`]: '', |
| 170 | + [`${mockFixturePath}/src/utils.ts`]: '', |
| 171 | + [`${mockFixturePath}/readme.md`]: '', |
| 172 | + }) |
| 173 | + |
| 174 | + const results = await globWithGitIgnore(['**/*'], { |
| 175 | + cwd: mockFixturePath, |
| 176 | + filter: filterTsFiles, |
| 177 | + }) |
| 178 | + |
| 179 | + expect(results.map(normalizePath).sort()).toEqual([ |
| 180 | + `${mockFixturePath}/src/index.ts`, |
| 181 | + `${mockFixturePath}/src/utils.ts`, |
| 182 | + ]) |
| 183 | + }) |
| 184 | + |
| 185 | + it('should combine filter with negated gitignore patterns', async () => { |
| 186 | + mockTestFs({ |
| 187 | + [`${mockFixturePath}/.gitignore`]: 'build/**\n!build/manifest.json', |
| 188 | + [`${mockFixturePath}/package.json`]: '{}', |
| 189 | + [`${mockFixturePath}/src/index.ts`]: '', |
| 190 | + [`${mockFixturePath}/build/output.js`]: '', |
| 191 | + [`${mockFixturePath}/build/manifest.json`]: '{}', |
| 192 | + }) |
| 193 | + |
| 194 | + const results = await globWithGitIgnore(['**/*'], { |
| 195 | + cwd: mockFixturePath, |
| 196 | + filter: filterJsonFiles, |
| 197 | + }) |
| 198 | + |
| 199 | + // Should include package.json and the negated build/manifest.json, but not build/output.js. |
| 200 | + expect(results.map(normalizePath).sort()).toEqual([ |
| 201 | + `${mockFixturePath}/build/manifest.json`, |
| 202 | + `${mockFixturePath}/package.json`, |
| 203 | + ]) |
| 204 | + }) |
| 205 | + }) |
| 206 | + |
| 207 | + describe('createSupportedFilesFilter()', () => { |
| 208 | + it('should create a filter function matching supported file patterns', () => { |
| 209 | + const supportedFiles = { |
| 210 | + npm: { |
| 211 | + packagejson: { pattern: 'package.json' }, |
| 212 | + packagelockjson: { pattern: 'package-lock.json' }, |
| 213 | + }, |
| 214 | + } |
| 215 | + |
| 216 | + const filter = createSupportedFilesFilter(supportedFiles) |
| 217 | + |
| 218 | + expect(filter('/path/to/package.json')).toBe(true) |
| 219 | + expect(filter('/path/to/package-lock.json')).toBe(true) |
| 220 | + expect(filter('/path/to/random.txt')).toBe(false) |
| 221 | + expect(filter('/path/to/nested/package.json')).toBe(true) |
| 222 | + }) |
| 223 | + }) |
| 224 | + |
| 225 | + describe('pathsToGlobPatterns()', () => { |
| 226 | + it('should convert "." to "**/*"', () => { |
| 227 | + expect(pathsToGlobPatterns(['.'])).toEqual(['**/*']) |
| 228 | + expect(pathsToGlobPatterns(['./'])).toEqual(['**/*']) |
| 229 | + }) |
| 230 | + |
| 231 | + it('should append "/**/*" to directory paths', () => { |
| 232 | + mockTestFs({ |
| 233 | + [`${mockFixturePath}/subdir`]: { |
| 234 | + 'file.txt': '', |
| 235 | + }, |
| 236 | + }) |
| 237 | + |
| 238 | + // The function checks if path is a directory using isDirSync. |
| 239 | + const result = pathsToGlobPatterns(['subdir'], mockFixturePath) |
| 240 | + expect(result).toEqual(['subdir/**/*']) |
| 241 | + }) |
| 242 | + |
| 243 | + it('should keep file paths unchanged', () => { |
| 244 | + mockTestFs({ |
| 245 | + [`${mockFixturePath}/file.txt`]: '', |
| 246 | + }) |
| 247 | + |
| 248 | + const result = pathsToGlobPatterns(['file.txt'], mockFixturePath) |
| 249 | + expect(result).toEqual(['file.txt']) |
| 250 | + }) |
| 251 | + }) |
| 252 | +}) |
0 commit comments