refs #2506 -- Initial implementation

git-initial-branch
Vadim Trochinsky 2025-07-31 09:57:40 +02:00
parent 5c6206bafa
commit fd6fa4090f
4 changed files with 130 additions and 31 deletions

View File

@ -62,20 +62,24 @@ def main():
print(f"No se pudo aumentar el límite de archivos abiertos: {e}")
parser = argparse.ArgumentParser(
prog = "OpenGnsys Git Image Create",
description = "Creates a git repository from a partition"
)
if len(sys.argv) != 6:
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, "Incorrect number of arguments. Usage: CrearImagenGit.py disk_num partition_num image_name repo tag"))
parser.add_argument("--disk", type=int, metavar="DISK", required=True, help="Disk ID")
parser.add_argument("--partition", type=int, metavar="PART", required=True, help="Disk partition")
parser.add_argument("--repo", type=str, metavar="REPO", required=True, help="Address of the Git repository to clone")
parser.add_argument("--tag", type=str, metavar="TAG", required=False, help="Tag to automatically create")
# repo - repositorio, ip address. Opcional porque oglive lo recibe como parametro de kernel
# tag - tag a crear automaticamente. Opcional, no necesitamos crear un tag siempre.
parser.add_help = True
args = parser.parse_args()
#disk_num, partition_num, image_name, repo, tag = sys.argv[1:6]
disk_num, partition_num, image_name, repo, tag = sys.argv[1:6]
opengnsys_log_dir = "/opt/opengnsys/log"
ip_address = NetLib.ogGetIpAddress()
logFilePath = f"{opengnsys_log_dir}/{ip_address}.log"
logFilePath = "/var/log/opengnsys.CrearImagenGit.log"
ogLog = OgLogger()
ogLog.setLevel(logging.DEBUG)
@ -95,8 +99,11 @@ def main():
logger.info("Starting CrearImagenGit")
# TODO:
# repo = repositorio, oggit@server.com:/oggit
# image = nombre repo
retval = create_image(disk_num, partition_num, repo, image_name, tag)
retval = create_image(args.disk, args.partition, repo, image_name, args.tag)

View File

@ -4,7 +4,7 @@ import subprocess
import sys
import time
import resource
import argparse
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
@ -94,6 +94,26 @@ def commit_image(disk_num, partition_num, repository, branch, options, msg):
return 0
def main():
parser = argparse.ArgumentParser(
prog = "OpenGnsys Git Image Modify",
description = "Commits changes to a partition to a git repository"
)
parser.add_argument("--disk", type=int, metavar="DISK", required=True, help="Disk ID")
parser.add_argument("--partition", type=int, metavar="PART", required=True, help="Disk partition")
parser.add_argument("--repo", type=str, metavar="REPO", required=True, help="Address of the Git repository to clone")
parser.add_argument("--branch", type=str, metavar="BRANCH", required=False, help="Branch to automatically create")
parser.add_argument("--options", type=str, metavar="OPTS", required=False, help="Options to branch creation (forcepush)")
parser.add_argument("--message", type=str, metavar="MSG", required=False, help="Commit message")
parser.add_help = True
args = parser.parse_args()
if len(sys.argv) != 7:
import json
args = json.dumps(sys.argv)

View File

@ -10,6 +10,10 @@ import DiskLib
from GitLib import OpengnsysGitLibrary, NTFSImplementation, OgProgressPrinterWeb
import argparse
class OgLogger(logging.StreamHandler):
def emit(self, record):
log_types = ["command"]
@ -42,20 +46,23 @@ if __name__ == "__main__":
print(f"No se pudo aumentar el límite de archivos abiertos: {e}")
if len(sys.argv) < 6:
print("Usage: python RestaurarImagenGit.py <disk> <partition> <repo> <ip> <ref> <protocol>")
sys.exit(1)
disk = sys.argv[1]
partition = sys.argv[2]
repo = sys.argv[3]
ipaddr = sys.argv[4]
gitref = sys.argv[5]
proto = sys.argv[6]
parser = argparse.ArgumentParser(
prog = "OpenGnsys Git Image Restore",
description = "Restores an image from Git"
)
opengnsys_log_dir = "/opt/opengnsys/log"
ip_address = NetLib.ogGetIpAddress()
logFilePath = f"{opengnsys_log_dir}/{ip_address}.log"
parser.add_argument("--disk", type=int, metavar="DISK", required=True, help="Disk ID")
parser.add_argument("--partition", type=int, metavar="PART", required=True, help="Disk partition")
parser.add_argument("--repo", type=str, metavar="REPO", required=True, help="Address of the Git repository to clone")
parser.add_argument("--branch", type=str, metavar="BRANCH", required=True, help="Branch to check out")
parser.add_argument("--commit", type=str, metavar="COMMIT_ID", required=True, help="Commit to check out")
parser.add_help = True
args = parser.parse_args()
logFilePath = "/var/log/opengnsys.RestaurarImagenGit.log"
ogLog = OgLogger()
ogLog.setLevel(logging.DEBUG)
@ -81,9 +88,9 @@ if __name__ == "__main__":
og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl)
og_git.progress_callback = OgProgressPrinterWeb()
device = DiskLib.ogDiskToDev(disk, partition)
device = DiskLib.ogDiskToDev(args.disk, args.partition)
og_git.cloneRepo(repo, device, device)
og_git.cloneRepo(args.repo, destination = device, boot_device = device, ref = args.commit, branch = args.branch)
logger.info("RestaurarImagenGit Finished.")

