2 from lutf_basetest import BaseTest
3 from lutf_paramiko import *
4 from clutf_global import *
5 from clutf_agent import *
7 from lutf_exception import LUTFError
8 import os, random, tempfile, shutil, pathlib
10 class LutfDir(BaseTest):
11 def __init__(self, dname, script=os.path.abspath(__file__),
14 super().__init__(script, target, self.dname)
17 return os.listdir(self.dname)
19 class LutfFile(BaseTest):
20 def __init__(self, fname, script=os.path.abspath(__file__),
21 full_path=False, target=None):
23 self.fname = os.path.join(os.getcwd(), fname)
26 super().__init__(script, target, self.fname, full_path=full_path)
27 self.file_handle = None
30 self.file_handle = open(self.fname, mode)
32 def write(self, data):
33 if not self.file_handle or self.file_handle.closed:
34 raise LUTFError("%s not opened" % self.fname)
35 self.file_handle.write(data)
37 def get_full_path(self):
41 lines = self.file_handle.readlines()
45 data = self.file_handle.read()
50 return self.file_handle.closed
54 if self.file_handle and not self.file_handle.closed:
55 self.file_handle.close()
58 if self.file_handle and not self.file_handle.closed:
59 self.file_handle.close()
64 self.file_handle = None
66 def find_replace_file(self, fname, search, replace, getline=False):
69 if not self.isclosed():
70 raise LUTFError("Can not perform operation on file. Close it first")
72 # if no replace is provided then just count the instances of the
75 with open(fname) as old_file:
82 except UnicodeDecodeError:
85 return count, found_line
88 fh, abs_path = tempfile.mkstemp()
89 with os.fdopen(fh,'w') as new_file:
90 with open(fname) as old_file:
96 new_file.write(replace)
100 except UnicodeDecodeError:
103 #Copy the file permissions from the old file to the new file
104 shutil.copymode(fname, abs_path)
105 #Remove original file
108 shutil.move(abs_path, fname)
113 return count, found_line
116 def find_replace_global(self, directory, search, replace, getline=False):
119 for filename in os.listdir(directory):
120 fpath = os.path.join(directory, filename)
122 c, line = self.find_replace_file(fpath, search, replace, getline)
127 count += self.find_replace_file(fpath, search, replace, getline)
132 def find_replace(self, search, replace):
134 if os.path.isdir(self.fname):
135 count = self.find_replace_global(self.fname, search, replace)
136 elif os.path.isfile(self.fname):
137 count = self.find_replace_file(self.fname, search, replace)
140 def find(self, search):
142 if os.path.isdir(self.fname):
143 count = self.find_replace_global(self.fname, search, None)
144 elif os.path.isfile(self.fname):
145 count = self.find_replace_file(self.fname, search, None)
148 def get(self, search):
150 if os.path.isdir(self.fname):
151 count, line = self.find_replace_global(self.fname, search, None, getline=True)
152 elif os.path.isfile(self.fname):
153 count, line = self.find_replace_file(self.fname, search, None, getline=True)