shell_helpers.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. #!/usr/bin/env python3
  2. import base64
  3. import distutils.file_util
  4. import itertools
  5. import os
  6. import shlex
  7. import shutil
  8. import signal
  9. import stat
  10. import subprocess
  11. import sys
  12. import threading
  13. from typing import List, Union
  14. import urllib.request
  15. class LF:
  16. '''
  17. LineFeed (AKA newline).
  18. Singleton class. Can be used in print_cmd to print out nicer command lines
  19. with --key on the same line as "--key value".
  20. '''
  21. pass
  22. class ShellHelpers:
  23. '''
  24. Helpers to do things which are easy from the shell,
  25. usually filesystem, process or pipe operations.
  26. Attempt to print shell equivalents of all commands to make things
  27. easy to debug and understand what is going on.
  28. '''
  29. _print_lock = threading.Lock()
  30. def __init__(self, dry_run=False, quiet=False):
  31. '''
  32. :param dry_run: don't run the commands, just potentially print them. Debug aid.
  33. :type dry_run: Bool
  34. :param quiet: don't print the commands
  35. :type dry_run: Bool
  36. '''
  37. self.dry_run = dry_run
  38. self.quiet = quiet
  39. @classmethod
  40. def _print_thread_safe(cls, string):
  41. '''
  42. Python sucks: a naive print adds a bunch of random spaces to stdout,
  43. and then copy pasting the command fails.
  44. https://stackoverflow.com/questions/3029816/how-do-i-get-a-thread-safe-print-in-python-2-6
  45. The initial use case was test-gdb which must create a thread for GDB to run the program in parallel.
  46. '''
  47. with cls._print_lock:
  48. sys.stdout.write(string + '\n')
  49. sys.stdout.flush()
  50. def add_newlines(self, cmd):
  51. out = []
  52. for arg in cmd:
  53. out.extend([arg, LF])
  54. return out
  55. def base64_encode(self, string):
  56. '''
  57. TODO deal with redirection and print nicely.
  58. '''
  59. return base64.b64encode(string.encode()).decode()
  60. def base64_decode(self, string):
  61. return base64.b64decode(string.encode()).decode()
  62. def chmod(self, path, add_rm_abs='+', mode_delta=stat.S_IXUSR):
  63. '''
  64. TODO extend further, shell print equivalent.
  65. '''
  66. old_mode = os.stat(path).st_mode
  67. if add_rm_abs == '+':
  68. new_mode = old_mode | mode_delta
  69. elif add_rm_abs == '':
  70. new_mode = mode_delta
  71. elif add_rm_abs == '-':
  72. new_mode = old_mode & ~mode_delta
  73. os.chmod(path, new_mode)
  74. @staticmethod
  75. def cmd_to_string(
  76. cmd: List[Union[str, LF]],
  77. cwd=None,
  78. extra_env=None,
  79. extra_paths=None,
  80. force_oneline: bool =False,
  81. ):
  82. '''
  83. Format a command given as a list of strings so that it can
  84. be viewed nicely and executed by bash directly and print it to stdout.
  85. If cmd contains:
  86. * no LF, then newlines are added after every word
  87. * exactly one LF at the end, then no newlines are added
  88. * otherwise: newlines are added exactly at each LF
  89. '''
  90. last_newline = ' \\\n'
  91. newline_separator = last_newline + ' '
  92. out = []
  93. if extra_env is None:
  94. extra_env = {}
  95. if cwd is not None:
  96. out.append('cd {} &&'.format(shlex.quote(cwd)))
  97. if extra_paths is not None:
  98. out.append('PATH="{}:${{PATH}}"'.format(':'.join(extra_paths)))
  99. for key in extra_env:
  100. out.append('{}={}'.format(shlex.quote(key), shlex.quote(extra_env[key])))
  101. cmd_quote = []
  102. newline_count = 0
  103. for arg in cmd:
  104. if arg == LF:
  105. if not force_oneline:
  106. cmd_quote.append(arg)
  107. newline_count += 1
  108. else:
  109. cmd_quote.append(shlex.quote(arg))
  110. if force_oneline or newline_count > 0:
  111. cmd_quote = [
  112. ' '.join(list(y))
  113. for x, y in itertools.groupby(
  114. cmd_quote,
  115. lambda z: z == LF
  116. )
  117. if not x
  118. ]
  119. out.extend(cmd_quote)
  120. if force_oneline or newline_count == 1 and cmd[-1] == LF:
  121. ending = ''
  122. else:
  123. ending = last_newline + ';'
  124. return newline_separator.join(out) + ending
  125. def copy_dir_if_update_non_recursive(self, srcdir, destdir, filter_ext=None):
  126. # TODO print rsync equivalent.
  127. os.makedirs(destdir, exist_ok=True)
  128. for basename in sorted(os.listdir(srcdir)):
  129. src = os.path.join(srcdir, basename)
  130. if os.path.isfile(src) or os.path.islink(src):
  131. noext, ext = os.path.splitext(basename)
  132. dest = os.path.join(destdir, basename)
  133. if (
  134. (filter_ext is None or ext == filter_ext) and
  135. (not os.path.exists(dest) or os.path.getmtime(src) > os.path.getmtime(dest))
  136. ):
  137. self.cp(src, dest)
  138. def copy_dir_if_update(self, srcdir, destdir, filter_ext=None):
  139. self.copy_dir_if_update_non_recursive(srcdir, destdir, filter_ext)
  140. srcdir_abs = os.path.abspath(srcdir)
  141. srcdir_abs_len = len(srcdir_abs)
  142. for path, dirnames, filenames in self.walk(srcdir_abs):
  143. for dirname in dirnames:
  144. dirpath = os.path.join(path, dirname)
  145. dirpath_relative_root = dirpath[srcdir_abs_len + 1:]
  146. self.copy_dir_if_update_non_recursive(
  147. dirpath,
  148. os.path.join(destdir, dirpath_relative_root),
  149. filter_ext
  150. )
  151. def cp(self, src, dest, **kwargs):
  152. self.print_cmd(['cp', src, dest])
  153. if not self.dry_run:
  154. if os.path.islink(src):
  155. if os.path.lexists(dest):
  156. os.unlink(dest)
  157. linkto = os.readlink(src)
  158. os.symlink(linkto, dest)
  159. else:
  160. shutil.copy2(src, dest)
  161. def print_cmd(
  162. self,
  163. cmd,
  164. cwd=None,
  165. cmd_file=None,
  166. extra_env=None,
  167. extra_paths=None,
  168. force_oneline=False,
  169. ):
  170. '''
  171. Print cmd_to_string to stdout.
  172. Optionally save the command to cmd_file file, and add extra_env
  173. environment variables to the command generated.
  174. '''
  175. if type(cmd) is str:
  176. cmd_string = cmd
  177. else:
  178. cmd_string = self.cmd_to_string(
  179. cmd,
  180. cwd=cwd,
  181. extra_env=extra_env,
  182. extra_paths=extra_paths,
  183. force_oneline=force_oneline,
  184. )
  185. if not self.quiet:
  186. self._print_thread_safe('+ ' + cmd_string)
  187. if cmd_file is not None:
  188. os.makedirs(os.path.dirname(cmd_file), exist_ok=True)
  189. with open(cmd_file, 'w') as f:
  190. f.write('#!/usr/bin/env bash\n')
  191. f.write(cmd_string)
  192. self.chmod(cmd_file)
  193. def rmrf(self, path):
  194. self.print_cmd(['rm', '-r', '-f', path, LF])
  195. if not self.dry_run and os.path.exists(path):
  196. if os.path.isdir(path):
  197. shutil.rmtree(path)
  198. else:
  199. os.unlink(path)
  200. def run_cmd(
  201. self,
  202. cmd,
  203. cmd_file=None,
  204. out_file=None,
  205. show_stdout=True,
  206. show_cmd=True,
  207. extra_env=None,
  208. extra_paths=None,
  209. delete_env=None,
  210. raise_on_failure=True,
  211. **kwargs
  212. ):
  213. '''
  214. Run a command. Write the command to stdout before running it.
  215. Wait until the command finishes execution.
  216. :param cmd: command to run. LF entries are magic get skipped.
  217. :type cmd: List[str]
  218. :param cmd_file: if not None, write the command to be run to that file
  219. :type cmd_file: str
  220. :param out_file: if not None, write the stdout and stderr of the command the file
  221. :type out_file: str
  222. :param show_stdout: wether to show stdout and stderr on the terminal or not
  223. :type show_stdout: bool
  224. :param extra_env: extra environment variables to add when running the command
  225. :type extra_env: Dict[str,str]
  226. :return: exit status of the command
  227. :rtype: int
  228. '''
  229. if out_file is None:
  230. if show_stdout:
  231. stdout = None
  232. stderr = None
  233. else:
  234. stdout = subprocess.DEVNULL
  235. stderr = subprocess.DEVNULL
  236. else:
  237. stdout = subprocess.PIPE
  238. stderr = subprocess.STDOUT
  239. if extra_env is None:
  240. extra_env = {}
  241. if delete_env is None:
  242. delete_env = []
  243. if 'cwd' in kwargs:
  244. cwd = kwargs['cwd']
  245. else:
  246. cwd = None
  247. env = os.environ.copy()
  248. env.update(extra_env)
  249. if extra_paths is not None:
  250. path = ':'.join(extra_paths)
  251. if 'PATH' in os.environ:
  252. path += ':' + os.environ['PATH']
  253. env['PATH'] = path
  254. for key in delete_env:
  255. if key in env:
  256. del env[key]
  257. if show_cmd:
  258. self.print_cmd(cmd, cwd=cwd, cmd_file=cmd_file, extra_env=extra_env, extra_paths=extra_paths)
  259. # Otherwise, if called from a non-main thread:
  260. # ValueError: signal only works in main thread
  261. if threading.current_thread() == threading.main_thread():
  262. # Otherwise Ctrl + C gives:
  263. # - ugly Python stack trace for gem5 (QEMU takes over terminal and is fine).
  264. # - kills Python, and that then kills GDB: https://stackoverflow.com/questions/19807134/does-python-always-raise-an-exception-if-you-do-ctrlc-when-a-subprocess-is-exec
  265. sigint_old = signal.getsignal(signal.SIGINT)
  266. signal.signal(signal.SIGINT, signal.SIG_IGN)
  267. # Otherwise BrokenPipeError when piping through | grep
  268. # But if I do this_module, my terminal gets broken at the end. Why, why, why.
  269. # https://stackoverflow.com/questions/14207708/ioerror-errno-32-broken-pipe-python
  270. # Ignoring the exception is not enough as it prints a warning anyways.
  271. #sigpipe_old = signal.getsignal(signal.SIGPIPE)
  272. #signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  273. cmd = self.strip_newlines(cmd)
  274. if not self.dry_run:
  275. # https://stackoverflow.com/questions/15535240/python-popen-write-to-stdout-and-log-file-simultaneously/52090802#52090802
  276. with subprocess.Popen(cmd, stdout=stdout, stderr=stderr, env=env, **kwargs) as proc:
  277. if out_file is not None:
  278. os.makedirs(os.path.split(os.path.abspath(out_file))[0], exist_ok=True)
  279. with open(out_file, 'bw') as logfile:
  280. while True:
  281. byte = proc.stdout.read(1)
  282. if byte:
  283. if show_stdout:
  284. sys.stdout.buffer.write(byte)
  285. try:
  286. sys.stdout.flush()
  287. except BlockingIOError:
  288. # TODO understand. Why, Python, why.
  289. pass
  290. logfile.write(byte)
  291. else:
  292. break
  293. if threading.current_thread() == threading.main_thread():
  294. signal.signal(signal.SIGINT, sigint_old)
  295. #signal.signal(signal.SIGPIPE, sigpipe_old)
  296. returncode = proc.returncode
  297. if returncode != 0 and raise_on_failure:
  298. e = Exception('Command exited with status: {}'.format(returncode))
  299. e.returncode = returncode
  300. raise e
  301. return returncode
  302. else:
  303. return 0
  304. def shlex_split(self, string):
  305. '''
  306. shlex_split, but also add Newline after every word.
  307. Not perfect since it does not group arguments, but I don't see a solution.
  308. '''
  309. return self.add_newlines(shlex.split(string))
  310. def strip_newlines(self, cmd):
  311. if type(cmd) is str:
  312. return cmd
  313. else:
  314. return [x for x in cmd if x != LF]
  315. def walk(self, root):
  316. '''
  317. Extended walk that can take files or directories.
  318. '''
  319. if not os.path.exists(root):
  320. raise Exception('Path does not exist: ' + root)
  321. if os.path.isfile(root):
  322. dirname, basename = os.path.split(root)
  323. yield dirname, [], [basename]
  324. else:
  325. for path, dirnames, filenames in os.walk(root):
  326. dirnames.sort()
  327. filenames.sort()
  328. yield path, dirnames, filenames
  329. def wget(self, url, download_path):
  330. '''
  331. Append extra KEY=val configs into the given config file.
  332. I wissh we could have a progress indicator, but impossible:
  333. https://stackoverflow.com/questions/51212/how-to-write-a-download-progress-indicator-in-python
  334. '''
  335. self.print_cmd([
  336. 'wget', LF,
  337. '-O', download_path, LF,
  338. url, LF,
  339. ])
  340. urllib.request.urlretrieve(url, download_path)
  341. def write_configs(self, config_path, configs, config_fragments=None, mode='a'):
  342. '''
  343. Append extra KEY=val configs into the given config file.
  344. '''
  345. if config_fragments is None:
  346. config_fragments = []
  347. for config_fragment in config_fragments:
  348. self.print_cmd(['cat', config_fragment, '>>', config_path])
  349. if not self.dry_run:
  350. with open(config_path, 'a') as config_file:
  351. for config_fragment in config_fragments:
  352. with open(config_fragment, 'r') as config_fragment_file:
  353. for line in config_fragment_file:
  354. config_file.write(line)
  355. self.write_string_to_file(config_path, '\n'.join(configs), mode=mode)
  356. def write_string_to_file(self, path, string, mode='w'):
  357. if mode == 'a':
  358. redirect = '>>'
  359. else:
  360. redirect = '>'
  361. self.print_cmd("cat << 'EOF' {} {}\n{}\nEOF".format(redirect, path, string))
  362. if not self.dry_run:
  363. with open(path, mode) as f:
  364. f.write(string)
  365. if __name__ == '__main__':
  366. shell_helpers = ShellHelpers()
  367. if 'cmd_to_string':
  368. # Default.
  369. assert shell_helpers.cmd_to_string(['cmd']) == 'cmd \\\n;'
  370. assert shell_helpers.cmd_to_string(['cmd', 'arg1']) == 'cmd \\\n arg1 \\\n;'
  371. assert shell_helpers.cmd_to_string(['cmd', 'arg1', 'arg2']) == 'cmd \\\n arg1 \\\n arg2 \\\n;'
  372. # Argument with a space gets escaped.
  373. assert shell_helpers.cmd_to_string(['cmd', 'arg1 arg2']) == "cmd \\\n 'arg1 arg2' \\\n;"
  374. # Ending in LF with no other LFs get separated only by spaces.
  375. assert shell_helpers.cmd_to_string(['cmd', LF]) == 'cmd'
  376. assert shell_helpers.cmd_to_string(['cmd', 'arg1', LF]) == 'cmd arg1'
  377. assert shell_helpers.cmd_to_string(['cmd', 'arg1', 'arg2', LF]) == 'cmd arg1 arg2'
  378. # More than one LF adds newline separators at each LF.
  379. assert shell_helpers.cmd_to_string(['cmd', LF, 'arg1', LF]) == 'cmd \\\n arg1 \\\n;'
  380. assert shell_helpers.cmd_to_string(['cmd', LF, 'arg1', LF, 'arg2', LF]) == 'cmd \\\n arg1 \\\n arg2 \\\n;'
  381. assert shell_helpers.cmd_to_string(['cmd', LF, 'arg1', 'arg2', LF]) == 'cmd \\\n arg1 arg2 \\\n;'
  382. # force_oneline separates everything simply by spaces.
  383. assert \
  384. shell_helpers.cmd_to_string(['cmd', LF, 'arg1', LF, 'arg2', LF], force_oneline=True) \
  385. == 'cmd arg1 arg2'