# All files / src/lib/quality-validator/utils fileSystem.js

0% Statements 0/300
0% Branches 0/1
0% Functions 0/1
0% Lines 0/300

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301

     /**
     * File system utilities for Quality Validator
     * Handles file reading, writing, and path resolution
     */
    import * as fs from 'fs';
    import * as path from 'path';
    import { AnalysisErrorClass } from '../types/index.js';
    import { logger } from './logger.js';
    /**
     * Get the project root directory
     */
    export function getProjectRoot() {
        return process.cwd();
    }
    /**
     * Resolve a file path relative to project root
     */
    export function resolvePath(filePath) {
        const normalized = path.normalize(filePath);
        // Security check: prevent directory traversal
        if (normalized.includes('..')) {
            throw new AnalysisErrorClass('Directory traversal detected', `Path contains '..': ${filePath}`);
        }
        const resolved = path.resolve(getProjectRoot(), normalized);
        const projectRoot = getProjectRoot();
        // Ensure path is within project
        if (!resolved.startsWith(projectRoot)) {
            throw new AnalysisErrorClass('Path outside project root', `Attempted to access: ${resolved}`);
        }
        return resolved;
    }
    /**
     * Normalize a file path relative to project root
     */
    export function normalizeFilePath(filePath) {
        const projectRoot = getProjectRoot();
        const resolved = resolvePath(filePath);
        return path.relative(projectRoot, resolved);
    }
    /**
     * Check if a path exists
     */
    export function pathExists(filePath) {
        try {
            return fs.existsSync(resolvePath(filePath));
        }
        catch {
            return false;
        }
    }
    /**
     * Check if path is a file
     */
    export function isFile(filePath) {
        try {
            const stat = fs.statSync(resolvePath(filePath));
            return stat.isFile();
        }
        catch {
            return false;
        }
    }
    /**
     * Check if path is a directory
     */
    export function isDirectory(dirPath) {
        try {
            const stat = fs.statSync(resolvePath(dirPath));
            return stat.isDirectory();
        }
        catch {
            return false;
        }
    }
    /**
     * Read a file as text
     */
    export function readFile(filePath) {
        try {
            const resolved = resolvePath(filePath);
            return fs.readFileSync(resolved, 'utf-8');
        }
        catch (error) {
            throw new AnalysisErrorClass(`Failed to read file: ${filePath}`, error.message);
        }
    }
    /**
     * Write a file
     */
    export function writeFile(filePath, content) {
        try {
            const resolved = resolvePath(filePath);
            const dir = path.dirname(resolved);
            // Create directory if it doesn't exist
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
            fs.writeFileSync(resolved, content, 'utf-8');
            logger.debug(`Written file: ${filePath}`);
        }
        catch (error) {
            throw new AnalysisErrorClass(`Failed to write file: ${filePath}`, error.message);
        }
    }
    /**
     * Read a JSON file
     */
    export function readJsonFile(filePath) {
        try {
            const content = readFile(filePath);
            return JSON.parse(content);
        }
        catch (error) {
            throw new AnalysisErrorClass(`Failed to parse JSON file: ${filePath}`, error.message);
        }
    }
    /**
     * Write a JSON file
     */
    export function writeJsonFile(filePath, data, pretty = true) {
        try {
            const content = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
            writeFile(filePath, content);
        }
        catch (error) {
            throw new AnalysisErrorClass(`Failed to write JSON file: ${filePath}`, error.message);
        }
    }
    /**
     * List files in directory recursively
     */
    export function listFilesRecursive(dirPath, extensions, excludePatterns = []) {
        const results = [];
        try {
            const resolved = resolvePath(dirPath);
            const walk = (currentPath) => {
                const entries = fs.readdirSync(currentPath, { withFileTypes: true });
                for (const entry of entries) {
                    const fullPath = path.join(currentPath, entry.name);
                    const relativePath = normalizeFilePath(fullPath);
                    // Check if should exclude
                    if (shouldExclude(relativePath, excludePatterns)) {
                        continue;
                    }
                    if (entry.isFile()) {
                        if (!extensions || extensions.some((ext) => entry.name.endsWith(ext))) {
                            results.push(relativePath);
                        }
                    }
                    else if (entry.isDirectory()) {
                        walk(fullPath);
                    }
                }
            };
            walk(resolved);
        }
        catch (error) {
            logger.warn(`Failed to list directory: ${dirPath}`, { error: error.message });
        }
        return results;
    }
    /**
     * Get all TypeScript/TSX source files
     */
    export function getSourceFiles(excludePatterns = []) {
        return listFilesRecursive('src', ['.ts', '.tsx'], excludePatterns);
    }
    /**
     * Get all test files
     */
    export function getTestFiles(excludePatterns = []) {
        const defaults = ['**/*.spec.ts', '**/*.spec.tsx', '**/*.test.ts', '**/*.test.tsx', '**/__tests__/**'];
        const patterns = [...defaults, ...excludePatterns];
        return listFilesRecursive('src', ['.ts', '.tsx'], patterns);
    }
    /**
     * Check if a file path matches any exclude pattern
     */
    export function shouldExclude(filePath, patterns) {
        for (const pattern of patterns) {
            if (matchesPattern(filePath, pattern)) {
                return true;
            }
        }
        return false;
    }
    /**
     * Simple glob pattern matching
     */
    export function matchesPattern(filePath, pattern) {
        // Convert glob pattern to regex
        const regexPattern = pattern
            .replace(/\./g, '\\.')
            .replace(/\*/g, '.*')
            .replace(/\?/g, '.');
        const regex = new RegExp(`^${regexPattern}$`);
        return regex.test(filePath);
    }
    /**
     * Get the number of lines in a file
     */
    export function getLineCount(filePath) {
        try {
            const content = readFile(filePath);
            return content.split('\n').length;
        }
        catch {
            return 0;
        }
    }
    /**
     * Get lines from a file between start and end
     */
    export function getLines(filePath, startLine, endLine) {
        try {
            const content = readFile(filePath);
            const lines = content.split('\n');
            return lines.slice(Math.max(0, startLine - 1), Math.min(lines.length, endLine));
        }
        catch {
            return [];
        }
    }
    /**
     * Create a directory if it doesn't exist
     */
    export function ensureDirectory(dirPath) {
        try {
            const resolved = resolvePath(dirPath);
            if (!fs.existsSync(resolved)) {
                fs.mkdirSync(resolved, { recursive: true });
                logger.debug(`Created directory: ${dirPath}`);
            }
        }
        catch (error) {
            throw new AnalysisErrorClass(`Failed to create directory: ${dirPath}`, error.message);
        }
    }
    /**
     * Delete a file or directory
     */
    export function deletePathSync(filePath) {
        try {
            const resolved = resolvePath(filePath);
            if (fs.existsSync(resolved)) {
                const stat = fs.statSync(resolved);
                if (stat.isDirectory()) {
                    fs.rmSync(resolved, { recursive: true, force: true });
                }
                else {
                    fs.unlinkSync(resolved);
                }
                logger.debug(`Deleted: ${filePath}`);
            }
        }
        catch (error) {
            throw new AnalysisErrorClass(`Failed to delete: ${filePath}`, error.message);
        }
    }
    /**
     * Get git root directory (if in git repo)
     */
    export function getGitRoot() {
        try {
            let current = getProjectRoot();
            while (current !== path.dirname(current)) {
                if (fs.existsSync(path.join(current, '.git'))) {
                    return current;
                }
                current = path.dirname(current);
            }
        }
        catch {
            // Not in a git repo
        }
        return null;
    }
    /**
     * Get list of changed files in git
     */
    export function getChangedFiles(since) {
        try {
            const { execSync } = require('child_process');
            const cmd = since
                ? `git diff --name-only ${since}`
                : 'git diff --name-only HEAD~1';
            const output = execSync(cmd, {
                cwd: getProjectRoot(),
                encoding: 'utf-8',
            });
            return output
                .split('\n')
                .filter((line) => line.trim().length > 0)
                .map((line) => line.trim());
        }
        catch {
            logger.warn('Failed to get changed files from git');
            return [];
        }
    }