Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
53 changes: 34 additions & 19 deletions jenkins_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'},
Expand Down Expand Up @@ -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)
Expand All @@ -102,26 +109,34 @@ 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:
with open(filename, 'r') as f:
config.readfp(f)
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('%s section not found in .jenkins-cli config'
' file' % environment)

def run_command(self, args):
command = args.jenkins_command
Expand Down
2 changes: 2 additions & 0 deletions jenkins_cli/cli_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
48 changes: 43 additions & 5 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,29 @@ 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")

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()

Expand All @@ -97,7 +111,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",
Expand All @@ -107,19 +121,43 @@ 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",
"password": "myPassword",
"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):

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()

Expand Down