2024-02-08 22:34:48 +01:00
|
|
|
#!/usr/bin/env python3
|
2024-02-07 14:49:55 +01:00
|
|
|
|
2024-08-19 17:09:53 +02:00
|
|
|
import argparse
|
2022-08-04 11:17:46 +02:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import subprocess
|
2024-02-07 14:49:55 +01:00
|
|
|
import sys
|
2024-09-12 18:03:30 +02:00
|
|
|
import logging
|
2024-06-23 02:46:05 +02:00
|
|
|
import time
|
2024-09-12 18:03:30 +02:00
|
|
|
from typing import Optional, TypeVar, Iterable, Generator
|
2024-05-20 18:00:15 +02:00
|
|
|
from pathlib import Path
|
2024-02-07 14:49:55 +01:00
|
|
|
|
|
|
|
import requests
|
2024-09-12 18:03:30 +02:00
|
|
|
import tqdm
|
2024-06-23 02:46:05 +02:00
|
|
|
import toml
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
from git import Repo, Head, Actor
|
|
|
|
|
2024-06-23 02:46:05 +02:00
|
|
|
# add apps/tools to sys.path
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
2024-05-20 18:00:15 +02:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
from app_caches import AppDir
|
2024-06-23 02:46:05 +02:00
|
|
|
from appslib.utils import ( # noqa: E402 pylint: disable=import-error,wrong-import-position
|
|
|
|
get_catalog,
|
|
|
|
)
|
2024-09-12 18:03:30 +02:00
|
|
|
import appslib.get_apps_repo as get_apps_repo
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-08-13 08:44:04 +02:00
|
|
|
TOOLS_DIR = Path(__file__).resolve().parent.parent
|
|
|
|
|
2022-08-04 11:17:46 +02:00
|
|
|
my_env = os.environ.copy()
|
|
|
|
my_env["GIT_TERMINAL_PROMPT"] = "0"
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
LOGIN = (TOOLS_DIR / ".github_login").open("r", encoding="utf-8").read().strip()
|
|
|
|
TOKEN = (TOOLS_DIR / ".github_token").open("r", encoding="utf-8").read().strip()
|
2022-08-04 11:17:46 +02:00
|
|
|
github_api = "https://api.github.com"
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
PATCHES_PATH = Path(__file__).resolve().parent / "patches"
|
|
|
|
|
2022-08-04 11:17:46 +02:00
|
|
|
|
|
|
|
def apps(min_level=4):
|
2024-06-23 02:46:05 +02:00
|
|
|
for app, infos in get_catalog().items():
|
2022-08-04 11:17:46 +02:00
|
|
|
if infos.get("state") == "working" and infos.get("level", -1) > min_level:
|
|
|
|
infos["id"] = app
|
|
|
|
yield infos
|
|
|
|
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
class AppToPatch:
|
|
|
|
def __init__(self, id: str, path: Path, info: dict) -> None:
|
|
|
|
self.id = id
|
|
|
|
self.path = path
|
|
|
|
self.info = info
|
|
|
|
self.patch: Optional[str] = None
|
|
|
|
self._repo: Optional[Repo] = None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def repo(self) -> Repo:
|
|
|
|
if self._repo is None:
|
|
|
|
self._repo = Repo(self.path)
|
|
|
|
return self._repo
|
|
|
|
|
|
|
|
def cache(self) -> None:
|
|
|
|
appdir = AppDir(self.id, self.path)
|
|
|
|
appdir.ensure(self.info["url"], self.info.get("branch", "master"), False, False)
|
|
|
|
|
|
|
|
def reset(self) -> None:
|
|
|
|
if self.get_diff():
|
|
|
|
logging.warning("%s had local changes, they were stashed.", self.id)
|
|
|
|
self.repo.git.stash("save")
|
|
|
|
self.repo.git.checkout("testing")
|
|
|
|
|
|
|
|
def apply(self, patch: str) -> None:
|
|
|
|
current_branch = self.repo.active_branch
|
|
|
|
self.repo.head.reset(f"{current_branch}", index=True, working_tree=True)
|
|
|
|
subprocess.call([PATCHES_PATH / patch / "patch"], cwd=self.path)
|
|
|
|
|
|
|
|
def get_diff(self) -> str:
|
|
|
|
return " ".join(str(d) for d in self.repo.index.diff(None, create_patch=True))
|
|
|
|
|
|
|
|
def diff(self) -> None:
|
|
|
|
diff = self.get_diff()
|
|
|
|
if not diff:
|
|
|
|
return
|
|
|
|
print(80 * "=")
|
|
|
|
print(f"Changes in : {self.id}")
|
|
|
|
print(80 * "=")
|
|
|
|
print()
|
|
|
|
print(diff)
|
|
|
|
print("\n\n\n")
|
|
|
|
|
|
|
|
def on_github(self) -> bool:
|
|
|
|
return "github.com/yunohost-apps" in self.info["url"].lower()
|
|
|
|
|
|
|
|
def fork_if_needed(self, session: requests.Session) -> None:
|
|
|
|
repo_name = self.info["url"].split("/")[-1]
|
|
|
|
r = session.get(github_api + f"/repos/{LOGIN}/{repo_name}")
|
|
|
|
if r.status_code == 200:
|
|
|
|
return
|
|
|
|
|
|
|
|
fork_repo_name = self.info["url"].split("github.com/")[-1]
|
|
|
|
r = session.post(github_api + f"/repos/{fork_repo_name}/forks")
|
|
|
|
r.raise_for_status()
|
|
|
|
time.sleep(2) # to avoid rate limiting lol
|
|
|
|
|
|
|
|
def commit(self, patch: str) -> None:
|
|
|
|
pr_title = (PATCHES_PATH / patch / "pr_title.md").open().read().strip()
|
|
|
|
title = f"[autopatch] {pr_title}"
|
|
|
|
self.repo.git.add(all=True)
|
|
|
|
self.repo.index.commit(title, author=Actor("Yunohost-Bot", None))
|
|
|
|
|
|
|
|
def push(self, patch: str, session: requests.Session) -> None:
|
|
|
|
if not self.get_diff():
|
|
|
|
return
|
|
|
|
|
|
|
|
if not self.on_github():
|
|
|
|
return
|
|
|
|
|
|
|
|
self.fork_if_needed(session)
|
|
|
|
|
|
|
|
base_branch = self.repo.active_branch
|
|
|
|
if patch in self.repo.heads:
|
|
|
|
self.repo.delete_head(patch)
|
|
|
|
head_branch = self.repo.create_head(patch)
|
|
|
|
head_branch.checkout()
|
|
|
|
|
|
|
|
self.commit(patch)
|
|
|
|
|
|
|
|
if "fork" in self.repo.remotes:
|
|
|
|
self.repo.delete_remote(self.repo.remote("fork"))
|
|
|
|
reponame = self.info["url"].rsplit("/", 1)[-1]
|
|
|
|
self.repo.create_remote(
|
|
|
|
"fork", url=f"https://{LOGIN}:{TOKEN}@github.com/{LOGIN}/{reponame}"
|
|
|
|
)
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
self.repo.remote(name="fork").push(progress=None, force=True)
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
self.create_pull_request(patch, head_branch, base_branch, session)
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
def create_pull_request(
|
|
|
|
self, patch: str, head: Head, base: Head, session: requests.Session
|
|
|
|
) -> None:
|
|
|
|
pr_title = (PATCHES_PATH / patch / "pr_title.md").open().read().strip()
|
|
|
|
pr_body = (PATCHES_PATH / patch / "pr_body.md").open().read().strip()
|
|
|
|
PR = {
|
|
|
|
"title": f"[autopatch] {pr_title}",
|
|
|
|
"body": f"This is an automatic PR\n\n{pr_body}",
|
|
|
|
"head": f"{LOGIN}:{head.name}",
|
|
|
|
"base": base.name,
|
|
|
|
"maintainer_can_modify": True,
|
|
|
|
}
|
2024-03-11 17:34:33 +01:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
fork_repo_name = self.info["url"].split("github.com/")[-1]
|
|
|
|
repo_name = self.info["url"].split("/")[-1]
|
|
|
|
r = session.post(github_api + f"/repos/{fork_repo_name}/pulls", json.dumps(PR))
|
|
|
|
r.raise_for_status()
|
|
|
|
print(json.loads(r.text)["html_url"])
|
|
|
|
time.sleep(4) # to avoid rate limiting lol
|
2022-08-04 11:17:46 +02:00
|
|
|
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
IterType = TypeVar("IterType")
|
2022-08-04 11:17:46 +02:00
|
|
|
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
def progressbar(elements: list[IterType]) -> Generator[IterType, None, None]:
|
|
|
|
return tqdm.tqdm(elements, total=len(elements), ascii=" ·#")
|
2022-08-04 11:17:46 +02:00
|
|
|
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
def main() -> None:
|
2024-08-19 17:09:53 +02:00
|
|
|
parser = argparse.ArgumentParser()
|
2024-09-12 18:03:30 +02:00
|
|
|
get_apps_repo.add_args(parser)
|
2024-09-12 14:48:36 +02:00
|
|
|
parser.add_argument(
|
|
|
|
"the_patch", type=str, nargs="?", help="The name of the patch to apply"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--cache", "-b", action="store_true", help="Init local git clone for all apps"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--apply", "-a", action="store_true", help="Apply patch on all local clones"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--diff", "-d", action="store_true", help="Inspect diff for all apps"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--push",
|
|
|
|
"-p",
|
|
|
|
action="store_true",
|
|
|
|
help="Push and create pull requests on all apps with non-empty diff",
|
|
|
|
)
|
2024-08-19 17:09:53 +02:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
get_apps_repo.from_args(args)
|
|
|
|
cache_path = get_apps_repo.cache_path(args)
|
|
|
|
cache_path.mkdir(exist_ok=True, parents=True)
|
|
|
|
|
2024-08-19 17:09:53 +02:00
|
|
|
if not (args.cache or args.apply or args.diff or args.push):
|
|
|
|
parser.error("We required --cache, --apply, --diff or --push.")
|
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
apps_to_patch: list[AppToPatch] = [
|
|
|
|
AppToPatch(info["id"], cache_path / info["id"], info) for info in apps()
|
|
|
|
]
|
|
|
|
|
2024-08-19 17:09:53 +02:00
|
|
|
if args.cache:
|
2024-09-12 18:03:30 +02:00
|
|
|
print("Caching apps...")
|
|
|
|
for app in progressbar(apps_to_patch):
|
|
|
|
app.cache()
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-08-19 17:09:53 +02:00
|
|
|
if args.apply:
|
|
|
|
if not args.the_patch:
|
|
|
|
parser.error("--apply requires the patch name to be passed")
|
2024-09-12 18:03:30 +02:00
|
|
|
print(f"Applying patch '{args.the_patch}' to apps...")
|
|
|
|
for app in progressbar(apps_to_patch):
|
|
|
|
app.reset()
|
|
|
|
app.apply(args.the_patch)
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-08-19 17:09:53 +02:00
|
|
|
if args.diff:
|
2024-09-12 18:03:30 +02:00
|
|
|
print("Printing diff of apps...")
|
|
|
|
for app in progressbar(apps_to_patch):
|
|
|
|
app.diff()
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-08-19 17:09:53 +02:00
|
|
|
if args.push:
|
|
|
|
if not args.the_patch:
|
|
|
|
parser.error("--push requires the patch name to be passed")
|
2024-09-12 18:03:30 +02:00
|
|
|
print("Pushing apps...")
|
|
|
|
with requests.Session() as session:
|
|
|
|
session.headers.update({"Authorization": f"token {TOKEN}"})
|
|
|
|
for app in progressbar(apps_to_patch):
|
|
|
|
app.push(args.the_patch, session)
|
2022-08-04 11:17:46 +02:00
|
|
|
|
2024-09-12 14:48:36 +02:00
|
|
|
|
2024-09-12 18:03:30 +02:00
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|