View File

@ -1425,7 +1425,7 @@ class OpengnsysGitLibrary:
self.logger.info("initRepo done")
return True
def cloneRepo(self, repo_name, destination, boot_device):
def cloneRepo(self, repo_name, destination, boot_device, ref = None, branch = None):
"""
Clones a repository to a specified destination and sets up the bootloader.
@ -1488,12 +1488,71 @@ class OpengnsysGitLibrary:
self.logger.info("Cloning repository from %s", repo_url)
repo = git.Repo.clone_from(repo_url, destination_dir, multi_options = [f"--separate-git-dir={real_git_dir}"], progress=self.progress_callback)
if repo_is_efi:
self._efi_install(root_directory=destination_dir)
if branch:
repo = git.Repo.clone_from(repo_url, destination_dir, branch = branch, multi_options = [f"--separate-git-dir={real_git_dir}"], progress=self.progress_callback)
self.logger.debug("Checking out indicated branch %s", branch)
remote_branch_ref = repo.heads[branch]
if branch in repo.heads:
self.logger.debug("Removing existing local branch %s", branch)
repo.delete_head(branch)
if ref:
self.logger.debug("Local branch adjusted to ref %s", ref)
local_ref = repo.create_head(branch, ref)
else:
self.logger.debug("Local branch is set to remote branch %s", remote_branch_ref)
local_ref = repo.create_head(branch, remote_branch_ref)
local_ref.set_tracking_branch(remote_branch_ref)
self.logger.debug("Checking out local branch %s", branch)
local_ref.checkout()
else:
self._grub_install(root_directory=destination_dir, boot_device=boot_device)
repo = git.Repo.clone_from(repo_url, destination_dir, multi_options = [f"--separate-git-dir={real_git_dir}"], progress=self.progress_callback)
branches_with_commit = repo.git.branch("-r", "--contains", ref).split("\n")
self.logger.debug("Branches with commit: %s", branches_with_commit)
if len(branches_with_commit) > 0:
remote_branch = branches_with_commit[0].strip()
if "->" in remote_branch:
# Git returned something like:
# origin/HEAD -> origin/main
#
# so take the second part.
remote_branch = remote_branch.split("->")[1].strip()
parts = remote_branch.split("/")
self.logger.info(f"Branch: {remote_branch}, parts: {parts}")
local_branch_name = parts[1]
if local_branch_name in repo.heads:
#self.logger.debug("Removing existing local branch %s", local_branch_name)
#repo.git.reset("--hard")
#repo.delete_head(local_branch_name)
self.logger.debug("Local branch %s exists, checking it out first", local_branch_name)
repo.git.checkout(local_branch_name)
self.logger.debug("Resetting branch %s to ref %s", local_branch_name, ref)
repo.git.reset("--hard", ref)
else:
self.logger.info("Checking out containing remote branch %s, as %s", remote_branch, local_branch_name)
repo.git.checkout("-b", local_branch_name, remote_branch)
try:
self.logger.info("Setting upstream: %s", local_branch_name)
repo.git.branch(f"--set-upstream-to={remote_branch}", local_branch_name)
except Exception as ex:
self.logger.error("Setting upstream failed: %s", ex)
else:
self.logger.info("Checking out REF %s", ref)
repo.git.checkout(ref)
self.fs.mklostandfound(destination_dir)
self._restore_metadata(destination_dir, set_device_uuids=True)
@ -1501,6 +1560,12 @@ class OpengnsysGitLibrary:
if self.fs.filesystem_type(mountpoint = destination_dir) == "ntfs":
self._ntfs_restore_secaudit(destination_dir)
if repo_is_efi:
self._efi_install(root_directory=destination_dir)
else:
self._grub_install(root_directory=destination_dir, boot_device=boot_device)
self.logger.info("Clone completed.")