|
| 1 | +import { readFile } from 'node:fs/promises'; |
| 2 | +import path from 'node:path'; |
| 3 | + |
| 4 | +import { discoverFiles } from './glob-discovery'; |
| 5 | +import { findPythonVersionMatches, type VersionMatch } from './patterns/python-version'; |
| 6 | + |
| 7 | +export interface ScanOptions { |
| 8 | + /** Absolute root directory to scan. */ |
| 9 | + root: string; |
| 10 | + /** Glob patterns to include relative to the root. */ |
| 11 | + patterns: string[]; |
| 12 | + /** Additional ignore patterns. */ |
| 13 | + ignore?: string[]; |
| 14 | + /** Follow symbolic links. Defaults to false. */ |
| 15 | + followSymbolicLinks?: boolean; |
| 16 | +} |
| 17 | + |
| 18 | +export interface ScanResult { |
| 19 | + filesScanned: number; |
| 20 | + matches: VersionMatch[]; |
| 21 | +} |
| 22 | + |
| 23 | +async function readFileSafe(filePath: string): Promise<string | null> { |
| 24 | + try { |
| 25 | + return await readFile(filePath, 'utf8'); |
| 26 | + } catch (error) { |
| 27 | + const err = error as { code?: string }; |
| 28 | + if (err && err.code === 'ENOENT') { |
| 29 | + return null; |
| 30 | + } |
| 31 | + throw error; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +export async function scanForPythonVersions(options: ScanOptions): Promise<ScanResult> { |
| 36 | + const { root, patterns, ignore, followSymbolicLinks } = options; |
| 37 | + const relativeFiles = await discoverFiles({ |
| 38 | + root, |
| 39 | + patterns, |
| 40 | + ignore, |
| 41 | + followSymbolicLinks, |
| 42 | + }); |
| 43 | + |
| 44 | + const matches: VersionMatch[] = []; |
| 45 | + let filesScanned = 0; |
| 46 | + |
| 47 | + for (const relative of relativeFiles) { |
| 48 | + const absolute = path.join(root, relative); |
| 49 | + const content = await readFileSafe(absolute); |
| 50 | + if (content === null) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + filesScanned += 1; |
| 55 | + const fileMatches = findPythonVersionMatches(relative, content); |
| 56 | + matches.push( |
| 57 | + ...fileMatches.map((match) => ({ |
| 58 | + ...match, |
| 59 | + file: relative, |
| 60 | + })), |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + matches.sort((a, b) => { |
| 65 | + const fileCompare = a.file.localeCompare(b.file); |
| 66 | + if (fileCompare !== 0) { |
| 67 | + return fileCompare; |
| 68 | + } |
| 69 | + if (a.line !== b.line) { |
| 70 | + return a.line - b.line; |
| 71 | + } |
| 72 | + if (a.column !== b.column) { |
| 73 | + return a.column - b.column; |
| 74 | + } |
| 75 | + return 0; |
| 76 | + }); |
| 77 | + |
| 78 | + return { filesScanned, matches }; |
| 79 | +} |
0 commit comments