neofetch_util.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 .presets import ColorProfile
  12. def get_command_path() -> str:
  13. """
  14. Get the absolute path of the neofetch command
  15. :return: Command path
  16. """
  17. return pkg_resources.resource_filename(__name__, 'scripts/neofetch_mod.sh')
  18. def get_distro_ascii() -> str:
  19. """
  20. Get the distro ascii
  21. :return: Distro ascii
  22. """
  23. return check_output([get_command_path(), "print_ascii"]).decode().strip()
  24. def run_neofetch(preset: ColorProfile, mode: AnsiMode):
  25. # Get existing ascii
  26. asc = get_distro_ascii()
  27. # Remove existing colors
  28. asc = re.sub('\\${.*?}', '', asc)
  29. # Add new colors
  30. lines = asc.split('\n')
  31. colors = preset.with_length(len(lines))
  32. asc = '\n'.join([colors[i].to_ansi(mode) + l for i, l in enumerate(lines)])
  33. # Write temp file
  34. with TemporaryDirectory() as tmp_dir:
  35. tmp_dir = Path(tmp_dir)
  36. path = tmp_dir / 'ascii.txt'
  37. path.write_text(asc)
  38. # Call neofetch with the temp file
  39. os.environ['ascii_len'] = str(max(len(l) for l in lines))
  40. os.environ['ascii_lines'] = str(len(lines))
  41. if platform.system() != 'Windows':
  42. os.system(f'{get_command_path()} --ascii --source {path.absolute()} --ascii-colors')
  43. if platform.system() == 'Windows':
  44. cmd = get_command_path().replace("\\", "/").replace("C:/", "/c/")
  45. path_str = str(path.absolute()).replace('\\', '/').replace('C:/', '/c/')
  46. cmd = f'ascii_len={max(len(l) for l in lines)} ascii_lines={len(lines)} ' \
  47. f'{cmd} --ascii --source {path_str} --ascii-colors'
  48. full_cmd = ['C:\\Program Files\\Git\\bin\\bash.exe', '-c', cmd]
  49. # print(full_cmd)
  50. subprocess.run(full_cmd)