[+] Generate distro detection script based on glob

This commit is contained in:
Hykilpikonna 2022-12-11 06:54:01 -05:00
parent 6404b37b9e
commit adc947cecd
No known key found for this signature in database
GPG key ID: 256CD01A41D7FA26
327 changed files with 1700 additions and 331 deletions

View file

@ -5,11 +5,13 @@ List distributions supported by neofetch
"""
from __future__ import annotations
import re
import string
import textwrap
from pathlib import Path
import regex
from hypy_utils import write
from hyfetch.distro import AsciiArt
@ -95,7 +97,39 @@ def generate_help(max_len: int, leading: str):
return wrap(out, max_len, leading)
def export_distro(d: AsciiArt):
def match_condition(match: str) -> str:
"""
Convert simple glob match condition to python
"""
match = [s.strip() for s in match.split("|")]
conds = []
for m in match:
stripped = m.strip("*'\"")
# Exact matches
if m.strip("*") == m:
conds.append(f"name == '{stripped}'")
continue
# Both sides are *
if m.startswith("*") and m.endswith("*"):
conds.append(f"(name.startswith('{stripped}') or name.endswith('{stripped}'))")
continue
# Ends with *
if m.endswith("*"):
conds.append(f"name.startswith('{stripped}')")
continue
# Starts with *
if m.startswith("*"):
conds.append(f"name.endswith('{stripped}')")
continue
return ' or '.join(conds)
def export_distro(d: AsciiArt) -> str:
"""
Export distro to a python script
"""
@ -104,20 +138,33 @@ def export_distro(d: AsciiArt):
varname = varname.replace(s, '_')
ascii = d.ascii.replace('"""', '\\"""')
script = f"""
from hyfetch.distro import AsciiArt
from ..distro import AsciiArt
{varname} = AsciiArt(match=r'''{d.match}''', color='{d.color}', ascii=r\"""
{ascii}
\""")
"""
Path('distros').mkdir(parents=True, exist_ok=True)
Path(f'distros/{varname}.py').write_text(script)
write(Path(__file__).parent.parent / f'hyfetch/distros/{varname}.py', script)
# Generate python script for identifying the distro
return f"""
if {match_condition(d.match)}:
from .{varname} import {varname}
return {varname}
"""
def export_distros():
distros = parse_ascii_distros()
print(len(distros))
[export_distro(d) for d in distros]
# print('\n'.join(d.match for d in distros))
py = """
# This file is automatically generated. Please do not modify.\n
from ..distro import AsciiArt
def detect(name: str) -> AsciiArt:
"""
py += '\n'.join(export_distro(d).strip('\n') for d in distros)
write(Path(__file__).parent.parent / f'hyfetch/distros/distro_detector.py', py)
if __name__ == '__main__':