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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1190x 1190x 198x 198x 198x 992x 992x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 11x 11x 28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 41x 41x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 5x 5x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 33x 33x 33x 33x 33x 33x 33x 33x 497x 497x 38x 38x 497x 33x 33x 33x 9x 1x 33x 33x 33x 33x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 1x 1x 4x 1x 1x 4x 5x 5x 5x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 1x 1x 16x 16x 1x 1x 16x 1x 1x 16x 16x 16x 1x 1x 16x 16x 16x 15x 15x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 41x 615x 615x 41x 1x 1x 1x 1x 1x 1x 497x 497x 497x 497x 497x 497x 497x 497x 497x 1190x 1190x 1190x 47x 47x 1190x 497x 497x 459x 459x 38x 38x 38x 497x 13x 28x 28x 28x 28x 28x 28x 5x 5x 28x 13x 38x 38x 497x 497x 497x 497x 25x 25x 239x 5x 5x 13x 8x 8x 8x 38x 38x 38x 38x 38x 497x 497x 497x 1x | /**
* Recipe Registry
*
* Central registry that holds all known recipes, performs auto-detection
* against a project directory, and applies user overrides.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { Recipe, RecipeDetectionRule, RecipeMatch, RecipeOverride } from './types.js';
import { BUILTIN_RECIPES } from './builtinRecipes.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Check whether a file pattern (which may contain simple globs like `*.tf`)
* matches any entry in a directory listing.
*/
function matchesFilePattern(pattern: string, entries: string[]): boolean {
if (pattern.includes('*')) {
const re = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
return entries.some((e) => re.test(e));
}
return entries.includes(pattern);
}
/**
* Recursively check whether *any* file in `dir` matches `pattern`.
* Only descends one level for content-pattern files that reference a
* sub-path (e.g. `config/routes.rb`).
*/
function fileExistsRelative(dir: string, filePath: string): boolean {
try {
const resolved = path.resolve(dir, filePath);
return fs.existsSync(resolved);
} catch {
return false;
}
}
function readFileSafe(filePath: string): string {
try {
return fs.readFileSync(filePath, 'utf-8');
} catch {
return '';
}
}
// ---------------------------------------------------------------------------
// Registry
// ---------------------------------------------------------------------------
/** Central recipe registry with detection, override, and validation logic. */
export class RecipeRegistry {
private recipes: Map<string, Recipe> = new Map();
constructor() {
this.loadBuiltinRecipes();
}
// -----------------------------------------------------------------------
// CRUD
// -----------------------------------------------------------------------
/**
* Register a recipe. Overwrites any existing recipe with the same name.
*/
register(recipe: Recipe): void {
this.recipes.set(recipe.name, recipe);
}
/** Retrieve a recipe by name. */
get(name: string): Recipe | undefined {
return this.recipes.get(name);
}
/** Return all registered recipes. */
list(): Recipe[] {
return Array.from(this.recipes.values());
}
// -----------------------------------------------------------------------
// Detection
// -----------------------------------------------------------------------
/**
* Auto-detect which recipes match a project directory.
*
* 1. Lists the top-level entries of `projectDir`.
* 2. For each recipe, checks whether any detection file exists.
* 3. Optionally reads file content to confirm patterns.
* 4. Returns matches sorted by confidence (descending).
*/
async detectRecipe(projectDir: string): Promise<RecipeMatch[]> {
let entries: string[];
try {
entries = fs.readdirSync(projectDir);
} catch {
return [];
}
const matches: RecipeMatch[] = [];
for (const recipe of this.recipes.values()) {
const result = this.evaluateDetection(recipe, projectDir, entries);
if (result) {
matches.push(result);
}
}
// Sort descending by confidence, then by priority
matches.sort((a, b) => {
if (b.confidence !== a.confidence) return b.confidence - a.confidence;
return b.recipe.detection.priority - a.recipe.detection.priority;
});
return matches;
}
// -----------------------------------------------------------------------
// Override application
// -----------------------------------------------------------------------
/**
* Apply user overrides on top of a base recipe, returning a new Recipe.
* The original recipe is not mutated.
*/
applyRecipe(recipe: Recipe, overrides?: RecipeOverride): Recipe {
if (!overrides) return { ...recipe };
// Deep-clone so the original recipe is never mutated
const merged: Recipe = JSON.parse(JSON.stringify(recipe));
if (overrides.overrides) {
const o = overrides.overrides;
if (o.dockerImage !== undefined) merged.dockerImage = o.dockerImage;
if (o.defaultBuildCommand !== undefined) merged.defaultBuildCommand = o.defaultBuildCommand;
if (o.timeoutMinutes !== undefined) merged.timeoutMinutes = o.timeoutMinutes;
if (o.requiredTags !== undefined) merged.requiredTags = o.requiredTags;
if (o.cache !== undefined) merged.cache = o.cache;
if (o.artifacts !== undefined) merged.artifacts = o.artifacts;
// Merge environment variables (override wins)
if (o.environment) {
merged.environment = { ...(merged.environment || {}), ...o.environment };
}
// Prepend override setup steps, append override teardown steps
if (o.setup) {
merged.setup = [...o.setup, ...(merged.setup || [])];
}
if (o.teardown) {
merged.teardown = [...(merged.teardown || []), ...o.teardown];
}
}
// Apply variable values – substitute into the recipe's declared variables
if (overrides.variables && merged.variables) {
for (const [key, value] of Object.entries(overrides.variables)) {
if (merged.variables[key]) {
merged.variables[key] = { ...merged.variables[key], default: value };
}
}
}
// Merge agent tags
if (overrides.agentTags) {
merged.requiredTags = [...(merged.requiredTags || []), ...overrides.agentTags];
}
return merged;
}
// -----------------------------------------------------------------------
// Validation
// -----------------------------------------------------------------------
/**
* Validate a recipe configuration, returning a list of errors (if any).
*/
validate(recipe: Recipe): { valid: boolean; errors: string[] } {
const errors: string[] = [];
if (!recipe.name || recipe.name.trim().length === 0) {
errors.push('Recipe must have a non-empty name');
}
if (!recipe.detection) {
errors.push('Recipe must have detection rules');
} else if (!recipe.detection.files || recipe.detection.files.length === 0) {
errors.push('Recipe detection must specify at least one file');
}
if (!recipe.defaultBuildCommand || recipe.defaultBuildCommand.trim().length === 0) {
errors.push('Recipe must have a defaultBuildCommand');
}
// Docker recipes need an image; native recipes need an OS
if (recipe.executionMode === 'docker' && !recipe.dockerImage) {
errors.push('Docker recipe must specify a dockerImage');
}
if (recipe.executionMode === 'native' && !recipe.requiredOS) {
errors.push('Native recipe must specify requiredOS');
}
if (recipe.cache) {
if (!recipe.cache.paths || recipe.cache.paths.length === 0) {
errors.push('Cache config must have at least one path');
}
}
return { valid: errors.length === 0, errors };
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
/** Load all built-in recipes into the registry. */
private loadBuiltinRecipes(): void {
for (const recipe of BUILTIN_RECIPES) {
this.recipes.set(recipe.name, recipe);
}
}
/**
* Evaluate a single recipe's detection rules against a project directory.
* Returns a RecipeMatch if the recipe matches, or null otherwise.
*/
private evaluateDetection(
recipe: Recipe,
projectDir: string,
entries: string[],
): RecipeMatch | null {
const detection: RecipeDetectionRule = recipe.detection;
// Phase 1: Check for matching files
const matchedFiles: string[] = [];
for (const pattern of detection.files) {
// Handle sub-paths like "config/routes.rb"
if (pattern.includes('/')) {
if (fileExistsRelative(projectDir, pattern)) {
matchedFiles.push(pattern);
}
} else if (matchesFilePattern(pattern, entries)) {
matchedFiles.push(pattern);
}
}
if (matchedFiles.length === 0) {
return null;
}
// Phase 2: Check content patterns (boosts confidence)
const matchedPatterns: string[] = [];
if (detection.contentPatterns && detection.contentPatterns.length > 0) {
for (const cp of detection.contentPatterns) {
// Empty pattern means "file existence only"
if (cp.pattern === '') {
if (fileExistsRelative(projectDir, cp.file)) {
matchedPatterns.push(`${cp.file} (exists)`);
}
continue;
}
const filePath = path.resolve(projectDir, cp.file);
const content = readFileSafe(filePath);
if (content && content.includes(cp.pattern)) {
matchedPatterns.push(`${cp.file}: "${cp.pattern}"`);
}
}
}
// Calculate confidence
const hasContentPatterns = detection.contentPatterns && detection.contentPatterns.length > 0;
let confidence: number;
if (!hasContentPatterns) {
// No content patterns defined – file match alone yields moderate confidence
confidence = 60 + Math.min(matchedFiles.length * 10, 30);
} else if (matchedPatterns.length > 0) {
// File + content pattern match yields high confidence
confidence = 80 + Math.min(matchedPatterns.length * 5, 20);
} else {
// Files matched but content patterns did not – low confidence
confidence = 40 + Math.min(matchedFiles.length * 5, 15);
}
return {
recipe,
confidence,
matchedFiles,
matchedPatterns: matchedPatterns.length > 0 ? matchedPatterns : undefined,
};
}
}
|