rc.xsh 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 os
  29. import re
  30. import shutil
  31. import subprocess
  32. import sys
  33. # default locale
  34. # will be used for all non-explicitly set LC_* variables
  35. $LANG = 'en_US.UTF-8'
  36. # fallback locales
  37. # GNU gettext gives preference to LANGUAGE over LC_ALL and LANG
  38. # for the purpose of message handling
  39. # https://www.gnu.org/software/gettext/manual/html_node/The-LANGUAGE-variable.html
  40. # cave: if this list contains 'de(_.*)?' at any (sic!) position
  41. # vim 7.4.1689 will switch to german
  42. $LANGUAGE = ':'.join(['en_US', 'en'])
  43. $LC_COLLATE = 'C.UTF-8'
  44. # char classification, case conversion & other char attrs
  45. $LC_CTYPE = 'de_AT.UTF-8'
  46. # $ locale currency_symbol
  47. $LC_MONETARY = 'de_AT.UTF-8'
  48. # $ locale -k LC_NUMERIC | head -n 3
  49. # decimal_point="."
  50. # thousands_sep=""
  51. # grouping=-1
  52. $LC_NUMERIC = 'C.UTF-8'
  53. # A4
  54. $LC_PAPER = 'de_AT.UTF-8'
  55. USER_BIN_PATH = os.path.join($HOME, '.local', 'bin')
  56. if os.path.isdir(USER_BIN_PATH):
  57. $PATH.insert(0, USER_BIN_PATH)
  58. $PAGER = 'less'
  59. $EDITOR = 'vim'
  60. # required by pinentry-tty when using gpg command:
  61. $GPG_TTY = $(tty)
  62. if shutil.which('gpgconf'):
  63. # required by scute
  64. $GPG_AGENT_INFO = $(gpgconf --list-dir agent-socket).rstrip() + ':0:1'
  65. if not 'SSH_CLIENT' in ${...}:
  66. # in gnupg 2.1.13 the location of agents socket changed
  67. $SSH_AUTH_SOCK = $(gpgconf --list-dir agent-ssh-socket).rstrip()
  68. # wrapper for termite required when launching termite from ranger:
  69. $TERMCMD = os.path.join(os.path.dirname(__file__), 'ranger-termite-termcmd')
  70. # https://docs.docker.com/engine/security/trust/content_trust/
  71. $DOCKER_CONTENT_TRUST = 1
  72. def dpkg_listfiles(pkg_name):
  73. assert isinstance(pkg_name, str)
  74. paths = $(dpkg --listfiles @(pkg_name)).split('\n')[:-1]
  75. assert len(paths) > 0, 'pkg {!r} not installed'.format(pkg_name)
  76. return paths
  77. def dpkg_search(path_search_pattern):
  78. assert isinstance(path_search_pattern, str)
  79. return re.findall(
  80. '^(\S+): (.*)$\n',
  81. $(dpkg --search @(path_search_pattern)),
  82. flags=re.MULTILINE,
  83. )
  84. def dpkg_welse(cmd):
  85. pkg_name, cmd_path = dpkg_which(cmd)
  86. return dpkg_listfiles(pkg_name)
  87. def dpkg_which(cmd):
  88. cmd_path = shutil.which(cmd)
  89. assert cmd_path, 'cmd {!r} not found'.format(cmd)
  90. matches = dpkg_search(cmd_path)
  91. assert len(matches) != 0, '{!r} not installed via dpkg'.format(cmd_path)
  92. assert len(matches) == 1
  93. return matches[0]
  94. def docker_build(dockerfile):
  95. p = subprocess.Popen(['sudo', 'docker', 'build', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  96. p.stdin.write(dockerfile.encode())
  97. p.stdin.close()
  98. image_id_regex = re.compile(rb'^Successfully built (\S+)\n$')
  99. image_id = None
  100. for line in p.stdout:
  101. sys.stdout.write(line.decode(sys.stdout.encoding))
  102. image_id_match = image_id_regex.search(line)
  103. if image_id_match:
  104. image_id, = image_id_match.groups()
  105. assert not image_id is None, 'could not determine image id'
  106. return image_id.decode(sys.stdout.encoding)
  107. def docker_run(image_id=None, dockerfile=None, caps=[]):
  108. assert image_id is None or dockerfile is None, \
  109. 'either pass kwarg image_id or dockerfile'
  110. if not image_id:
  111. image_id = docker_build(dockerfile)
  112. params = ['sudo', 'docker', 'run',
  113. '--rm=true', '--interactive=true', '--tty=true',
  114. '--cap-drop=all', '--security-opt=no-new-privileges']
  115. params.extend(['--cap-add={}'.format(c) for c in caps])
  116. params.append(image_id)
  117. import shlex
  118. print(' '.join([shlex.quote(p) for p in params]))
  119. subprocess.run(params, check=True)
  120. def locate(*patterns, match_all=True, ignore_case=True):
  121. params = []
  122. if match_all:
  123. params.insert(0, '--all')
  124. if ignore_case:
  125. params.insert(0, '--ignore-case')
  126. return $(locate @(params) -- @(patterns)).split('\n')[:-1]
  127. def timestamp_now_utc():
  128. return dt.datetime.utcnow().replace(tzinfo=dt.timezone.utc)
  129. def timestamp_now_local():
  130. # if called without tz argument astimezone() assumes
  131. # the system local timezone for the target timezone
  132. return timestamp_now_utc().astimezone()
  133. def timestamp_iso_local():
  134. # if called without tz argument astimezone() assumes
  135. # the system local timezone for the target timezone
  136. return timestamp_now_local().strftime('%Y%m%dT%H%M%S%z')
  137. aliases['d'] = ['sudo', 'docker']
  138. aliases['d-r'] = lambda args: docker_run(**{
  139. 'dockerfile' if '\n' in args[0] else 'image_id': args[0],
  140. })
  141. aliases['dpkg-welse'] = lambda args: '\n'.join(dpkg_welse(args[0]))
  142. aliases['dpkg-which'] = lambda args: '\t'.join(dpkg_which(args[0]))
  143. aliases['g'] = ['git']
  144. aliases['ll'] = ['ls', '-l', '--all', '--indicator-style=slash',
  145. '--human-readable', '--time-style=long-iso', '--color=auto']
  146. if shutil.which('startx') and $(tty).rstrip() == '/dev/tty1':
  147. startx
  148. # vim: filetype=python