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

Fix new linter warnings

parent 94d4b040
......@@ -81,14 +81,14 @@ def main() -> None:
try:
parser.parse()
except GitCommandError as git_error:
Utils.log(LogType.Error, str(git_error))
Utils.log(LogType.ERROR, str(git_error))
except SystemExit:
pass
except KeyboardInterrupt:
pass
except: # noqa: E722
print()
Utils.log(LogType.Error, "git-lab crashed. This should not happen.")
Utils.log(LogType.ERROR, "git-lab crashed. This should not happen.")
print(
"Please help us to fix it by opening an issue on",
"https://invent.kde.org/sdk/git-lab/-/issues.",
......
......@@ -34,7 +34,7 @@ class AllInstancesConnection: # pylint: disable=too-few-public-methods
connection.auth()
self._connections.append(connection)
except GitlabAuthenticationError:
Utils.log(LogType.Error, "Could not log into GitLab")
Utils.log(LogType.ERROR, "Could not log into GitLab")
sys.exit(1)
def __init__(self) -> None:
......
......@@ -48,7 +48,7 @@ class Config:
def __migrate_to_version_1(self) -> None:
if "version" not in self.__config:
Utils.log(LogType.Info, "Migrating configuration file to version 1")
Utils.log(LogType.INFO, "Migrating configuration file to version 1")
new_config: Dict[str, Any] = {"version": 1, "instances": {}}
......@@ -72,9 +72,9 @@ class Config:
else:
if not os.path.isdir(config_dir):
os.mkdir(config_dir)
file = open(self.config_path, "w+")
json.dump({"version": 1, "instances": {}}, file)
file.close()
with open(self.config_path, "w+") as file:
json.dump({"version": 1, "instances": {}}, file)
file.close()
self.__file = open(self.config_path, "r+")
self.__config = json.load(self.__file)
......@@ -155,8 +155,8 @@ class Workflow(Enum):
"""
# Never reorder this values! The config file stores the actual numbers.
Fork = auto() # push merge request branches to a fork of the upstream repository
Workbranch = auto() # push merge request branches to the upstream repository
FORK = auto() # push merge request branches to a fork of the upstream repository
WORKBRANCH = auto() # push merge request branches to the upstream repository
class RepositoryConfig:
......@@ -173,13 +173,13 @@ class RepositoryConfig:
if repository_path:
self.config_path = repository_path + os.path.sep + ".git" + os.path.sep + "gitlabconfig"
else:
Utils.log(LogType.Error, "Current directory is not a git repository")
Utils.log(LogType.ERROR, "Current directory is not a git repository")
sys.exit(1)
if not os.path.isfile(self.config_path):
file = open(self.config_path, "w+")
json.dump({}, file)
file.close()
with open(self.config_path, "w+") as file:
json.dump({}, file)
file.close()
self.__file = open(self.config_path, "r+")
self.__config = json.load(self.__file)
......@@ -192,7 +192,7 @@ class RepositoryConfig:
try:
value = self.__config["workflow"]
except KeyError:
return Workflow.Fork
return Workflow.FORK
return Workflow(value)
......
......@@ -37,27 +37,27 @@ class EditorInput: # pylint: disable=too-few-public-methods
self.__fulltext = newtext
def __input(self, extra_text: str, placeholder_title: str, placeholder_body: str) -> None:
file = tempfile.NamedTemporaryFile("r+")
file.write("# Please enter a title below (one line)\n")
file.write("{}\n".format(placeholder_title))
file.write("# Please enter a description below (optional) (multiple lines)\n")
file.write("{}\n".format(placeholder_body))
file.write("\n")
file.write("# Lines starting with '#' will be ignored.\n")
file.write("# An empty title aborts the workflow.\n")
file.write("# {}".format(extra_text))
file.flush()
subprocess.call(Utils.editor() + [file.name])
file.seek(0)
self.__fulltext = file.read()
with tempfile.NamedTemporaryFile("r+") as file:
file.write("# Please enter a title below (one line)\n")
file.write("{}\n".format(placeholder_title))
file.write("# Please enter a description below (optional) (multiple lines)\n")
file.write("{}\n".format(placeholder_body))
file.write("\n")
file.write("# Lines starting with '#' will be ignored.\n")
file.write("# An empty title aborts the workflow.\n")
file.write("# {}".format(extra_text))
file.flush()
subprocess.call(Utils.editor() + [file.name])
file.seek(0)
self.__fulltext = file.read()
def __fulltext_valid(self) -> bool:
lines = self.__fulltext.splitlines()
if not lines or not lines[0]:
Utils.log(LogType.Error, "The first line (title) can't be empty")
Utils.log(LogType.ERROR, "The first line (title) can't be empty")
return False
return True
......@@ -68,7 +68,7 @@ class EditorInput: # pylint: disable=too-few-public-methods
self.__input(extra_text, placeholder_title, placeholder_body)
self.__fulltext_remove_comments()
if not self.__fulltext_valid():
Utils.log(LogType.Error, "Text not valid, aborting")
Utils.log(LogType.ERROR, "Text not valid, aborting")
sys.exit(1)
lines: List[str] = self.__fulltext.splitlines()
......
......@@ -66,13 +66,13 @@ class Feature:
try:
if name in self.__repo.refs:
self.__git.checkout(name)
Utils.log(LogType.Info, "Switched to branch '{}'".format(name))
Utils.log(LogType.INFO, "Switched to branch '{}'".format(name))
else:
self.__git.checkout(start, b=name) # create a new branch
Utils.log(LogType.Info, "Switched to a new branch '{}'".format(name))
Utils.log(LogType.INFO, "Switched to a new branch '{}'".format(name))
except GitCommandError as git_error:
Utils.log(LogType.Error, git_error.stderr.strip())
Utils.log(LogType.ERROR, git_error.stderr.strip())
def list(self) -> None:
"""
......
......@@ -126,11 +126,11 @@ class IssuesList(RepositoryConnection):
issues = self._remote_project.issues.list(**args)
for issue in issues:
formatting = TextFormatting.green if issue.state == "opened" else TextFormatting.red
formatting = TextFormatting.GREEN if issue.state == "opened" else TextFormatting.RED
row: List[str] = [
TextFormatting.bold + issue.references["full"] + TextFormatting.end,
TextFormatting.BOLD + issue.references["full"] + TextFormatting.END,
issue.title,
formatting + issue.state + TextFormatting.end,
formatting + issue.state + TextFormatting.END,
]
table.add_row(row)
......@@ -144,7 +144,7 @@ class IssuesList(RepositoryConnection):
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")
Utils.log(LogType.ERROR, "Issue are disabled for this project")
class IssuesShow(RepositoryConnection):
......@@ -157,7 +157,7 @@ class IssuesShow(RepositoryConnection):
try:
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}")
Utils.log(LogType.WARNING, f"No issue with ID {issue_id}")
sys.exit(1)
def open_web(self) -> None:
......@@ -167,16 +167,16 @@ class IssuesShow(RepositoryConnection):
Utils.xdg_open(self.issue.web_url)
def __str__(self) -> str:
formatting = TextFormatting.green if self.issue.state == "opened" else TextFormatting.red
formatting = TextFormatting.GREEN if self.issue.state == "opened" else TextFormatting.RED
textbuffer: str = ""
textbuffer += (
TextFormatting.bold
TextFormatting.BOLD
+ self.issue.title
+ TextFormatting.end
+ TextFormatting.END
+ f" (#{self.issue.iid}) "
+ formatting
+ self.issue.state
+ TextFormatting.end
+ TextFormatting.END
+ os.linesep
)
textbuffer += self.issue.description
......
......@@ -50,7 +50,7 @@ def run(args: argparse.Namespace) -> None:
:param args: parsed arguments
"""
# To fork or not to fork
fork: bool = RepositoryConfig().workflow() == Workflow.Fork
fork: bool = RepositoryConfig().workflow() == Workflow.FORK
creator: MergeRequestCreator = MergeRequestCreator(args.target_branch, fork)
creator.check()
creator.commit()
......@@ -84,7 +84,7 @@ class MergeRequestCreator(RepositoryConnection):
"""
if self._local_repo.active_branch.name == "master":
Utils.log(
LogType.Warning,
LogType.WARNING,
"Creating merge requests from master is a bad idea.",
"Please check out a new a branch before creating a merge request.",
"To cancel, please press Ctrl + C.",
......@@ -96,7 +96,7 @@ class MergeRequestCreator(RepositoryConnection):
and "invent.kde.org" in self._connection.url
):
Utils.log(
LogType.Warning,
LogType.WARNING,
"Pushing to the upstream repository, but the branch name doesn't start with work/.",
)
print(
......@@ -112,7 +112,7 @@ class MergeRequestCreator(RepositoryConnection):
index: IndexFile = self._local_repo.index
if len(index.diff("HEAD")) > 0:
Utils.log(LogType.Info, "You have staged but uncommited changes.")
Utils.log(LogType.INFO, "You have staged but uncommited changes.")
create_commit: bool = Utils.ask_bool("do you want to create a new commit?")
if create_commit:
......@@ -121,7 +121,7 @@ class MergeRequestCreator(RepositoryConnection):
try:
subprocess.check_call(["git", "commit"])
except subprocess.CalledProcessError:
Utils.log(LogType.Error, "git exited with an error code")
Utils.log(LogType.ERROR, "git exited with an error code")
sys.exit(1)
def fork(self) -> None:
......@@ -153,7 +153,7 @@ class MergeRequestCreator(RepositoryConnection):
self._local_repo.create_remote("fork", url=self.__remote_fork.ssh_url_to_repo)
except GitlabCreateError:
Utils.log(
LogType.Info,
LogType.INFO,
"Fork exists, but no fork remote exists locally, trying to guess the url",
)
# Detect ssh url
......@@ -200,14 +200,14 @@ class MergeRequestCreator(RepositoryConnection):
image = extract_expr.findall(match)[0]
if not image.startswith("http"):
Utils.log(LogType.Info, "Uploading", image)
Utils.log(LogType.INFO, "Uploading", image)
filename: str = os.path.basename(image)
try:
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)
Utils.log(LogType.WARNING, "Failed to upload image", image)
print("The file does not exist.")
return output_text
......@@ -226,7 +226,7 @@ class MergeRequestCreator(RepositoryConnection):
if len(mrs) > 0:
merge_request = mrs[0]
Utils.log(
LogType.Info,
LogType.INFO,
'Updating existing merge request "{}" at: {}'.format(
merge_request.title, merge_request.web_url
),
......@@ -253,4 +253,4 @@ class MergeRequestCreator(RepositoryConnection):
"remove_source_branch": True,
}
)
Utils.log(LogType.Info, "Created merge request at", merge_request.web_url)
Utils.log(LogType.INFO, "Created merge request at", merge_request.web_url)
......@@ -119,17 +119,17 @@ class MergeRequestList(RepositoryConnection):
row.append(merge_request.web_url)
else:
row.append(
TextFormatting.bold + merge_request.references["full"] + TextFormatting.end
TextFormatting.BOLD + merge_request.references["full"] + TextFormatting.END
)
row.append(merge_request.title)
if merge_request.state == "merged":
row.append(TextFormatting.green + merge_request.state + TextFormatting.end)
row.append(TextFormatting.GREEN + merge_request.state + TextFormatting.END)
elif merge_request.state == "opened":
row.append(merge_request.state)
elif merge_request.state == "closed":
row.append(TextFormatting.red + merge_request.state + TextFormatting.end)
row.append(TextFormatting.RED + merge_request.state + TextFormatting.END)
table.add_row(row)
......
......@@ -41,7 +41,7 @@ class RepositoryConnection:
try:
origin = self._local_repo.remote(name="origin")
except ValueError:
Utils.log(LogType.Error, "No origin remote exists")
Utils.log(LogType.ERROR, "No origin remote exists")
sys.exit(1)
repository: str = next(origin.urls)
......@@ -50,12 +50,12 @@ class RepositoryConnection:
gitlab_hostname: Optional[str] = urlparse(gitlab_url).hostname
if not gitlab_hostname:
Utils.log(LogType.Error, "Failed to detect GitLab hostname")
Utils.log(LogType.ERROR, "Failed to detect GitLab hostname")
sys.exit(1)
auth_token: Optional[str] = self.__config.token(gitlab_hostname)
if not auth_token:
Utils.log(LogType.Error, "No authentication token found. ")
Utils.log(LogType.ERROR, "No authentication token found. ")
print(
"Please create a token with the api and write_repository scopes on {}/{}.".format(
gitlab_url, "profile/personal_access_tokens"
......@@ -66,7 +66,7 @@ class RepositoryConnection:
self.__login(gitlab_url, auth_token)
if not self._connection:
Utils.log(LogType.Error, "Failed to connect to GitLab")
Utils.log(LogType.ERROR, "Failed to connect to GitLab")
sys.exit(1)
try:
......@@ -74,7 +74,7 @@ class RepositoryConnection:
Utils.str_id_for_url(Utils.normalize_url(repository))
)
except (GitlabHttpError, GitlabGetError):
Utils.log(LogType.Error, "The repository could not be found on the GitLab instance.")
Utils.log(LogType.ERROR, "The repository could not be found on the GitLab instance.")
print(
"If the repository was recently moved, please update the origin remote using git."
)
......@@ -85,5 +85,5 @@ class RepositoryConnection:
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))
Utils.log(LogType.ERROR, "Could not log into GitLab: {}".format(hostname))
sys.exit(1)
......@@ -15,6 +15,9 @@ from lab.utils import Utils
def parser(
subparsers: argparse._SubParsersAction, # pylint: disable=protected-access
) -> argparse.ArgumentParser:
"""
Subparser for the rewrite-remote command
"""
rewrite_remote_parser: argparse.ArgumentParser = subparsers.add_parser(
"rewrite-remote", help="Rewrite the remote url to ssh"
)
......@@ -28,6 +31,9 @@ def parser(
def run(args: argparse.Namespace) -> None:
"""
:param args: parsed arguments
"""
repo: Repo = Utils.get_cwd_repo()
remote_url = repo.git.remote("get-url", args.remote)
ssh_url = Utils.ssh_url_from_http(Utils.normalize_url(remote_url))
......
......@@ -70,9 +70,9 @@ class Search(AllInstancesConnection):
table.add_row(
[
TextFormatting.bold + result["path_with_namespace"] + TextFormatting.end,
TextFormatting.BOLD + result["path_with_namespace"] + TextFormatting.END,
description,
TextFormatting.underline + result["ssh_url_to_repo"] + TextFormatting.end,
TextFormatting.UNDERLINE + result["ssh_url_to_repo"] + TextFormatting.END,
]
)
......
......@@ -50,7 +50,7 @@ def run(args: argparse.Namespace) -> None:
try:
file = open(args.filename, "r")
except FileNotFoundError:
Utils.log(LogType.Error, "Failed to open file", args.filename)
Utils.log(LogType.ERROR, "Failed to open file", args.filename)
sys.exit(1)
else:
file = sys.stdin
......@@ -73,5 +73,5 @@ class Snippets(RepositoryConnection):
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)
Utils.log(LogType.INFO, "Created snippet at", snippet.web_url)
print("You can access it raw at", snippet.raw_url)
......@@ -25,9 +25,9 @@ class LogType(Enum):
Enum representing the type of log message
"""
Info = auto()
Warning = auto()
Error = auto()
INFO = auto()
WARNING = auto()
ERROR = auto()
class TextFormatting: # pylint: disable=too-few-public-methods
......@@ -35,17 +35,17 @@ class TextFormatting: # pylint: disable=too-few-public-methods
Structure containing constants for working with text formatting
"""
purple: Final[str] = "\033[0;95m"
cyan: Final[str] = "\033[0;36m"
darkcyan: Final[str] = "\033[0;96m"
blue: Final[str] = "\033[0;34m"
green: Final[str] = "\033[0;32m"
yellow: Final[str] = "\033[0;33m"
red: Final[str] = "\033[0;31m"
lightred: Final[str] = "\033[1;31m"
bold: Final[str] = "\033[1m"
underline: Final[str] = "\033[4m"
end: Final[str] = "\033[0m"
PURPLE: Final[str] = "\033[0;95m"
CYAN: Final[str] = "\033[0;36m"
DARKCYAN: Final[str] = "\033[0;96m"
BLUE: Final[str] = "\033[0;34m"
GREEN: Final[str] = "\033[0;32m"
YELLOW: Final[str] = "\033[0;33m"
RED: Final[str] = "\033[0;31m"
LIGHTRED: Final[str] = "\033[1;31m"
BOLD: Final[str] = "\033[1m"
UNDERLINE: Final[str] = "\033[4m"
END: Final[str] = "\033[0m"
class Utils:
......@@ -67,15 +67,15 @@ class Utils:
"""
Prints a message in a colorful and consistent way
"""
prefix = TextFormatting.bold
if log_type == LogType.Info:
prefix = TextFormatting.BOLD
if log_type == LogType.INFO:
prefix += "Info"
elif log_type == LogType.Warning:
prefix += TextFormatting.yellow + "Warning" + TextFormatting.end
elif log_type == LogType.Error:
prefix += TextFormatting.red + "Error" + TextFormatting.end
elif log_type == LogType.WARNING:
prefix += TextFormatting.YELLOW + "Warning" + TextFormatting.END
elif log_type == LogType.ERROR:
prefix += TextFormatting.RED + "Error" + TextFormatting.END
prefix += TextFormatting.end
prefix += TextFormatting.END
if len(prefix) > 0:
prefix += ":"
......@@ -99,7 +99,7 @@ class Utils:
if "@" in url and ":" in url:
return "ssh://" + url.replace(":", "/")
Utils.log(LogType.Error, "Invalid url", url)
Utils.log(LogType.ERROR, "Invalid url", url)
sys.exit(1)
@staticmethod
......@@ -142,7 +142,7 @@ class Utils:
return "https://" + repository_url.hostname
# If everything failed, exit
Utils.log(LogType.Error, "Failed to detect GitLab instance url")
Utils.log(LogType.ERROR, "Failed to detect GitLab instance url")
sys.exit(1)
@staticmethod
......@@ -154,7 +154,7 @@ class Utils:
try:
return Repo(Utils.find_dotgit(os.getcwd()))
except InvalidGitRepositoryError:
Utils.log(LogType.Error, "Current directory is not a git repository")
Utils.log(LogType.ERROR, "Current directory is not a git repository")
sys.exit(1)
@staticmethod
......
......@@ -44,7 +44,7 @@ def run(args: argparse.Namespace) -> None:
"""
repository_config = RepositoryConfig()
if args.fork:
repository_config.set_workflow(Workflow.Fork)
repository_config.set_workflow(Workflow.FORK)
elif args.workbranch:
repository_config.set_workflow(Workflow.Workbranch)
repository_config.set_workflow(Workflow.WORKBRANCH)
repository_config.save()
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