simple gitlab file updater

#667
Raw
Author
Anonymous
Created
Feb. 1, 2023, 7:36 p.m.
Expires
Never
Size
2.0 KB
Hits
34
Syntax
Python
Private
✗ No
import gitlab


class GitlabClient:
    def __init__(self, token, proj_id):
        self.token = token
        self.proj_id = proj_id
        self.branch = "main"

        # dont use directly
        # use function 'gl()' to get the authenticated python-gitlab client returned
        self._gl = None

    def gl(self):
        """_summary_
        gitlab API client as a singleton
        Returns:
            obj: Gitlab API client object
        """

        if self._gl is None:
            self._gl = gitlab.Gitlab(private_token=self.token)
            self._gl.auth()

        return self._gl

    def fetch_file(self, filepath, tmp_filename):
        """_summary_

        this method will query GitLab project repo to fetch and return the manifest (yml)
        file we want to edit.

        Args:
            filepath (str): gitlab repo filepath + filename + extension
            tmp_filename (str): constant name of the temporary manifest.yml file
        Returns:
            nothing
        """
        project = self.gl().projects.get(self.proj_id)

        with open(tmp_filename, "wb") as f:
            project.files.raw(
                file_path=filepath, ref=self.branch, streamed=True, action=f.write
            )

    def push_file(self, filepath, tmp_filename):
        """_summary_

        this method will commit & push the manifest (yml) file to our Gitlab repo

        Args:
            filepath (str): gitlab repo filepath + filename + extension
            tmp_filename (str): constant name of the temporary manifest.yml file
        Returns:
            nothing
        """
        data = {
            "branch": self.branch,
            "commit_message": "img tag updated by deploy_bot",
            "actions": [
                {
                    "action": "update",
                    "file_path": filepath,
                    "content": open(tmp_filename).read(),
                },
            ],
        }

        project = self.gl().projects.get(self.proj_id)

        _ = project.commits.create(data)