File editors
| 21 | |
| 22 | |
| 23 | class CsFile: |
| 24 | """ File editors """ |
| 25 | |
| 26 | def __init__(self, filename): |
| 27 | self.filename = filename |
| 28 | self.load() |
| 29 | |
| 30 | def load(self): |
| 31 | self.new_config = [] |
| 32 | self.config = [] |
| 33 | try: |
| 34 | for line in open(self.filename): |
| 35 | self.new_config.append(line) |
| 36 | except IOError: |
| 37 | logging.debug("File %s does not exist" % self.filename) |
| 38 | else: |
| 39 | logging.debug("Reading file %s" % self.filename) |
| 40 | self.config = list(self.new_config) |
| 41 | |
| 42 | def is_changed(self): |
| 43 | if set(self.config) != set(self.new_config): |
| 44 | return True |
| 45 | else: |
| 46 | return False |
| 47 | |
| 48 | def __len__(self): |
| 49 | return len(self.config) |
| 50 | |
| 51 | def empty(self): |
| 52 | self.config = [] |
| 53 | self.new_config = [] |
| 54 | |
| 55 | def repopulate(self): |
| 56 | self.new_config = [] |
| 57 | |
| 58 | def commit(self): |
| 59 | if not self.is_changed(): |
| 60 | logging.info("Nothing to commit. The %s file did not change" % self.filename) |
| 61 | return False |
| 62 | handle = open(self.filename, "w+") |
| 63 | for line in self.new_config: |
| 64 | handle.write(line) |
| 65 | handle.close() |
| 66 | logging.info("Wrote edited file %s" % self.filename) |
| 67 | self.config = list(self.new_config) |
| 68 | logging.info("Updated file in-cache configuration") |
| 69 | return True |
| 70 | |
| 71 | def dump(self): |
| 72 | for line in self.new_config: |
| 73 | print(line) |
| 74 | |
| 75 | def addeq(self, string): |
| 76 | """ Update a line in a file of the form token=something |
| 77 | match on token= and replace something if needed |
| 78 | Add line if token is not present |
| 79 | """ |
| 80 | token = string.split('=')[0] + '=' |
no outgoing calls