blob: 3093419cc70ab0dcd4c9f612825b105ee5f1e3b9 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
2# SPDX-License-Identifier: MIT
3#
4
Patrick Williamsc124f4f2015-09-15 14:41:29 -05005import os
6import re
Patrick Williamsf1e5d692016-03-30 15:21:19 -05007import errno
Patrick Williamsc124f4f2015-09-15 14:41:29 -05008
9def write_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050010 # In case data is None, return immediately
11 if data is None:
12 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050013 wdata = data.rstrip() + "\n"
14 with open(path, "w") as f:
15 f.write(wdata)
16
17def append_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050018 # In case data is None, return immediately
19 if data is None:
20 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050021 wdata = data.rstrip() + "\n"
22 with open(path, "a") as f:
23 f.write(wdata)
24
25def read_file(path):
26 data = None
27 with open(path) as f:
28 data = f.read()
29 return data
30
31def remove_from_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050032 # 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 Williamsd8c66bc2016-06-20 12:57:21 -050043
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))