"""
This module contains the ModelGitConfig class, which facilitates operations related to Git configurations,
such as fetching information about the GitHub repository, refreshing repository information, and changing
configuration settings.
"""
import os
import re
import git
import yaml
[docs]
class ModelGitConfig:
"""
The ModelGitConfig class manages configurations related to Git repositories for MoilApp.
Attributes:
_model: The associated ModelApps instance.
_github_repository (git.Repo): The Git repository object.
_github_config (dict): The GitHub configuration data.
Methods:
- __init__: Initializes the ModelGitConfig class.
- _init_github_information: Fetches information about the GitHub repository.
- refresh_github_information: Refreshes the GitHub repository information.
- change_config_github: Changes the configuration for the GitHub repository.
"""
def __init__(self, model):
self._model = model
self._github_repository = None
self._github_config = self._model.main_config["Github_config"]
self._init_github_information()
@property
def github_repository(self):
"""
Get the GitHub repository associated with the instance.
Return:
str: The name of the GitHub repository.
"""
try:
return self._github_repository
except Exception as e:
self._model.activity_logger.error(f"ModelGitConfig.github_repository(): Error: {str(e)}")
def _init_github_information(self):
"""
Fetch information about the GitHub repository.
Returns:
Tuple: A tuple containing the `git.Repo` object for the repository and a dictionary with the following keys:
- 'origin_url': The URL of the repository's origin.
- 'user_name': The username of the repository's owner.
- 'active_branch': The name of the currently active branch.
- 'list_branch': A list of the repository's branch names.
- 'token': The personal access token (PAT) used to authenticate with the repository, or `None` if no PAT is specified.
Raise:
None.
"""
try:
if self._model.debug_mode:
self._model.activity_logger.info("ModelGitConfig: _init_github_information(), "
"Fetch information about GitHub repository")
path_file = os.path.dirname(os.path.realpath(__file__ + "/../.."))
self._github_repository = git.Repo(path_file)
if self._github_config["active_branch"] is None:
try:
list_branch = []
for branch in self.github_repository.heads:
list_branch.append(str(branch))
user_name = re.search('.com/(.*)/moilapp', self.github_repository.remotes.origin.url)
token = None
if user_name is not None:
user_name = user_name.group(1)
token = re.search(f'https://{user_name}:(.*)@github.com/', self.github_repository.remotes.origin.url)
if token is not None:
token = token.group(1)
self._github_config["origin_url"] = self.github_repository.remotes.origin.url
self._github_config["token"] = token
self._github_config["user_name"] = user_name
self._github_config["active_branch"] = str(self.github_repository.active_branch)
self._github_config["list_branch"] = list_branch
except BaseException as e:
message = f"This workdir: '{e}' is not GitHub repository!"
self._github_config["error"] = message
self._model.save_main_config_update()
except Exception as e:
self._model.activity_logger.error(f"ModelGitConfig._init_github_information(): Error: {str(e)}")
[docs]
def change_config_github(self, token=None, branch=None):
"""
Change the configuration for the GitHub repository.
The function loads the current configuration for the GitHub repository
from a YAML file, updates it with the provided token and/or branch name,
and writes it back to the file. If a token is provided and the current
repository URL does not include the token, the function updates the
repository URL with the new token. Finally, the function emits a signal
with the updated configuration.
Args:
token (str, optional): The access token to use when connecting to the
GitHub repository. If provided, the function will update the
configuration file with the new token. Defaults to None.
branch (str, optional): The name of the active branch to use. If
provided, the function will update the configuration file with
the new branch name. Defaults to None.
Return:
None
Raise:
None
"""
try:
if self._model.debug_mode:
self._model.activity_logger.info("ModelGitConfig: change_config_github(), "
"Change information of GitHub repository with args token and branch")
cached_file = os.path.normpath(os.path.join(os.getcwd(), os.pardir, "src/models/cached/github_config.yaml"))
with open(cached_file, "r", encoding="utf-8") as file:
configuration = yaml.safe_load(file)
if token:
configuration["token"] = token
if configuration["token"] is not None:
check_token = re.search(configuration["token"], self._model.repo_github.remotes.origin.url)
if check_token is None:
remote_url = re.sub('https://', f"https://{configuration['user_name']}:{token}@",
configuration['origin_url'])
self._model.repo_github.remotes["origin"].set_url(remote_url)
configuration["origin_url"] = self._model.repo_github.remotes.origin.url
if branch:
configuration["active_branch"] = branch
with open(cached_file, "w", encoding="utf-8") as outfile:
yaml.dump(configuration, outfile, default_flow_style=False)
self._model.git_repository_info.emit(configuration)
except Exception as e:
self._model.activity_logger.error(f"ModelGitConfig.change_config_github(): Error: {str(e)}")