forked from ssannandeji/Zenject-2019
-
Notifications
You must be signed in to change notification settings - Fork 262
/
SystemHelper.py
327 lines (235 loc) · 10.3 KB
/
SystemHelper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
from mtm.log.Logger import Logger
from mtm.util.VarManager import VarManager
from mtm.util.ProcessRunner import ProcessRunner
from mtm.util.ProcessRunner import ResultType
import fnmatch
from mtm.util.Assert import *
import mtm.ioc.Container as Container
from mtm.ioc.Inject import Inject
from mtm.ioc.Inject import InjectOptional
import time
import os
import shlex
import subprocess
import shutil
import platform
from glob import glob
class ProcessErrorCodeException(Exception):
pass
class ProcessTimeoutException(Exception):
pass
class SystemHelper:
'''Responsibilities:
- Miscellaneous file-handling/path-related operations
- Wrapper to execute arbitrary commands
'''
_varManager = Inject('VarManager')
_log = Inject('Logger')
_processRunner = Inject('ProcessRunner')
# Use an hour timeout
def __init__(self, timeout = 60 * 60):
self._timeout = timeout
def canonicalizePath(self, pathStr):
# Make one standard representation of the given path
# This will remove ..\ and also change to always use back slashes since this is what os.path.join etc. uses
return self._varManager.expandPath(pathStr)
def executeAndWait(self, commandStr, startDir = None):
expandedStr = self._varManager.expand(commandStr)
self._log.debug("Executing '%s'" % expandedStr)
vals = self._splitCommandStr(expandedStr)
if startDir != None:
startDir = self._varManager.expand(startDir)
result = self._processRunner.waitForProcessOrTimeout(vals, self._timeout, startDir)
if result == ResultType.Error:
raise ProcessErrorCodeException('Command returned with error code while executing: %s' % expandedStr)
if result == ResultType.TimedOut:
raise ProcessTimeoutException('Timed out while waiting for command: %s' % expandedStr)
assertThat(result == ResultType.Success)
def executeNoWait(self, commandStr, startDir = None):
expandedStr = self._varManager.expand(commandStr)
self._log.debug("Executing '{0}'".format(expandedStr))
vals = self._splitCommandStr(expandedStr)
if startDir != None:
startDir = self._varManager.expand(startDir)
self._processRunner.execNoWait(vals, startDir)
# This is only used to execute shell-specific commands like copy, mklink, etc.
def executeShellCommand(self, commandStr, startDir = None):
expandedStr = self._varManager.expand(commandStr)
self._log.debug("Executing '%s'" % expandedStr)
if startDir != None:
startDir = self._varManager.expand(startDir)
result = self._processRunner.execShellCommand(expandedStr, startDir)
if result == ResultType.Error:
raise ProcessErrorCodeException('Command returned with error code while executing: %s' % expandedStr)
assertThat(result == ResultType.Success, "Expected success result but found '{0}'".format(result))
def _splitCommandStr(self, commandStr):
# Hacky but necessary since shlex.split will otherwise remove our backslashes
if platform.platform().startswith('Windows'):
commandStr = commandStr.replace(os.sep, os.sep + os.sep)
# Convert command to argument list to avoid issues with escape characters, etc.
# Based on an answer here: http://stackoverflow.com/questions/12081970/python-using-quotes-in-the-subprocess-popen
return shlex.split(commandStr)
def executeAndReturnOutput(self, commandStr):
self._log.debug("Executing '%s'" % commandStr)
return subprocess.getoutput(self._splitCommandStr(commandStr)).strip()
def walkDir(self, dirPath):
dirPath = self._varManager.expand(dirPath)
return os.listdir(dirPath)
def getParentDirectoriesWithSelf(self, path):
yield path
for parentDir in self.getParentDirectories(path):
yield parentDir
def getParentDirectories(self, path):
path = self._varManager.expand(path)
lastParentDir = None
parentDir = os.path.dirname(path)
while parentDir and parentDir != lastParentDir:
yield parentDir
lastParentDir = parentDir
parentDir = os.path.dirname(parentDir)
def createDirectory(self, dirPath):
dirPath = self._varManager.expand(dirPath)
assertThat(not self.directoryExists(dirPath), 'Tried to create a directory that already exists')
os.makedirs(dirPath)
def makeMissingDirectoriesInPath(self, dirPath):
dirPath = self._varManager.expand(dirPath)
try:
os.makedirs(os.path.dirname(dirPath))
except:
pass
def copyFile(self, fromPath, toPath):
toPath = self._varManager.expand(toPath)
fromPath = self._varManager.expand(fromPath)
self.makeMissingDirectoriesInPath(toPath)
shutil.copy2(fromPath, toPath)
def move(self, fromPath, toPath):
toPath = self._varManager.expand(toPath)
fromPath = self._varManager.expand(fromPath)
self.makeMissingDirectoriesInPath(toPath)
shutil.move(fromPath, toPath)
def IsDir(self, path):
return os.path.isdir(self._varManager.expand(path))
def clearDirectoryContents(self, dirPath):
dirPath = self._varManager.expand(dirPath)
if not os.path.exists(dirPath):
return
for fileName in os.listdir(dirPath):
filePath = os.path.join(dirPath, fileName)
if os.path.isfile(filePath):
os.unlink(filePath)
elif os.path.isdir(filePath):
shutil.rmtree(filePath)
def deleteDirectoryWaitIfNecessary(self, dirPath):
dirPath = self._varManager.expand(dirPath)
if not os.path.isdir(dirPath):
# Already removed
return
attemptsLeft = 10
while True:
try:
shutil.rmtree(dirPath)
except Exception as e:
self._log.warn('Could not delete directory at "{0}". Waiting to try again...'.format(dirPath))
time.sleep(5)
attemptsLeft -= 1
if attemptsLeft < 0:
raise e
continue
break
def deleteDirectory(self, dirPath):
dirPath = self._varManager.expand(dirPath)
os.system('rmdir /S /Q "{0}"'.format(dirPath))
def deleteDirectoryIfExists(self, dirPath):
dirPath = self._varManager.expand(dirPath)
if os.path.exists(dirPath):
shutil.rmtree(dirPath)
return True
return False
def deleteEmptyDirectoriesUnder(self, dirPath):
dirPath = self._varManager.expandPath(dirPath)
if not os.path.isdir(dirPath):
return 0
# Can't process long paths on windows
if len(dirPath) >= 256:
return 0
files = os.listdir(dirPath)
numDirsDeleted = 0
for fileName in files:
fullpath = os.path.join(dirPath, fileName)
if os.path.isdir(fullpath):
numDirsDeleted += self.deleteEmptyDirectoriesUnder(fullpath)
files = os.listdir(dirPath)
if len(files) == 0:
self._log.debug("Removing empty folder '%s'" % dirPath)
os.rmdir(dirPath)
numDirsDeleted += 1
metaFilePath = dirPath + '/../' + os.path.basename(dirPath) + '.meta'
if os.path.isfile(metaFilePath):
self._log.debug("Removing meta file '%s'" % metaFilePath)
os.remove(metaFilePath)
return numDirsDeleted
def fileExists(self, path):
return os.path.isfile(self._varManager.expand(path))
def directoryExists(self, dirPath):
return os.path.exists(self._varManager.expand(dirPath))
def copyDirectory(self, fromPath, toPath):
fromPath = self._varManager.expand(fromPath)
toPath = self._varManager.expand(toPath)
self._log.debug("Copying directory '{0}' to '{1}'".format(fromPath, toPath))
shutil.copytree(fromPath, toPath)
def readFileAsText(self, path):
with self.openInputFile(path) as f:
return f.read()
def writeFileAsText(self, path, text):
with self.openOutputFile(path) as f:
f.write(text)
def openOutputFile(self, path):
path = self._varManager.expand(path)
self.makeMissingDirectoriesInPath(path)
return open(path, 'w', encoding='utf-8', errors='ignore')
def openInputFile(self, path):
return open(self._varManager.expand(path), 'r', encoding='utf-8', errors='ignore')
def removeFile(self, fileName):
os.remove(self._varManager.expand(fileName))
def removeFileIfExists(self, fileName):
fullPath = self._varManager.expand(fileName)
if os.path.isfile(fullPath):
os.remove(fullPath)
return True
return False
def findFilesByPattern(self, startDir, pattern):
startDir = self._varManager.expand(startDir)
for root, dirs, files in os.walk(startDir):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
def renameFile(self, currentName, newName):
os.rename(self._varManager.expand(currentName), self._varManager.expand(newName))
def removeFileWaitIfNecessary(self, fileName):
outputPath = self._varManager.expand(fileName)
if not os.path.isfile(outputPath):
# File already removed
return
while True:
try:
os.remove(outputPath)
except OSError:
self._log.warn('Could not delete file at "{0}". Waiting to try again...'.format(outputPath))
time.sleep(5)
continue
break
def removeByRegex(self, regex):
regex = self._varManager.expand(regex)
count = 0
for filePath in glob(regex):
os.unlink(filePath)
count += 1
self._log.debug("Removed %s files matching '%s'" % (count, regex))
def makeMissingDirectoriesInPath(self, dirPath):
dirPath = self._varManager.expand(dirPath)
self._log.debug("Making missing directories in path '{0}'".format(dirPath))
try:
os.makedirs(os.path.dirname(dirPath))
except:
pass