desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Base command for repoquery'
| def _repoquery_cmd(self, cmd, output=False, output_type='json'):
| cmds = ['/usr/bin/repoquery', '--plugins', '--quiet']
cmds.extend(cmd)
rval = {}
results = ''
err = None
if self.verbose:
print ' '.join(cmds)
(returncode, stdout, stderr) = _run(cmds)
rval = {'returncode': returncode, 'results': results, 'cmd': ' '.join(cmds)}
if (retu... |
'setup method will create a file and set to known configuration'
| def setUp(self):
| yed = Yedit(YeditTest.filename)
yed.yaml_dict = YeditTest.data
yed.write()
|
'Testing a get'
| def test_load(self):
| yed = Yedit('yedit_test.yml')
self.assertEqual(yed.yaml_dict, self.data)
|
'Testing a simple write'
| def test_write(self):
| yed = Yedit('yedit_test.yml')
yed.put('key1', 1)
yed.write()
self.assertTrue(('key1' in yed.yaml_dict))
self.assertEqual(yed.yaml_dict['key1'], 1)
|
'Testing a write of multilayer key'
| def test_write_x_y_z(self):
| yed = Yedit('yedit_test.yml')
yed.put('x.y.z', 'modified')
yed.write()
yed.load()
self.assertEqual(yed.get('x.y.z'), 'modified')
|
'Testing a simple delete'
| def test_delete_a(self):
| yed = Yedit('yedit_test.yml')
yed.delete('a')
yed.write()
yed.load()
self.assertTrue(('a' not in yed.yaml_dict))
|
'Testing delete of layered key'
| def test_delete_b_c(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.delete('b:c')
yed.write()
yed.load()
self.assertTrue(('b' in yed.yaml_dict))
self.assertFalse(('c' in yed.yaml_dict['b']))
|
'Testing a create'
| def test_create(self):
| os.unlink(YeditTest.filename)
yed = Yedit('yedit_test.yml')
yed.create('foo', 'bar')
yed.write()
yed.load()
self.assertTrue(('foo' in yed.yaml_dict))
self.assertTrue((yed.yaml_dict['foo'] == 'bar'))
|
'Testing a create with content'
| def test_create_content(self):
| content = {'foo': 'bar'}
yed = Yedit('yedit_test.yml', content)
yed.write()
yed.load()
self.assertTrue(('foo' in yed.yaml_dict))
self.assertTrue(yed.yaml_dict['foo'], 'bar')
|
'Testing a create with content'
| def test_array_insert(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', 'inject')
self.assertTrue((yed.get('b:c:d[0]') == 'inject'))
|
'Testing a create with content'
| def test_array_insert_first_index(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', 'inject')
self.assertTrue((yed.get('b:c:d[1]') == 'f'))
|
'Testing a create with content'
| def test_array_insert_second_index(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', 'inject')
self.assertTrue((yed.get('b:c:d[2]') == 'g'))
|
'Testing a create with content'
| def test_dict_array_dict_access(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}])
self.assertTrue((yed.get('b:c:d[0]:[0]:x:y') == 'inject'))
|
'Testing multilevel delete'
| def test_dict_array_dict_replace(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}])
yed.put('b:c:d[0]:[0]:x:y', 'testing')
self.assertTrue(('b' in yed.yaml_dict))
self.assertTrue(('c' in yed.yaml_dict['b']))
self.assertTrue(('d' in yed.yaml_dict['b']['c']))
self.assertTrue(isinstance(... |
'Testing multilevel delete'
| def test_dict_array_dict_remove(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}])
yed.delete('b:c:d[0]:[0]:x:y')
self.assertTrue(('b' in yed.yaml_dict))
self.assertTrue(('c' in yed.yaml_dict['b']))
self.assertTrue(('d' in yed.yaml_dict['b']['c']))
self.assertTrue(isinstance(yed.yaml... |
'Testing exist in dict'
| def test_key_exists_in_dict(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}])
self.assertTrue(yed.exists('b:c', 'd'))
|
'Testing exist in list'
| def test_key_exists_in_list(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}])
self.assertTrue(yed.exists('b:c:d', [{'x': {'y': 'inject'}}]))
self.assertFalse(yed.exists('b:c:d', [{'x': {'y': 'test'}}]))
|
'Testing update to list with index'
| def test_update_to_list_with_index(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('x:y:z', [1, 2, 3])
yed.update('x:y:z', [5, 6], index=2)
self.assertTrue((yed.get('x:y:z') == [1, 2, [5, 6]]))
self.assertTrue(yed.exists('x:y:z', [5, 6]))
self.assertFalse(yed.exists('x:y:z', 4))
|
'Testing update to list with index'
| def test_update_to_list_with_curr_value(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('x:y:z', [1, 2, 3])
yed.update('x:y:z', [5, 6], curr_value=3)
self.assertTrue((yed.get('x:y:z') == [1, 2, [5, 6]]))
self.assertTrue(yed.exists('x:y:z', [5, 6]))
self.assertFalse(yed.exists('x:y:z', 4))
|
'Testing update to list'
| def test_update_to_list(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('x:y:z', [1, 2, 3])
yed.update('x:y:z', [5, 6])
self.assertTrue((yed.get('x:y:z') == [1, 2, 3, [5, 6]]))
self.assertTrue(yed.exists('x:y:z', [5, 6]))
self.assertFalse(yed.exists('x:y:z', 4))
|
'Testing append to list'
| def test_append_twice_to_list(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('x:y:z', [1, 2, 3])
yed.append('x:y:z', [5, 6])
yed.append('x:y:z', [5, 6])
self.assertTrue((yed.get('x:y:z') == [1, 2, 3, [5, 6], [5, 6]]))
self.assertFalse(yed.exists('x:y:z', 4))
|
'Testing update to dict'
| def test_add_item_to_dict(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('x:y:z', {'a': 1, 'b': 2})
yed.update('x:y:z', {'c': 3, 'd': 4})
self.assertTrue((yed.get('x:y:z') == {'a': 1, 'b': 2, 'c': 3, 'd': 4}))
self.assertTrue(yed.exists('x:y:z', {'c': 3}))
|
'test dict value with none value'
| def test_first_level_dict_with_none_value(self):
| yed = Yedit(content={'a': None}, separator=':')
yed.put('a:b:c', 'test')
self.assertTrue((yed.get('a:b:c') == 'test'))
self.assertTrue(yed.get('a:b'), {'c': 'test'})
|
'test dict value with none value'
| def test_adding_yaml_variable(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('z:y', '{{test}}')
self.assertTrue((yed.get('z:y') == '{{test}}'))
|
'test dict value with none value'
| def test_keys_with_underscore(self):
| yed = Yedit('yedit_test.yml', separator=':')
yed.put('z_:y_y', {'test': '{{test}}'})
self.assertTrue((yed.get('z_:y_y') == {'test': '{{test}}'}))
|
'test update on top level array'
| def test_first_level_array_update(self):
| yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}], separator=':')
yed.update('', {'c': 4})
self.assertTrue(({'c': 4} in yed.get('')))
|
'test remove top level key'
| def test_first_level_array_delete(self):
| yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}])
yed.delete('')
self.assertTrue(({'b': 3} not in yed.get('')))
|
'test dict value with none value'
| def test_first_level_array_get(self):
| yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}])
yed.get('')
self.assertTrue(([{'a': 1}, {'b': 2}, {'b': 3}] == yed.yaml_dict))
|
'test dict value with none value'
| def test_pop_list_item(self):
| yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}], separator=':')
yed.pop('', {'b': 2})
self.assertTrue(([{'a': 1}, {'b': 3}] == yed.yaml_dict))
|
'test dict value with none value'
| def test_pop_list_item_2(self):
| z = list(range(10))
yed = Yedit(content=z, separator=':')
yed.pop('', 5)
z.pop(5)
self.assertTrue((z == yed.yaml_dict))
|
'test dict value with none value'
| def test_pop_dict_key(self):
| yed = Yedit(content={'a': {'b': {'c': 1, 'd': 2}}}, separator='#')
yed.pop('a#b', 'c')
self.assertTrue(({'a': {'b': {'d': 2}}} == yed.yaml_dict))
|
'test providing source path objects that differ from current object state'
| def test_accessing_path_with_unexpected_objects(self):
| yed = Yedit(content={'a': {'b': {'c': ['d', 'e']}}})
with self.assertRaises(YeditException):
yed.put('a.b.c.d', 'x')
|
'test creating new objects with an embedded list in the creation path'
| def test_creating_new_objects_with_embedded_list(self):
| yed = Yedit(content={'a': {'b': 12}})
with self.assertRaises(YeditException):
yed.put('new.stuff[0].here', 'value')
|
'test creating new object(s) where the final piece is a list'
| def test_creating_new_objects_with_trailing_list(self):
| yed = Yedit(content={'a': {'b': 12}})
with self.assertRaises(YeditException):
yed.put('new.stuff.here[0]', 'item')
|
'test editing top level with not list or dict'
| def test_empty_key_with_int_value(self):
| yed = Yedit(content={'a': {'b': 12}})
result = yed.put('', 'b')
self.assertFalse(result[0])
|
'test editing top level with not list or dict'
| def test_setting_separator(self):
| yed = Yedit(content={'a': {'b': 12}})
yed.separator = ':'
self.assertEqual(yed.separator, ':')
|
'test removing all data'
| def test_remove_all(self):
| data = Yedit.remove_entry({'a': {'b': 12}}, '')
self.assertTrue(data)
|
'test removing list entry'
| def test_remove_list_entry(self):
| data = {'a': {'b': [{'c': 3}]}}
results = Yedit.remove_entry(data, 'a.b[0]')
self.assertTrue(results)
self.assertTrue(data, {'a': {'b': []}})
|
'test parse_value'
| def test_parse_value_string_true(self):
| results = Yedit.parse_value('true', 'str')
self.assertEqual(results, 'true')
|
'test parse_value'
| def test_parse_value_bool_true(self):
| results = Yedit.parse_value('true', 'bool')
self.assertTrue(results)
|
'test parse_value'
| def test_parse_value_bool_exception(self):
| with self.assertRaises(YeditException):
Yedit.parse_value('TTT', 'bool')
|
'test parse_value'
| @mock.patch('yedit.Yedit.write')
def test_run_ansible_basic(self, mock_write):
| params = {'src': None, 'backup': False, 'separator': '.', 'state': 'present', 'edits': [], 'value': None, 'key': None, 'content': {'a': {'b': {'c': 1}}}, 'content_type': ''}
results = Yedit.run_ansible(params)
mock_write.side_effect = [(True, params['content'])]
self.assertFalse(results['changed'])
|
'test parse_value'
| @mock.patch('yedit.Yedit.write')
def test_run_ansible_and_write(self, mock_write):
| params = {'src': '/tmp/test', 'backup': False, 'separator': '.', 'state': 'present', 'edits': [], 'value': None, 'key': None, 'content': {'a': {'b': {'c': 1}}}, 'content_type': ''}
results = Yedit.run_ansible(params)
mock_write.side_effect = [(True, params['content'])]
self.assertTrue(results['changed']... |
'TearDown method'
| def tearDown(self):
| os.unlink(YeditTest.filename)
|
'Testing querying a package'
| @mock.patch('repoquery._run')
def test_querying_a_package(self, mock_cmd):
| params = {'state': 'list', 'name': 'bash', 'query_type': 'repos', 'verbose': False, 'show_duplicates': False, 'match_version': None, 'ignore_excluders': False}
valid_stderr = 'Repo rhel-7-server-extras-rpms forced skip_if_unavailable=True due to: /etc/pki/entitlement/3268107132875399464-key.pe... |
'getter method for separator'
| @property
def separator(self):
| return self._separator
|
'setter method for separator'
| @separator.setter
def separator(self, inc_sep):
| self._separator = inc_sep
|
'getter method for yaml_dict'
| @property
def yaml_dict(self):
| return self.__yaml_dict
|
'setter method for yaml_dict'
| @yaml_dict.setter
def yaml_dict(self, value):
| self.__yaml_dict = value
|
'parse the key allowing the appropriate separator'
| @staticmethod
def parse_key(key, sep='.'):
| common_separators = list((Yedit.com_sep - set([sep])))
return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
|
'validate the incoming key'
| @staticmethod
def valid_key(key, sep='.'):
| common_separators = list((Yedit.com_sep - set([sep])))
if (not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key)):
return False
return True
|
'remove data at location key'
| @staticmethod
def remove_entry(data, key, sep='.'):
| if ((key == '') and isinstance(data, dict)):
data.clear()
return True
elif ((key == '') and isinstance(data, list)):
del data[:]
return True
if ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_ke... |
'Get an item from a dictionary with key notation a.b.c
d = {\'a\': {\'b\': \'c\'}}}
key = a#b
return c'
| @staticmethod
def add_entry(data, key, item=None, sep='.'):
| if (key == ''):
pass
elif ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for (arr_ind, dict_key) in key_indexes[:(-1)]:
if dict_key:
if (isinstance(data, dict) and (dict_key in data) ... |
'Get an item from a dictionary with key notation a.b.c
d = {\'a\': {\'b\': \'c\'}}}
key = a.b
return c'
| @staticmethod
def get_entry(data, key, sep='.'):
| if (key == ''):
pass
elif ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for (arr_ind, dict_key) in key_indexes:
if (dict_key and isinstance(data, dict)):
data = data.get(dict_key)
... |
'Actually write the file contents to disk. This helps with mocking.'
| @staticmethod
def _write(filename, contents):
| tmp_filename = (filename + '.yedit')
with open(tmp_filename, 'w') as yfd:
yfd.write(contents)
os.rename(tmp_filename, filename)
|
'write to file'
| def write(self):
| if (not self.filename):
raise YeditException('Please specify a filename.')
if (self.backup and self.file_exists()):
shutil.copy(self.filename, (self.filename + '.orig'))
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
try:
Yedit._... |
'read from file'
| def read(self):
| if ((self.filename is None) or (not self.file_exists())):
return None
contents = None
with open(self.filename) as yfd:
contents = yfd.read()
return contents
|
'return whether file exists'
| def file_exists(self):
| if os.path.exists(self.filename):
return True
return False
|
'return yaml file'
| def load(self, content_type='yaml'):
| contents = self.read()
if ((not contents) and (not self.content)):
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
t... |
'get a specified key'
| def get(self, key):
| try:
entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
except KeyError:
entry = None
return entry
|
'remove a key, value pair from a dict or an item for a list'
| def pop(self, path, key_or_item):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
return (False, self.yaml_dict)
if isinstance(entry, dict):
if (key_or_item in entry):
entry.pop(key_or_item)
return (True, self.yam... |
'remove path from a dict'
| def delete(self, path):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
return (False, self.yaml_dict)
result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
if (not result):
return (False, self.yaml_dict)
re... |
'check if value exists at path'
| def exists(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, list):
if (value in entry):
return True
return False
elif isinstance(entry, dict):
if isinstance(value, dict):
rval = Fals... |
'append value to a list'
| def append(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
self.put(path, [])
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
if (not isinstance(entry, list)):
return (False, self.yaml_dict)
... |
'put path, value into a dict'
| def update(self, path, value, index=None, curr_value=None):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
if (not isinstance(value, dict)):
raise YeditException(('Cannot replace key, value entry in dict with non-dict type. ... |
'put path, value into a dict'
| def put(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry == value):
return (False, self.yaml_dict)
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader)
except ... |
'create a yaml file'
| def create(self, path, value):
| if (not self.file_exists()):
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
try:
tmp_copy.fa.set_block_style()
except A... |
'return the current value'
| @staticmethod
def get_curr_value(invalue, val_type):
| if (invalue is None):
return None
curr_value = invalue
if (val_type == 'yaml'):
curr_value = yaml.load(invalue)
elif (val_type == 'json'):
curr_value = json.loads(invalue)
return curr_value
|
'determine value type passed'
| @staticmethod
def parse_value(inc_value, vtype=''):
| true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON']
false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF']
if (isinstance(inc_value, str) and ('bool' in vtype)):
if ((inc_value not in true_bools) and (inc_value not in false_bools... |
'run through a list of edits and process them one-by-one'
| @staticmethod
def process_edits(edits, yamlfile):
| results = []
for edit in edits:
value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
if (edit.get('action') == 'update'):
curr_value = Yedit.get_curr_value(Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format'))
rval = yamlfile.update(edi... |
'perform the idempotent crud operations'
| @staticmethod
def run_ansible(params):
| yamlfile = Yedit(filename=params['src'], backup=params['backup'], separator=params['separator'])
state = params['state']
if params['src']:
rval = yamlfile.load()
if ((yamlfile.yaml_dict is None) and (state != 'present')):
return {'failed': True, 'msg': ('Error opening file ... |
'Constructor for YumList'
| def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
| super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.ignore_excluders = ignore_excluders
self.verbose = verbose
if self.match_version:
self.show_duplicates = True
sel... |
'build the repoquery cmd options'
| def build_cmd(self):
| repo_cmd = []
repo_cmd.append(('--pkgnarrow=' + self.query_type))
repo_cmd.append(('--queryformat=' + self.query_format))
if self.show_duplicates:
repo_cmd.append('--show-duplicates')
if self.ignore_excluders:
repo_cmd.append(('--config=' + self.tmp_file.name))
repo_cmd.append(se... |
'format the package data into something that can be presented'
| @staticmethod
def process_versions(query_output):
| version_dict = defaultdict(dict)
for version in query_output.decode().split('\n'):
pkg_info = version.split('|')
pkg_version = {}
pkg_version['version'] = pkg_info[0]
pkg_version['release'] = pkg_info[1]
pkg_version['arch'] = pkg_info[2]
pkg_version['repo'] = pkg_... |
'Gather and present the versions of each package'
| def format_versions(self, formatted_versions):
| versions_dict = {}
versions_dict['available_versions_full'] = list(formatted_versions.keys())
if self.match_version:
versions_dict['matched_versions_full'] = []
versions_dict['requested_match_version'] = self.match_version
versions_dict['matched_versions'] = []
versions_dict['ava... |
'perform a repoquery'
| def repoquery(self):
| if self.ignore_excluders:
self.tmp_file = tempfile.NamedTemporaryFile()
with open('/etc/yum.conf', 'r') as file_handler:
yum_conf_lines = file_handler.readlines()
yum_conf_lines = [('exclude=' if l.startswith('exclude=') else l) for l in yum_conf_lines]
with open(self.tmp... |
'run the ansible idempotent code'
| @staticmethod
def run_ansible(params, check_mode):
| repoquery = Repoquery(params['name'], params['query_type'], params['show_duplicates'], params['match_version'], params['ignore_excluders'], params['verbose'])
state = params['state']
if (state == 'list'):
results = repoquery.repoquery()
if (results['returncode'] != 0):
return {'f... |
'getter method for separator'
| @property
def separator(self):
| return self._separator
|
'setter method for separator'
| @separator.setter
def separator(self, inc_sep):
| self._separator = inc_sep
|
'getter method for yaml_dict'
| @property
def yaml_dict(self):
| return self.__yaml_dict
|
'setter method for yaml_dict'
| @yaml_dict.setter
def yaml_dict(self, value):
| self.__yaml_dict = value
|
'parse the key allowing the appropriate separator'
| @staticmethod
def parse_key(key, sep='.'):
| common_separators = list((Yedit.com_sep - set([sep])))
return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
|
'validate the incoming key'
| @staticmethod
def valid_key(key, sep='.'):
| common_separators = list((Yedit.com_sep - set([sep])))
if (not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key)):
return False
return True
|
'remove data at location key'
| @staticmethod
def remove_entry(data, key, sep='.'):
| if ((key == '') and isinstance(data, dict)):
data.clear()
return True
elif ((key == '') and isinstance(data, list)):
del data[:]
return True
if ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_ke... |
'Get an item from a dictionary with key notation a.b.c
d = {\'a\': {\'b\': \'c\'}}}
key = a#b
return c'
| @staticmethod
def add_entry(data, key, item=None, sep='.'):
| if (key == ''):
pass
elif ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for (arr_ind, dict_key) in key_indexes[:(-1)]:
if dict_key:
if (isinstance(data, dict) and (dict_key in data) ... |
'Get an item from a dictionary with key notation a.b.c
d = {\'a\': {\'b\': \'c\'}}}
key = a.b
return c'
| @staticmethod
def get_entry(data, key, sep='.'):
| if (key == ''):
pass
elif ((not (key and Yedit.valid_key(key, sep))) and isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for (arr_ind, dict_key) in key_indexes:
if (dict_key and isinstance(data, dict)):
data = data.get(dict_key)
... |
'Actually write the file contents to disk. This helps with mocking.'
| @staticmethod
def _write(filename, contents):
| tmp_filename = (filename + '.yedit')
with open(tmp_filename, 'w') as yfd:
yfd.write(contents)
os.rename(tmp_filename, filename)
|
'write to file'
| def write(self):
| if (not self.filename):
raise YeditException('Please specify a filename.')
if (self.backup and self.file_exists()):
shutil.copy(self.filename, (self.filename + '.orig'))
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
try:
Yedit._... |
'read from file'
| def read(self):
| if ((self.filename is None) or (not self.file_exists())):
return None
contents = None
with open(self.filename) as yfd:
contents = yfd.read()
return contents
|
'return whether file exists'
| def file_exists(self):
| if os.path.exists(self.filename):
return True
return False
|
'return yaml file'
| def load(self, content_type='yaml'):
| contents = self.read()
if ((not contents) and (not self.content)):
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
t... |
'get a specified key'
| def get(self, key):
| try:
entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
except KeyError:
entry = None
return entry
|
'remove a key, value pair from a dict or an item for a list'
| def pop(self, path, key_or_item):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
return (False, self.yaml_dict)
if isinstance(entry, dict):
if (key_or_item in entry):
entry.pop(key_or_item)
return (True, self.yam... |
'remove path from a dict'
| def delete(self, path):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
return (False, self.yaml_dict)
result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
if (not result):
return (False, self.yaml_dict)
re... |
'check if value exists at path'
| def exists(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, list):
if (value in entry):
return True
return False
elif isinstance(entry, dict):
if isinstance(value, dict):
rval = Fals... |
'append value to a list'
| def append(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry is None):
self.put(path, [])
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
if (not isinstance(entry, list)):
return (False, self.yaml_dict)
... |
'put path, value into a dict'
| def update(self, path, value, index=None, curr_value=None):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
if (not isinstance(value, dict)):
raise YeditException(('Cannot replace key, value entry in dict with non-dict type. ... |
'put path, value into a dict'
| def put(self, path, value):
| try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if (entry == value):
return (False, self.yaml_dict)
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader)
except ... |
'create a yaml file'
| def create(self, path, value):
| if (not self.file_exists()):
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
try:
tmp_copy.fa.set_block_style()
except A... |
'return the current value'
| @staticmethod
def get_curr_value(invalue, val_type):
| if (invalue is None):
return None
curr_value = invalue
if (val_type == 'yaml'):
curr_value = yaml.load(invalue)
elif (val_type == 'json'):
curr_value = json.loads(invalue)
return curr_value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.