Skip to content

Implement Config File Loader, Ignore Parser, and Context Loader#25

Merged
JeremyDev87 merged 1 commit into
masterfrom
feat/20
Dec 18, 2025
Merged

Implement Config File Loader, Ignore Parser, and Context Loader#25
JeremyDev87 merged 1 commit into
masterfrom
feat/20

Conversation

@JeremyDev87

Copy link
Copy Markdown
Owner

Implement Config File Loader, Ignore Parser, and Context Loader

📋 Summary

Implements the file loading infrastructure for CodingBuddy's user configuration system. Adds automatic detection and loading of codingbuddy.config.{js,mjs,json} files, .codingignore parsing with gitignore-style patterns, and .codingbuddy/ directory context file loading. All components are integrated into a NestJS service for use by the MCP server.

Closes #20

✨ Solution

1. Config File Loader (config.loader.ts)

Features:

  • Auto-detects config files in priority order: codingbuddy.config.js.mjs.json
  • Supports JavaScript/ESM files via dynamic import() with file:// URL conversion
  • Supports JSON files with parsing and validation
  • Validates loaded config using Zod schema from config.schema.ts
  • Returns ConfigLoadResult with config, source path, and warnings
  • Custom ConfigLoadError with file path and cause for better debugging

Key Functions:

  • findConfigFile(projectRoot): Finds first available config file
  • loadConfig(projectRoot): Loads and validates config (returns empty config if not found)
  • loadJsConfig(filePath): Dynamic import for JS/ESM files
  • loadJsonConfig(filePath): JSON parsing with error handling
  • validateAndTransform(raw, filePath): Zod validation with detailed errors

2. Ignore Parser (ignore.parser.ts)

Features:

  • Gitignore-style pattern matching syntax
  • Supports wildcards (*, **, ?), negation (!), directory-only (/)
  • Root-anchored patterns (/dist/ matches only at root)
  • Windows path normalization (backslash → forward slash)
  • Default ignore patterns included (node_modules, .git, dist, etc.)
  • Negation support (e.g., !important.log to include despite *.log)

Key Functions:

  • loadIgnoreFile(projectRoot): Loads .codingignore file
  • parseIgnoreContent(content): Parses ignore file content
  • patternToRegex(pattern): Converts gitignore pattern to RegExp
  • shouldIgnore(path, patterns): Checks if path matches ignore patterns
  • filterIgnored(paths, patterns): Filters array of paths
  • getDefaultIgnorePatterns(): Returns common ignore patterns

