format_code
Formats code files according to a chosen style guide like Prettier or ESLint, with options for automatic fixing and custom configurations.
Instructions
Format code using specified style guide
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Path to the file to format | |
| style | No | Code style guide to use (e.g., prettier, eslint) | prettier |
| config | No | Configuration options for the formatter | |
| fix | No | Whether to fix issues automatically |
Implementation Reference
- The executeCommand method that calls codeService.formatCode() to format the file at the given path, and returns the result with success/error messaging.
protected async executeCommand(context: CommandContext): Promise<CommandResult> { try { const codeService = context.container.getService<CodeAnalysisService>('codeAnalysisService'); const result = await codeService.formatCode( context.args.path, { style: context.args.style, config: context.args.config, fix: context.args.fix } ); return { content: [{ type: 'text', text: JSON.stringify({ message: result.modified ? 'Code formatted successfully' : 'Code is already properly formatted', path: context.args.path, style: context.args.style, modified: result.modified, changes: result.changes }, null, 2) }] }; } catch (error) { return { content: [{ type: 'text', text: `Failed to format code: ${error instanceof Error ? error.message : String(error)}` }] }; } } } - The core formatCode implementation: reads the file, parses it with Babel, regenerates it, compares, and optionally writes changes back to disk.
async formatCode( path: string, options?: { style?: 'prettier' | 'eslint' | 'standard' | 'custom'; config?: Record<string, any>; fix?: boolean; } ): Promise<{ modified: boolean; changes: Array<{ line: number; description: string }>; }> { const originalContent = await fs.readFile(path, 'utf-8'); const changes: Array<{ line: number; description: string }> = []; // For now, just re-parse and regenerate to normalize the code const ast = parser.parse(originalContent, { sourceType: 'module', plugins: ['jsx', 'typescript', 'decorators-legacy'] }); const output = generate(ast, { retainLines: false, compact: false, concise: false, comments: true }); const modified = originalContent !== output.code; if (modified && options?.fix !== false) { await fs.writeFile(path, output.code); // Simple line-by-line comparison for changes const oldLines = originalContent.split('\n'); const newLines = output.code.split('\n'); for (let i = 0; i < Math.max(oldLines.length, newLines.length); i++) { if (oldLines[i] !== newLines[i]) { changes.push({ line: i + 1, description: 'Line formatted' }); } } } return { modified, changes }; } - Input schema definition (inputSchema and FormatCodeArgsSchema) specifying path (required), style, config, and fix parameters for the format_code tool.
const FormatCodeArgsSchema = { type: 'object', properties: { path: { type: 'string', description: 'Path to the file to format' }, style: { type: 'string', description: 'Code style guide to use (e.g., prettier, eslint)', default: 'prettier' }, config: { type: 'object', description: 'Configuration options for the formatter', additionalProperties: true }, fix: { type: 'boolean', description: 'Whether to fix issues automatically', default: true } }, required: ['path'] }; export class FormatCodeCommand extends BaseCommand { readonly name = 'format_code'; readonly description = 'Format code using specified style guide'; readonly inputSchema = { type: 'object', properties: { path: { type: 'string', description: 'Path to the file to format' }, style: { type: 'string', description: 'Code style guide to use (e.g., prettier, eslint)', default: 'prettier' }, config: { type: 'object', description: 'Configuration options for the formatter', additionalProperties: true }, fix: { type: 'boolean', description: 'Whether to fix issues automatically', default: true } }, required: ['path'], additionalProperties: false }; - Interface definition for the formatCode method, specifying the path and optional style/config/fix parameters and the return type.
formatCode( path: string, options?: { style?: 'prettier' | 'eslint' | 'standard' | 'custom'; config?: Record<string, any>; fix?: boolean; } ): Promise<{ modified: boolean; changes: Array<{ line: number; description: string }>; }>; analyzeQuality(path: string): Promise<any>; } - src/commands/registry/CommandLoader.ts:117-146 (registration)Registration of FormatCodeCommand: imported from the code module (line 121) and registered with the registry (line 146).
const codeModule = await import('../implementations/code/index.js'); if (this.enableDebugLogs) { console.log('Code commands available:', Object.keys(codeModule)); } const { AnalyzeCodeCommand, ModifyCodeCommand, SuggestRefactoringCommand, FormatCodeCommand } = codeModule; // Register git commands this.registry.register(new GitInitCommand()); this.registry.register(new GitAddCommand()); this.registry.register(new GitCommitCommand()); this.registry.register(new GitPushCommand()); this.registry.register(new GitPullCommand()); this.registry.register(new GitBranchCommand()); this.registry.register(new GitCheckoutCommand()); this.registry.register(new GitLogCommand()); this.registry.register(new GitCloneCommand()); this.registry.register(new GitHubCreatePRCommand()); this.registry.register(new GitStatusCommand()); // Register search commands this.registry.register(new SearchFilesCommand()); this.registry.register(new SearchContentCommand()); this.registry.register(new FuzzySearchCommand()); this.registry.register(new SemanticSearchCommand()); // Register code commands this.registry.register(new AnalyzeCodeCommand()); this.registry.register(new ModifyCodeCommand()); this.registry.register(new SuggestRefactoringCommand()); this.registry.register(new FormatCodeCommand());