blob: a50aaa84c2901c211dc88a81abed31fabddc0802 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williams92b42cb2022-09-03 06:53:57 -05002# Copyright OpenEmbedded Contributors
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: MIT
5#
6
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007import os
8import re
Patrick Williamsf1e5d692016-03-30 15:21:19 -05009import errno
Patrick Williamsc124f4f2015-09-15 14:41:29 -050010
11def write_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050012 # In case data is None, return immediately
13 if data is None:
14 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015 wdata = data.rstrip() + "\n"
16 with open(path, "w") as f:
17 f.write(wdata)
18
19def append_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050020 # In case data is None, return immediately
21 if data is None:
22 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050023 wdata = data.rstrip() + "\n"
24 with open(path, "a") as f:
25 f.write(wdata)
26
27def read_file(path):
28 data = None
29 with open(path) as f:
30 data = f.read()
31 return data
32
33def remove_from_file(path, data):
Patrick Williamsf1e5d692016-03-30 15:21:19 -050034 # 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 Williamsd8c66bc2016-06-20 12:57:21 -050045
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))