neofetch_util.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 get_custom_distro_ascii(distro: str) -> str:
  25. """
  26. Get the distro ascii of a specific distro
  27. :return: Distro ascii
  28. """
  29. os.environ['CUSTOM_DISTRO'] = distro
  30. return check_output([get_command_path(), "print_custom_ascii"]).decode().strip()
  31. def replace_colors(asc: str, preset: ColorProfile, mode: AnsiMode):
  32. # Remove existing colors
  33. asc = re.sub('\\${.*?}', '', asc)
  34. # Add new colors
  35. lines = asc.split('\n')
  36. colors = preset.with_length(len(lines))
  37. asc = '\n'.join([colors[i].to_ansi(mode) + l for i, l in enumerate(lines)])
  38. return asc, lines
  39. def run_neofetch(preset: ColorProfile, mode: AnsiMode):
  40. asc, lines = replace_colors(get_distro_ascii(), preset, mode)
  41. # Write temp file
  42. with TemporaryDirectory() as tmp_dir:
  43. tmp_dir = Path(tmp_dir)
  44. path = tmp_dir / 'ascii.txt'
  45. path.write_text(asc)
  46. # Call neofetch with the temp file
  47. os.environ['ascii_len'] = str(max(len(l) for l in lines))
  48. os.environ['ascii_lines'] = str(len(lines))
  49. if platform.system() != 'Windows':
  50. os.system(f'{get_command_path()} --ascii --source {path.absolute()} --ascii-colors')
  51. if platform.system() == 'Windows':
  52. cmd = get_command_path().replace("\\", "/").replace("C:/", "/c/")
  53. path_str = str(path.absolute()).replace('\\', '/').replace('C:/', '/c/')
  54. cmd = f'ascii_len={max(len(l) for l in lines)} ascii_lines={len(lines)} ' \
  55. f'{cmd} --ascii --source {path_str} --ascii-colors'
  56. full_cmd = ['C:\\Program Files\\Git\\bin\\bash.exe', '-c', cmd]
  57. # print(full_cmd)
  58. subprocess.run(full_cmd)