2022-10-17 19:54:47 +02:00
|
|
|
import fnmatch
|
2022-10-17 14:55:30 +02:00
|
|
|
import logging
|
2022-11-06 12:18:16 +01:00
|
|
|
import os
|
2022-10-17 19:54:47 +02:00
|
|
|
import pathlib
|
2022-10-17 14:55:30 +02:00
|
|
|
import subprocess
|
|
|
|
|
2022-11-06 12:18:16 +01:00
|
|
|
import requests
|
2022-10-17 19:54:47 +02:00
|
|
|
|
|
|
|
from lib.binary import BINARY
|
2022-10-17 14:58:18 +02:00
|
|
|
|
|
|
|
LFS_SUFFIX = "filter=lfs diff=lfs merge=lfs -text"
|
2022-10-17 14:55:30 +02:00
|
|
|
|
2022-10-17 15:17:25 +02:00
|
|
|
|
2022-10-17 14:55:30 +02:00
|
|
|
class Git:
|
|
|
|
"""Local git repository"""
|
|
|
|
|
|
|
|
def __init__(self, path, committer=None, committer_email=None):
|
|
|
|
self.path = pathlib.Path(path)
|
|
|
|
self.committer = committer
|
|
|
|
self.committer_email = committer_email
|
|
|
|
|
|
|
|
def exists(self):
|
|
|
|
"""Check if the path is a valid git repository"""
|
|
|
|
return (self.path / ".git").exists()
|
|
|
|
|
|
|
|
def create(self):
|
|
|
|
"""Create a local git repository"""
|
|
|
|
self.path.mkdir(parents=True, exist_ok=True)
|
2022-11-06 12:18:16 +01:00
|
|
|
self.open()
|
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
def git_run(self, args, **kwargs):
|
|
|
|
"""Run a git command"""
|
|
|
|
if "env" in kwargs:
|
|
|
|
envs = kwargs["env"].copy()
|
|
|
|
del kwargs["env"]
|
|
|
|
else:
|
|
|
|
envs = os.environ.copy()
|
|
|
|
envs["GIT_LFS_SKIP_SMUDGE"] = "1"
|
|
|
|
envs["GIT_CONFIG_GLOBAL"] = "/dev/null"
|
|
|
|
return subprocess.run(
|
|
|
|
["git"] + args,
|
2024-04-08 14:55:37 +02:00
|
|
|
cwd=self.path,
|
|
|
|
check=True,
|
2024-05-17 14:41:42 +02:00
|
|
|
env=envs,
|
|
|
|
**kwargs,
|
2024-04-08 14:55:37 +02:00
|
|
|
)
|
2022-10-17 14:55:30 +02:00
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
def open(self):
|
2024-05-17 20:05:54 +02:00
|
|
|
if not self.exists():
|
|
|
|
self.git_run(["init", "--object-format=sha256", "-b", "factory"])
|
2024-05-17 21:47:35 +02:00
|
|
|
self.git_run(["config", "lfs.allowincompletepush", "true"])
|
2024-05-17 14:41:42 +02:00
|
|
|
|
2022-10-17 14:55:30 +02:00
|
|
|
def is_dirty(self):
|
|
|
|
"""Check if there is something to commit"""
|
2024-05-17 14:41:42 +02:00
|
|
|
status_str = self.git_run(
|
|
|
|
["status", "--porcelain=2"],
|
2024-04-08 14:55:37 +02:00
|
|
|
stdout=subprocess.PIPE,
|
2024-05-17 14:41:42 +02:00
|
|
|
).stdout.decode("utf-8")
|
|
|
|
return len(list(filter(None, status_str.split("\n")))) > 0
|
2022-10-17 14:55:30 +02:00
|
|
|
|
|
|
|
def branches(self):
|
2024-05-17 14:41:42 +02:00
|
|
|
br = (
|
|
|
|
self.git_run(
|
|
|
|
["for-each-ref", "--format=%(refname:short)", "refs/heads/"],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
)
|
|
|
|
.stdout.decode("utf-8")
|
|
|
|
.split()
|
|
|
|
)
|
2024-04-08 14:55:37 +02:00
|
|
|
if len(br) == 0:
|
2024-05-17 14:41:42 +02:00
|
|
|
br.append("factory") # unborn branch?
|
2024-04-08 14:55:37 +02:00
|
|
|
return br
|
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
def branch(self, branch, commit="HEAD"):
|
|
|
|
commit = (
|
|
|
|
self.git_run(
|
|
|
|
["rev-parse", "--verify", "--end-of-options", commit + "^{commit}"],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
)
|
|
|
|
.stdout.decode("utf-8")
|
|
|
|
.strip()
|
|
|
|
)
|
|
|
|
return self.git_run(["branch", branch, commit])
|
2022-10-17 14:55:30 +02:00
|
|
|
|
|
|
|
def checkout(self, branch):
|
|
|
|
"""Checkout into the branch HEAD"""
|
|
|
|
new_branch = False
|
|
|
|
if branch not in self.branches():
|
2024-06-10 15:35:11 +02:00
|
|
|
self.git_run(["switch", "-q", "--orphan", branch])
|
2022-10-17 14:55:30 +02:00
|
|
|
new_branch = True
|
|
|
|
else:
|
2024-04-08 14:55:37 +02:00
|
|
|
ref = f"refs/heads/{branch}"
|
2024-05-17 14:41:42 +02:00
|
|
|
if (self.path / ".git" / ref).exists():
|
2024-05-17 20:07:16 +02:00
|
|
|
self.git_run(["switch", "--no-guess", "-q", branch])
|
2022-10-17 14:55:30 +02:00
|
|
|
return new_branch
|
|
|
|
|
|
|
|
def commit(
|
|
|
|
self,
|
|
|
|
user,
|
|
|
|
user_email,
|
|
|
|
user_time,
|
|
|
|
message,
|
|
|
|
parents=None,
|
|
|
|
committer=None,
|
|
|
|
committer_email=None,
|
|
|
|
committer_time=None,
|
|
|
|
):
|
|
|
|
"""Add all the files and create a new commit in the current HEAD"""
|
|
|
|
|
|
|
|
if not committer:
|
|
|
|
committer = self.committer if self.committer else self.user
|
|
|
|
committer_email = (
|
|
|
|
self.committer_email if self.committer_email else self.user_email
|
|
|
|
)
|
|
|
|
committer_time = committer_time if committer_time else user_time
|
|
|
|
|
2022-11-06 09:49:52 +01:00
|
|
|
if self.is_dirty():
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(["add", "--all", "."])
|
2022-10-17 14:55:30 +02:00
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
tree_id = (
|
|
|
|
self.git_run(["write-tree"], stdout=subprocess.PIPE)
|
|
|
|
.stdout.decode("utf-8")
|
|
|
|
.strip()
|
|
|
|
)
|
2024-04-08 14:55:37 +02:00
|
|
|
|
|
|
|
parent_array = []
|
|
|
|
if isinstance(parents, list):
|
|
|
|
for parent in filter(None, parents):
|
2024-05-17 14:41:42 +02:00
|
|
|
parent_array = parent_array + ["-p", parent]
|
2024-04-08 14:55:37 +02:00
|
|
|
elif isinstance(parents, str):
|
2024-05-17 14:41:42 +02:00
|
|
|
parent_array = ["-p", parents]
|
|
|
|
|
|
|
|
commit_id = (
|
|
|
|
self.git_run(
|
|
|
|
["commit-tree"] + parent_array + [tree_id],
|
|
|
|
env={
|
|
|
|
"GIT_AUTHOR_NAME": user,
|
|
|
|
"GIT_AUTHOR_EMAIL": user_email,
|
|
|
|
"GIT_AUTHOR_DATE": f"{int(user_time.timestamp())} +0000",
|
|
|
|
"GIT_COMMITTER_NAME": committer,
|
|
|
|
"GIT_COMMITTER_EMAIL": committer_email,
|
|
|
|
"GIT_COMMITTER_DATE": f"{int(committer_time.timestamp())} +0000",
|
|
|
|
},
|
|
|
|
input=message.encode("utf-8"),
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
)
|
|
|
|
.stdout.decode("utf-8")
|
|
|
|
.rstrip()
|
2022-10-17 14:55:30 +02:00
|
|
|
)
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(["reset", "--soft", commit_id])
|
2024-04-08 14:55:37 +02:00
|
|
|
return commit_id
|
2022-10-17 14:55:30 +02:00
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
def branch_head(self, branch="HEAD"):
|
|
|
|
return (
|
|
|
|
self.git_run(
|
|
|
|
["rev-parse", "--verify", "--end-of-options", branch],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
)
|
|
|
|
.stdout.decode("utf-8")
|
|
|
|
.strip()
|
|
|
|
)
|
2022-11-01 09:03:03 +01:00
|
|
|
|
2022-11-03 10:37:26 +01:00
|
|
|
def set_branch_head(self, branch, commit):
|
2024-05-17 14:41:42 +02:00
|
|
|
return self.git_run(["update-ref", f"refs/heads/{branch}", commit])
|
2022-11-03 10:37:26 +01:00
|
|
|
|
2022-10-17 14:55:30 +02:00
|
|
|
def gc(self):
|
2022-11-03 20:14:56 +01:00
|
|
|
logging.debug(f"Garbage recollect and repackage {self.path}")
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(
|
|
|
|
["gc", "--auto"],
|
2022-10-17 14:55:30 +02:00
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
)
|
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
# def clean(self):
|
|
|
|
# for path, _ in self.repo.status().items():
|
|
|
|
# logging.debug(f"Cleaning {path}")
|
|
|
|
# try:
|
|
|
|
# (self.path / path).unlink()
|
|
|
|
# self.repo.index.remove(path)
|
|
|
|
# except Exception as e:
|
|
|
|
# logging.warning(f"Error removing file {path}: {e}")
|
2022-10-17 14:55:30 +02:00
|
|
|
|
|
|
|
def add(self, filename):
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(["add", filename])
|
2022-10-17 14:55:30 +02:00
|
|
|
|
2024-06-10 17:31:14 +02:00
|
|
|
def add_default_gitignore(self):
|
|
|
|
if not (self.path / ".gitignore").exists():
|
|
|
|
with (self.path / ".gitignore").open("w") as f:
|
|
|
|
f.write(".osc\n")
|
|
|
|
self.add(".gitignore")
|
|
|
|
|
2022-10-17 14:55:30 +02:00
|
|
|
def add_default_lfs_gitattributes(self, force=False):
|
|
|
|
if not (self.path / ".gitattributes").exists() or force:
|
|
|
|
with (self.path / ".gitattributes").open("w") as f:
|
|
|
|
content = ["## Default LFS"]
|
|
|
|
content += [f"*{b} {LFS_SUFFIX}" for b in sorted(BINARY)]
|
|
|
|
f.write("\n".join(content))
|
|
|
|
f.write("\n")
|
|
|
|
self.add(".gitattributes")
|
|
|
|
|
|
|
|
def add_specific_lfs_gitattributes(self, binaries):
|
|
|
|
self.add_default_lfs_gitattributes(force=True)
|
|
|
|
if binaries:
|
|
|
|
with (self.path / ".gitattributes").open("a") as f:
|
|
|
|
content = ["## Specific LFS patterns"]
|
|
|
|
content += [f"{b} {LFS_SUFFIX}" for b in sorted(binaries)]
|
|
|
|
f.write("\n".join(content))
|
|
|
|
f.write("\n")
|
|
|
|
self.add(".gitattributes")
|
|
|
|
|
|
|
|
def get_specific_lfs_gitattributes(self):
|
|
|
|
with (self.path / ".gitattributes").open() as f:
|
|
|
|
patterns = [
|
|
|
|
line.split()[0]
|
|
|
|
for line in f
|
|
|
|
if line.strip() and not line.startswith("#")
|
|
|
|
]
|
|
|
|
binary = {f"*{b}" for b in BINARY}
|
|
|
|
return [p for p in patterns if p not in binary]
|
|
|
|
|
|
|
|
def add_lfs(self, filename, sha256, size):
|
|
|
|
with (self.path / filename).open("w") as f:
|
|
|
|
f.write("version https://git-lfs.github.com/spec/v1\n")
|
|
|
|
f.write(f"oid sha256:{sha256}\n")
|
|
|
|
f.write(f"size {size}\n")
|
|
|
|
self.add(filename)
|
|
|
|
|
|
|
|
if not self.is_lfs_tracked(filename):
|
|
|
|
logging.debug(f"Add specific LFS file {filename}")
|
|
|
|
specific_patterns = self.get_specific_lfs_gitattributes()
|
|
|
|
specific_patterns.append(filename)
|
|
|
|
self.add_specific_lfs_gitattributes(specific_patterns)
|
|
|
|
|
|
|
|
def is_lfs_tracked(self, filename):
|
|
|
|
with (self.path / ".gitattributes").open() as f:
|
|
|
|
patterns = (
|
|
|
|
line.split()[0]
|
|
|
|
for line in f
|
|
|
|
if line.strip() and not line.startswith("#")
|
|
|
|
)
|
|
|
|
return any(fnmatch.fnmatch(filename, line) for line in patterns)
|
|
|
|
|
2022-11-02 15:14:38 +01:00
|
|
|
def remove(self, file: pathlib.Path):
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(
|
|
|
|
["rm", "-q", "-f", "--ignore-unmatch", file.name],
|
2024-04-08 14:55:37 +02:00
|
|
|
)
|
2022-10-17 14:55:30 +02:00
|
|
|
patterns = self.get_specific_lfs_gitattributes()
|
2022-11-02 15:14:38 +01:00
|
|
|
if file.name in patterns:
|
|
|
|
patterns.remove(file.name)
|
2022-10-17 14:55:30 +02:00
|
|
|
self.add_specific_lfs_gitattributes(patterns)
|
2022-11-06 12:18:16 +01:00
|
|
|
|
|
|
|
def add_gitea_remote(self, package):
|
|
|
|
repo_name = package.replace("+", "_")
|
|
|
|
org_name = "rpm"
|
|
|
|
|
|
|
|
if not os.getenv("GITEA_TOKEN"):
|
|
|
|
logging.warning("Not adding a remote due to missing $GITEA_TOKEN")
|
|
|
|
return
|
|
|
|
|
2023-06-19 10:59:56 +02:00
|
|
|
url = f"https://src.opensuse.org/api/v1/org/{org_name}/repos"
|
2022-11-06 12:18:16 +01:00
|
|
|
response = requests.post(
|
|
|
|
url,
|
2024-05-17 20:39:55 +02:00
|
|
|
data={"name": repo_name, "object_format_name": "sha256"},
|
2022-11-06 12:18:16 +01:00
|
|
|
headers={"Authorization": f"token {os.getenv('GITEA_TOKEN')}"},
|
|
|
|
timeout=10,
|
|
|
|
)
|
|
|
|
# 409 Conflict (Already existing)
|
|
|
|
# 201 Created
|
|
|
|
if response.status_code not in (201, 409):
|
|
|
|
print(response.data)
|
2023-06-19 10:59:56 +02:00
|
|
|
url = f"gitea@src.opensuse.org:{org_name}/{repo_name}.git"
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(
|
|
|
|
["remote", "add", "origin", url],
|
2024-04-08 14:55:37 +02:00
|
|
|
)
|
2022-11-08 09:22:32 +01:00
|
|
|
|
2022-12-02 09:12:11 +01:00
|
|
|
def push(self, force=False):
|
2024-05-17 20:06:25 +02:00
|
|
|
if "origin" not in self.git_run(
|
|
|
|
["remote"],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
).stdout.decode("utf-8"):
|
2024-05-17 21:47:35 +02:00
|
|
|
logging.warning("Not pushing to remote because no 'origin' configured")
|
2024-05-17 14:41:42 +02:00
|
|
|
return
|
2024-04-08 14:55:37 +02:00
|
|
|
|
2024-05-17 14:41:42 +02:00
|
|
|
cmd = ["push"]
|
|
|
|
if force:
|
|
|
|
cmd.append("-f")
|
2024-05-17 21:47:35 +02:00
|
|
|
cmd += ["origin", "--all"]
|
2024-05-17 14:41:42 +02:00
|
|
|
self.git_run(cmd)
|