From 78cdba9aa78280aeeaa85e08d749a56f3dff74a8 Mon Sep 17 00:00:00 2001 From: Vadim Troshchinskiy Date: Wed, 23 Jul 2025 19:10:34 +0200 Subject: [PATCH] refs #2506: Branch creation support --- ogclient/interfaceAdm/ModificarImagenGit.py | 32 ++++++-- ogclient/lib/python3/GitLib/__init__.py | 88 ++++++--------------- 2 files changed, 49 insertions(+), 71 deletions(-) diff --git a/ogclient/interfaceAdm/ModificarImagenGit.py b/ogclient/interfaceAdm/ModificarImagenGit.py index 1babb39..6e61866 100755 --- a/ogclient/interfaceAdm/ModificarImagenGit.py +++ b/ogclient/interfaceAdm/ModificarImagenGit.py @@ -67,30 +67,48 @@ class OgLogger(logging.StreamHandler): -def commit_image(disk_num, partition_num, image_name, msg): +def commit_image(disk_num, partition_num, repository, branch, options, msg): ntfs_impl = NTFSImplementation.NTFS3G og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl) og_git.progress_callback = OgProgressPrinterWeb() device = DiskLib.ogDiskToDev(disk_num, partition_num) - og_git.commit(device = device, message = msg) - og_git.push(device = device) + + force_push = False + opts = options.split(",") + if "force_push" in opts: + force_push = True + + try: + if branch: + if not og_git.create_branch(device = device, name = branch): + sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, f"Failed to create branch")) + + og_git.commit(device = device, message = msg) + og_git.push(device = device, force = force_push) + except Exception as ex: + sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, f"Exception during commit: {ex}")) + return 0 def main(): - if len(sys.argv) != 5: + if len(sys.argv) != 7: import json args = json.dumps(sys.argv) - sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, f"Incorrect number of arguments. Usage: ModificarImagenGit.py disk_num partition_num image_name repo msg. Received args: {args}")) + sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, f"Incorrect number of arguments. Got {len(sys.argv)}. Usage: ModificarImagenGit.py disk_num partition_num repo new_branch options msg. Received args: {args}")) # 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. - disk_num, partition_num, image_name, msg = sys.argv[1:5] + disk_num, partition_num, repo, branch, options, msg = sys.argv[1:7] + print(f"Repo : {repo}") + print(f"Branch : {branch}") + print(f"Options: {options}") + print(f"Msg : {msg}") opengnsys_log_dir = "/opt/opengnsys/log" ip_address = NetLib.ogGetIpAddress() @@ -114,7 +132,7 @@ def main(): logger.info("Starting ModificarImagenGit") - retval = commit_image(disk_num, partition_num, image_name, msg) + retval = commit_image(disk_num, partition_num, repo, branch, options, msg) logger.info("ModificarImagenGit done, return code %i", retval) diff --git a/ogclient/lib/python3/GitLib/__init__.py b/ogclient/lib/python3/GitLib/__init__.py index 1ddc079..daa5c96 100755 --- a/ogclient/lib/python3/GitLib/__init__.py +++ b/ogclient/lib/python3/GitLib/__init__.py @@ -48,6 +48,7 @@ from GitLib.disk import * from GitLib.ntfs import * from GitLib.kernel import parse_kernel_cmdline +import CacheLib #import requests @@ -287,7 +288,8 @@ class OpengnsysGitLibrary: self.repo_image_path = "oggit" self.ntfs_implementation = ntfs_implementation - self.cache_dir = self._runBashFunction("ogMountCache", []) + self.cache_dir = CacheLib.ogMountCache() + # Si no hay cache, se va a crear el .git en el FS directamente if (not self.cache_dir) and require_cache: @@ -604,64 +606,6 @@ class OpengnsysGitLibrary: except OSError as e: self.logger.warning('Failed to delete %s. Error: %s', file_path, e) - - def _runBashFunction(self, function, arguments): - """ - Executes an OpenGnsys bash function with given arguments. - - This method creates a temporary bash script that sources all `.lib` files in a specific directory, - writes the specified bash function and its arguments to the script, makes the script executable, - and then runs the script. The output and errors from the script execution are captured and logged. - - This is a temporary migration convenience function, it won't be present once the rest of the - code is migrated to Python. - - Args: - function (str): The name of the bash function to execute. - arguments (list): A list of arguments to pass to the bash function. - - Returns: - str: The standard output from the executed bash function. - - Logs: - - Debug information about the bash function and arguments being run. - - The path of the temporary file created. - - The command being executed. - - The standard output and standard error from the script execution. - """ - # Create a temporary file - self.logger.debug(f"Running bash function: {function} {arguments}") - - with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file: - temp_file.write("#!/bin/bash\n") - temp_file.write("for lib in /opt/opengnsys/client/lib/engine/bin/*.lib ; do\n") - temp_file.write(" source $lib\n") - temp_file.write("done\n") - - #temp_file.write("source /opt/oglive/rootfs/opt/opengnsys/lib/engine/bin/Cache.lib") - #temp_file.write("source /opt/oglive/rootfs/opt/opengnsys/lib/engine/bin/Git.lib") - - temp_file.write(f"{function} \"$@\"\n") - - # Make the temporary file executable - os.chmod(temp_file.name, 0o755) - - self.logger.debug(f"File: {temp_file.name}") - - - # Run the temporary file - command = [temp_file.name] + arguments - self.logger.debug(f"Running: {command} {arguments}") - result = subprocess.run(command, shell=False, capture_output=True, text=True, check=True) - output = result.stdout.strip() - - self.logger.debug(f"STDOUT: {output}") - self.logger.debug(f"STDERR: {result.stderr}") - - return output - - - def _getOgRepository(self, name): return f"{self.repo_user}@{self.repo_server}:{self.repo_image_path}/{name}.git" @@ -1394,7 +1338,7 @@ class OpengnsysGitLibrary: self.logger.debug("Fetching origin, callback=%s", self.progress_callback) origin.fetch(progress=self.progress_callback) - repo.heads.master.set_tracking_branch(origin.refs.master) + repo.heads.main.set_tracking_branch(origin.refs.main) metadata_ret = self._create_metadata(path, initial_creation=True) @@ -1616,7 +1560,23 @@ class OpengnsysGitLibrary: # Restaurar cosas modificadas para git self._restore_metadata(path, destructive_only=True) - def push(self, path = None, device = None): + def create_branch(self, path = None, device = None, name = ""): + if path is None: + path = self.fs.ensure_mounted(device) + + repo = git.Repo(path) + if name in repo.branches: + self.logger.error("Can't create branch, it already exists") + return False + + self.logger.info("Creating branch %s", name) + + new_branch = repo.create_head(name) + repo.head.reference = new_branch + repo.head.reset(index=True, working_tree=True) + return True + + def push(self, path = None, device = None, force = False): """ Push local changes to ogrepository @@ -1635,9 +1595,10 @@ class OpengnsysGitLibrary: return origin = repo.remotes["origin"] - repo.heads.master.set_tracking_branch(origin.refs.master) + repo.heads.main.set_tracking_branch(origin.refs.main) - origin.push(progress=self.progress_callback) + ret = origin.push(progress=self.progress_callback, force = force) + ret.raise_if_error() #repo.git.push("--set-upstream", "origin", repo.head.ref, "--force") # force = True) @@ -1793,7 +1754,6 @@ if __name__ == '__main__': og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl) - # og_git._runBashFunction("ogMountCache", []) # if args.init_repo: