From 389a663cce7860acddcdaf25cc5d52e5978c3d13 Mon Sep 17 00:00:00 2001 From: Ondřej Nosek Date: Feb 06 2024 21:27:53 +0000 Subject: '_set_token' method moved to a shared place This method was used only by fedpkg in the past. With implementing a similar functionality in rhpkg, move this code to rpkg where it can be shared by multiple tools. The original method accepted the token as a command-line argument and this wasn't a sane approach. Now the token is safely put via getpass method. JIRA: RHELCMP-13435 Relates: rhbz#2089694 Signed-off-by: Ondřej Nosek --- diff --git a/pyrpkg/cli.py b/pyrpkg/cli.py index 5b74a26..8c65708 100644 --- a/pyrpkg/cli.py +++ b/pyrpkg/cli.py @@ -3161,3 +3161,57 @@ class cliClient(object): "should be an integer.") val = None return val + + # this method have to be specified in a derived class + def _check_token(self, token, token_type): + raise rpkgError('Undefined method for checking the token.') + + def _set_token(self, token_type): + TOKEN = getpass.getpass(prompt="Input the token: ") + + # Get the path to the local config file. + PATH = os.path.join(os.path.expanduser('~'), + '.config', + 'rpkg', + '{0}.conf'.format(self.name)) + + # load new config parser + local_config = configparser.ConfigParser() + local_config.read(PATH) + + # Ensure that user config file exists. + if not os.path.isfile(PATH): + self.log.warning("WARNING: User config file not found at: {0}".format(PATH)) + self.log.info("The config file will be created.") + # Make sure there is subdirectory already prepared. + try: + # Use parameter "exist_ok=True" in Python 3 only + os.makedirs(os.path.dirname(PATH)) + except OSError: + # Directory already exists or could not be created. + pass + if not os.path.isdir(os.path.dirname(PATH)): + self.log.error("ERROR: Could not create a directory for the user config file.") + return + + # Check that the user passed a valid token + if self._check_token(TOKEN, token_type): + + print("updating config '{}'".format(PATH)) + + # Update the token in the config object. + section = "{0}.{1}".format(self.name, token_type) + + # add the section if it doesn't already exist + if not local_config.has_section(section): + local_config.add_section(section) + + # update the token + local_config.set(section, "token", TOKEN) + + # Write the config to the user's config file. + with open(PATH, "w") as fp: + try: + local_config.write(fp) + except configparser.ConfigParser.Error: + self.log.error("ERROR: Could not write to user config file.")