From bf7853102ce95bb5cb0a73955bab1df2153091ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radom=C3=ADr=20Bos=C3=A1k?= Date: Thu, 1 Jun 2017 16:27:43 +0200 Subject: [PATCH 1/4] Support multiple Jenkins instances in config file This commit adds sections to the .jenkins-cli config file. The section which should be used is specified with the -e or --environment. If no environment is specified, the "DEFAULT" section is used. Fixes #36 --- README.md | 6 +++++ jenkins_cli/cli.py | 51 ++++++++++++++++++++++-------------- jenkins_cli/cli_arguments.py | 2 ++ tests/test_cli.py | 12 +++++---- 4 files changed, 47 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index ce6fb87..3c6852c 100644 --- a/README.md +++ b/README.md @@ -38,9 +38,15 @@ Host, username and password may be specified either by the command line argument **.jenkins-cli** example ```txt +[DEFAULT] host=http://localhost:8082/ username=username password=****** + +[prod] +host=https://production-jenkins.example.com/ +username=username +password=xxxxxx ``` # Commands overview: diff --git a/jenkins_cli/cli.py b/jenkins_cli/cli.py index 8deb99f..5de5a42 100644 --- a/jenkins_cli/cli.py +++ b/jenkins_cli/cli.py @@ -7,6 +7,12 @@ import socket from xml.etree import ElementTree +try: + from ConfigParser import ConfigParser, NoSectionError +except ImportError: + from configparser import ConfigParser, NoSectionError + + STATUSES_COLOR = {'blue': {'symbol': 'S', 'color': '\033[94m', 'descr': 'Stable'}, @@ -87,12 +93,13 @@ class JenkinsCli(object): "%s branch set to: %s") def __init__(self, args, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): - self.jenkins = self.auth(args.host, args.username, args.password, timeout) + self.jenkins = self.auth(args.host, args.username, args.password, + args.environment, timeout) @classmethod - def auth(cls, host=None, username=None, password=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): + def auth(cls, host=None, username=None, password=None, environment=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): if host is None or username is None or password is None: - settings_dict = cls.read_settings_from_file() + settings_dict = cls.read_settings_from_file(environment) try: host = host or settings_dict['host'] username = username or settings_dict.get('username', None) @@ -102,26 +109,32 @@ def auth(cls, host=None, username=None, password=None, timeout=socket._GLOBAL_DE return jenkins.Jenkins(host, username, password, timeout) @classmethod - def read_settings_from_file(cls): - try: - current_folder = os.getcwd() - filename = os.path.join(current_folder, cls.SETTINGS_FILE_NAME) + def read_settings_from_file(cls, environment): + # get config filename + current_folder = os.getcwd() + filename = os.path.join(current_folder, cls.SETTINGS_FILE_NAME) + if not os.path.exists(filename): + home_folder = os.path.expanduser("~") + filename = os.path.join(home_folder, cls.SETTINGS_FILE_NAME) if not os.path.exists(filename): - home_folder = os.path.expanduser("~") - filename = os.path.join(home_folder, cls.SETTINGS_FILE_NAME) - if not os.path.exists(filename): - return {} - f = open(filename, 'r') - jenkins_settings = f.read() + return {} + + # use the DEFAULT section if no env is specified + if not environment: + environment = 'DEFAULT' + + # read the config file + config = ConfigParser() + try: + config.readfp(open(filename, 'r')) except Exception as e: raise CliException('Error reading %s: %s' % (filename, e)) - settings_dict = {} - for setting_line in jenkins_settings.split('\n'): - if "=" in setting_line: - key, value = setting_line.split("=", 1) - settings_dict[key.strip()] = value.strip() - return settings_dict + # return the variables as dict + try: + return dict(config.items(environment)) + except NoSectionError: + raise CliException('No such environment: %s' % environment) def run_command(self, args): command = args.jenkins_command diff --git a/jenkins_cli/cli_arguments.py b/jenkins_cli/cli_arguments.py index 43ab3aa..ac6ee80 100644 --- a/jenkins_cli/cli_arguments.py +++ b/jenkins_cli/cli_arguments.py @@ -20,6 +20,8 @@ def load_parser(): parser.add_argument('--username', metavar='username', help='Jenkins Username', default=None) parser.add_argument('--password', metavar='password', help='Jenkins Password', default=None) parser.add_argument('--version', '-v', action='version', version='jenkins-cli %s' % version) + parser.add_argument('-e', '--environment', + help='Which config section to use') subparsers = parser.add_subparsers(title='Available commands', dest='jenkins_command') diff --git a/tests/test_cli.py b/tests/test_cli.py index 80d6f19..dc19429 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -75,11 +75,13 @@ def test_auth_has_file_settings(self, patched_init, read_settings_from_file): class TestCliFileUsing(fake_filesystem_unittest.TestCase): - HOME_FILE_CONTENT = ("host =https://jenkins.host.com\n" + HOME_FILE_CONTENT = ("[DEFAULT]\n" + "host =https://jenkins.host.com\n" "username= username\n" "some weird settings = value = value") - LOCAL_FILE_CONTENT = ("host=http://jenkins.localhosthost.ua\n" + LOCAL_FILE_CONTENT = ("[DEFAULT]\n" + "host=http://jenkins.localhosthost.ua\n" "username=Denys\n" "password=myPassword\n" "other_setting=some_value") @@ -97,7 +99,7 @@ def test_read_settings_from_file(self): self.fs.CreateFile(home_folder_filename, contents=self.HOME_FILE_CONTENT) self.assertTrue(os.path.exists(home_folder_filename)) - settings_dict = JenkinsCli.read_settings_from_file() + settings_dict = JenkinsCli.read_settings_from_file(environment=None) self.assertEqual(settings_dict, {"host": 'https://jenkins.host.com', "username": "username", @@ -107,7 +109,7 @@ def test_read_settings_from_file(self): self.fs.CreateFile(local_folder_filename, contents=self.LOCAL_FILE_CONTENT) self.assertTrue(os.path.exists(local_folder_filename)) - settings_dict = JenkinsCli.read_settings_from_file() + settings_dict = JenkinsCli.read_settings_from_file(environment=None) self.assertEqual(settings_dict, {"host": 'http://jenkins.localhosthost.ua', "username": "Denys", @@ -119,7 +121,7 @@ def test_read_settings_from_file(self): class TestCliCommands(unittest.TestCase): def setUp(self): - self.args = Namespace(host='http://jenkins.host.com', username=None, password=None) + self.args = Namespace(host='http://jenkins.host.com', username=None, password=None, environment=None) self.print_patcher = mock.patch('jenkins_cli.cli.print') self.patched_print = self.print_patcher.start() From fa96fd39ac8b955bcb9f96955d59e8bf707df199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radom=C3=ADr=20Bos=C3=A1k?= Date: Sun, 4 Jun 2017 09:34:33 +0200 Subject: [PATCH 2/4] Make missing config section error message clearer --- jenkins_cli/cli.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jenkins_cli/cli.py b/jenkins_cli/cli.py index 5de5a42..ee407a4 100644 --- a/jenkins_cli/cli.py +++ b/jenkins_cli/cli.py @@ -134,7 +134,8 @@ def read_settings_from_file(cls, environment): try: return dict(config.items(environment)) except NoSectionError: - raise CliException('No such environment: %s' % environment) + raise CliException('%s section not found in .jenkins-cli config' + ' file' % environment) def run_command(self, args): command = args.jenkins_command From 530353eeb912c81b1dbe4ed27bb61723901f5ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radom=C3=ADr=20Bos=C3=A1k?= Date: Sun, 4 Jun 2017 10:00:49 +0200 Subject: [PATCH 3/4] Add unit test for reading different config section --- tests/test_cli.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/test_cli.py b/tests/test_cli.py index dc19429..0db6640 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -86,6 +86,18 @@ class TestCliFileUsing(fake_filesystem_unittest.TestCase): "password=myPassword\n" "other_setting=some_value") + MULTIENV_FILE_CONTENT = ("[DEFAULT]\n" + "host =https://jenkins.host.com\n" + "username= username\n" + "some default settings = value = value\n" + "\n" + "[alternative]\n" + "host=http://jenkins.localhosthost.ua\n" + "username=Denys\n" + "password=myPassword\n" + "other_setting=some_value" + ) + def setUp(self): self.setUpPyfakefs() @@ -117,6 +129,30 @@ def test_read_settings_from_file(self): "other_setting": "some_value" }) + def test_read_settings_from_file_alt_environment(self): + # make sure we are in the fake fs + current_folder = os.getcwd() + local_folder_filename = os.path.join(current_folder, JenkinsCli.SETTINGS_FILE_NAME) + self.assertFalse(os.path.exists(local_folder_filename)) + + # create the fake config file + self.fs.CreateFile(local_folder_filename, + contents=self.MULTIENV_FILE_CONTENT) + self.assertTrue(os.path.exists(local_folder_filename)) + + # read the config from the file + settings_dict = JenkinsCli.read_settings_from_file(environment='alternative') + + # test and that the alternative environment is used, with the missing + # values being provided from the DEFAULT environmtne + self.assertEqual(settings_dict, + {"host": 'http://jenkins.localhosthost.ua', + "username": "Denys", + "password": "myPassword", + "other_setting": "some_value", + 'some default settings': 'value = value' + }) + class TestCliCommands(unittest.TestCase): From b39255052b741a568c7dbfc1128e58201ef4195d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radom=C3=ADr=20Bos=C3=A1k?= Date: Sun, 4 Jun 2017 10:03:42 +0200 Subject: [PATCH 4/4] Close the config file properly --- jenkins_cli/cli.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jenkins_cli/cli.py b/jenkins_cli/cli.py index ee407a4..3c0de7a 100644 --- a/jenkins_cli/cli.py +++ b/jenkins_cli/cli.py @@ -126,7 +126,8 @@ def read_settings_from_file(cls, environment): # read the config file config = ConfigParser() try: - config.readfp(open(filename, 'r')) + with open(filename, 'r') as f: + config.readfp(f) except Exception as e: raise CliException('Error reading %s: %s' % (filename, e))