tools.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import os
  2. import errno
  3. import sys
  4. import argparse
  5. sha1cache_version = "3"
  6. class PathType(object):
  7. def __init__(self, type='file', exists=True, dash_ok=True):
  8. assert exists in (True, False, None)
  9. assert type in ('file','dir','symlink',None) or hasattr(type,'__call__')
  10. self._exists = exists
  11. self._type = type
  12. self._dash_ok = dash_ok
  13. pass
  14. def __call__(self, string):
  15. if string=='-':
  16. if self._type == 'dir':
  17. raise argparse.ArgumentTypeError('standard input/output (-) not allowed as directory path')
  18. elif not self._dash_ok:
  19. raise argparse.ArgumentTypeError('standard input/output (-) not allowed')
  20. else:
  21. e = os.path.exists(string)
  22. if self._exists is True:
  23. if not e:
  24. raise argparse.ArgumentTypeError("path does not exist: '%s'" % string)
  25. if self._type is None:
  26. pass
  27. elif self._type=='file':
  28. if not os.path.isfile(string):
  29. raise argparse.ArgumentTypeError("path is not a file: '%s'" % string)
  30. return os.path.abspath(string)
  31. elif self._type=='dir':
  32. if not os.path.isdir(string):
  33. raise argparse.ArgumentTypeError("path is not a directory: '%s'" % string)
  34. return os.path.abspath(string)
  35. elif not self._type(string):
  36. raise argparse.ArgumentTypeError("path not valid: '%s'" % string)
  37. else:
  38. if self._exists is False and e:
  39. raise argparse.ArgumentTypeError("path exists: '%s'" % string)
  40. return os.path.abspath(string)
  41. pass
  42. pass
  43. return string
  44. pass
  45. pass
  46. class BoolType(object):
  47. def __call__(self, string):
  48. if string in ['0', 'false', 'False']:
  49. return False
  50. pass
  51. elif string in ['1', 'true', 'True']:
  52. return True
  53. pass
  54. pass
  55. pass
  56. class IntegerType(object):
  57. def __call__(self, string):
  58. return int(string)
  59. pass
  60. pass
  61. class FloatType(object):
  62. def __call__(self, string):
  63. return float(string)
  64. pass
  65. pass
  66. class Tools(object):
  67. def __init__(self):
  68. self.parser = argparse.ArgumentParser()
  69. self.add_argument('--tools_path', 'tools_path', type=PathType(type='dir'))
  70. temp_dir = self.get_temp_dir()
  71. self.make_dir(temp_dir)
  72. self._initialize()
  73. pass
  74. def _initialize(self):
  75. pass
  76. def add_argument(self, argument, help, **kwds):
  77. self.parser.add_argument(argument, help = help, **kwds)
  78. pass
  79. def add_argument_bool(self, argument, help):
  80. self.parser.add_argument(argument, help = help, type=BoolType())
  81. pass
  82. def add_argument_integer(self, argument, help):
  83. self.parser.add_argument(argument, help = help, type=IntegerType())
  84. pass
  85. def add_argument_float(self, argument, help):
  86. self.parser.add_argument(argument, help = help, type=FloatType())
  87. pass
  88. def add_argument_file(self, argument, help, **kwds):
  89. self.parser.add_argument(argument, help = help, type=PathType(type='file', **kwds))
  90. pass
  91. def add_argument_dir(self, argument, help, **kwds):
  92. self.parser.add_argument(argument, help = help, type=PathType(type='dir', **kwds))
  93. pass
  94. def add_arguments(self, argument, help, **kwds):
  95. self.parser.add_argument(argument, nargs = '*', help = help)
  96. pass
  97. def command_call(self, msg, process, args):
  98. import shlex
  99. import subprocess
  100. process_path = os.path.abspath(process)
  101. if sys.version_info > (3,0):
  102. proc = subprocess.Popen([process_path] + args, shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  103. else:
  104. proc = subprocess.Popen([process_path] + args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  105. pass
  106. out, err = proc.communicate()
  107. exitcode = proc.returncode
  108. if exitcode != 0:
  109. if sys.version_info > (3, 0):
  110. err = err.encode("utf-8")
  111. pass
  112. self.error_result("{0} code error {1}:\n{2}\n{3}".format(msg, exitcode, out, err))
  113. return False
  114. pass
  115. return True
  116. pass
  117. def error_result(self, msg):
  118. print("# {0}".format(msg))
  119. pass
  120. def successful_result(self):
  121. print("@@@\n")
  122. pass
  123. def get_reg_value(self, KeyPath, ValueName, Error):
  124. if sys.version_info > (3, 0):
  125. import winreg as winreg
  126. pass
  127. else:
  128. import _winreg as winreg
  129. pass
  130. try:
  131. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, KeyPath, 0, winreg.KEY_QUERY_VALUE) as k:
  132. Value = winreg.QueryValueEx(k, ValueName)
  133. return str(Value[0])
  134. pass
  135. except Exception as ex:
  136. Error.append(type(ex))
  137. Error.append(str(ex))
  138. pass
  139. return None
  140. pass
  141. def make_dir(self, dirname):
  142. if not os.path.exists(dirname):
  143. try:
  144. os.makedirs(dirname)
  145. pass
  146. except OSError as exc: # Guard against race condition
  147. if exc.errno != errno.EEXIST:
  148. raise
  149. pass
  150. pass
  151. pass
  152. pass
  153. def make_dir_for_file(self, filepath):
  154. result_dirname = os.path.dirname(filepath)
  155. self.make_dir(result_dirname)
  156. pass
  157. def exist_file(self, filepath):
  158. if filepath is None:
  159. return False
  160. pass
  161. return os.path.isfile(filepath)
  162. pass
  163. def get_file_sha1(self, filepath):
  164. import hashlib
  165. f = open(filepath, "rb")
  166. sha1 = hashlib.sha1()
  167. while True:
  168. data = f.read(65536)
  169. if not data:
  170. break
  171. pass
  172. sha1.update(data)
  173. pass
  174. sha1hex = sha1.hexdigest()
  175. return sha1hex
  176. pass
  177. def get_text_sha1(self, text):
  178. import hashlib
  179. sha1 = hashlib.sha1(bytes(text, 'utf-8'))
  180. sha1hex = sha1.hexdigest()
  181. return sha1hex
  182. pass
  183. def get_file_sha1_new_path(self, filepath, ext):
  184. sha1hex = self.get_file_sha1(filepath)
  185. sha1path = sha1hex[:2] + "/" + sha1hex[2:] + ext
  186. return sha1hex, sha1path
  187. pass
  188. def run(self):
  189. try:
  190. self._pre_run()
  191. except Exception as e:
  192. print("pre run except: {0}".format(e))
  193. pass
  194. try:
  195. if self._run(self.args) is True:
  196. self.successful_result()
  197. pass
  198. except Exception as e:
  199. print("run except: {0}".format(e))
  200. pass
  201. try:
  202. self._post_run(self.args)
  203. except Exception as e:
  204. print("post run except: {0}".format(e))
  205. pass
  206. pass
  207. def _pre_run(self):
  208. self.args = self.parser.parse_args()
  209. pass
  210. def _run(self, args):
  211. return True
  212. pass
  213. def _post_run(self, args):
  214. pass
  215. def get_temp_dir(self):
  216. import tempfile
  217. temp_dir = tempfile.gettempdir()
  218. return os.path.join(temp_dir, ".libmovie")
  219. pass
  220. def get_temp_path(self, filename):
  221. temp_dir = self.get_temp_dir()
  222. return os.path.join(temp_dir, filename)
  223. pass
  224. def get_sha1_cach_path(self, tag, filename):
  225. temp_dir = self.get_temp_dir()
  226. tag_sha1 = self.get_text_sha1(tag)
  227. path = os.path.join(temp_dir, '.sha1cache{0}'.format(sha1cache_version), tag_sha1, filename[:2], filename[2:])
  228. self.make_dir_for_file(path)
  229. return path
  230. pass
  231. def get_tools_path(self, filename):
  232. return os.path.join(self.args.tools_path, "tools", filename)
  233. pass
  234. def get_ext(self, filepath):
  235. return os.path.splitext(filepath)[1]
  236. pass
  237. def change_ext(self, filepath, newext):
  238. return os.path.splitext(filepath)[0] + '.' + newext
  239. pass
  240. def get_prefix_sha1path(self, sha1path):
  241. return os.path.split(sha1path)[0]
  242. pass
  243. def copy_file(self, src, dst):
  244. from shutil import copyfile
  245. copyfile(src, dst)
  246. pass
  247. pass
  248. def run(tools):
  249. t = tools()
  250. t.run()
  251. pass