All files / src/ignore ignore-manager.js

56.79% Statements 46/81
55.17% Branches 16/29
50% Functions 6/12
56.79% Lines 46/81

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 2992x 2x 2x             1x 1x 1x             1x                                                                                                                                                                                                   173x 173x   173x 111x     62x     62x     62x 62x     62x     62x 540x 540x     62x 62x             602x   602x 602x 62x 62x 62x                     62x 62x   62x 3348x     3348x 1178x       2170x 2170x     2170x         2170x     62x             173x 173x 173x     173x       173x 173x   173x                                                                                                                                                                               2x  
const fs = require('fs-extra');
const path = require('path');
const ignore = require('ignore');
 
/**
 * Quản lý ignore patterns theo chuẩn Git
 */
class IgnoreManager {
  constructor(projectPath) {
    this.projectPath = projectPath;
    this.ignoreInstances = new Map(); // Cache ignore instances theo thư mục
    this.defaultIgnores = this.getDefaultIgnores();
  }
 
  /**
   * Lấy danh sách ignore patterns mặc định
   */
  getDefaultIgnores() {
    return [
      // Node.js
      'node_modules/',
      'npm-debug.log*',
      'yarn-debug.log*',
      'yarn-error.log*',
      '.npm',
      '.yarn/',
      
      // Build outputs
      'dist/',
      'build/',
      'out/',
      'target/',
      'bin/',
      'obj/',
      
      // IDE và Editor
      '.vscode/',
      '.idea/',
      '*.swp',
      '*.swo',
      '*~',
      '.DS_Store',
      'Thumbs.db',
      
      // Logs
      'logs/',
      '*.log',
      
      // Environment files
      '.env',
      '.env.local',
      '.env.development.local',
      '.env.test.local',
      '.env.production.local',
      
      // Cache directories
      '.cache/',
      '.parcel-cache/',
      '.next/',
      '.nuxt/',
      
      // Coverage reports
      'coverage/',
      '*.lcov',
      
      // Dependency directories
      'bower_components/',
      'jspm_packages/',
      
      // Java
      '*.class',
      '*.jar',
      '*.war',
      '*.ear',
      '.gradle/',
      
      // Python
      '__pycache__/',
      '*.py[cod]',
      '*$py.class',
      '*.so',
      '.Python',
      'env/',
      'venv/',
      '.venv/',
      'pip-log.txt',
      'pip-delete-this-directory.txt',
      
      // .NET
      '[Bb]in/',
      '[Oo]bj/',
      '*.user',
      '*.suo',
      '*.userosscache',
      '*.sln.docstates',
      
      // Temporary files
      '*.tmp',
      '*.temp',
      '*.bak',
      '*.backup',
      
      // OS generated files
      '.DS_Store?',
      'ehthumbs.db',
      'Icon?',
      
      // VG Coder output
      'vg-output/'
    ];
  }
 
  /**
   * Lấy ignore instance cho một thư mục cụ thể
   */
  async getIgnoreInstance(dirPath) {
    const relativePath = path.relative(this.projectPath, dirPath);
    const cacheKey = relativePath || '.';
    
    if (this.ignoreInstances.has(cacheKey)) {
      return this.ignoreInstances.get(cacheKey);
    }
 
    const ig = ignore();
    
    // Thêm default ignores
    ig.add(this.defaultIgnores);
    
    // Đọc .gitignore từ root đến thư mục hiện tại
    const pathParts = relativePath ? relativePath.split(path.sep) : [];
    let currentPath = this.projectPath;
    
    // Đọc .gitignore từ root
    await this.addGitignoreFromPath(ig, currentPath);
    
    // Đọc .gitignore từ các thư mục con theo thứ tự
    for (const part of pathParts) {
      currentPath = path.join(currentPath, part);
      await this.addGitignoreFromPath(ig, currentPath);
    }
    
    this.ignoreInstances.set(cacheKey, ig);
    return ig;
  }
 