Pattern Examples:

  • node_modules/ - Matches node_modules directory anywhere
  • *.log - Matches .log files anywhere
  • /dist/ - Matches dist directory only at root
  • **/*.test.ts - Matches .test.ts files at any depth
  • !important.log - Negates previous patterns

3. Context Loader (context.loader.ts)

Features:

  • Recursively loads all files from .codingbuddy/ directory
  • Categorizes files by type based on subdirectory:
    • context/ → Project context files
    • prompts/ → Custom prompts
    • agents/ → Custom agent configurations
    • Other → Additional files
  • Supports multiple file formats: .md, .txt, .json, .yaml, .js, .ts, .jsx, .tsx
  • Formats context for AI consumption with markdown sections
  • Non-fatal error handling (continues loading even if some files fail)

Key Functions:

  • loadContextFiles(projectRoot): Loads all context files
  • getContextFileType(relativePath): Determines file type from path
  • isLoadableFile(filePath): Checks if file extension is supported
  • formatContextForAI(files): Formats files into markdown for AI
  • getFilesByType(files, type): Filters files by type

Directory Structure:

.codingbuddy/
├── context/          # Project context (architecture, API docs)
│   ├── architecture.md
│   └── api-guide.md
├── prompts/          # Custom prompts
│   └── review.md
└── agents/           # Custom agent configs
    └── reviewer.json

4. Config Service (config.service.ts)

Features:

  • NestJS injectable service integrating all loaders
  • Provides unified ProjectConfig interface:
    • settings: Main config from codingbuddy.config.js
    • ignorePatterns: Combined default + user ignore patterns
    • contextFiles: All loaded context files
    • sources: Metadata about loaded file paths
  • Lazy loading with caching (loads once, caches result)
  • Reload support for hot-reload scenarios
  • Configurable project root (via CODINGBUDDY_PROJECT_ROOT env var)
  • Comprehensive logging for debugging

Key Methods:

  • loadProjectConfig(): Loads all configuration (called on module init)
  • getProjectConfig(): Returns cached config or loads if not loaded
  • getSettings(): Returns main config settings
  • getIgnorePatterns(): Returns all ignore patterns
  • shouldIgnorePath(path): Checks if path should be ignored
  • getContextFiles(): Returns all context files
  • getFormattedContext(): Returns formatted context for AI
  • reload(): Forces reload from disk

5. NestJS Module (config.module.ts)

  • Provides ConfigService to NestJS dependency injection
  • Exports ConfigService for use in other modules

🧪 Testing

Test Coverage

  • Config Loader: 10 tests covering file detection, loading, validation, error handling
  • Ignore Parser: 19 tests covering pattern matching, wildcards, negation, Windows paths
  • Context Loader: 18 tests covering file type detection, loading, formatting

Total: 47 tests, all passing ✅

Test Scenarios

Config Loader:

  • ✅ Priority order detection (js → mjs → json)
  • ✅ JavaScript/ESM dynamic import
  • ✅ JSON parsing
  • ✅ Schema validation with detailed errors
  • ✅ Empty config handling
  • ✅ Error wrapping with file paths

Ignore Parser:

  • ✅ Simple patterns (node_modules/)
  • ✅ Wildcard patterns (*.log, **/*.test.ts)
  • ✅ Root-anchored patterns (/dist/)
  • ✅ Negation patterns (!important.log)
  • ✅ Windows path normalization
  • ✅ Default ignore patterns

Context Loader:

  • ✅ File type detection by subdirectory
  • ✅ Recursive directory traversal
  • ✅ File extension filtering
  • ✅ Formatting for AI consumption
  • ✅ Error handling (non-fatal)

🎯 Benefits

1. Automatic Configuration Discovery

Users don't need to manually specify config file paths. The system automatically finds and loads configuration.

2. Multiple Format Support

Supports JavaScript (for dynamic config) and JSON (for static config), giving users flexibility.

3. Gitignore-Style Ignore Patterns

Familiar syntax that developers already know, reducing learning curve.

4. Rich Context Loading

Allows users to provide additional project context beyond the main config file.

5. Unified Service Interface

Single ConfigService provides all configuration data, simplifying MCP server integration.

📖 Usage Example

// In MCP server handler
import { ConfigService } from './config/config.service';

@Injectable()
export class RulesHandler {
  constructor(private configService: ConfigService) {}

  async handleRequest() {
    const config = await this.configService.getProjectConfig();
    
    // Access main settings
    const language = config.settings.language;
    
    // Check if path should be ignored
    const shouldIgnore = await this.configService.shouldIgnorePath('node_modules/lodash');
    
    // Get formatted context for AI
    const context = await this.configService.getFormattedContext();
  }
}

✅ Acceptance Criteria

  • Automatic config file detection
  • Schema-based validation
  • User-friendly error messages on failure
  • Default values applied when no config file exists
  • Gitignore-style ignore pattern support
  • Context file loading from .codingbuddy/
  • NestJS service integration
  • Comprehensive test coverage

…t loader

- Load codingbuddy.config.{js,mjs,json} with validation
- Parse .codingignore files with gitignore-style patterns
- Load .codingbuddy/ directory files (context, prompts, agents)
- Add NestJS ConfigService integrating all loaders
- Add comprehensive test coverage

close #20
@JeremyDev87 JeremyDev87 self-assigned this Dec 18, 2025
@JeremyDev87 JeremyDev87 marked this pull request as ready for review December 18, 2025 09:07
@JeremyDev87 JeremyDev87 merged commit c1e8699 into master Dec 18, 2025
2 checks passed
@JeremyDev87 JeremyDev87 deleted the feat/20 branch December 21, 2025 15:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Config File Loader Implementation

2 participants