Список и запуск целей Makefile
Показывает цели Makefile с описаниями, по умолчанию делает dry-run и защищает опасные цели.
Что делает скрипт
Скрипт разбирает простые цели Makefile и печатает их вместе с комментариями после ##. Без --apply выполняется make -n, поэтому команды только показываются. Для целей clean, distclean, install и deploy требуется дополнительный флаг --force.
- Цели clean и install меняют проект. Для них нужен --force.
Быстрый старт
python makefile_runner.py --path . --target test
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python makefile_runner.py --path .python makefile_runner.py --path . --target buildpython makefile_runner.py --path . --target test --apply
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
choco install make -y
brew install make
sudo apt install make
makefile_runner.py
#!/usr/bin/env python3
"""Просмотр и безопасный запуск целей Makefile."""
from __future__ import annotations
import argparse
import re
import shutil
import subprocess
from pathlib import Path
TARGET_RE = re.compile(r"^([A-Za-z0-9_][A-Za-z0-9_.-]*)\s*:(?!=)")
DANGEROUS = {"clean", "distclean", "mrproper", "install", "uninstall", "deploy", "release"}
def find_makefile(root: Path) -> Path | None:
for name in ("GNUmakefile", "Makefile", "makefile"):
candidate = root / name
if candidate.is_file():
return candidate
return None
def parse_targets(path: Path) -> dict[str, str]:
targets: dict[str, str] = {}
for raw in path.read_text(encoding="utf-8", errors="replace").splitlines():
if raw.startswith("\t") or raw.lstrip().startswith("#"):
continue
match = TARGET_RE.match(raw)
if not match:
continue
name = match.group(1)
if name.startswith(".") or "%" in name:
continue
description = ""
if "##" in raw:
description = raw.split("##", 1)[1].strip()
targets[name] = description
return targets
def main() -> int:
parser = argparse.ArgumentParser(description="Запустить цель Makefile")
parser.add_argument("--path", type=Path, default=Path("."), help="Папка проекта")
parser.add_argument("--target", help="Имя цели")
parser.add_argument("--apply", action="store_true", help="Выполнить цель")
parser.add_argument("--force", action="store_true", help="Разрешить опасную цель")
args = parser.parse_args()
root = args.path.expanduser().resolve()
if not root.is_dir():
print(f"Папка не найдена: {root}")
return 2
makefile = find_makefile(root)
if not makefile:
print("Makefile не найден.")
return 2
if not shutil.which("make"):
print("Не найден make. Установите GNU Make.")
return 2
targets = parse_targets(makefile)
if not targets:
print("В Makefile не найдено простых целей.")
return 0
if not args.target:
print(f"Makefile: {makefile}")
for name in sorted(targets):
description = targets[name]
print(f" {name:24} {description}")
print("Укажите --target для запуска.")
return 0
if args.target not in targets:
print(f"Цель не найдена: {args.target}")
return 2
if args.target in DANGEROUS and not args.force:
print(f"Цель {args.target} может изменить или удалить файлы. Добавьте --force.")
return 2
command = ["make", "-C", str(root)]
if not args.apply:
command.append("-n")
command.append(args.target)
print("Команда: " + " ".join(command))
result = subprocess.run(command, text=True)
if not args.apply:
print("Это dry-run. Для выполнения добавьте --apply.")
return result.returncode
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.