From 8eabdb3909017ae425732f5615a96cc9601227d6 Mon Sep 17 00:00:00 2001 From: Guilherme Gallo Date: Mon, 22 Jan 2024 20:16:43 -0300 Subject: [PATCH] bin/ci: Refactor read_token function Make `read_token` utilize the `get_gitlab_pipeline_from_url` to reuse code from `gitlab_gql.py`. Signed-off-by: Guilherme Gallo Part-of: --- bin/ci/ci_run_n_monitor.py | 13 +++++++++---- bin/ci/gitlab_common.py | 26 ++++++++++++++++++-------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/bin/ci/ci_run_n_monitor.py b/bin/ci/ci_run_n_monitor.py index 293b5c515f2..63fcb6ffb8a 100755 --- a/bin/ci/ci_run_n_monitor.py +++ b/bin/ci/ci_run_n_monitor.py @@ -26,12 +26,14 @@ from typing import TYPE_CHECKING, Iterable, Literal, Optional import gitlab from colorama import Fore, Style from gitlab_common import ( - get_gitlab_project, + GITLAB_URL, + TOKEN_DIR, get_gitlab_pipeline_from_url, + get_gitlab_project, + get_token_from_default_dir, + pretty_duration, read_token, wait_for_pipeline, - pretty_duration, - GITLAB_URL, ) from gitlab_gql import GitlabGQL, create_job_needs_dag, filter_dag, print_dag @@ -274,7 +276,10 @@ def parse_args() -> None: parser.add_argument( "--token", metavar="token", - help="force GitLab token, otherwise it's read from ~/.config/gitlab-token", + type=str, + default=get_token_from_default_dir(), + help="Use the provided GitLab token or token file, " + f"otherwise it's read from {TOKEN_DIR / 'gitlab-token'}", ) parser.add_argument( "--force-manual", action="store_true", help="Force jobs marked as manual" diff --git a/bin/ci/gitlab_common.py b/bin/ci/gitlab_common.py index 57f6c696215..718a41d9377 100644 --- a/bin/ci/gitlab_common.py +++ b/bin/ci/gitlab_common.py @@ -71,15 +71,25 @@ def get_token_from_default_dir() -> str: raise ex -def read_token(token_arg: Optional[str]) -> str: - """pick token from args or file""" +def read_token(token_arg: str | Path | None) -> str | None: + """ + Reads the token from the given file path or returns the token argument if it is not a file. + + Args: + token_arg (str | Path | None): The file path or the token itself. + + Returns: + str | None: The token string or None if the token is not provided. + """ if token_arg: - return token_arg - return ( - open(os.path.expanduser("~/.config/gitlab-token"), encoding="utf-8") - .readline() - .rstrip() - ) + token_path = Path(token_arg) + if token_path.is_file(): + # if is a file, read it + return token_path.read_text().strip() + return str(token_arg) + + # if the token is not provided neither its file, return None + return None def wait_for_pipeline(projects, sha: str, timeout=None):