yedit.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # pylint: skip-file
  2. class YeditException(Exception):
  3. ''' Exception class for Yedit '''
  4. pass
  5. class Yedit(object):
  6. ''' Class to modify yaml files '''
  7. def __init__(self, filename=None, content=None):
  8. self.content = content
  9. self.filename = filename
  10. self.__yaml_dict = content
  11. if self.filename and not self.content:
  12. self.get()
  13. elif self.filename and self.content:
  14. self.write()
  15. @property
  16. def yaml_dict(self):
  17. ''' getter method for yaml_dict '''
  18. return self.__yaml_dict
  19. @yaml_dict.setter
  20. def yaml_dict(self, value):
  21. ''' setter method for yaml_dict '''
  22. self.__yaml_dict = value
  23. @staticmethod
  24. def remove_entry(data, keys):
  25. ''' remove an item from a dictionary with key notation a.b.c
  26. d = {'a': {'b': 'c'}}}
  27. keys = a.b
  28. item = c
  29. '''
  30. if "." in keys:
  31. key, rest = keys.split(".", 1)
  32. if key in data.keys():
  33. Yedit.remove_entry(data[key], rest)
  34. else:
  35. del data[keys]
  36. @staticmethod
  37. def add_entry(data, keys, item):
  38. ''' Add an item to a dictionary with key notation a.b.c
  39. d = {'a': {'b': 'c'}}}
  40. keys = a.b
  41. item = c
  42. '''
  43. if "." in keys:
  44. key, rest = keys.split(".", 1)
  45. if key not in data:
  46. data[key] = {}
  47. if not isinstance(data, dict):
  48. raise YeditException('Invalid add_entry called on a [%s] of type [%s].' % (data, type(data)))
  49. else:
  50. Yedit.add_entry(data[key], rest, item)
  51. else:
  52. data[keys] = item
  53. @staticmethod
  54. def get_entry(data, keys):
  55. ''' Get an item from a dictionary with key notation a.b.c
  56. d = {'a': {'b': 'c'}}}
  57. keys = a.b
  58. return c
  59. '''
  60. if keys and "." in keys:
  61. key, rest = keys.split(".", 1)
  62. if not isinstance(data[key], dict):
  63. raise YeditException('Invalid get_entry called on a [%s] of type [%s].' % (data, type(data)))
  64. else:
  65. return Yedit.get_entry(data[key], rest)
  66. else:
  67. return data.get(keys, None)
  68. def write(self):
  69. ''' write to file '''
  70. if not self.filename:
  71. raise YeditException('Please specify a filename.')
  72. with open(self.filename, 'w') as yfd:
  73. yfd.write(yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  74. def read(self):
  75. ''' write to file '''
  76. # check if it exists
  77. if not self.exists():
  78. return None
  79. contents = None
  80. with open(self.filename) as yfd:
  81. contents = yfd.read()
  82. return contents
  83. def exists(self):
  84. ''' return whether file exists '''
  85. if os.path.exists(self.filename):
  86. return True
  87. return False
  88. def get(self):
  89. ''' return yaml file '''
  90. contents = self.read()
  91. if not contents:
  92. return None
  93. # check if it is yaml
  94. try:
  95. self.yaml_dict = yaml.load(contents)
  96. except yaml.YAMLError as _:
  97. # Error loading yaml
  98. return None
  99. return self.yaml_dict
  100. def delete(self, key):
  101. ''' put key, value into a yaml file '''
  102. try:
  103. entry = Yedit.get_entry(self.yaml_dict, key)
  104. except KeyError as _:
  105. entry = None
  106. if not entry:
  107. return (False, self.yaml_dict)
  108. Yedit.remove_entry(self.yaml_dict, key)
  109. self.write()
  110. return (True, self.get())
  111. def put(self, key, value):
  112. ''' put key, value into a yaml file '''
  113. try:
  114. entry = Yedit.get_entry(self.yaml_dict, key)
  115. except KeyError as _:
  116. entry = None
  117. if entry == value:
  118. return (False, self.yaml_dict)
  119. Yedit.add_entry(self.yaml_dict, key, value)
  120. self.write()
  121. return (True, self.get())
  122. def create(self, key, value):
  123. ''' create the file '''
  124. if not self.exists():
  125. self.yaml_dict = {key: value}
  126. self.write()
  127. return (True, self.get())
  128. return (False, self.get())