rc.xsh 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. $VI_MODE = True
  2. $AUTO_PUSHD = True
  3. $XONSH_AUTOPAIR = True
  4. # tab selection: do not execute cmd when pressing enter
  5. $COMPLETIONS_CONFIRM = True
  6. xontrib load vox z
  7. def _last_exit_status():
  8. try:
  9. exit_status = __xonsh_history__.rtns[-1]
  10. return exit_status if exit_status != 0 else None
  11. except IndexError:
  12. return None
  13. $PROMPT_FIELDS['last_exit_status'] = _last_exit_status
  14. $SHLVL = int($SHLVL) + 1 if 'SHLVL' in ${...} else 1
  15. $XONSH_STDERR_PREFIX = '{RED}'
  16. $XONSH_STDERR_POSTFIX = '{NO_COLOR}'
  17. $DYNAMIC_CWD_WIDTH = '30%'
  18. $DYNAMIC_CWD_ELISION_CHAR = '…'
  19. $PROMPT = ''.join([
  20. '{RED}{last_exit_status:[{}] }',
  21. '{BOLD_GREEN}{user}@{hostname} ',
  22. '{YELLOW}{cwd} ',
  23. '{{BLUE}}{} '.format('{prompt_end}' * $SHLVL),
  24. '{NO_COLOR}',
  25. ])
  26. $RIGHT_PROMPT = '{gitstatus}{env_name: {}}'
  27. import datetime as dt
  28. import io
  29. import json
  30. import os
  31. import re
  32. import select
  33. import shlex
  34. import shutil
  35. import subprocess
  36. import sys
  37. import threading
  38. # default locale
  39. # will be used for all non-explicitly set LC_* variables
  40. $LANG = 'en_US.UTF-8'
  41. # fallback locales
  42. # GNU gettext gives preference to LANGUAGE over LC_ALL and LANG
  43. # for the purpose of message handling
  44. # https://www.gnu.org/software/gettext/manual/html_node/The-LANGUAGE-variable.html
  45. # cave: if this list contains 'de(_.*)?' at any (sic!) position
  46. # vim 7.4.1689 will switch to german
  47. $LANGUAGE = ':'.join(['en_US', 'en'])
  48. $LC_COLLATE = 'C.UTF-8'
  49. # char classification, case conversion & other char attrs
  50. $LC_CTYPE = 'de_AT.UTF-8'
  51. # $ locale currency_symbol
  52. $LC_MONETARY = 'de_AT.UTF-8'
  53. # $ locale -k LC_NUMERIC | head -n 3
  54. # decimal_point="."
  55. # thousands_sep=""
  56. # grouping=-1
  57. $LC_NUMERIC = 'C.UTF-8'
  58. # A4
  59. $LC_PAPER = 'de_AT.UTF-8'
  60. USER_BIN_PATH = os.path.join($HOME, '.local', 'bin')
  61. if os.path.isdir(USER_BIN_PATH):
  62. $PATH.insert(0, USER_BIN_PATH)
  63. $PAGER = 'less'
  64. $EDITOR = 'vim'
  65. # required by pinentry-tty when using gpg command:
  66. $GPG_TTY = $(tty)
  67. if shutil.which('gpgconf'):
  68. # required by scute
  69. $GPG_AGENT_INFO = $(gpgconf --list-dir agent-socket).rstrip() + ':0:1'
  70. if not 'SSH_CLIENT' in ${...}:
  71. # in gnupg 2.1.13 the location of agents socket changed
  72. $SSH_AUTH_SOCK = $(gpgconf --list-dir agent-ssh-socket).rstrip()
  73. # wrapper for termite required when launching termite from ranger:
  74. $TERMCMD = os.path.join(os.path.dirname(__file__), 'ranger-termite-termcmd')
  75. # https://docs.docker.com/engine/security/trust/content_trust/
  76. $DOCKER_CONTENT_TRUST = 1
  77. class DockerImage:
  78. def __init__(self, image):
  79. attrs, = json.loads(subprocess.check_output(['sudo', 'docker', 'image', 'inspect', image])
  80. .decode(sys.stdout.encoding))
  81. self._id = attrs['Id']
  82. self._tags = attrs['RepoTags']
  83. def __repr__(self):
  84. return '{}(id={!r}, tags={!r})'.format(type(self).__name__, self._id, self._tags)
  85. @classmethod
  86. def build(cls, dockerfile):
  87. out = io.BytesIO()
  88. with StdoutTee(out) as tee:
  89. p = subprocess.Popen(['sudo', 'docker', 'build', '-'],
  90. stdin=subprocess.PIPE, stdout=tee)
  91. p.stdin.write(dockerfile.encode())
  92. p.stdin.close()
  93. assert p.wait() == 0, 'docker build failed'
  94. image_id, = re.search(rb'^Successfully built (\S+)$', out.getvalue(), re.MULTILINE).groups()
  95. return cls(image_id.decode(sys.stdout.encoding))
  96. @classmethod
  97. def pull(cls, image):
  98. out = io.BytesIO()
  99. with StdoutTee(out) as tee:
  100. subprocess.run(['sudo', 'docker', 'image', 'pull', image], stdout=tee)
  101. repo_digest, = re.search(rb'^Digest: (sha\S+:\S+)$', out.getvalue(), re.MULTILINE).groups()
  102. return cls('{}@{}'.format(image, repo_digest.decode()))
  103. def run(self, detach=False, publish_ports=[], args=[], caps=[]):
  104. params = ['sudo', 'docker', 'run', '--rm']
  105. if detach:
  106. params.append('--detach')
  107. else:
  108. params.extend(['--interactive', '--tty'])
  109. params.extend('--publish=' + ':'.join([str(a) for a in p]) for p in publish_ports)
  110. params.extend(['--security-opt=no-new-privileges', '--cap-drop=all'])
  111. params.extend(['--cap-add={}'.format(c) for c in caps])
  112. params.append(self._id)
  113. params.extend(args)
  114. sys.stderr.write('{}\n'.format(shlex_join(params)))
  115. subprocess.run(params, check=True)
  116. class StdoutTee:
  117. def __init__(self, sink):
  118. self._sink = sink
  119. def __enter__(self):
  120. self._read_fd, self._write_fd = os.pipe()
  121. self._thread = threading.Thread(target=self._loop)
  122. self._thread.start()
  123. return self
  124. def _loop(self):
  125. while True:
  126. try:
  127. data = os_read_non_blocking(self._read_fd)
  128. except OSError: # fd closed
  129. return
  130. if data:
  131. self._sink.write(data)
  132. sys.stdout.buffer.write(data)
  133. sys.stdout.flush()
  134. def fileno(self):
  135. return self._write_fd
  136. def __exit__(self, exc_type, exc_value, traceback):
  137. os.close(self._read_fd)
  138. os.close(self._write_fd)
  139. self._thread.join()
  140. def dpkg_listfiles(pkg_name):
  141. assert isinstance(pkg_name, str)
  142. paths = $(dpkg --listfiles @(pkg_name)).split('\n')[:-1]
  143. assert len(paths) > 0, 'pkg {!r} not installed'.format(pkg_name)
  144. return paths
  145. def dpkg_search(path_search_pattern):
  146. assert isinstance(path_search_pattern, str)
  147. return re.findall(
  148. '^(\S+): (.*)$\n',
  149. $(dpkg --search @(path_search_pattern)),
  150. flags=re.MULTILINE,
  151. )
  152. def dpkg_welse(cmd):
  153. pkg_name, cmd_path = dpkg_which(cmd)
  154. return dpkg_listfiles(pkg_name)
  155. def dpkg_which(cmd):
  156. cmd_path = shutil.which(cmd)
  157. assert cmd_path, 'cmd {!r} not found'.format(cmd)
  158. matches = dpkg_search(cmd_path)
  159. assert len(matches) != 0, '{!r} not installed via dpkg'.format(cmd_path)
  160. assert len(matches) == 1
  161. return matches[0]
  162. def locate(*patterns, match_all=True, ignore_case=True):
  163. params = []
  164. if match_all:
  165. params.insert(0, '--all')
  166. if ignore_case:
  167. params.insert(0, '--ignore-case')
  168. return $(locate @(params) -- @(patterns)).split('\n')[:-1]
  169. def os_read_non_blocking(fd, buffer_size_bytes=8*1024, timeout_seconds=0.1):
  170. if fd in select.select([fd], [], [], timeout_seconds)[0]:
  171. return os.read(fd, buffer_size_bytes)
  172. else:
  173. return None
  174. def shlex_join(params):
  175. return ' '.join(shlex.quote(p) for p in params)
  176. def timestamp_now_utc():
  177. return dt.datetime.utcnow().replace(tzinfo=dt.timezone.utc)
  178. def timestamp_now_local():
  179. # if called without tz argument astimezone() assumes
  180. # the system local timezone for the target timezone
  181. return timestamp_now_utc().astimezone()
  182. def timestamp_iso_local():
  183. # if called without tz argument astimezone() assumes
  184. # the system local timezone for the target timezone
  185. return timestamp_now_local().strftime('%Y%m%dT%H%M%S%z')
  186. aliases['d'] = ['sudo', 'docker']
  187. aliases['d-r'] = ['d', 'run', '--rm=true',
  188. '--cap-drop=all', '--security-opt=no-new-privileges']
  189. aliases['dpkg-welse'] = lambda args: '\n'.join(dpkg_welse(args[0]))
  190. aliases['dpkg-which'] = lambda args: '\t'.join(dpkg_which(args[0]))
  191. aliases['g'] = ['git']
  192. aliases['ll'] = ['ls', '-l', '--all', '--indicator-style=slash',
  193. '--human-readable', '--time-style=long-iso', '--color=auto']
  194. if shutil.which('startx') and $(tty).rstrip() == '/dev/tty1':
  195. startx
  196. # vim: filetype=python