aides-spec/aides_spec/utils/from_pkgbuild.py
2025-01-05 11:37:11 +03:00

103 lines
3 KiB
Python

import os
import shutil
import sys
import tempfile
import git
import tree_sitter_bash as tsbash
from tree_sitter import Language, Parser
from aides_spec.replacers.arch_replacer import ArchReplacer
# from aides_spec.replacers.checksums_replacer import ChecksumsReplacer
# from aides_spec.replacers.local_sources_replacer import LocalSourcesReplacer
from aides_spec.replacers.simple_replacer import SimpleReplacer
from aides_spec.replacers.sources import SourcesReplacer
parser_ts = None
def download_pkgbuild_and_all_files(pkgname):
aur_url = f"https://aur.archlinux.org/{pkgname}.git"
with tempfile.TemporaryDirectory() as tmpdirname:
try:
print(f"Клонируем репозиторий для {pkgname}")
git.Repo.clone_from(aur_url, tmpdirname)
print(f"Файлы для {pkgname} загружены в {tmpdirname}")
for root, dirs, files in os.walk(tmpdirname):
dirs[:] = [d for d in dirs if d not in [".git"]]
files = [
file
for file in files
if file not in ["PKGBUILD", ".SRCINFO"]
]
for file in files:
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, tmpdirname)
destination_path = os.path.join(os.getcwd(), relative_path)
os.makedirs(
os.path.dirname(destination_path), exist_ok=True
)
shutil.copy(file_path, destination_path)
with open(os.path.join(tmpdirname, "PKGBUILD"), "rb") as f:
return f.read()
return
except Exception as e:
print(f"Ошибка при скачивании репозитория: {e}")
sys.exit(1)
def download_pkgbuild(pkgname):
return download_pkgbuild_and_all_files(pkgname)
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
HEADER = """#
# WARNING: Automatic converted from PKGBUILD and may contains errors
#
"""
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,
# LocalSourcesReplacer,
# ChecksumsReplacer,
]
new_content = process_file(content, tree, replacers)
new_content = bytes(HEADER, encoding="utf-8") + new_content
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)