neofetch_util.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from __future__ import annotations
  2. import os
  3. import platform
  4. import re
  5. import subprocess
  6. from pathlib import Path
  7. from subprocess import check_output
  8. from tempfile import TemporaryDirectory
  9. import pkg_resources
  10. from .color_util import AnsiMode
  11. from .constants import COLOR_MODE
  12. from .presets import ColorProfile
  13. def get_command_path() -> str:
  14. """
  15. Get the absolute path of the neofetch command
  16. :return: Command path
  17. """
  18. return pkg_resources.resource_filename(__name__, 'scripts/neofetch_mod.sh')
  19. def get_distro_ascii() -> str:
  20. """
  21. Get the distro ascii
  22. :return: Distro ascii
  23. """
  24. return check_output([get_command_path(), "print_ascii"]).decode().strip()
  25. def get_custom_distro_ascii(distro: str) -> str:
  26. """
  27. Get the distro ascii of a specific distro
  28. :return: Distro ascii
  29. """
  30. os.environ['CUSTOM_DISTRO'] = distro
  31. return check_output([get_command_path(), "print_custom_ascii"]).decode().strip()
  32. def replace_colors(asc: str, preset: ColorProfile, mode: AnsiMode = COLOR_MODE):
  33. # Remove existing colors
  34. asc = re.sub('\\${.*?}', '', asc)
  35. # Add new colors
  36. lines = asc.split('\n')
  37. colors = preset.with_length(len(lines))
  38. asc = '\n'.join([colors[i].to_ansi(mode) + l for i, l in enumerate(lines)])
  39. return asc, lines
  40. def run_neofetch(preset: ColorProfile, mode: AnsiMode):
  41. asc, lines = replace_colors(get_distro_ascii(), preset, mode)
  42. # Write temp file
  43. with TemporaryDirectory() as tmp_dir:
  44. tmp_dir = Path(tmp_dir)
  45. path = tmp_dir / 'ascii.txt'
  46. path.write_text(asc)
  47. # Call neofetch with the temp file
  48. os.environ['ascii_len'] = str(max(len(l) for l in lines))
  49. os.environ['ascii_lines'] = str(len(lines))
  50. if platform.system() != 'Windows':
  51. os.system(f'{get_command_path()} --ascii --source {path.absolute()} --ascii-colors')
  52. if platform.system() == 'Windows':
  53. cmd = get_command_path().replace("\\", "/").replace("C:/", "/c/")
  54. path_str = str(path.absolute()).replace('\\', '/').replace('C:/', '/c/')
  55. cmd = f'ascii_len={max(len(l) for l in lines)} ascii_lines={len(lines)} ' \
  56. f'{cmd} --ascii --source {path_str} --ascii-colors'
  57. full_cmd = ['C:\\Program Files\\Git\\bin\\bash.exe', '-c', cmd]
  58. # print(full_cmd)
  59. subprocess.run(full_cmd)