code2prompt-executor.ts•3.69 kB
import { exec } from 'child_process';
import { promisify } from 'util';
import path from 'path';
const execAsync = promisify(exec);
export interface Code2PromptOptions {
/** Working directory to analyze */
workingDir: string;
/** Specific files or folders to include (optional) */
include?: string[];
/** Files or patterns to exclude (optional) */
exclude?: string[];
/** Output token count information */
outputTokens?: boolean;
/** Custom template to use */
template?: string;
}
export interface Code2PromptResult {
output: string;
tokenCount?: number;
error?: string;
}
/**
* Executes code2prompt with specified options
*/
export async function executeCode2Prompt(options: Code2PromptOptions): Promise<Code2PromptResult> {
try {
// Build command arguments
const args: string[] = [];
// Add include patterns
if (options.include && options.include.length > 0) {
args.push('--include');
args.push(`"${options.include.join(',')}"`)
}
// Add exclude patterns
if (options.exclude && options.exclude.length > 0) {
args.push('--exclude');
args.push(`"${options.exclude.join(',')}"`)
}
// Add token counting
if (options.outputTokens) {
args.push('--tokens');
}
// Add custom template
if (options.template) {
args.push('--template');
args.push(options.template);
}
// Add the working directory path
args.push(`"${options.workingDir}"`);
const command = `code2prompt ${args.join(' ')}`;
console.log(`Executing: ${command}`);
const { stdout, stderr } = await execAsync(command, {
cwd: process.cwd(),
maxBuffer: 10 * 1024 * 1024, // 10MB buffer for large codebases
});
if (stderr && !stderr.includes('Warning')) {
console.warn('code2prompt stderr:', stderr);
}
// Parse token count if requested
let tokenCount: number | undefined;
if (options.outputTokens && stderr) {
const tokenMatch = stderr.match(/Token count: (\d+)/);
if (tokenMatch) {
tokenCount = parseInt(tokenMatch[1], 10);
}
}
return {
output: stdout.trim(),
tokenCount,
};
} catch (error) {
console.error('Error executing code2prompt:', error);
return {
output: '',
error: error instanceof Error ? error.message : 'Unknown error occurred',
};
}
}
/**
* Executes comprehensive codebase analysis using code2prompt
*/
export async function executeComprehensiveAnalysis(workingDir: string): Promise<Code2PromptResult> {
return executeCode2Prompt({
workingDir,
outputTokens: true,
exclude: [
'node_modules/**',
'.git/**',
'*.log',
'dist/**',
'build/**',
'.next/**',
'coverage/**',
'*.tmp',
'*.cache'
]
});
}
/**
* Executes targeted analysis on specific files/folders
*/
export async function executeTargetedAnalysis(
workingDir: string,
targetPaths: string[]
): Promise<Code2PromptResult> {
// Validate target paths exist
const validPaths = targetPaths.filter(targetPath => {
const fullPath = path.resolve(workingDir, targetPath);
try {
require('fs').accessSync(fullPath);
return true;
} catch {
console.warn(`Target path does not exist: ${targetPath}`);
return false;
}
});
if (validPaths.length === 0) {
return {
output: '',
error: 'No valid target paths provided',
};
}
return executeCode2Prompt({
workingDir,
include: validPaths,
outputTokens: true,
exclude: [
'*.log',
'*.tmp',
'*.cache'
]
});
}