aides-spec/alr_spec/main.py
2024-12-01 22:24:12 +03:00

99 lines
2.6 KiB
Python

import argparse
import sys
from typing import Annotated, Optional
import requests
import typer
import tree_sitter_bash as tsbash
from tree_sitter import Language, Parser
from alr_spec.replacers.arch_replacer import ArchReplacer
from alr_spec.replacers.simple_replacer import SimpleReplacer
from alr_spec.replacers.sources_replacer import SourcesReplacer
def download_pkgbuild(pkgname):
aur_url = (
f"https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h={pkgname}"
)
try:
response = requests.get(aur_url)
response.raise_for_status()
return response.content
except requests.RequestException as e:
print(f"Ошибка загрузки PKGBUILD из AUR: {e}")
sys.exit(1)
parser_ts = None
def process_file(content, tree, replacers):
for replacer_class in replacers:
replacer = replacer_class(content, tree)
content = replacer.process()
tree = parser_ts.parse(content, tree)
return content
def create_from_pkgbuild(content, output_file):
global parser_ts
BASH_LANGUAGE = Language(tsbash.language())
parser_ts = Parser(BASH_LANGUAGE)
tree = parser_ts.parse(content)
replacers = [
SimpleReplacer,
ArchReplacer,
SourcesReplacer,
]
new_content = process_file(content, tree, replacers)
try:
with open(output_file, "wb") as f:
f.write(new_content)
print(f"Файл успешно записан в {output_file}.")
except IOError as e:
print(f"Ошибка при записи файла: {e}")
sys.exit(1)
app = typer.Typer()
@app.command()
def lint(name: str):
print(f"Hello {name}")
@app.command()
def create(
from_aur: Annotated[Optional[str], typer.Option()] = None,
from_pkgbuild: Annotated[Optional[str], typer.Option()] = None,
output_file: Annotated[str, typer.Option("--output", "-o")] = "alr.sh",
):
if from_aur:
print(f"Загружаем PKGBUILD для пакета '{from_aur}' из AUR...")
content = download_pkgbuild(from_aur)
create_from_pkgbuild(content, output_file)
elif from_pkgbuild:
print(f"Читаем PKGBUILD из локального файла '{from_pkgbuild}'...")
try:
with open(from_pkgbuild, "rb") as f:
content = f.read()
create_from_pkgbuild(content, output_file)
except IOError as e:
print(f"Ошибка чтения файла '{from_pkgbuild}': {e}")
sys.exit(1)
else:
sys.exit(1)
def main():
app()
if __name__ == "__main__":
main()