495 lines
26 KiB
Python
495 lines
26 KiB
Python
"""Read-only checks of function-driven Markdown conventions; no dependencies."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import re
|
||
import unicodedata
|
||
from pathlib import Path
|
||
from urllib.parse import unquote
|
||
|
||
|
||
SECTIONS = (
|
||
"Участники", "Предусловия", "Основной поток", "Альтернативы и ошибки",
|
||
"Результат", "Коды завершения",
|
||
)
|
||
CODE = re.compile(r"\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b")
|
||
LINK = re.compile(r"\[([^\]]+)\]\(#([^)]+)\)")
|
||
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
|
||
LEGACY_REQUIREMENT_ID_PATTERN = r"[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+"
|
||
QUALIFIED_REQUIREMENT_ID_PATTERN = r"[A-Z][A-Z0-9]*(?:\.[A-Z][A-Z0-9]*)+-\d{2,}"
|
||
REQUIREMENT_ID_PATTERN = rf"(?:{QUALIFIED_REQUIREMENT_ID_PATTERN}|{LEGACY_REQUIREMENT_ID_PATTERN})"
|
||
REQUIREMENT_ID = re.compile(rf"^\*\*ID:\*\* `({REQUIREMENT_ID_PATTERN})`$", re.MULTILINE)
|
||
FR_ID_PATTERN = rf"(?:{QUALIFIED_REQUIREMENT_ID_PATTERN}\.)?FR-\d{{2,}}"
|
||
FR_ID = re.compile(rf"^(?:(?P<requirement>{QUALIFIED_REQUIREMENT_ID_PATTERN})\.)?(?P<number>FR-\d{{2,}})$")
|
||
FR_HEADING = re.compile(rf"^##### ({FR_ID_PATTERN})(?: \[(DB|API|UI)\])?: (.+)$", re.MULTILINE)
|
||
HTML_ANCHOR = re.compile(r"<a\b[^>]*\bid\s*=", re.IGNORECASE)
|
||
DB_TABLE_COLUMNS = ("Поле", "Тип", "Ограничения и значение по умолчанию", "Назначение")
|
||
CONTRACT_COLUMNS = ("Поле", "Тип", "Обязательность", "Ограничения и значение по умолчанию", "Назначение")
|
||
RESPONSE_CONTRACT_COLUMNS = (*CONTRACT_COLUMNS, "Формирование значения")
|
||
CAPABILITY_CODES_PATH = Path(__file__).with_name("capability-codes.md")
|
||
CAPABILITY_CODE_ROW = re.compile(r"^\|\s*`([^`]+)`\s*\|\s*`([^`]+)`\s*\|$")
|
||
|
||
|
||
def plain_text(value: str) -> str:
|
||
value = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", value)
|
||
return re.sub(r"^[\d.\-\s]+|[`*_]", "", value).strip()
|
||
|
||
|
||
def heading_slug(title: str) -> str:
|
||
"""Build the heading fragment used by GitHub-style Markdown renderers."""
|
||
title = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", title)
|
||
title = re.sub(r"[`*_~]", "", title).lower()
|
||
slug: list[str] = []
|
||
for char in title:
|
||
category = unicodedata.category(char)[0]
|
||
if char.isspace():
|
||
if slug and slug[-1] != "-":
|
||
slug.append("-")
|
||
elif char in {"-", "_"} or category in {"L", "M", "N"}:
|
||
slug.append(char)
|
||
return "".join(slug).strip("-")
|
||
|
||
|
||
def parse_fr_reference(label: str) -> tuple[str | None, str] | None:
|
||
"""Return an optional requirement ID and the local FR number from a link label."""
|
||
label = label.strip()
|
||
match = FR_ID.fullmatch(label)
|
||
if match:
|
||
return match.group("requirement"), match.group("number")
|
||
match = re.fullmatch(
|
||
rf"({LEGACY_REQUIREMENT_ID_PATTERN})\s*/\s*(FR-\d{{2,}})", label
|
||
)
|
||
if match:
|
||
return match.group(1), match.group(2)
|
||
return None
|
||
|
||
|
||
def load_capability_codes() -> tuple[dict[str, str], list[str]]:
|
||
codes: dict[str, str] = {}
|
||
errors: list[str] = []
|
||
try:
|
||
lines = CAPABILITY_CODES_PATH.read_text(encoding="utf-8").splitlines()
|
||
except OSError as error:
|
||
return {}, [f"не удалось прочитать реестр capability codes: {error}"]
|
||
|
||
prefixes: dict[str, str] = {}
|
||
for line in lines:
|
||
match = CAPABILITY_CODE_ROW.match(line)
|
||
if not match:
|
||
continue
|
||
capability_path, prefix = match.groups()
|
||
if capability_path in codes:
|
||
errors.append(f"путь capability повторяется в реестре: {capability_path}")
|
||
if prefix in prefixes:
|
||
errors.append(f"префикс {prefix} повторяется для {prefixes[prefix]} и {capability_path}")
|
||
codes[capability_path] = prefix
|
||
prefixes[prefix] = capability_path
|
||
return codes, errors
|
||
|
||
|
||
def spec_capability_path(path: Path) -> str | None:
|
||
parts = path.parts
|
||
indexes = [index for index, part in enumerate(parts) if part == "specs"]
|
||
if not indexes:
|
||
return None
|
||
capability_parts = parts[indexes[-1] + 1:-1]
|
||
return "/".join(capability_parts) if capability_parts else None
|
||
|
||
|
||
def heading_targets(text: str) -> tuple[set[str], dict[str, tuple[str, str]]]:
|
||
"""Return generated heading fragments and fragments that target FR headings."""
|
||
targets: set[str] = set()
|
||
fr_targets: dict[str, tuple[str, str]] = {}
|
||
duplicates: dict[str, int] = {}
|
||
requirement_id = ""
|
||
for line in text.splitlines():
|
||
if line.startswith("### Requirement:"):
|
||
requirement_id = ""
|
||
id_match = REQUIREMENT_ID.match(line)
|
||
if id_match:
|
||
requirement_id = id_match.group(1)
|
||
|
||
match = HEADING.match(line)
|
||
if not match:
|
||
continue
|
||
slug = heading_slug(match.group(2))
|
||
if not slug:
|
||
continue
|
||
duplicate_index = duplicates.get(slug, 0)
|
||
duplicates[slug] = duplicate_index + 1
|
||
target = slug if duplicate_index == 0 else f"{slug}-{duplicate_index}"
|
||
targets.add(target)
|
||
|
||
fr_match = FR_HEADING.match(line)
|
||
if fr_match and requirement_id:
|
||
fr_id = FR_ID.fullmatch(fr_match.group(1))
|
||
if fr_id:
|
||
fr_targets[target] = (requirement_id, fr_id.group("number"))
|
||
return targets, fr_targets
|
||
|
||
|
||
def requirement_blocks(text: str):
|
||
heading = re.compile(r"^## .*|^### Requirement: (.+)$", re.MULTILINE)
|
||
headings = list(heading.finditer(text))
|
||
operation = ""
|
||
for index, match in enumerate(headings):
|
||
if not match.group(1):
|
||
operation = match.group().removeprefix("## ")
|
||
continue
|
||
if operation in {"REMOVED Requirements", "RENAMED Requirements"}:
|
||
continue
|
||
end = headings[index + 1].start() if index + 1 < len(headings) else len(text)
|
||
yield match.group(1), text[match.end():end]
|
||
|
||
|
||
def check_database_table_pattern(content: str) -> list[str]:
|
||
errors: list[str] = []
|
||
tables: list[list[str]] = []
|
||
current: list[str] = []
|
||
for line in content.splitlines():
|
||
if line.strip().startswith("|"):
|
||
current.append(line.strip())
|
||
elif current:
|
||
tables.append(current)
|
||
current = []
|
||
if current:
|
||
tables.append(current)
|
||
|
||
if len(tables) != 1:
|
||
return ["паттерн таблицы БД требует ровно одну Markdown-таблицу"]
|
||
rows = [[cell.strip() for cell in row.strip("|").split("|")] for row in tables[0]]
|
||
if len(rows) < 3 or tuple(rows[0]) != DB_TABLE_COLUMNS:
|
||
return ["таблица БД должна иметь заголовки Поле, Тип, Ограничения и значение по умолчанию, Назначение"]
|
||
if len(rows[1]) != len(DB_TABLE_COLUMNS) or any(not re.fullmatch(r":?-{3,}:?", cell) for cell in rows[1]):
|
||
errors.append("в таблице БД некорректная строка разделителя")
|
||
|
||
field_names: set[str] = set()
|
||
for row in rows[2:]:
|
||
if len(row) != len(DB_TABLE_COLUMNS) or any(not cell for cell in row):
|
||
errors.append("каждая строка таблицы БД должна содержать четыре непустые ячейки")
|
||
continue
|
||
field_name = row[0].strip("`")
|
||
if field_name in field_names:
|
||
errors.append(f"поле `{field_name}` повторяется в таблице БД")
|
||
field_names.add(field_name)
|
||
return errors
|
||
|
||
|
||
def check_message_contract_pattern(content: str, direction: str | None = None) -> list[str]:
|
||
errors: list[str] = []
|
||
contract_type_match = re.search(r"(?m)^Тип контракта: (request|response)$", content)
|
||
if direction is None and not contract_type_match:
|
||
errors.append("контракт должен явно указывать Тип контракта: request или response")
|
||
selected_direction = direction or (contract_type_match.group(1) if contract_type_match else "")
|
||
columns = (
|
||
RESPONSE_CONTRACT_COLUMNS
|
||
if selected_direction == "response"
|
||
else CONTRACT_COLUMNS
|
||
)
|
||
|
||
tables: list[list[str]] = []
|
||
current: list[str] = []
|
||
for line in content.splitlines():
|
||
if line.strip().startswith("|"):
|
||
current.append(line.strip())
|
||
elif current:
|
||
tables.append(current)
|
||
current = []
|
||
if current:
|
||
tables.append(current)
|
||
|
||
if len(tables) != 1:
|
||
return errors + ["паттерн контракта требует ровно одну Markdown-таблицу"]
|
||
rows = [[cell.strip() for cell in row.strip("|").split("|")] for row in tables[0]]
|
||
if len(rows) < 3 or tuple(rows[0]) != columns:
|
||
required_columns = ", ".join(columns)
|
||
return errors + [f"таблица контракта должна содержать колонки: {required_columns}"]
|
||
if len(rows[1]) != len(columns) or any(not re.fullmatch(r":?-{3,}:?", cell) for cell in rows[1]):
|
||
errors.append("в таблице контракта некорректная строка разделителя")
|
||
|
||
field_names: set[str] = set()
|
||
for row in rows[2:]:
|
||
if len(row) != len(columns) or any(not cell for cell in row):
|
||
errors.append("каждая строка таблицы контракта должна содержать нужное число непустых ячеек")
|
||
continue
|
||
field_name = row[0].strip(chr(96))
|
||
if field_name in field_names:
|
||
errors.append(f"поле контракта {field_name} повторяется")
|
||
field_names.add(field_name)
|
||
if row[2] not in {"Обязательное", "Опциональное"}:
|
||
errors.append(f"поле контракта {field_name} должно явно задавать обязательность")
|
||
|
||
return errors
|
||
|
||
|
||
def check_http_endpoint_contract(content: str) -> list[str]:
|
||
errors: list[str] = []
|
||
headings = re.findall(r"^##### (.+)$", content, re.MULTILINE)
|
||
if headings != ["Request", "Response"]:
|
||
return ["CONTRACT должен содержать только подразделы Request и Response в этом порядке"]
|
||
|
||
request, response = re.split(r"^##### (?:Request|Response)\s*$", content, maxsplit=2, flags=re.MULTILINE)[1:]
|
||
if len(re.findall(r"(?m)^Метод: \x60?(?:GET|POST|PUT|PATCH|DELETE)\x60?; путь: \x60?/\S+", request)) != 1:
|
||
errors.append("в Request укажи один HTTP-метод и путь endpoint")
|
||
request_tables = sum(line.strip().startswith("|") for line in request.splitlines())
|
||
if request_tables:
|
||
errors.extend(check_message_contract_pattern(request, "request"))
|
||
elif not re.search(r"Тело запроса(?: и query-параметры)? отсутств(?:ует|уют)", request):
|
||
errors.append("в Request укажи таблицу тела запроса или явно отметь его отсутствие")
|
||
|
||
if not re.search(r"(?m)^HTTP status:", response):
|
||
errors.append("в Response укажи HTTP status")
|
||
errors.extend(check_message_contract_pattern(response, "response"))
|
||
return errors
|
||
|
||
|
||
def check_requirement(
|
||
name: str,
|
||
block: str,
|
||
targets: set[str],
|
||
fr_targets: dict[str, tuple[str, str]],
|
||
require_qualified_ids: bool = False,
|
||
) -> list[str]:
|
||
errors: list[str] = []
|
||
ids = REQUIREMENT_ID.findall(block)
|
||
if len(ids) != 1:
|
||
return [f"{name}: нужен один стабильный **ID:** с префиксом capability и номером Requirement"]
|
||
requirement_id = ids[0]
|
||
is_qualified = "." in requirement_id
|
||
if require_qualified_ids and not is_qualified:
|
||
errors.append("новый или изменённый Requirement должен иметь составной ID capability, например CFG.AS-01")
|
||
level_four = re.findall(r"^#### (.+)$", block, re.MULTILINE)
|
||
has_contract = len(level_four) == 3 and level_four[2] == "CONTRACT"
|
||
expected_level_four = ["Функциональные требования", "CONTRACT"] if has_contract else ["Функциональные требования"]
|
||
if (
|
||
len(level_four) != len(expected_level_four) + 1
|
||
or not level_four[0].startswith("Scenario: ")
|
||
or level_four[1:] != expected_level_four
|
||
):
|
||
return [f"{name}: нужны один Scenario, Функциональные требования и опциональный завершающий CONTRACT"]
|
||
|
||
scenario_heading = level_four[0].removeprefix("Scenario: ")
|
||
is_short_use_case = scenario_heading.startswith("Сокращенный use case:")
|
||
scenario, details = block.split("#### Функциональные требования", 1)
|
||
scenario = scenario.split("#### Scenario:", 1)[1].split("\n", 1)[1]
|
||
if has_contract:
|
||
if is_short_use_case:
|
||
errors.append("Requirement с HTTP CONTRACT должен использовать полный Use case")
|
||
details, contract_content = details.split("#### CONTRACT", 1)
|
||
errors.extend(check_http_endpoint_contract(contract_content))
|
||
sections = re.findall(r"^##### (.+)$", scenario, re.MULTILINE)
|
||
narrative = ""
|
||
outcomes = ""
|
||
short_use_case_flow_lines: list[str] = []
|
||
|
||
if is_short_use_case:
|
||
if sections != ["Основной поток"]:
|
||
errors.append("сокращенный use case должен содержать только Основной поток")
|
||
before_flow, separator, flow = scenario.partition("##### Основной поток")
|
||
if not separator or before_flow.strip():
|
||
errors.append("сокращенный use case содержит только раздел Основной поток")
|
||
short_use_case_flow_lines = [line.strip() for line in flow.splitlines() if line.strip()]
|
||
if any(not re.match(r"^\d+\. .+", line) for line in short_use_case_flow_lines):
|
||
errors.append("основной поток сокращенного use case содержит только нумерованные шаги")
|
||
if any(len(plain_text(line)) > 240 for line in short_use_case_flow_lines):
|
||
errors.append("шаг сокращенного use case длиннее 240 знаков; детали должны быть в FR")
|
||
else:
|
||
required = [section for section in sections if section != "Назначение"]
|
||
if required != list(SECTIONS) or sections.count("Назначение") > 1:
|
||
errors.append("разделы Scenario не соответствуют шаблону")
|
||
if "Назначение" in sections and sections[0] != "Назначение":
|
||
errors.append("опциональное Назначение должно предшествовать Участники")
|
||
for section in sections:
|
||
content = re.split(r"^##### ", scenario.split(f"##### {section}\n", 1)[1], maxsplit=1, flags=re.MULTILINE)[0]
|
||
if not content.strip():
|
||
errors.append(f"пустой раздел Scenario: {section}")
|
||
|
||
narrative, separator, outcomes = scenario.partition("##### Коды завершения")
|
||
if not separator:
|
||
errors.append("нет списка кодов завершения")
|
||
if re.search(r"^\s*\|", narrative, re.MULTILINE):
|
||
errors.append("техническая таблица должна находиться в FR")
|
||
for paragraph in re.split(r"\n\s*\n", narrative):
|
||
lines = [line for line in paragraph.splitlines() if line.strip() and not line.startswith("#")]
|
||
chunks = lines if all(re.match(r"^(?:\d+\.|-) ", line) for line in lines) else [" ".join(lines)]
|
||
if any(len(plain_text(chunk)) > 240 for chunk in chunks):
|
||
errors.append("абзац или шаг Scenario длиннее 240 знаков; перенеси детали в FR")
|
||
|
||
if re.search(r"(?im)^\s*(?:[-*]\s*)?(?:\*\*)?(?:GIVEN|WHEN|THEN|AND|BUT)\b", scenario):
|
||
errors.append("Scenario содержит Gherkin")
|
||
if "```" in scenario or "~~~" in scenario:
|
||
errors.append("блок кода должен находиться в FR")
|
||
|
||
flow = scenario.partition("##### Основной поток")[2]
|
||
if not is_short_use_case:
|
||
flow = flow.partition("##### Альтернативы и ошибки")[0]
|
||
steps = [int(number) for number in re.findall(r"^(\d+)\. ", flow, re.MULTILINE)]
|
||
if not steps or steps != list(range(1, len(steps) + 1)):
|
||
errors.append("основной поток должен содержать последовательные нумерованные шаги")
|
||
|
||
raw_definitions = list(FR_HEADING.finditer(details))
|
||
if len(raw_definitions) != len(re.findall(r"^##### ", details, re.MULTILINE)):
|
||
errors.append("подразделы Функциональных требований должны иметь заголовки с ID вида <requirement-id>.FR-NN")
|
||
definitions: list[tuple[re.Match[str], re.Match[str]]] = []
|
||
for match in raw_definitions:
|
||
fr_id_match = FR_ID.fullmatch(match.group(1))
|
||
if not fr_id_match:
|
||
errors.append(f"некорректный ID FR в заголовке: {match.group(1)}")
|
||
continue
|
||
definitions.append((match, fr_id_match))
|
||
numbers = [int(fr_id_match.group("number").removeprefix("FR-")) for _, fr_id_match in definitions]
|
||
if not numbers or numbers[0] != 1 or numbers != sorted(set(numbers)):
|
||
errors.append("FR должны начинаться с FR-01 и иметь уникальные возрастающие номера")
|
||
|
||
fr_contents: dict[str, str] = {}
|
||
for index, (match, fr_id_match) in enumerate(definitions):
|
||
fr_id = fr_id_match.group("number")
|
||
expected_fr_id = f"{requirement_id}.{fr_id}" if is_qualified else fr_id
|
||
if match.group(1) != expected_fr_id:
|
||
errors.append(f"заголовок FR должен использовать полный ID {expected_fr_id}")
|
||
target = heading_slug(match.group(0).removeprefix("##### "))
|
||
if fr_targets.get(target) != (requirement_id, fr_id):
|
||
errors.append(f"заголовок {match.group(1)} не создаёт ожидаемый Markdown-якорь")
|
||
next_definition = definitions[index + 1][0] if index + 1 < len(definitions) else None
|
||
end = next_definition.start() if next_definition else len(details)
|
||
fr_contents[fr_id] = details[match.end():end]
|
||
format_type = match.group(2)
|
||
title = match.group(3)
|
||
if format_type == "DB" or title.lower().startswith("таблица хранения "):
|
||
errors.extend(check_database_table_pattern(fr_contents[fr_id]))
|
||
if format_type == "API" and re.match(r"контракт (?:сообщения|запроса|ответа)\b", title, re.IGNORECASE):
|
||
errors.extend(check_message_contract_pattern(fr_contents[fr_id]))
|
||
if has_contract and format_type == "API":
|
||
errors.append("HTTP request/response-контракт описывается в CONTRACT, не в FR [API]")
|
||
|
||
for label, raw_target in LINK.findall(block):
|
||
target = unquote(raw_target)
|
||
if target not in targets:
|
||
errors.append(f"ссылка {label} ведёт на отсутствующий Markdown-заголовок #{target}")
|
||
continue
|
||
linked_fr = parse_fr_reference(label)
|
||
if "FR-" in label and not linked_fr:
|
||
errors.append(f"ссылка {label} должна содержать полный ID FR")
|
||
if linked_fr:
|
||
target_fr = fr_targets.get(target)
|
||
linked_requirement, linked_number = linked_fr
|
||
if target_fr is None or target_fr[1] != linked_number:
|
||
errors.append(f"ссылка {label} должна вести на заголовок соответствующего FR")
|
||
if linked_requirement and target_fr and target_fr[0] != linked_requirement:
|
||
errors.append(f"ссылка {label} ведёт на FR другого Requirement")
|
||
if target_fr and "." in target_fr[0] and label != f"{target_fr[0]}.{target_fr[1]}":
|
||
errors.append(f"ссылка {label} должна использовать полный ID {target_fr[0]}.{target_fr[1]}")
|
||
|
||
if is_short_use_case:
|
||
for step in short_use_case_flow_lines:
|
||
has_local_fr = False
|
||
for label, raw_target in LINK.findall(step):
|
||
linked_fr = parse_fr_reference(label)
|
||
target_fr = fr_targets.get(unquote(raw_target))
|
||
expected_label = f"{requirement_id}.FR-{linked_fr[1].removeprefix('FR-')}" if linked_fr and is_qualified else (linked_fr[1] if linked_fr else "")
|
||
if linked_fr and target_fr == (requirement_id, linked_fr[1]) and label == expected_label:
|
||
has_local_fr = True
|
||
break
|
||
if not has_local_fr:
|
||
errors.append("каждый шаг сокращенного use case должен ссылаться на локальный FR")
|
||
else:
|
||
rows = [line for line in outcomes.splitlines() if line.startswith("|")]
|
||
if not rows or rows[0] != "| Код | Смысл | Связанные FR |":
|
||
errors.append("таблица завершения должна иметь колонки Код, Смысл, Связанные FR")
|
||
codes = []
|
||
for row in rows[2:]:
|
||
cells = [cell.strip() for cell in row.strip("|").split("|")]
|
||
if len(cells) != 3 or not re.fullmatch(r"`[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+`", cells[0]):
|
||
errors.append("некорректная строка таблицы кодов завершения")
|
||
continue
|
||
code = cells[0].strip("`")
|
||
codes.append(code)
|
||
references = [
|
||
fr_targets[target][1]
|
||
for _, raw_target in LINK.findall(cells[2])
|
||
if (target := unquote(raw_target)) in fr_targets
|
||
and fr_targets[target][0] == requirement_id
|
||
]
|
||
if not cells[1] or not references or not any(code in fr_contents[fr_id] for fr_id in references if fr_id in fr_contents):
|
||
errors.append(f"{code}: нужны смысл и ссылка на локальный FR, описывающий этот код")
|
||
if not codes or len(codes) != len(set(codes)):
|
||
errors.append("список кодов завершения пуст или содержит дубликаты")
|
||
if set(CODE.findall(narrative)) != set(codes):
|
||
errors.append("коды в потоке/альтернативах должны совпадать со списком завершения")
|
||
return [f"{requirement_id}: {error}" for error in errors]
|
||
|
||
def validate(
|
||
path: Path,
|
||
base: Path | None = None,
|
||
require_qualified_ids: bool = False,
|
||
capability_codes: dict[str, str] | None = None,
|
||
) -> list[str]:
|
||
text = path.read_text(encoding="utf-8")
|
||
if HTML_ANCHOR.search(text):
|
||
return ["HTML-якоря запрещены; используйте автоматически сгенерированные Markdown-якоря заголовков"]
|
||
|
||
targets, fr_targets = heading_targets(text)
|
||
if base:
|
||
base_targets, base_fr_targets = heading_targets(base.read_text(encoding="utf-8"))
|
||
targets.update(base_targets)
|
||
fr_targets.update(base_fr_targets)
|
||
|
||
errors = []
|
||
if capability_codes is None:
|
||
capability_codes, registry_errors = load_capability_codes()
|
||
errors.extend(registry_errors)
|
||
blocks = list(requirement_blocks(text))
|
||
ids = REQUIREMENT_ID.findall(text)
|
||
if len(ids) != len(set(ids)):
|
||
errors.append("повторяющиеся ID Requirements")
|
||
capability_path = spec_capability_path(path)
|
||
for requirement_id in ids:
|
||
if "." not in requirement_id:
|
||
continue
|
||
prefix = capability_codes.get(capability_path or "")
|
||
if not prefix:
|
||
errors.append(f"для capability {capability_path or '<не определена>'} нет префикса в capability-codes.md")
|
||
elif not re.fullmatch(rf"{re.escape(prefix)}-\d{{2,}}", requirement_id):
|
||
errors.append(f"ID {requirement_id} не соответствует префиксу {prefix} для {capability_path}")
|
||
if not blocks and not re.search(r"^## (REMOVED|RENAMED) Requirements$", text, re.MULTILINE):
|
||
errors.append("нет Requirements")
|
||
for name, block in blocks:
|
||
errors.extend(check_requirement(name, block, targets, fr_targets, require_qualified_ids))
|
||
return errors
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("paths", nargs="*", type=Path, default=[Path("openspec/specs")])
|
||
parser.add_argument("--base", type=Path, help="master spec referenced from a delta")
|
||
parser.add_argument(
|
||
"--require-qualified-ids",
|
||
action="store_true",
|
||
help="требовать составные ID у Requirements в новых или изменённых specs",
|
||
)
|
||
args = parser.parse_args()
|
||
paths = sorted({file for path in args.paths for file in (path.rglob("spec.md") if path.is_dir() else [path])})
|
||
if not paths:
|
||
parser.error("не найдены spec.md")
|
||
capability_codes, registry_errors = load_capability_codes()
|
||
failed = False
|
||
for error in registry_errors:
|
||
print(f"ERROR {CAPABILITY_CODES_PATH}: {error}")
|
||
failed = True
|
||
for path in paths:
|
||
try:
|
||
errors = validate(path, args.base, args.require_qualified_ids, capability_codes)
|
||
except OSError as error:
|
||
errors = [str(error)]
|
||
for error in errors:
|
||
print(f"ERROR {path}: {error}")
|
||
if not errors:
|
||
print(f"OK {path}")
|
||
failed |= bool(errors)
|
||
return int(failed)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|