Skip to content

Commit

Permalink
hubble: N802
Browse files Browse the repository at this point in the history
  • Loading branch information
buhman committed Jul 12, 2016
1 parent b5209b1 commit 8929a3a
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 43 deletions.
2 changes: 2 additions & 0 deletions examples/get-customer-credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
# opt-cmd in hubblerc.
# -----------------------------------------------------------------------------

# flake8: noqa

from __future__ import print_function

from argparse import ArgumentParser
Expand Down
24 changes: 12 additions & 12 deletions hubble/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ def items(self, section=_UNSET, raw=False, vars=None):


class SafeConfigParser(InheritanceConfigParser):
""" Simple subclass to add the safeGet() method """
def getError(self):
""" Simple subclass to add the safe_get() method """
def get_error(self):
return None

def safeGet(self, section, key):
def safe_get(self, section, key):
try:
return super(SafeConfigParser, self).get(section, key)
except (NoSectionError, NoOptionError):
Expand All @@ -93,19 +93,19 @@ def __init__(self, msg):
SafeConfigParser.__init__(self)
self.msg = msg

def getError(self):
def get_error(self):
return self.msg


def openFd(file):
def open_fd(file):
""" Open the file if possible, else return None """
try:
return open(file)
except IOError:
return None


def readConfigs(files=None, default_section=None):
def read_configs(files=None, default_section=None):
"""Given a list of file names, return a list of handles to succesfully
opened files
Expand All @@ -115,10 +115,10 @@ def readConfigs(files=None, default_section=None):
if not any([os.path.exists(rc) for rc in files]):
return ErrorConfigParser("Unable to find config files in these"
" locations [%s]" % ", ".join(files))
return parseConfigs([openFd(file) for file in files], default_section)
return parse_configs([open_fd(file) for file in files], default_section)


def parseConfigs(fds, default_section=None):
def parse_configs(fds, default_section=None):
"""Given a list of file handles, parse all the files with
ConfigParser()
Expand All @@ -136,11 +136,11 @@ def parseConfigs(fds, default_section=None):
return config


def validateVariableExists(args):
def validate_variable_exists(args):
""" Throw is the env and the variable does not exist in the config """
conf = readConfigs()
if conf.getError():
raise RuntimeError(conf.getError())
conf = read_configs()
if conf.get_error():
raise RuntimeError(conf.get_error())

try:
# attempt to get the variable from the requested environment
Expand Down
4 changes: 2 additions & 2 deletions hubble/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from __future__ import print_function

from argparse import ArgumentParser, RawDescriptionHelpFormatter
from hubble.config import validateVariableExists
from hubble.config import validate_variable_exists
import keyring
import getpass

Expand Down Expand Up @@ -52,7 +52,7 @@ def main():
password = None
try:
if args.variable:
validateVariableExists(args)
validate_variable_exists(args)
password = getpass.getpass(
'Enter Credential (CTRL-D to abort) > ')
except RuntimeError as e:
Expand Down
40 changes: 20 additions & 20 deletions hubble/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from subprocess import check_output, CalledProcessError, Popen, PIPE
from configparser import NoSectionError
from hubble.config import readConfigs
from hubble.config import read_configs
import argparse
import textwrap
import logging
Expand Down Expand Up @@ -81,10 +81,10 @@ def add(self, envs, section=None):
def eval(self):
""" Exapand all the ${variable} directives in the collection """
for key, pair in self.items():
self[key].value = self.expandVar(key, pair)
self[key].value = self.expand_var(key, pair)
return self

def expandVar(self, variable, pair):
def expand_var(self, variable, pair):
""" Find a ${some_var} signature and expand it """
result = pair.value
# Find all the ${...}
Expand All @@ -99,9 +99,9 @@ def expandVar(self, variable, pair):
raise RuntimeError("no such environment variable "
"'%s' in '%s'" % (key, result))
# Expand keyring values if any
return self.expandKeyringVar(variable, pair, result)
return self.expand_keyring_var(variable, pair, result)

def expandKeyringVar(self, variable, pair, value):
def expand_keyring_var(self, variable, pair, value):
""" Find 'USE_KEYRING' directives and expand them using the keyring """
identifier = value.strip()
if identifier.startswith("USE_KEYRING"):
Expand All @@ -118,7 +118,7 @@ def expandKeyringVar(self, variable, pair, value):
return keys.get_password(variable, None)
return value

def toDict(self):
def to_dict(self):
"""
Convert the entire collection of Pair() objects to a
dict({'key': str()}) only where export == True
Expand All @@ -144,7 +144,7 @@ def green(msg):
return "\033[92m%s\033[0m" % msg


def getEnvironments(args, choice, config):
def get_environments(args, choice, config):
""" Get the environment collection requested from args.env """
sections = [choice]
results = []
Expand Down Expand Up @@ -175,7 +175,7 @@ def f(i):
return results


def toDict(buf):
def to_dict(buf):
""" Parse a string of 'key=value' into a dict({'key': 'value'}) """
try:
# Convert the bytes to string
Expand Down Expand Up @@ -204,12 +204,12 @@ def run(cmd, env):
# Execute the command with the current env
# overlaid with our built environment
environ = os.environ.copy()
environ.update(env.toDict())
environ.update(env.to_dict())
# Use of undocumented 'env' option on check_output
return toDict(check_output(cmd, shell=True, env=environ))
return to_dict(check_output(cmd, shell=True, env=environ))


def cmdPath(cmd, conf):
def cmd_path(cmd, conf):
""" Find the 'cmd' in the config, or default to /usr/bin/'cmd' """
basename = os.path.basename(cmd)
try:
Expand All @@ -221,8 +221,8 @@ def cmdPath(cmd, conf):
return "/usr/bin/%s" % basename


def evalArgs(conf, parser):
env = conf.safeGet(conf.default_section, 'default-env')
def eval_args(conf, parser):
env = conf.safe_get(conf.default_section, 'default-env')
# If no default environment set, look for an
# environment choice on the command line
if not env:
Expand Down Expand Up @@ -262,18 +262,18 @@ def main():

try:
# Read the configs
conf = readConfigs(default_section='hubble')
conf = read_configs(default_section='hubble')
# Evaluate the command line arguments and return our args
# the commands args and the environment choice the user made
hubble_args, other_args, choice = evalArgs(conf, parser)
hubble_args, other_args, choice = eval_args(conf, parser)
# Do this so we pass along the -h to the command
# if we are using invocation discovery
if hubble_args.help and (choice is None):
return parser.print_help()

# If there was an error
if conf.getError():
print(conf.getError())
if conf.get_error():
print(conf.get_error())
return 1

if choice is None:
Expand All @@ -288,7 +288,7 @@ def main():
log.setLevel(logging.DEBUG)

# Read environment values from config files
environments = getEnvironments(hubble_args, choice, conf)
environments = get_environments(hubble_args, choice, conf)
processes = []
for env in environments:
# Populate environment vars by running opt-cmd
Expand All @@ -311,7 +311,7 @@ def main():
# If our invocation name is not 'hubble'
if not sys.argv[0].endswith('hubble'):
# Use the invocation name as our 'cmd'
env.add({'cmd': cmdPath(sys.argv[0], conf)})
env.add({'cmd': cmd_path(sys.argv[0], conf)})

if hubble_args.execute:
# Use the command provided
Expand All @@ -334,7 +334,7 @@ def main():
# Grab a copy of the local environment and inject it into
# our environment
environ = os.environ.copy()
environ.update(env.toDict())
environ.update(env.to_dict())

try:
# Run the requested command
Expand Down
19 changes: 10 additions & 9 deletions hubble/tests/unit/test_hubble.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
# limitations under the License.


from hubble.shell import getEnvironments, Env, run, toDict, empty
from hubble.config import parseConfigs
from hubble.shell import get_environments, Env, run, to_dict, empty
from hubble.config import parse_configs
from six.moves import StringIO
import unittest
import argparse
Expand All @@ -30,14 +30,14 @@ def test_env(self):
self.assertEqual(env['string'].value, "My name is Derrick Wippler")
self.assertEqual(env['string'].section, "section")

def test_env_toDict(self):
def test_env_to_dict(self):
env = Env()
env.set('first', 'Derrick', 'section')
env.set('last', 'Wippler', 'section')
env.set('no-export', 'wat', 'section', export=False)
self.assertEqual(env.toDict(), {'first': 'Derrick', 'last': 'Wippler'})
self.assertEqual(env.to_dict(), {'first': 'Derrick', 'last': 'Wippler'})

def test_getEnvironments(self):
def test_get_environments(self):
parser = argparse.ArgumentParser()
parser.add_argument('env')
parser.add_argument('--user', default='', required=False)
Expand All @@ -51,8 +51,9 @@ def test_getEnvironments(self):
"FIRST=Derrick\n"
"last=Wippler\n")
file.name = "test-config.ini"
config = parseConfigs([file], default_section='hubble')
env = getEnvironments(args, 'name', config)
config = parse_configs([file], default_section='hubble')
env = get_environments(args, 'name', config)

self.assertIn('name', env[0])
self.assertEqual(env[0]['name'].value, 'My name is Derrick Wippler')

Expand All @@ -68,9 +69,9 @@ def test_empty(self):
self.assertEqual(empty(" "), True)
self.assertEqual(empty(" r"), False)

def test_toDict(self):
def test_to_dict(self):
expected = {'key': 'value', 'foo': 'bar'}
self.assertEqual(toDict(b"key=value\nfoo=bar\n"), expected)
self.assertEqual(to_dict(b"key=value\nfoo=bar\n"), expected)

def test_run(self):
env = run('echo "USER=thrawn\nSHELL=bash"', Env())
Expand Down

0 comments on commit 8929a3a

Please sign in to comment.