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