  /**
   * Thêm patterns từ .gitignore file
   */
  async addGitignoreFromPath(ig, dirPath) {
    const gitignorePath = path.join(dirPath, '.gitignore');
    
    try {
      if (await fs.pathExists(gitignorePath)) {
        const content = await fs.readFile(gitignorePath, 'utf8');
        const patterns = this.parseGitignoreContent(content, dirPath);
        ig.add(patterns);
      }
    } catch (error) {
      // Ignore errors reading .gitignore files
    }
  }
 
  /**
   * Parse nội dung .gitignore
   */
  parseGitignoreContent(content, basePath) {
    const lines = content.split('\n');
    const patterns = [];
    
    for (let line of lines) {
      line = line.trim();
      
      // Skip empty lines và comments
      if (!line || line.startsWith('#')) {
        continue;
      }
      
      // Xử lý relative path từ basePath
      const relativePath = path.relative(this.projectPath, basePath);
      Iif (relativePath && !line.startsWith('/')) {
        // Nếu pattern không bắt đầu bằng /, thêm relative path
        line = path.posix.join(relativePath, line);
      } else Iif (line.startsWith('/')) {
        // Remove leading slash cho absolute patterns
        line = line.substring(1);
      }
      
      patterns.push(line);
    }
    
    return patterns;
  }
 
  /**
   * Kiểm tra xem một file/thư mục có bị ignore không
   */
  async shouldIgnore(filePath) {
    try {
      const absolutePath = path.resolve(this.projectPath, filePath);
      const relativePath = path.relative(this.projectPath, absolutePath);
      
      // Không ignore nếu file nằm ngoài project
      Iif (relativePath.startsWith('..')) {
        return false;
      }
      
      const dirPath = path.dirname(absolutePath);
      const ig = await this.getIgnoreInstance(dirPath);
      
      return ig.ignores(relativePath);
    } catch (error) {
      return false;
    }
  }
 
  /**
   * Lọc danh sách files/directories
   */
  async filterIgnored(items) {
    const results = [];
    
    for (const item of items) {
      const shouldIgnore = await this.shouldIgnore(item);
      if (!shouldIgnore) {
        results.push(item);
      }
    }
    
    return results;
  }
 
  /**
   * Lấy tất cả patterns đang được áp dụng cho một thư mục
   */
  async getAppliedPatterns(dirPath = this.projectPath) {
    const ig = await this.getIgnoreInstance(dirPath);
    return {
      default: this.defaultIgnores,
      gitignore: ig._rules.filter(rule => !this.defaultIgnores.includes(rule.origin))
    };
  }
 
  /**
   * Kiểm tra xem có .gitignore file nào không
   */
  async hasGitignoreFiles() {
    const gitignoreFiles = [];
    
    const checkGitignore = async (dirPath) => {
      const gitignorePath = path.join(dirPath, '.gitignore');
      if (await fs.pathExists(gitignorePath)) {
        gitignoreFiles.push(path.relative(this.projectPath, gitignorePath));
      }
    };
    
    // Kiểm tra root
    await checkGitignore(this.projectPath);
    
    // Kiểm tra subdirectories (chỉ 2 levels để tránh quá chậm)
    try {
      const items = await fs.readdir(this.projectPath);
      for (const item of items) {
        const itemPath = path.join(this.projectPath, item);
        const stat = await fs.stat(itemPath);
        if (stat.isDirectory()) {
          await checkGitignore(itemPath);
          
          // Level 2
          try {
            const subItems = await fs.readdir(itemPath);
            for (const subItem of subItems) {
              const subItemPath = path.join(itemPath, subItem);
              const subStat = await fs.stat(subItemPath);
              if (subStat.isDirectory()) {
                await checkGitignore(subItemPath);
              }
            }
          } catch (error) {
            // Ignore errors
          }
        }
      }
    } catch (error) {
      // Ignore errors
    }
    
    return gitignoreFiles;
  }
 
  /**
   * Clear cache
   */
  clearCache() {
    this.ignoreInstances.clear();
  }
}
 
module.exports = IgnoreManager;