[OE-core] [PATCH v4 2/4] devtool: function to replace strings inside a text file
leonardo.sandoval.gonzalez at linux.intel.com
leonardo.sandoval.gonzalez at linux.intel.com
Thu Jun 29 16:40:50 UTC 2017
From: Leonardo Sandoval <leonardo.sandoval.gonzalez at linux.intel.com>
Signed-off-by: Leonardo Sandoval <leonardo.sandoval.gonzalez at linux.intel.com>
---
scripts/lib/devtool/__init__.py | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
diff --git a/scripts/lib/devtool/__init__.py b/scripts/lib/devtool/__init__.py
index 29c4c05071..7f4f817a8e 100644
--- a/scripts/lib/devtool/__init__.py
+++ b/scripts/lib/devtool/__init__.py
@@ -292,3 +292,40 @@ def ensure_npm(config, basepath, fixed_setup=False, check_exists=True):
raise DevtoolError(msg)
else:
raise
+
+def replace_from_file(path, old, new):
+ """Replace strings on a file"""
+
+ def read_file(path):
+ data = None
+ with open(path) as f:
+ data = f.read()
+ return data
+
+ def write_file(path, data):
+ if data is None:
+ return
+ wdata = data.rstrip() + "\n"
+ with open(path, "w") as f:
+ f.write(wdata)
+
+ # In case old is None, return immediately
+ if old is None:
+ return
+ try:
+ rdata = read_file(path)
+ except IOError as e:
+ # if file does not exit, just quit, otherwise raise an exception
+ if e.errno == errno.ENOENT:
+ return
+ else:
+ raise
+
+ old_contents = rdata.splitlines()
+ new_contents = []
+ for old_content in old_contents:
+ try:
+ new_contents.append(old_content.replace(old, new))
+ except ValueError:
+ pass
+ write_file(path, "\n".join(new_contents))
--
2.12.0
More information about the Openembedded-core
mailing list