Unverified Commit f920362b authored by Jonah Brüchert's avatar Jonah Brüchert
Browse files

Use protected members instead of getters for base classes

parent 2c71bf05
......@@ -22,14 +22,17 @@ class AllInstancesConnection: # pylint: disable=too-few-public-methods
Base class that connects to all known instances
"""
# protected
_connections: List[Gitlab] = []
# private
__config: Config
__connections: List[Gitlab] = []
def __login(self, hostname: str, token: str) -> None:
try:
connection: Gitlab = Gitlab(hostname, private_token=token)
connection.auth()
self.__connections.append(connection)
self._connections.append(connection)
except GitlabAuthenticationError:
Utils.log(LogType.Error, "Could not log into GitLab")
sys.exit(1)
......@@ -43,9 +46,3 @@ class AllInstancesConnection: # pylint: disable=too-few-public-methods
if isinstance(token, str):
self.__login("https://" + hostname, token)
def connections(self) -> List[Gitlab]:
"""
:return the list of connections
"""
return self.__connections
......@@ -102,21 +102,21 @@ class IssuesList(RepositoryConnection):
state = "closed"
args["state"] = state
issues: List[ProjectIssue]
issues: List[ProjectIssue] = []
if not self.for_project and self.assigned:
# List issues all over the instance assigned to me
args["scope"] = "assigned_to_me"
issues = self.connection().issues.list(**args)
issues = self._connection.issues.list(**args)
elif not self.for_project and not self.assigned:
# Request both created and assigned issues on the whole instance
args["scope"] = "created_by_me"
issues = self.connection().issues.list(**args)
issues = self._connection.issues.list(**args)
args["scope"] = "assigned_to_me"
issues += self.connection().issues.list(**args)
issues += self._connection.issues.list(**args)
elif self.for_project and not self.assigned:
# Request all issues on the current project
args["scope"] = "all"
issues = self.remote_project().issues.list(**args)
issues = self._remote_project.issues.list(**args)
for issue in issues:
formatting = TextFormatting.green if issue.state == "opened" else TextFormatting.red
......@@ -134,8 +134,8 @@ class IssuesList(RepositoryConnection):
"""
Open issue with xdg-open
"""
if self.remote_project().issues_enabled:
Utils.xdg_open(f"{self.remote_project().web_url}/-/issues")
if self._remote_project.issues_enabled:
Utils.xdg_open(f"{self._remote_project.web_url}/-/issues")
else:
Utils.log(LogType.Error, "Issue are disabled for this project")
......@@ -148,7 +148,7 @@ class IssuesShow(RepositoryConnection):
def __init__(self, issue_id: int):
RepositoryConnection.__init__(self)
try:
self.issue: ProjectIssue = self.remote_project().issues.get(issue_id, lazy=False)
self.issue: ProjectIssue = self._remote_project.issues.get(issue_id, lazy=False)
except GitlabGetError:
Utils.log(LogType.Warning, f"No issue with ID {issue_id}")
sys.exit(1)
......
......@@ -56,14 +56,14 @@ class MergeRequestCheckout(RepositoryConnection):
"""
Checks out the merge request with the specified id in the local worktree
"""
self.__mr = self.remote_project().mergerequests.get(merge_request_id, lazy=False)
self.__mr = self._remote_project.mergerequests.get(merge_request_id, lazy=False)
print('Checking out merge request "{}"...'.format(self.__mr.title))
print(" branch:", self.__mr.source_branch)
fetch_info = self.local_repo().remotes.origin.fetch(
fetch_info = self._local_repo.remotes.origin.fetch(
"merge-requests/{}/head".format(merge_request_id)
)[0]
if self.__mr.source_branch in self.local_repo().refs:
if self.__mr.source_branch in self._local_repo.refs:
# Make sure not to overwrite local changes
overwrite = Utils.ask_bool(
'Branch "{}" already exists locally, do you want to overwrite it?'.format(
......@@ -75,8 +75,8 @@ class MergeRequestCheckout(RepositoryConnection):
print("Aborting")
sys.exit(1)
self.local_repo().refs.master.checkout()
self.local_repo().delete_head(self.__mr.source_branch, "-f")
self._local_repo.refs.master.checkout()
self._local_repo.delete_head(self.__mr.source_branch, "-f")
head = self.local_repo().create_head(self.__mr.source_branch, fetch_info.ref)
head = self._local_repo.create_head(self.__mr.source_branch, fetch_info.ref)
head.checkout()
......@@ -81,9 +81,9 @@ class MergeRequestCreator(RepositoryConnection):
Run some sanity checks and warn the user if necessary
"""
if (
not self.local_repo().active_branch.name.startswith("work/")
not self._local_repo.active_branch.name.startswith("work/")
and not self.__fork
and "invent.kde.org" in self.connection().url
and "invent.kde.org" in self._connection.url
):
Utils.log(
LogType.Warning,
......@@ -100,7 +100,7 @@ class MergeRequestCreator(RepositoryConnection):
Determine whether there are uncommitted changes, and ask the user what to do about them
"""
index: IndexFile = self.local_repo().index
index: IndexFile = self._local_repo.index
if len(index.diff("HEAD")) > 0:
Utils.log(LogType.Info, "You have staged but uncommited changes.")
create_commit: bool = Utils.ask_bool("do you want to create a new commit?")
......@@ -120,27 +120,27 @@ class MergeRequestCreator(RepositoryConnection):
If the fork already exists, no new fork will be created.
"""
if "fork" in self.local_repo().remotes:
if "fork" in self._local_repo.remotes:
# Fork already exists
fork_str_id: str = Utils.str_id_for_url(self.local_repo().remotes.fork.url)
fork_str_id: str = Utils.str_id_for_url(self._local_repo.remotes.fork.url)
# Try to retrieve the remote project object, if it doesn't exist on the server,
# go on with the logic to create a new fork.
try:
self.__remote_fork = self.connection().projects.get(fork_str_id)
self.__remote_fork = self._connection.projects.get(fork_str_id)
return
except GitlabGetError:
pass
try:
self.__remote_fork = self.remote_project().forks.create({})
self.__remote_fork = self._remote_project.forks.create({})
# WORKAROUND: the return of create() is unreliable,
# and sometimes doesn't allow to create merge requests,
# so request a fresh project object.
self.__remote_fork = self.connection().projects.get(self.__remote_fork.id)
self.__remote_fork = self._connection.projects.get(self.__remote_fork.id)
self.local_repo().create_remote("fork", url=self.__remote_fork.ssh_url_to_repo)
self._local_repo.create_remote("fork", url=self.__remote_fork.ssh_url_to_repo)
except GitlabCreateError:
Utils.log(
LogType.Info,
......@@ -148,13 +148,13 @@ class MergeRequestCreator(RepositoryConnection):
)
# Detect ssh url
url = Utils.ssh_url_from_http(
self.connection().user.web_url + "/" + self.remote_project().path
self._connection.user.web_url + "/" + self._remote_project.path
)
self.local_repo().create_remote("fork", url=url)
self._local_repo.create_remote("fork", url=url)
str_id: str = Utils.str_id_for_url(self.local_repo().remotes.fork.url)
self.__remote_fork = self.connection().projects.get(str_id)
str_id: str = Utils.str_id_for_url(self._local_repo.remotes.fork.url)
self.__remote_fork = self._connection.projects.get(str_id)
def push(self) -> None:
"""
......@@ -162,11 +162,11 @@ class MergeRequestCreator(RepositoryConnection):
"""
remote: Remote
if self.__fork:
remote = self.local_repo().remotes.fork
remote = self._local_repo.remotes.fork
remote.push(force=True)
else:
remote = self.local_repo().remotes.origin
remote.push(refspec=self.local_repo().head, force=True)
remote = self._local_repo.remotes.origin
remote.push(refspec=self._local_repo.head, force=True)
def __upload_assets(self, text: str) -> str:
"""
......@@ -188,7 +188,7 @@ class MergeRequestCreator(RepositoryConnection):
filename: str = os.path.basename(image)
try:
uploaded_file = self.remote_project().upload(filename, filepath=image)
uploaded_file = self._remote_project.upload(filename, filepath=image)
output_text = output_text.replace(image, uploaded_file["url"])
except FileNotFoundError:
Utils.log(LogType.Warning, "Failed to upload image", image)
......@@ -201,10 +201,10 @@ class MergeRequestCreator(RepositoryConnection):
Creates a merge request with the changes from the current branch
"""
mrs: List[ProjectMergeRequest] = self.remote_project().mergerequests.list(
source_branch=self.local_repo().active_branch.name,
mrs: List[ProjectMergeRequest] = self._remote_project.mergerequests.list(
source_branch=self._local_repo.active_branch.name,
target_branch=self.__target_branch,
target_project_id=self.remote_project().id,
target_project_id=self._remote_project.id,
)
if len(mrs) > 0:
......@@ -218,21 +218,21 @@ class MergeRequestCreator(RepositoryConnection):
return
e_input = EditorInput(
placeholder_title=self.local_repo().head.commit.summary,
placeholder_body=self.local_repo().head.commit.message.split("\n", 1)[1].strip(),
placeholder_title=self._local_repo.head.commit.summary,
placeholder_body=self._local_repo.head.commit.message.split("\n", 1)[1].strip(),
extra_text="The markdown syntax for embedding images "
+ "![description](/path/to/file) can be used to upload images.",
)
project: Project = self.__remote_fork if self.__fork else self.remote_project()
project: Project = self.__remote_fork if self.__fork else self._remote_project
merge_request = project.mergerequests.create(
{
"source_branch": self.local_repo().active_branch.name,
"source_branch": self._local_repo.active_branch.name,
"target_branch": self.__target_branch,
"title": e_input.title,
"description": self.__upload_assets(e_input.body),
"target_project_id": self.remote_project().id,
"target_project_id": self._remote_project.id,
"allow_maintainer_to_push": True,
"remove_source_branch": True,
}
......
......@@ -87,9 +87,9 @@ class MergeRequestList(RepositoryConnection):
merge_requests: List[ProjectMergeRequest] = []
if self.for_project:
base = self.remote_project()
base = self._remote_project
else:
base = self.connection()
base = self._connection
if self.merged and self.opened and self.closed:
merge_requests = base.mergerequests.list()
......
......@@ -26,19 +26,20 @@ class RepositoryConnection:
Creates a connection to the gitlab instance used by the current repository
"""
# protected
_connection: Gitlab
_local_repo: Repo
_remote_project: Project
# private
__connection: Gitlab
__local_repo: Repo
__remote_project: Project
__gitlab_token: str
__config: Config
def __init__(self) -> None:
self.__local_repo = Utils.get_cwd_repo()
self._local_repo = Utils.get_cwd_repo()
self.__config = Config()
try:
origin = self.__local_repo.remote(name="origin")
origin = self._local_repo.remote(name="origin")
except ValueError:
Utils.log(LogType.Error, "No origin remote exists")
sys.exit(1)
......@@ -64,37 +65,18 @@ class RepositoryConnection:
sys.exit(1)
self.__login(gitlab_url, auth_token)
if not self.__connection:
if not self._connection:
Utils.log(LogType.Error, "Failed to connect to GitLab")
sys.exit(1)
self.__remote_project = self.__connection.projects.get(
self._remote_project = self._connection.projects.get(
Utils.str_id_for_url(Utils.normalize_url(repository))
)
def __login(self, hostname: str, token: str) -> None:
try:
self.__connection: Gitlab = Gitlab(hostname, private_token=token)
self.__gitlab_token = token
self.__connection.auth()
self._connection: Gitlab = Gitlab(hostname, private_token=token)
self._connection.auth()
except (GitlabAuthenticationError, GitlabGetError):
Utils.log(LogType.Error, "Could not log into GitLab: {}".format(hostname))
sys.exit(1)
def connection(self) -> Gitlab:
"""
Returns the Gitlab connection
"""
return self.__connection
def local_repo(self) -> Repo:
"""
Returns the local repository
"""
return self.__local_repo
def remote_project(self) -> Project:
"""
Returns the remote project (for the origin remote)
"""
return self.__remote_project
......@@ -55,7 +55,7 @@ class Search(AllInstancesConnection):
"""
table = Table()
for connection in self.connections():
for connection in self._connections:
for result in connection.search("projects", query):
description: Optional[str] = result["description"]
if description:
......
......@@ -66,7 +66,7 @@ class Snippets(RepositoryConnection):
"""
paste the contents of a TextIO object
"""
snippet: Snippet = self.connection().snippets.create(
snippet: Snippet = self._connection.snippets.create(
{"title": title, "file_name": file.name, "content": file.read(), "visibility": "public"}
)
Utils.log(LogType.Info, "Created snippet at", snippet.web_url)
......
[MESSAGES CONTROL]
disable=bad-continuation
disable=bad-continuation,too-few-public-methods
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment