Skip to content

Commit

Permalink
Refactor nargs
Browse files Browse the repository at this point in the history
  • Loading branch information
wohlgejm committed Jul 25, 2017
1 parent 8af4e34 commit d041865
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 28 deletions.
32 changes: 4 additions & 28 deletions accountable/accountable.py
Expand Up @@ -9,6 +9,7 @@

from accountable.config import Config
from accountable.resource import Resource
from accountable.nargs import nargs_to_dict


class Accountable(object):
Expand Down Expand Up @@ -49,11 +50,11 @@ def issue_meta(self):
return data

def issue_create(self, options):
payload = Nargs(options).__dict__()
payload = nargs_to_dict(options)
return self.resource.post('issue', payload)

def checkout_branch(self, options):
payload = Nargs(options).__dict__()
payload = nargs_to_dict(options)
new_issue = self.issue_create(options)
summary = payload['fields']['summary']
key = new_issue['key']
Expand All @@ -80,7 +81,7 @@ def project_components(self, project_key):
return self.resource.get('project/{}/components'.format(project_key))

def issue_update(self, options):
payload = Nargs(options).__dict__()
payload = nargs_to_dict(options)
self.resource.put('issue/{}'.format(self.issue_key),
payload)
return self.issue_meta()
Expand Down Expand Up @@ -131,28 +132,3 @@ def _field_name(field):
return field.upper()
else:
return list(field.keys())[0].upper()


class Nargs(object):
def __init__(self, options):
self._dict = self._args_to_dict(options)

def __dict__(self):
return self._dict

def _args_to_dict(self, args_tuple):
d = {}
for arg in zip(args_tuple[0::2], args_tuple[1::2]):
keys = arg[0].split('.')
self._set_nested_key(keys, arg[1], d)
return {'fields': d}

def _set_nested_key(self, key, value, d):
if isinstance(key, list) and len(key) > 1:
head, tail = key[0], key[1:]
if not d.get(head):
d[head] = {}
self._set_nested_key(tail, value, d[head])
else:
d[list(key)[0]] = value
return d
34 changes: 34 additions & 0 deletions accountable/nargs.py
@@ -0,0 +1,34 @@
from __future__ import absolute_import

try:
from collections import MutableSequence
except ImportError:
from collections.abc import MutableSequence
import ast


def nargs_to_dict(nargs):
d = {}
for arg in zip(nargs[0::2], nargs[1::2]):
key, value = arg
parsed_value = eval_value(value)
rec_nargs_to_dict(key, parsed_value, d)
return {'fields': d}


def rec_nargs_to_dict(key, value, d):
if isinstance(key, MutableSequence):
keys = key.split('.')
head, tail = keys[0], keys[1:]
if not d.get(head):
d[head] = {}
rec_nargs_to_dict(tail, value, d[head])
d[key] = value
return d


def eval_value(value):
try:
return ast.literal_eval(value)
except (SyntaxError, ValueError):
return value

0 comments on commit d041865

Please sign in to comment.