Brad Bishop | c342db3 | 2019-05-15 21:57:59 -0400 | [diff] [blame] | 1 | # |
| 2 | # SPDX-License-Identifier: MIT |
| 3 | # |
| 4 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 5 | import os |
| 6 | import re |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 7 | import errno |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 8 | |
| 9 | def write_file(path, data): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 10 | # In case data is None, return immediately |
| 11 | if data is None: |
| 12 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 13 | wdata = data.rstrip() + "\n" |
| 14 | with open(path, "w") as f: |
| 15 | f.write(wdata) |
| 16 | |
| 17 | def append_file(path, data): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 18 | # In case data is None, return immediately |
| 19 | if data is None: |
| 20 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 21 | wdata = data.rstrip() + "\n" |
| 22 | with open(path, "a") as f: |
| 23 | f.write(wdata) |
| 24 | |
| 25 | def read_file(path): |
| 26 | data = None |
| 27 | with open(path) as f: |
| 28 | data = f.read() |
| 29 | return data |
| 30 | |
| 31 | def remove_from_file(path, data): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 32 | # In case data is None, return immediately |
| 33 | if data is None: |
| 34 | return |
| 35 | try: |
| 36 | rdata = read_file(path) |
| 37 | except IOError as e: |
| 38 | # if file does not exit, just quit, otherwise raise an exception |
| 39 | if e.errno == errno.ENOENT: |
| 40 | return |
| 41 | else: |
| 42 | raise |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 43 | |
| 44 | contents = rdata.strip().splitlines() |
| 45 | for r in data.strip().splitlines(): |
| 46 | try: |
| 47 | contents.remove(r) |
| 48 | except ValueError: |
| 49 | pass |
| 50 | write_file(path, "\n".join(contents)) |