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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 79x 79x 79x 79x 2x 16x 16x 16x 16x 16x 84x 84x 80x 84x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 84x 59x 59x 59x 59x 59x 59x 1x 2x 1x 59x 58x 58x 59x 59x 84x 16x 16x 16x 16x 2x 16x 16x 16x 16x 16x 16x 16x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 16x 16x 2x 2x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 18x 18x 18x 5x 5x 13x 13x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 5x 4x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 5x 5x 5x 5x 5x 5x 2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 32x 13x 32x 19x 19x 19x 11x 11x 69x 57x 11x 11x 19x 8x 8x 8x 8x 5x 1x 5x 4x 4x 8x 3x 3x 3x 3x 3x 3x 8x 8x 57x 57x 8x 19x 32x 32x 13x 13x 126x 126x 19x 19x 19x 126x 107x 107x 126x 13x 13x 13x 13x 2x 2x 2x 2x 2x 2x 6x 8x 8x 6x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x | import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { getApiKey } from '../config/secret';
import { getAIConfig, getAIMaxTokens, getAITimeout } from '../config/ai';
import { createProvider } from '../ai/factory';
import { RuleConverter } from './converters/converter';
import { loadActiveRules } from './yaml-parser';
import { parseTemplate } from './converters/template-converter';
import { buildDedupOnlyPrompt } from './converters/dedup-prompt';
import type { ConversionResult, ImportableRule, PreviewDecision } from './import-types';
import { t, getLanguage } from '../i18n/messages';
interface ParsedYamlItem {
id?: string;
severity?: string;
description?: string;
message?: string;
languages?: string[];
excludeLanguages?: string[];
duplicateOf?: string;
duplicateLevel?: string;
duplicateReason?: string;
[key: string]: unknown;
}
function stripQuotes(raw: string): string {
const m = raw.match(/^(['"])(.*)\1$/);
return m ? m[2] : raw;
}
function parseSimpleYaml(content: string): ParsedYamlItem[] {
const items: ParsedYamlItem[] = [];
let current: ParsedYamlItem | null = null;
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) { continue; }
if (trimmed.startsWith('- ')) {
if (current) { items.push(current); }
current = {};
const indentMatch = trimmed.match(/^- (\w[\w-]*)\s*:\s*(.*)$/);
if (indentMatch) {
const key = indentMatch[1];
const raw = indentMatch[2].trim();
if (raw.startsWith('[') && raw.endsWith(']')) {
current[key] = raw.slice(1, -1).split(',').map(s =>
s.trim().replace(/^['"]|['"]$/g, '')
);
} else {
current[key] = stripQuotes(raw);
}
}
} else if (current) {
const propMatch = trimmed.match(/^(\w[\w-]*)\s*:\s*(.*)$/);
if (propMatch) {
const key = propMatch[1];
const raw = propMatch[2].trim();
if (!raw || raw === '[]') {
current[key] = [];
} else if (raw.startsWith('[') && raw.endsWith(']')) {
current[key] = raw.slice(1, -1).split(',').map(s =>
s.trim().replace(/^['"]|['"]$/g, '')
);
} else {
current[key] = stripQuotes(raw);
}
}
}
}
if (current) { items.push(current); }
return items;
}
export function parseImportableYaml(content: string): ImportableRule[] {
const items = parseSimpleYaml(content);
const validSeverities = new Set(['error', 'warning', 'info']);
return items
.filter(item => item.description || item.message)
.map((item, idx) => ({
id: (item.id && item.id.trim()) ? item.id.trim() : `rule-${idx + 1}`,
severity: item.severity && validSeverities.has(item.severity)
? item.severity as 'error' | 'warning' | 'info'
: 'warning',
description: (item.description ?? item.message ?? ''),
message: (item.message ?? item.description ?? ''),
languages: item.languages as string[] | undefined,
excludeLanguages: item.excludeLanguages as string[] | undefined,
duplicateOf: item.duplicateOf as string | undefined,
duplicateLevel: item.duplicateLevel as 'exact' | 'overlap' | 'none' | undefined,
duplicateReason: item.duplicateReason as string | undefined,
}));
}
export interface DedupResult {
duplicateLevel: 'exact' | 'overlap' | 'none';
duplicateOf?: string;
duplicateReason?: string;
}
export async function dedupSingleRule(
rule: ImportableRule,
context: vscode.ExtensionContext,
): Promise<DedupResult | null> {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
const existingRules = workspaceRoot ? loadActiveRules(workspaceRoot) : [];
const singleYaml = [
`- id: ${rule.id}`,
` severity: ${rule.severity}`,
` description: ${rule.description}`,
` message: ${rule.message}`,
...(rule.languages?.length ? [` languages: [${rule.languages.join(', ')}]`] : []),
...(rule.excludeLanguages?.length ? [` excludeLanguages: [${rule.excludeLanguages.join(', ')}]`] : []),
].join('\n');
const { system, user } = buildDedupOnlyPrompt(singleYaml, existingRules);
for (let attempt = 0; attempt < 2; attempt++) {
const out = await convertContentWithAI(user, context, system, true);
if (!out) { continue; }
const parsed = parseImportableYaml(out);
if (parsed.length === 0) { continue; }
const r = parsed[0];
return {
duplicateLevel: r.duplicateLevel ?? 'none',
duplicateOf: r.duplicateOf,
duplicateReason: r.duplicateReason,
};
}
return null;
}
export function buildFinalYaml(
yamlContent: string,
rules: ImportableRule[],
decision: PreviewDecision,
): string {
if (decision.editedRules && decision.editedRules.length > 0) {
return renderRulesToYaml(decision.editedRules, decision);
}
return buildFinalYamlFromRaw(yamlContent, rules, decision);
}
function renderRulesToYaml(
rules: ImportableRule[],
decision: PreviewDecision,
): string {
const lines: string[] = [];
for (const rule of rules) {
const keep = decision.keepRule[rule.id] ?? rule.duplicateLevel !== 'exact';
const ruleLines: string[] = [];
ruleLines.push(`- id: ${rule.id}`);
ruleLines.push(` severity: ${rule.severity}`);
ruleLines.push(` description: ${rule.description}`);
ruleLines.push(` message: ${rule.message}`);
if (rule.languages && rule.languages.length > 0) {
ruleLines.push(` languages: [${rule.languages.join(', ')}]`);
}
if (rule.excludeLanguages && rule.excludeLanguages.length > 0) {
ruleLines.push(` excludeLanguages: [${rule.excludeLanguages.join(', ')}]`);
}
if (keep) {
lines.push(...ruleLines);
} else {
const dupLevel = rule.duplicateLevel ?? 'none';
const dupOf = rule.duplicateOf ?? 'manual';
if (dupLevel === 'exact') {
lines.push(t('yaml.duplicateExact', { 0: dupOf }));
} else if (dupLevel === 'overlap') {
lines.push(t('yaml.duplicateOverlap', { 0: dupOf }));
if (rule.duplicateReason) {
lines.push(t('yaml.overlapReason', { 0: rule.duplicateReason }));
}
} else {
lines.push(t('yaml.manualComment'));
}
lines.push(t('yaml.enableHint'));
for (const rl of ruleLines) {
lines.push(`# ${rl}`);
}
}
lines.push('');
}
return lines.join('\n');
}
function buildFinalYamlFromRaw(
yamlContent: string,
rules: ImportableRule[],
decision: PreviewDecision,
): string {
const defaultKeep = (rule: ImportableRule) => rule.duplicateLevel !== 'exact';
const shouldKeep = (rule: ImportableRule) =>
decision.keepRule[rule.id] ?? defaultKeep(rule);
const lines = yamlContent.split('\n');
const output: string[] = [];
let currentRuleId: string | null = null;
let ruleLines: string[] = [];
function flushRule(): void {
if (currentRuleId === null) {
output.push(...ruleLines);
} else {
const rule = rules.find(r => r.id === currentRuleId);
const keep = rule ? shouldKeep(rule) : true;
if (keep) {
const filtered = ruleLines.filter(
line => !line.trimStart().startsWith('duplicateOf:') &&
!line.trimStart().startsWith('duplicateLevel:') &&
!line.trimStart().startsWith('duplicateReason:')
);
output.push(...filtered);
} else {
const level = rule?.duplicateLevel ?? 'exact';
const dupInfo = rule?.duplicateOf ?? 'unknown';
const reason = rule?.duplicateReason ?? '';
if (level === 'exact') {
if (dupInfo.startsWith('custom/')) {
output.push(t('yaml.duplicateExactCustom', { 0: dupInfo.slice(7) }));
} else {
output.push(t('yaml.duplicateExactGeneric', { 0: dupInfo }));
}
} else {
if (dupInfo.startsWith('custom/')) {
output.push(t('yaml.duplicateOverlapCustom', { 0: level, 1: dupInfo.slice(7) }));
} else {
output.push(t('yaml.duplicateOverlapGeneric', { 0: level, 1: dupInfo }));
}
if (reason) { output.push(t('yaml.overlapReason', { 0: reason })); }
}
output.push(t('yaml.enableHint'));
for (const line of ruleLines) {
output.push(line.trim() ? `# ${line}` : '#');
}
}
}
ruleLines = [];
}
for (const line of lines) {
const ruleStart = line.match(/^-\s+id:\s*(.+)/);
if (ruleStart) {
flushRule();
currentRuleId = ruleStart[1].trim();
ruleLines = [line];
} else if (currentRuleId) {
ruleLines.push(line);
} else {
ruleLines.push(line);
}
}
flushRule();
return output.join('\n');
}
function normalizeRuleIds(rules: ImportableRule[]): ImportableRule[] {
const seen = new Set<string>();
return rules.map((rule, idx) => {
let id = rule.id
.toLowerCase()
.replace(/[^a-z0-9-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
if (!id) {
id = `rule-${idx + 1}`;
}
if (seen.has(id)) {
let suffix = 2;
while (seen.has(`${id}-${suffix}`)) { suffix++; }
id = `${id}-${suffix}`;
}
seen.add(id);
return { ...rule, id };
});
}
export class ImportService {
private converters: Map<string, RuleConverter> = new Map();
registerConverter(converter: RuleConverter): void {
for (const ext of converter.supportedExtensions) {
this.converters.set(ext, converter);
}
}
async convert(
srcPath: string,
context: vscode.ExtensionContext,
): Promise<ConversionResult> {
const ext = path.extname(srcPath).toLowerCase();
const converter = this.converters.get(ext);
if (!converter) {
throw new Error(t('import.unsupportedFormat', { 0: ext }));
}
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
const existingRules = workspaceRoot ? loadActiveRules(workspaceRoot) : [];
const yamlContent = await converter.convert(srcPath, context, existingRules);
if (!yamlContent) {
throw new Error(t('import.conversionFailed'));
}
const parsedRules = parseImportableYaml(yamlContent);
const rules = normalizeRuleIds(parsedRules);
const exactCount = rules.filter(r => r.duplicateLevel === 'exact').length;
const overlapCount = rules.filter(r => r.duplicateLevel === 'overlap').length;
return {
rules,
yamlContent,
sourceFileName: path.basename(srcPath),
exactCount,
overlapCount,
};
}
async importTemplate(
srcPath: string,
name: string,
context: vscode.ExtensionContext,
): Promise<ConversionResult> {
const { rules, validRules, yamlContent, skippedCount } = parseTemplate(srcPath);
let dedupedValidRules: ImportableRule[] = validRules;
if (validRules.length > 0) {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
const existingRules = workspaceRoot ? loadActiveRules(workspaceRoot) : [];
const { system, user } = buildDedupOnlyPrompt(yamlContent, existingRules);
const dedupedYaml = await convertContentWithAI(user, context, system);
if (dedupedYaml) {
dedupedValidRules = parseImportableYaml(dedupedYaml);
} else {
vscode.window.showWarningMessage(t('import.dedupFailed'));
}
}
const errorRules = rules.filter(r => r.validationIssues?.length);
const allRules = [...dedupedValidRules, ...errorRules];
const exactCount = dedupedValidRules.filter(r => r.duplicateLevel === 'exact').length;
const overlapCount = dedupedValidRules.filter(r => r.duplicateLevel === 'overlap').length;
return {
rules: allRules,
yamlContent,
sourceFileName: path.basename(srcPath),
exactCount,
overlapCount,
skippedCount,
errorCount: errorRules.length,
};
}
applyConversion(
result: ConversionResult,
decision: PreviewDecision,
targetPath: string,
): void {
const finalYaml = buildFinalYaml(result.yamlContent, result.rules, decision);
const dir = path.dirname(targetPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(targetPath, finalYaml, 'utf-8');
}
}
function buildFallbackPrompt(): string {
const lang = getLanguage();
if (lang === 'ja') {
return `あなたはコードレビュールール変換ツールです。ユーザーが提供した自然言語のルール記述を、構造化されたYAML形式に変換してください。
各ルールには以下のフィールドが必要です:
- id: ルールの一意識別子(kebab-case英語)
- severity: 重要度(error / warning / info)
- description: ルールの簡単な説明
- message: 違反時のメッセージ
- languages: 対象言語配列(オプション、例:[javascript, typescript])
出力形式の例:
- id: no-console-log
severity: warning
description: console.logの使用禁止
message: loggerツールを使用してconsole.logを代替してください
languages: [javascript, typescript]
YAMLのみを出力し、追加説明は不要です。
出力言語:ja`;
}
if (lang === 'en') {
return `You are a code review rule converter. Convert the natural language rule description provided by the user into structured YAML format for a code review tool.
Each rule must include the following fields:
- id: Unique rule identifier (kebab-case English)
- severity: Severity level (error / warning / info)
- description: Short rule description
- message: Violation message
- languages: Applicable language array (optional, e.g., [javascript, typescript])
Output format example:
- id: no-console-log
severity: warning
description: Forbid using console.log
message: Use a logger tool instead of console.log
languages: [javascript, typescript]
Output YAML only, no extra explanation.
Output language: en`;
}
return `你是一个代码审查规则转换器。将用户提供的自然语言规则描述,转换为结构化的 YAML 格式,用于代码审查工具。
每条规则需要包含以下字段:
- id: 规则唯一标识(kebab-case 英文)
- severity: 严重级别(error / warning / info)
- description: 规则简短描述
- message: 违反时的提示消息
- languages: 适用语言数组(可选,如 [javascript, typescript])
输出格式示例:
- id: no-console-log
severity: warning
description: 禁止使用 console.log
message: 请使用 logger 工具替代 console.log
languages: [javascript, typescript]
仅输出 YAML,不要额外说明。
输出语言:zh-CN`;
}
export async function convertContentWithAI(
content: string,
context: vscode.ExtensionContext,
systemPrompt?: string,
quiet?: boolean,
): Promise<string | null> {
if (!content.trim()) {
if (!quiet) {
vscode.window.showErrorMessage(t('import.emptyFile'));
}
return null;
}
const apiKey = await getApiKey(context);
if (!apiKey) {
if (!quiet) {
vscode.window.showErrorMessage(t('import.needApiKey'));
}
return null;
}
const config = getAIConfig();
const provider = createProvider(config.provider, apiKey, config.baseUrl, context.extensionUri);
const prompt = systemPrompt ?? buildFallbackPrompt();
let yamlOutput: string;
try {
yamlOutput = await provider.chat(prompt, content, {
model: config.model,
temperature: 0,
maxTokens: getAIMaxTokens(),
timeoutMs: getAITimeout() * 1000,
seed: 42,
});
} catch (err) {
if (!quiet) {
if (err instanceof DOMException && err.name === 'AbortError') {
vscode.window.showErrorMessage(t('import.timeout'));
} else {
const msg = err instanceof Error ? err.message : String(err);
vscode.window.showErrorMessage(t('import.aiFail', { 0: msg }));
}
}
return null;
}
const cleaned = yamlOutput
.replace(/```(yaml|yml)?\s*/gi, '')
.replace(/```\s*$/gm, '')
.trim();
if (!cleaned) {
if (!quiet) {
vscode.window.showErrorMessage(t('import.emptyResponse'));
}
return null;
}
return cleaned;
}
|