From d558400e532a312ab5d94da481184884c3f4d4b6 Mon Sep 17 00:00:00 2001 From: kshithijiyer Date: Tue, 7 May 2019 18:45:18 +0530 Subject: Adding find_and_replace_in_file & check_if_pattern_in_file to library. The function do the following in a nutshell: 1. find_and_replace_in_file: Find and replace a given pattern in a specific file. 2. check_if_pattern_in_file: Check if a give pattern is in seen in file or not. Change-Id: Ib035f54490592f2be32a30f0e8a10e7847812990 Signed-off-by: kshithijiyer --- .../glustolibs/gluster/glusterfile.py | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'glustolibs-gluster/glustolibs') diff --git a/glustolibs-gluster/glustolibs/gluster/glusterfile.py b/glustolibs-gluster/glustolibs/gluster/glusterfile.py index 2f1c45e7b..413a4f9a7 100755 --- a/glustolibs-gluster/glustolibs/gluster/glusterfile.py +++ b/glustolibs-gluster/glustolibs/gluster/glusterfile.py @@ -417,6 +417,52 @@ def get_dht_linkto_xattr(host, fqpath): return linkto_xattr +def find_and_replace_in_file(host, fpattern, rpattern, fqpath): + """Find and replace all occurances of a given pattern in a specific file. + + Args: + host (str): The hostname/ip of the remote system. + fpattern(str): Pattern to be found in file. + rpattern(str): Pattern to used as replacement in file. + fqpath (str): The fully-qualified path to the file. + + Returns: + True: If find and replace is successful. + False: If find and replace is failed. + Note: + / can't be given as an input in patterns(fpattern/rpattern). + Please follow proper regex format for patterns. + """ + cmd = (" sed -i 's/%s/%s/g' %s" % (fpattern, rpattern, fqpath)) + ret, _, _ = g.run(host, cmd) + + if ret != 0: + return False + return True + + +def check_if_pattern_in_file(host, pattern, fqpath): + """Check if a give pattern is in seen in file or not. + + Args: + host (str): The hostname/ip of the remote system. + pattern(str): Pattern to be found in file. + fqpath (str): The fully-qualified path to the file. + + Returns: + 0: If pattern present in file. + 1: If pattern not present in file. + -1: If command was not executed. + """ + cmd = ("cat %s | grep '%s'" % (fqpath, pattern)) + ret, out, _ = g.run(host, cmd) + if ret: + return -1 + if not out: + return 1 + return 0 + + class GlusterFile(object): """Class to handle files specific to Gluster (client and backend)""" def __init__(self, host, fqpath): -- cgit