chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,748 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import textwrap
|
||||
import types
|
||||
from collections.abc import Callable, Iterator
|
||||
from typing import Any, get_type_hints
|
||||
|
||||
from kitty.conf.types import Definition, MultiOption, Option, ParserFuncType, unset
|
||||
from kitty.fast_data_types import NULL_COLOR_VALUE
|
||||
from kitty.options.utils import parse_options_for_map
|
||||
from kitty.simple_cli_definitions import serialize_as_go_string
|
||||
|
||||
|
||||
def chunks[_T](lst: list[_T], n: int) -> Iterator[list[_T]]:
|
||||
for i in range(0, len(lst), n):
|
||||
yield lst[i : i + n]
|
||||
|
||||
|
||||
def atoi(text: str) -> str:
|
||||
return f'{int(text):08d}' if text.isdigit() else text
|
||||
|
||||
|
||||
def natural_keys(text: str) -> tuple[str, ...]:
|
||||
return tuple(atoi(c) for c in re.split(r'(\d+)', text))
|
||||
|
||||
|
||||
def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
class_lines: list[str] = []
|
||||
tc_lines: list[str] = []
|
||||
a = class_lines.append
|
||||
t = tc_lines.append
|
||||
a('class Options:')
|
||||
t('class Parser:')
|
||||
choices = {}
|
||||
imports: set[tuple[str, str]] = set()
|
||||
tc_imports: set[tuple[str, str]] = set()
|
||||
ki_imports: 're.Pattern[str]' = re.compile(r'\b((?:kittens|kitty).+?)[,\]]')
|
||||
|
||||
def option_type_as_str(x: Any) -> str:
|
||||
needs_import = False
|
||||
if type(x) is type:
|
||||
ans = x.__name__
|
||||
needs_import = True
|
||||
else:
|
||||
ans = repr(x)
|
||||
ans = ans.replace('NoneType', 'None')
|
||||
if needs_import and getattr(x, '__module__', None) and x.__module__ not in ('builtins', 'typing'):
|
||||
imports.add((x.__module__, x.__name__))
|
||||
return ans
|
||||
|
||||
def option_type_data(option: Option | MultiOption) -> tuple[Callable[[Any], Any], str]:
|
||||
func = option.parser_func
|
||||
if func.__module__ == 'builtins':
|
||||
return func, getattr(func, '__name__')
|
||||
th = get_type_hints(func)
|
||||
rettype = th['return']
|
||||
typ = option_type_as_str(rettype)
|
||||
if isinstance(option, MultiOption):
|
||||
typ = typ[typ.index('[') + 1 : -1]
|
||||
typ = typ.replace('tuple', 'dict', 1)
|
||||
kq = ki_imports.search(typ)
|
||||
if kq is not None:
|
||||
kqi = kq.group(1)
|
||||
kqim, kqii = kqi.rsplit('.', 1)
|
||||
imports.add((kqim, ''))
|
||||
return func, typ
|
||||
|
||||
is_mutiple_vars = {}
|
||||
option_names = set()
|
||||
color_table = list(map(str, range(256)))
|
||||
choice_dedup: dict[str, str] = {}
|
||||
choice_parser_dedup: dict[str, str] = {}
|
||||
|
||||
def parser_function_declaration(option_name: str) -> None:
|
||||
t('')
|
||||
t(f' def {option_name}(self, val: str, ans: dict[str, typing.Any]) -> None:')
|
||||
|
||||
for option in sorted(defn.iter_all_options(), key=lambda a: natural_keys(a.name)):
|
||||
option_names.add(option.name)
|
||||
parser_function_declaration(option.name)
|
||||
if isinstance(option, MultiOption):
|
||||
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
|
||||
func, typ = option_type_data(option)
|
||||
assert isinstance(func, types.FunctionType)
|
||||
for val in option:
|
||||
if val.add_to_default:
|
||||
gr = mval[val.only]
|
||||
for k, v in func(val.defval_as_str):
|
||||
gr[k] = v
|
||||
is_mutiple_vars[option.name] = typ, mval
|
||||
sig = inspect.signature(func)
|
||||
tc_imports.add((func.__module__, func.__name__))
|
||||
if len(sig.parameters) == 1:
|
||||
t(f' for k, v in {func.__name__}(val):')
|
||||
t(f' ans["{option.name}"][k] = v')
|
||||
else:
|
||||
t(f' for k, v in {func.__name__}(val, ans["{option.name}"]):')
|
||||
t(f' ans["{option.name}"][k] = v')
|
||||
continue
|
||||
|
||||
if option.choices:
|
||||
typ = 'typing.Literal[{}]'.format(', '.join(repr(x) for x in option.choices))
|
||||
ename = f'choices_for_{option.name}'
|
||||
if typ in choice_dedup:
|
||||
typ = choice_dedup[typ]
|
||||
else:
|
||||
choice_dedup[typ] = ename
|
||||
choices[ename] = typ
|
||||
typ = ename
|
||||
func = str
|
||||
elif defn.has_color_table and option.is_color_table_color:
|
||||
func, typ = option_type_data(option)
|
||||
assert isinstance(func, types.FunctionType)
|
||||
t(f' ans[{option.name!r}] = {func.__name__}(val)')
|
||||
tc_imports.add((func.__module__, func.__name__))
|
||||
cnum = int(option.name[5:])
|
||||
if option.defval_as_string == 'none':
|
||||
color_table[cnum] = f'0x{NULL_COLOR_VALUE:x}'
|
||||
else:
|
||||
color_table[cnum] = f'0x{func(option.defval_as_string).__int__():06x}'
|
||||
continue
|
||||
else:
|
||||
func, typ = option_type_data(option)
|
||||
try:
|
||||
params = dict(inspect.signature(func).parameters)
|
||||
except Exception:
|
||||
params = {}
|
||||
assert isinstance(func, types.FunctionType)
|
||||
if 'dict_with_parse_results' in params:
|
||||
t(f' {func.__name__}(val, ans)')
|
||||
else:
|
||||
t(f' ans[{option.name!r}] = {func.__name__}(val)')
|
||||
if func.__module__ != 'builtins':
|
||||
tc_imports.add((func.__module__, func.__name__))
|
||||
|
||||
defval_as_obj = func(option.defval_as_string)
|
||||
if isinstance(defval_as_obj, frozenset):
|
||||
defval = 'frozenset({' + ', '.join(repr(x) for x in sorted(defval_as_obj)) + '})'
|
||||
else:
|
||||
defval = repr(defval_as_obj)
|
||||
if option.macos_defval is not unset:
|
||||
md = repr(func(option.macos_defval))
|
||||
defval = f'{md} if is_macos else {defval}'
|
||||
imports.add(('kitty.constants', 'is_macos'))
|
||||
a(f' {option.name}: {typ} = {defval}')
|
||||
if option.choices:
|
||||
ecname = f'choices_for_{option.name}'
|
||||
crepr = f'frozenset({option.choices!r})'
|
||||
if crepr in choice_parser_dedup:
|
||||
crepr = choice_parser_dedup[crepr]
|
||||
else:
|
||||
choice_parser_dedup[crepr] = ecname
|
||||
t(' val = val.lower()')
|
||||
t(f' if val not in self.choices_for_{option.name}:')
|
||||
t(f' raise ValueError(f"The value {{val}} is not a valid choice for {option.name}")')
|
||||
t(f' ans["{option.name}"] = val')
|
||||
t('')
|
||||
t(f' {ecname} = {crepr}')
|
||||
|
||||
for option_name, (typ, mval) in is_mutiple_vars.items():
|
||||
a(f' {option_name}: {typ} = {{}}')
|
||||
|
||||
for parser, aliases in defn.deprecations.items():
|
||||
assert isinstance(parser, types.FunctionType)
|
||||
for alias in aliases:
|
||||
parser_function_declaration(alias)
|
||||
tc_imports.add((parser.__module__, parser.__name__))
|
||||
t(f' {parser.__name__}({alias!r}, val, ans)')
|
||||
|
||||
action_parsers = {}
|
||||
|
||||
def resolve_import(ftype: str) -> str:
|
||||
if '.' in ftype:
|
||||
fmod, ftype = ftype.rpartition('.')[::2]
|
||||
else:
|
||||
fmod = f'{loc}.options.utils'
|
||||
imports.add((fmod, ftype))
|
||||
return ftype
|
||||
|
||||
if loc == 'kitty':
|
||||
imports.add(('kitty.options.utils', 'KeyFallbackType'))
|
||||
|
||||
for aname, action in defn.actions.items():
|
||||
option_names.add(aname)
|
||||
action_parsers[aname] = func = action.parser_func
|
||||
assert isinstance(func, types.FunctionType)
|
||||
th = get_type_hints(func)
|
||||
rettype = th['return']
|
||||
typ = option_type_as_str(rettype)
|
||||
typ = typ[typ.index('[') + 1 : -1]
|
||||
a(f' {aname}: list[{typ}] = []')
|
||||
for imp in action.imports:
|
||||
resolve_import(imp)
|
||||
for fname, ftype in action.fields.items():
|
||||
ftype = resolve_import(ftype)
|
||||
fval = f'{ftype}()' if ftype == 'AliasMap' else '{}'
|
||||
a(f' {fname}: {ftype} = {fval}')
|
||||
parser_function_declaration(aname)
|
||||
t(f' for k in {func.__name__}(val):')
|
||||
t(f' ans[{aname!r}].append(k)')
|
||||
tc_imports.add((func.__module__, func.__name__))
|
||||
|
||||
if defn.has_color_table:
|
||||
imports.add(('array', 'array'))
|
||||
a(' color_table: "array[int]" = array("L", (')
|
||||
for grp in chunks(color_table, 8):
|
||||
a(' ' + ', '.join(grp) + ',')
|
||||
a(' ))')
|
||||
|
||||
a(' config_paths: tuple[str, ...] = ()')
|
||||
a(' all_config_paths: tuple[str, ...] = ()')
|
||||
a(' config_overrides: tuple[str, ...] = ()')
|
||||
a('')
|
||||
a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:')
|
||||
if defn.has_color_table:
|
||||
a(' self.color_table = array(self.color_table.typecode, self.color_table)')
|
||||
a(' if options_dict is not None:')
|
||||
a(' null = object()')
|
||||
a(' for key in option_names:')
|
||||
a(' val = options_dict.get(key, null)')
|
||||
a(' if val is not null:')
|
||||
a(' setattr(self, key, val)')
|
||||
|
||||
a('')
|
||||
a(' @property')
|
||||
a(' def _fields(self) -> tuple[str, ...]:')
|
||||
a(' return option_names')
|
||||
|
||||
a('')
|
||||
a(' def __iter__(self) -> typing.Iterator[str]:')
|
||||
a(' return iter(self._fields)')
|
||||
|
||||
a('')
|
||||
a(' def __len__(self) -> int:')
|
||||
a(' return len(self._fields)')
|
||||
|
||||
a('')
|
||||
a(' def _copy_of_val(self, name: str) -> typing.Any:')
|
||||
a(' ans = getattr(self, name)')
|
||||
a(' if isinstance(ans, dict):\n ans = ans.copy()')
|
||||
a(' elif isinstance(ans, list):\n ans = ans[:]')
|
||||
a(' return ans')
|
||||
|
||||
a('')
|
||||
a(' def _asdict(self) -> dict[str, typing.Any]:')
|
||||
a(' return {k: self._copy_of_val(k) for k in self}')
|
||||
|
||||
a('')
|
||||
a(' def _replace(self, **kw: typing.Any) -> "Options":')
|
||||
a(' ans = Options()')
|
||||
a(' for name in self:')
|
||||
a(' setattr(ans, name, self._copy_of_val(name))')
|
||||
a(' for name, val in kw.items():')
|
||||
a(' setattr(ans, name, val)')
|
||||
a(' return ans')
|
||||
|
||||
a('')
|
||||
a(' def __getitem__(self, key: int | str) -> typing.Any:')
|
||||
a(' k = option_names[key] if isinstance(key, int) else key')
|
||||
a(' try:')
|
||||
a(' return getattr(self, k)')
|
||||
a(' except AttributeError:')
|
||||
a(' pass')
|
||||
a(' raise KeyError(f"No option named: {k}")')
|
||||
|
||||
if defn.has_color_table:
|
||||
a('')
|
||||
a(' def __getattr__(self, key: str) -> typing.Any:')
|
||||
a(' if key.startswith("color"):')
|
||||
a(' q = key[5:]')
|
||||
a(' if q.isdigit():')
|
||||
a(' k = int(q)')
|
||||
a(' if 0 <= k <= 255:')
|
||||
a(' x = self.color_table[k]')
|
||||
a(f' if x == 0x{NULL_COLOR_VALUE:x}:')
|
||||
a(' return None')
|
||||
a(' return Color((x >> 16) & 255, (x >> 8) & 255, x & 255)')
|
||||
a(' raise AttributeError(key)')
|
||||
a('')
|
||||
a(' def __setattr__(self, key: str, val: typing.Any) -> typing.Any:')
|
||||
a(' if key.startswith("color"):')
|
||||
a(' q = key[5:]')
|
||||
a(' if q.isdigit():')
|
||||
a(' k = int(q)')
|
||||
a(' if 0 <= k <= 255:')
|
||||
a(' if val is None:')
|
||||
a(f' self.color_table[k] = 0x{NULL_COLOR_VALUE:x}')
|
||||
a(' else:')
|
||||
a(' self.color_table[k] = int(val)')
|
||||
a(' return')
|
||||
a(' object.__setattr__(self, key, val)')
|
||||
|
||||
a('')
|
||||
a('')
|
||||
a('defaults = Options()')
|
||||
a('')
|
||||
for option_name, (typ, mval) in is_mutiple_vars.items():
|
||||
a(f'defaults.{option_name} = {mval[""]!r}')
|
||||
if mval['macos']:
|
||||
imports.add(('kitty.constants', 'is_macos'))
|
||||
a('if is_macos:')
|
||||
a(f' defaults.{option_name}.update({mval["macos"]!r}')
|
||||
if mval['macos']:
|
||||
imports.add(('kitty.constants', 'is_macos'))
|
||||
a('if not is_macos:')
|
||||
a(f' defaults.{option_name}.update({mval["linux"]!r}')
|
||||
|
||||
a('')
|
||||
for aname, func in action_parsers.items():
|
||||
a(f'defaults.{aname} = [')
|
||||
only: dict[str, list[tuple[str, Callable[..., Any]]]] = {}
|
||||
for sc in defn.iter_all_maps(aname):
|
||||
if not sc.add_to_default:
|
||||
continue
|
||||
text = sc.parseable_text
|
||||
if sc.only:
|
||||
only.setdefault(sc.only, []).append((text, func))
|
||||
else:
|
||||
for val in func(text):
|
||||
a(f' # {sc.name}')
|
||||
a(f' {val!r},')
|
||||
a(']')
|
||||
a('')
|
||||
if only:
|
||||
imports.add(('kitty.constants', 'is_macos'))
|
||||
for cond, items in only.items():
|
||||
cond = 'is_macos' if cond == 'macos' else 'not is_macos'
|
||||
a(f'if {cond}:')
|
||||
for text, parser_func in items:
|
||||
for val in parser_func(text):
|
||||
a(f' defaults.{aname}.append({val!r})')
|
||||
a('')
|
||||
|
||||
t('')
|
||||
t('')
|
||||
t('def create_result_dict() -> dict[str, typing.Any]:')
|
||||
t(' return {')
|
||||
for oname in is_mutiple_vars:
|
||||
t(f' {oname!r}: {{}},')
|
||||
for aname in defn.actions:
|
||||
t(f' {aname!r}: [],')
|
||||
t(' }')
|
||||
|
||||
t('')
|
||||
t('')
|
||||
t(f'actions: frozenset[str] = frozenset({tuple(defn.actions)!r})')
|
||||
t('')
|
||||
t('')
|
||||
t('def merge_result_dicts(defaults: dict[str, typing.Any], vals: dict[str, typing.Any]) -> dict[str, typing.Any]:')
|
||||
t(' ans = {}')
|
||||
t(' for k, v in defaults.items():')
|
||||
t(' if isinstance(v, dict):')
|
||||
t(' ans[k] = merge_dicts(v, vals.get(k, {}))')
|
||||
t(' elif k in actions:')
|
||||
t(' ans[k] = v + vals.get(k, [])')
|
||||
t(' else:')
|
||||
t(' ans[k] = vals.get(k, v)')
|
||||
t(' return ans')
|
||||
tc_imports.add(('kitty.conf.utils', 'merge_dicts'))
|
||||
|
||||
t('')
|
||||
t('')
|
||||
t('parser = Parser()')
|
||||
t('')
|
||||
t('')
|
||||
t('def parse_conf_item(key: str, val: str, ans: dict[str, typing.Any]) -> bool:')
|
||||
t(' func = getattr(parser, key, None)')
|
||||
t(' if func is not None:')
|
||||
t(' func(val, ans)')
|
||||
t(' return True')
|
||||
t(' return False')
|
||||
|
||||
preamble = ['# generated by gen-config.py DO NOT edit', '']
|
||||
a = preamble.append
|
||||
|
||||
def output_imports(imports: set[tuple[str, str]], add_module_imports: bool = True) -> None:
|
||||
a('# isort: skip_file')
|
||||
a('import typing')
|
||||
a('import collections.abc # noqa: F401, RUF100')
|
||||
seen_mods = {'typing'}
|
||||
mmap: dict[str, list[str]] = {}
|
||||
for mod, name in imports:
|
||||
mmap.setdefault(mod, []).append(name)
|
||||
for mod in sorted(mmap):
|
||||
names = list(filter(None, sorted(mmap[mod])))
|
||||
if names:
|
||||
lines = textwrap.wrap(', '.join(names), 100)
|
||||
if len(lines) == 1:
|
||||
s = lines[0]
|
||||
else:
|
||||
s = '\n '.join(lines)
|
||||
s = f'(\n {s}\n)'
|
||||
a(f'from {mod} import {s}')
|
||||
else:
|
||||
s = ''
|
||||
if add_module_imports and mod not in seen_mods and mod != s:
|
||||
a(f'import {mod}')
|
||||
seen_mods.add(mod)
|
||||
|
||||
output_imports(imports)
|
||||
a('')
|
||||
if choices:
|
||||
for name, cdefn in choices.items():
|
||||
a(f'{name} = {cdefn}')
|
||||
|
||||
a('')
|
||||
a('option_names = (')
|
||||
for option_name in sorted(option_names, key=natural_keys):
|
||||
a(f' {option_name!r},')
|
||||
a(')')
|
||||
class_def = '\n'.join(preamble + ['', ''] + class_lines)
|
||||
|
||||
preamble = ['# generated by gen-config.py DO NOT edit', '']
|
||||
a = preamble.append
|
||||
output_imports(tc_imports, False)
|
||||
|
||||
return class_def, '\n'.join(preamble + ['', ''] + tc_lines)
|
||||
|
||||
|
||||
def generate_c_conversion(loc: str, ctypes: list[Option | MultiOption]) -> str:
|
||||
lines: list[str] = []
|
||||
basic_converters = {
|
||||
'int': 'PyLong_AsLong',
|
||||
'uint': 'PyLong_AsUnsignedLong',
|
||||
'bool': 'PyObject_IsTrue',
|
||||
'float': 'PyFloat_AsFloat',
|
||||
'double': 'PyFloat_AsDouble',
|
||||
'percent': 'percent',
|
||||
'time': 'parse_s_double_to_monotonic_t',
|
||||
'time-ms': 'parse_ms_long_to_monotonic_t',
|
||||
}
|
||||
|
||||
for opt in ctypes:
|
||||
lines.append('')
|
||||
lines.append(f'static void\nconvert_from_python_{opt.name}(PyObject *val, Options *opts) {{')
|
||||
is_special = opt.ctype.startswith('!')
|
||||
if is_special:
|
||||
func = opt.ctype[1:]
|
||||
lines.append(f' {func}(val, opts);')
|
||||
else:
|
||||
func = basic_converters.get(opt.ctype, opt.ctype)
|
||||
lines.append(f' opts->{opt.name} = {func}(val);')
|
||||
lines.append('}')
|
||||
lines.append('')
|
||||
lines.append(f'static void\nconvert_from_opts_{opt.name}(PyObject *py_opts, Options *opts) {{')
|
||||
lines.append(f' PyObject *ret = PyObject_GetAttrString(py_opts, "{opt.name}");')
|
||||
lines.append(' if (ret == NULL) return;')
|
||||
lines.append(f' convert_from_python_{opt.name}(ret, opts);')
|
||||
lines.append(' Py_DECREF(ret);')
|
||||
lines.append('}')
|
||||
|
||||
lines.append('')
|
||||
lines.append('static bool\nconvert_opts_from_python_opts(PyObject *py_opts, Options *opts) {')
|
||||
for opt in ctypes:
|
||||
lines.append(f' convert_from_opts_{opt.name}(py_opts, opts);')
|
||||
lines.append(' if (PyErr_Occurred()) return false;')
|
||||
lines.append(' return true;')
|
||||
lines.append('}')
|
||||
|
||||
preamble = ['// generated by gen-config.py DO NOT edit', '// vim:fileencoding=utf-8', '#pragma once', '#include "to-c.h"']
|
||||
return '\n'.join(preamble + ['', ''] + lines)
|
||||
|
||||
|
||||
def write_output(loc: str, defn: Definition, extra_after_type_defn: str = '') -> None:
|
||||
cls, tc = generate_class(defn, loc)
|
||||
ctypes = []
|
||||
has_secret = []
|
||||
for opt in defn.root_group.iter_all_non_groups():
|
||||
if isinstance(opt, (Option, MultiOption)) and opt.ctype:
|
||||
ctypes.append(opt)
|
||||
if getattr(opt, 'has_secret', False):
|
||||
has_secret.append(opt.name)
|
||||
with open(os.path.join(*loc.split('.'), 'options', 'types.py'), 'w') as f:
|
||||
f.write(f'{cls}\n')
|
||||
f.write(extra_after_type_defn)
|
||||
if has_secret:
|
||||
f.write('\n\nsecret_options = ' + repr(tuple(has_secret)))
|
||||
with open(os.path.join(*loc.split('.'), 'options', 'parse.py'), 'w') as f:
|
||||
f.write(f'{tc}\n')
|
||||
if ctypes:
|
||||
c = generate_c_conversion(loc, ctypes)
|
||||
with open(os.path.join(*loc.split('.'), 'options', 'to-c-generated.h'), 'w') as f:
|
||||
f.write(f'{c}\n')
|
||||
|
||||
|
||||
def go_type_data(parser_func: ParserFuncType, ctype: str, is_multiple: bool = False) -> tuple[str, str]:
|
||||
if ctype or is_multiple:
|
||||
if ctype in ('string', ''):
|
||||
if is_multiple:
|
||||
return 'string', '[]string{val}, nil'
|
||||
return 'string', 'val, nil'
|
||||
if ctype.startswith('strdict_'):
|
||||
_, rsep, fsep = ctype.split('_', 2)
|
||||
return 'map[string]string', f'config.ParseStrDict(val, `{rsep}`, `{fsep}`)'
|
||||
return f'*{ctype}', f'Parse{ctype}(val)'
|
||||
assert isinstance(parser_func, types.FunctionType)
|
||||
p = parser_func.__name__
|
||||
if p == 'int':
|
||||
return 'int64', 'strconv.ParseInt(val, 10, 64)'
|
||||
if p == 'str':
|
||||
return 'string', 'val, nil'
|
||||
if p == 'float':
|
||||
return 'float64', 'strconv.ParseFloat(val, 10, 64)'
|
||||
if p == 'to_bool':
|
||||
return 'bool', 'config.StringToBool(val), nil'
|
||||
if p == 'to_color':
|
||||
return 'style.RGBA', 'style.ParseColor(val)'
|
||||
if p == 'to_color_or_none':
|
||||
return 'style.NullableColor', 'style.ParseColorOrNone(val)'
|
||||
if p == 'positive_int':
|
||||
return 'uint64', 'strconv.ParseUint(val, 10, 64)'
|
||||
if p == 'positive_float':
|
||||
return 'float64', 'config.PositiveFloat(val)'
|
||||
if p == 'unit_float':
|
||||
return 'float64', 'config.UnitFloat(val)'
|
||||
if p == 'python_string':
|
||||
return 'string', 'config.StringLiteral(val)'
|
||||
th = get_type_hints(parser_func)
|
||||
rettype = th['return']
|
||||
return {int: 'int64', str: 'string', float: 'float64'}[rettype], f'{p}(val)'
|
||||
|
||||
|
||||
mod_map = {
|
||||
'shift': 'shift',
|
||||
'⇧': 'shift',
|
||||
'alt': 'alt',
|
||||
'option': 'alt',
|
||||
'opt': 'alt',
|
||||
'⌥': 'alt',
|
||||
'super': 'super',
|
||||
'command': 'super',
|
||||
'cmd': 'super',
|
||||
'⌘': 'super',
|
||||
'control': 'ctrl',
|
||||
'ctrl': 'ctrl',
|
||||
'⌃': 'ctrl',
|
||||
'hyper': 'hyper',
|
||||
'meta': 'meta',
|
||||
'num_lock': 'num_lock',
|
||||
'caps_lock': 'caps_lock',
|
||||
}
|
||||
|
||||
|
||||
def normalize_shortcut(spec: str) -> str:
|
||||
if spec.endswith('+'):
|
||||
spec = spec[:-1] + 'plus'
|
||||
parts = spec.lower().split('+')
|
||||
key = parts[-1]
|
||||
if len(parts) == 1:
|
||||
return key
|
||||
mods = parts[:-1]
|
||||
return '+'.join(mod_map.get(x, x) for x in mods) + '+' + key
|
||||
|
||||
|
||||
def normalize_shortcuts(spec: str) -> Iterator[str]:
|
||||
spec = spec.replace('++', '+plus')
|
||||
spec = re.sub(r'([^+])>', '\\1\0', spec)
|
||||
for x in spec.split('\0'):
|
||||
yield normalize_shortcut(x)
|
||||
|
||||
|
||||
def gen_go_code(defn: Definition) -> str:
|
||||
lines = [
|
||||
'import "fmt"',
|
||||
'import "strconv"',
|
||||
'import "github.com/kovidgoyal/kitty/tools/config"',
|
||||
'import "github.com/kovidgoyal/kitty/tools/utils/style"',
|
||||
'var _ = fmt.Println',
|
||||
'var _ = config.StringToBool',
|
||||
'var _ = strconv.Atoi',
|
||||
'var _ = style.ParseColor',
|
||||
]
|
||||
a = lines.append
|
||||
keyboard_shortcuts = tuple(defn.iter_all_maps())
|
||||
choices = {}
|
||||
go_types = {}
|
||||
go_parsers = {}
|
||||
defaults = {}
|
||||
multiopts = {''}
|
||||
for option in sorted(defn.iter_all_options(), key=lambda a: natural_keys(a.name)):
|
||||
name = option.name.capitalize()
|
||||
if isinstance(option, MultiOption):
|
||||
go_types[name], go_parsers[name] = go_type_data(option.parser_func, option.ctype, True)
|
||||
multiopts.add(name)
|
||||
defval = []
|
||||
for x in option.items:
|
||||
if x.add_to_default:
|
||||
defval.append(option.parser_func(x.defval_as_str))
|
||||
defaults[name] = defval
|
||||
else:
|
||||
defaults[name] = option.parser_func(option.defval_as_string)
|
||||
if option.choices:
|
||||
choices[name] = option.choices
|
||||
go_types[name] = f'{name}_Choice_Type'
|
||||
go_parsers[name] = f'Parse_{name}(val)'
|
||||
continue
|
||||
go_types[name], go_parsers[name] = go_type_data(option.parser_func, option.ctype)
|
||||
|
||||
for oname in choices:
|
||||
a(f'type {go_types[oname]} int')
|
||||
a('type Config struct {')
|
||||
for name, gotype in go_types.items():
|
||||
if name in multiopts:
|
||||
a(f'{name} []{gotype}')
|
||||
else:
|
||||
a(f'{name} {gotype}')
|
||||
if keyboard_shortcuts:
|
||||
a('KeyboardShortcuts []*config.KeyAction')
|
||||
a('}')
|
||||
|
||||
def cval(x: str) -> str:
|
||||
return x.replace('-', '_')
|
||||
|
||||
a('func NewConfig() *Config {')
|
||||
a('return &Config{')
|
||||
from kitty.fast_data_types import Color
|
||||
|
||||
def basic_defval(d: Any) -> str:
|
||||
if isinstance(d, str):
|
||||
dval = f'{name}_{cval(d)}' if name in choices else f'`{d}`'
|
||||
elif isinstance(d, bool):
|
||||
dval = repr(d).lower()
|
||||
elif isinstance(d, dict):
|
||||
dval = 'map[string]string{'
|
||||
for k, v in d.items():
|
||||
dval += f'"{serialize_as_go_string(k)}": "{serialize_as_go_string(v)}",'
|
||||
dval += '}'
|
||||
elif isinstance(d, list):
|
||||
dval = '[]string{'
|
||||
for k in d:
|
||||
dval += f'"{serialize_as_go_string(k)}",'
|
||||
dval += '}'
|
||||
elif isinstance(d, Color):
|
||||
dval = f'style.RGBA{{Red:{d.red}, Green: {d.green}, Blue: {d.blue}}}'
|
||||
if 'NullableColor' in go_types[name]:
|
||||
dval = f'style.NullableColor{{IsSet: true, Color:{dval}}}'
|
||||
else:
|
||||
dval = repr(d)
|
||||
return dval
|
||||
|
||||
for name, pname in go_parsers.items():
|
||||
d = defaults[name]
|
||||
if d:
|
||||
a(f'{name}: {basic_defval(d)},')
|
||||
if keyboard_shortcuts:
|
||||
a('KeyboardShortcuts: []*config.KeyAction{')
|
||||
for sc in keyboard_shortcuts:
|
||||
options, leftover = parse_options_for_map(sc.parseable_text)
|
||||
allow_fallback = ','.join(x.value for x in options.allow_fallback)
|
||||
key_spec, action = leftover.split(None, 1)
|
||||
aname, _, aargs = action.partition(' ')
|
||||
aname = serialize_as_go_string(aname)
|
||||
aargs = serialize_as_go_string(aargs)
|
||||
fb = f', AllowFallback: "{serialize_as_go_string(allow_fallback)}"'
|
||||
a(f'{{Name: "{aname}", Args: "{aargs}"{fb}, Normalized_keys: []string{{')
|
||||
ns = normalize_shortcuts(key_spec)
|
||||
a(', '.join(f'"{serialize_as_go_string(x)}"' for x in ns) + ',')
|
||||
a('}},')
|
||||
a('},')
|
||||
|
||||
a('}}')
|
||||
|
||||
for oname, choice_vals in choices.items():
|
||||
a('const (')
|
||||
for i, c in enumerate(choice_vals):
|
||||
c = cval(c)
|
||||
if i == 0:
|
||||
a(f'{oname}_{c} {oname}_Choice_Type = iota')
|
||||
else:
|
||||
a(f'{oname}_{c}')
|
||||
a(')')
|
||||
a(f'func (x {oname}_Choice_Type) String() string {{')
|
||||
a('switch x {')
|
||||
a('default: return ""')
|
||||
for c in choice_vals:
|
||||
a(f'case {oname}_{cval(c)}: return "{c}"')
|
||||
a('}}')
|
||||
a(f'func {go_parsers[oname].split("(")[0]}(val string) (ans {go_types[oname]}, err error) {{')
|
||||
a('switch val {')
|
||||
for c in choice_vals:
|
||||
a(f'case "{c}": return {oname}_{cval(c)}, nil')
|
||||
vals = ', '.join(choice_vals)
|
||||
a(f'default: return ans, fmt.Errorf("%#v is not a valid value for %s. Valid values are: %s", val, "{c}", "{vals}")')
|
||||
a('}}')
|
||||
|
||||
has_parsers = bool(go_parsers or keyboard_shortcuts)
|
||||
a('func (c *Config) Parse(key, val string) (err error) {')
|
||||
if has_parsers:
|
||||
a('switch key {')
|
||||
a('default: return fmt.Errorf("Unknown configuration key: %#v", key)')
|
||||
for oname, pname in go_parsers.items():
|
||||
ol = oname.lower()
|
||||
is_multiple = oname in multiopts
|
||||
a(f'case "{ol}":')
|
||||
if is_multiple:
|
||||
a(f'var temp_val []{go_types[oname]}')
|
||||
else:
|
||||
a(f'var temp_val {go_types[oname]}')
|
||||
a(f'temp_val, err = {pname}')
|
||||
a(f'if err != nil {{ return fmt.Errorf("Failed to parse {ol} = %#v with error: %w", val, err) }}')
|
||||
if is_multiple:
|
||||
a(f'c.{oname} = append(c.{oname}, temp_val...)')
|
||||
else:
|
||||
a(f'c.{oname} = temp_val')
|
||||
if keyboard_shortcuts:
|
||||
a('case "map":')
|
||||
a('tempsc, err := config.ParseMap(val)')
|
||||
a('if err != nil { return fmt.Errorf("Failed to parse map = %#v with error: %w", val, err) }')
|
||||
a('c.KeyboardShortcuts = append(c.KeyboardShortcuts, tempsc)')
|
||||
a('}')
|
||||
a('return}')
|
||||
else:
|
||||
a('return fmt.Errorf("Unknown configuration key: %#v", key)')
|
||||
a('}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# To use run it as:
|
||||
# kitty +runpy 'from kitty.conf.generate import main; main()' /path/to/kitten/file.py
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
from kittens.runner import path_to_custom_kitten, resolved_kitten
|
||||
from kitty.constants import config_dir
|
||||
|
||||
kitten = sys.argv[-1]
|
||||
if not kitten.endswith('.py'):
|
||||
kitten += '.py'
|
||||
kitten = resolved_kitten(kitten)
|
||||
path = os.path.realpath(path_to_custom_kitten(config_dir, kitten))
|
||||
if not os.path.dirname(path):
|
||||
raise SystemExit(f'No custom kitten named {kitten} found')
|
||||
sys.path.insert(0, os.path.dirname(path))
|
||||
package_name = os.path.basename(os.path.dirname(path))
|
||||
m = importlib.import_module('kitten_options_definition')
|
||||
defn = getattr(m, 'definition')
|
||||
loc = package_name
|
||||
cls, tc = generate_class(defn, loc)
|
||||
with open(os.path.join(os.path.dirname(path), 'kitten_options_types.py'), 'w') as f:
|
||||
f.write(f'{cls}\n')
|
||||
with open(os.path.join(os.path.dirname(path), 'kitten_options_parse.py'), 'w') as f:
|
||||
f.write(f'{tc}\n')
|
||||
@@ -0,0 +1,781 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import builtins
|
||||
import re
|
||||
import textwrap
|
||||
import typing
|
||||
from collections.abc import Callable, Iterable, Iterator, Sequence
|
||||
from functools import lru_cache
|
||||
from importlib import import_module
|
||||
from re import Match
|
||||
from typing import Any, Optional, Union, cast
|
||||
|
||||
import kitty.conf.utils as generic_parsers
|
||||
from kitty.constants import website_url
|
||||
from kitty.types import run_once
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
Only = typing.Literal['macos', 'linux', '']
|
||||
else:
|
||||
Only = str
|
||||
|
||||
|
||||
class Unset:
|
||||
def __bool__(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
unset = Unset()
|
||||
ParserFuncType = Callable[[str], Any]
|
||||
|
||||
|
||||
def expand_opt_references(conf_name: str, text: str) -> str:
|
||||
conf_name += '.'
|
||||
|
||||
def expand(m: 'Match[str]') -> str:
|
||||
ref = m.group(1)
|
||||
if '<' not in ref and '.' not in ref:
|
||||
# full ref
|
||||
return f':opt:`{ref} <{conf_name}{ref}>`'
|
||||
return str(m.group())
|
||||
|
||||
return re.sub(r':opt:`(.+?)`', expand, text)
|
||||
|
||||
|
||||
@run_once
|
||||
def ref_map() -> dict[str, dict[str, str]]:
|
||||
import json
|
||||
|
||||
from ..fast_data_types import get_docs_ref_map
|
||||
|
||||
ans: dict[str, dict[str, str]] = json.loads(get_docs_ref_map())
|
||||
return ans
|
||||
|
||||
|
||||
def resolve_ref(ref: str, website_url: Callable[[str], str] = website_url) -> str:
|
||||
m = ref_map()
|
||||
href = m['ref'].get(ref, '')
|
||||
prefix, rest = ref.partition('-')[::2]
|
||||
if href:
|
||||
pass
|
||||
elif ref.startswith('conf-kitty-'):
|
||||
href = f'conf#{ref}'
|
||||
elif ref.startswith('conf-kitten-'):
|
||||
parts = ref.split('-')
|
||||
href = 'kittens/' + parts[2] + f'/#{ref}'
|
||||
elif ref.startswith('at_'):
|
||||
base = ref.split('_', 1)[1]
|
||||
href = 'remote-control/#at-' + base.replace('_', '-')
|
||||
elif ref.startswith('at-'):
|
||||
base = ref.split('-', 1)[1]
|
||||
href = 'remote-control/#at-' + base.replace('_', '-')
|
||||
elif ref.startswith('action-group-'):
|
||||
href = f'actions/#{ref}'
|
||||
elif prefix == 'action':
|
||||
href = f'actions/#{rest.replace("_", "-")}'
|
||||
elif prefix in ('term', 'envvar'):
|
||||
href = 'glossary/#' + ref
|
||||
elif prefix == 'doc':
|
||||
href = rest.lstrip('/')
|
||||
elif prefix in ('issues', 'pull', 'discussions'):
|
||||
t, num = ref.partition(':')[::2]
|
||||
href = f'https://github.com/kovidgoyal/kitty/{prefix}/{rest}'
|
||||
if not (href.startswith('https://') or href.startswith('http://')):
|
||||
href = website_url(href)
|
||||
return href
|
||||
|
||||
|
||||
def remove_markup(text: str) -> str:
|
||||
|
||||
imap = {'iss': 'issues-', 'pull': 'pull-', 'disc': 'discussions-'}
|
||||
|
||||
def extract(m: 'Match[str]') -> tuple[str, str]:
|
||||
parts = m.group(2).split('<')
|
||||
t = parts[0].strip()
|
||||
q = parts[-1].rstrip('>')
|
||||
return t, q
|
||||
|
||||
def sub(m: 'Match[str]') -> str:
|
||||
key = m.group(1)
|
||||
if key in ('ref', 'iss', 'pull', 'disc'):
|
||||
t, q = extract(m)
|
||||
q = imap.get(key, '') + q
|
||||
url = resolve_ref(q)
|
||||
if not url:
|
||||
raise KeyError(f'Failed to resolve :{m.group(1)}: {q}')
|
||||
return f'{t} <{url}>'
|
||||
if key == 'doc':
|
||||
t, q = extract(m)
|
||||
return f'{t} <{website_url(q)}>'
|
||||
if key in ('term', 'option'):
|
||||
t, _ = extract(m)
|
||||
return t
|
||||
if key in ('ac', 'opt'):
|
||||
t, q = extract(m)
|
||||
return f'{t} {q}' if q and q != t else t
|
||||
if key == 'code':
|
||||
return m.group(2).replace('\\\\', '\\')
|
||||
|
||||
return str(m.group(2))
|
||||
|
||||
return re.sub(r':([a-zA-Z0-9]+):`(.+?)`', sub, text, flags=re.DOTALL)
|
||||
|
||||
|
||||
def strip_inline_literal(text: str) -> str:
|
||||
return re.sub(r'``([^`]+)``', r'`\1`', text, flags=re.DOTALL)
|
||||
|
||||
|
||||
def iter_blocks(lines: Iterable[str]) -> Iterator[tuple[list[str], int]]:
|
||||
current_block: list[str] = []
|
||||
prev_indent = 0
|
||||
for line in lines:
|
||||
indent_size = len(line) - len(line.lstrip())
|
||||
if indent_size != prev_indent or not line:
|
||||
if current_block:
|
||||
yield current_block, prev_indent
|
||||
current_block = []
|
||||
prev_indent = indent_size
|
||||
if not line:
|
||||
yield [''], 100
|
||||
else:
|
||||
current_block.append(line)
|
||||
if current_block:
|
||||
yield current_block, indent_size
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def block_wrapper(comment_symbol: str) -> textwrap.TextWrapper:
|
||||
return textwrap.TextWrapper(initial_indent=comment_symbol, subsequent_indent=comment_symbol, width=70, break_long_words=False)
|
||||
|
||||
|
||||
def wrapped_block(lines: Iterable[str], comment_symbol: str = '#: ') -> Iterator[str]:
|
||||
wrapper = block_wrapper(comment_symbol)
|
||||
for block, indent_size in iter_blocks(lines):
|
||||
if indent_size > 0:
|
||||
for line in block:
|
||||
if not line:
|
||||
yield line
|
||||
else:
|
||||
yield comment_symbol + line
|
||||
else:
|
||||
for line in wrapper.wrap('\n'.join(block)):
|
||||
yield line
|
||||
|
||||
|
||||
def render_block(text: str, comment_symbol: str = '#: ') -> str:
|
||||
text = remove_markup(text)
|
||||
text = strip_inline_literal(text)
|
||||
lines = text.splitlines()
|
||||
return '\n'.join(wrapped_block(lines, comment_symbol))
|
||||
|
||||
|
||||
class CoalescedIteratorData:
|
||||
option_groups: dict[int, list['Option']] = {}
|
||||
action_groups: dict[str, list['Mapping']] = {}
|
||||
coalesced: set[int] = set()
|
||||
initialized: bool = False
|
||||
kitty_mod: str = 'kitty_mod'
|
||||
|
||||
def initialize(self, root: 'Group') -> None:
|
||||
if self.initialized:
|
||||
return
|
||||
self.root = root
|
||||
option_groups = self.option_groups = {}
|
||||
current_group: list[Option] = []
|
||||
action_groups: dict[str, list[Mapping]] = {}
|
||||
self.action_groups = action_groups
|
||||
coalesced = self.coalesced = set()
|
||||
self.kitty_mod = 'kitty_mod'
|
||||
for item in root.iter_all_non_groups():
|
||||
if isinstance(item, Option):
|
||||
if item.name == 'kitty_mod':
|
||||
self.kitty_mod = item.defval_as_string
|
||||
if current_group:
|
||||
if item.needs_coalescing:
|
||||
current_group.append(item)
|
||||
coalesced.add(id(item))
|
||||
continue
|
||||
option_groups[id(current_group[0])] = current_group[1:]
|
||||
current_group = [item]
|
||||
else:
|
||||
current_group.append(item)
|
||||
elif isinstance(item, Mapping):
|
||||
if item.name in action_groups:
|
||||
coalesced.add(id(item))
|
||||
action_groups[item.name].append(item)
|
||||
else:
|
||||
action_groups[item.name] = []
|
||||
if current_group:
|
||||
option_groups[id(current_group[0])] = current_group[1:]
|
||||
|
||||
def option_group_for_option(self, opt: 'Option') -> list['Option']:
|
||||
return self.option_groups.get(id(opt), [])
|
||||
|
||||
def action_group_for_action(self, ac: 'Mapping') -> list['Mapping']:
|
||||
return self.action_groups.get(ac.name, [])
|
||||
|
||||
|
||||
class Option:
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
defval: str,
|
||||
macos_default: Unset | str,
|
||||
parser_func: ParserFuncType,
|
||||
long_text: str,
|
||||
documented: bool,
|
||||
group: 'Group',
|
||||
choices: tuple[str, ...],
|
||||
ctype: str,
|
||||
has_secret: bool = False,
|
||||
):
|
||||
self.name = name
|
||||
self.ctype = ctype
|
||||
self.defval_as_string = defval
|
||||
self.macos_defval = macos_default
|
||||
self.long_text = long_text
|
||||
self.documented = documented
|
||||
self.group = group
|
||||
self.parser_func = parser_func
|
||||
self.choices = choices
|
||||
self.has_secret = has_secret
|
||||
|
||||
@property
|
||||
def needs_coalescing(self) -> bool:
|
||||
return self.documented and not self.long_text
|
||||
|
||||
@property
|
||||
def is_color_table_color(self) -> bool:
|
||||
return self.name.startswith('color') and self.name[5:].isdigit()
|
||||
|
||||
def as_conf(self, commented: bool = False, level: int = 0, option_group: Sequence['Option'] = ()) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
if not self.documented:
|
||||
return ans
|
||||
if option_group:
|
||||
sz = max(len(self.name), max(len(o.name) for o in option_group))
|
||||
a(f'{self.name.ljust(sz)} {self.defval_as_string}'.rstrip())
|
||||
for o in option_group:
|
||||
a(f'{o.name.ljust(sz)} {o.defval_as_string}'.rstrip())
|
||||
else:
|
||||
a(f'{self.name} {self.defval_as_string}'.rstrip())
|
||||
if self.long_text:
|
||||
a('')
|
||||
a(render_block(self.long_text))
|
||||
a('')
|
||||
return ans
|
||||
|
||||
def as_rst(
|
||||
self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str, level: int = 0, option_group: Sequence['Option'] = ()
|
||||
) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
if not self.documented:
|
||||
return ans
|
||||
mopts = [self] + list(option_group)
|
||||
a('.. opt:: ' + ', '.join(f'{conf_name}.{mo.name}' for mo in mopts))
|
||||
if any(mo.defval_as_string for mo in mopts):
|
||||
a('.. code-block:: conf')
|
||||
a('')
|
||||
sz = max(len(x.name) for x in mopts)
|
||||
for mo in mopts:
|
||||
a((' {:%ds} {}' % sz).format(mo.name, mo.defval_as_string))
|
||||
a('')
|
||||
if self.long_text:
|
||||
a(expand_opt_references(conf_name, self.long_text))
|
||||
a('')
|
||||
return ans
|
||||
|
||||
|
||||
class MultiVal:
|
||||
def __init__(self, val_as_str: str, add_to_default: bool, documented: bool, only: Only) -> None:
|
||||
self.defval_as_str = val_as_str
|
||||
self.documented = documented
|
||||
self.only = only
|
||||
self.add_to_default = add_to_default
|
||||
|
||||
|
||||
class MultiOption:
|
||||
def __init__(self, name: str, parser_func: ParserFuncType, long_text: str, group: 'Group', ctype: str, has_secret: bool = False):
|
||||
self.name = name
|
||||
self.ctype = ctype
|
||||
self.parser_func = parser_func
|
||||
self.long_text = long_text
|
||||
self.group = group
|
||||
self.has_secret = has_secret
|
||||
self.items: list[MultiVal] = []
|
||||
|
||||
def add_value(self, val_as_str: str, add_to_default: bool, documented: bool, only: Only) -> None:
|
||||
self.items.append(MultiVal(val_as_str, add_to_default, documented, only))
|
||||
|
||||
def __iter__(self) -> Iterator[MultiVal]:
|
||||
yield from self.items
|
||||
|
||||
def as_conf(self, commented: bool = False, level: int = 0) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
documented = False
|
||||
for k in self.items:
|
||||
if k.documented:
|
||||
documented = True
|
||||
if k.add_to_default:
|
||||
a(f'{self.name} {k.defval_as_str}'.rstrip())
|
||||
else:
|
||||
# Comment out multi-options that have no default values
|
||||
a(f'# {self.name}'.rstrip())
|
||||
if not k.add_to_default and k.defval_as_str:
|
||||
a('')
|
||||
a(f'#: E.g. {self.name} {k.defval_as_str}'.rstrip())
|
||||
if self.long_text and documented:
|
||||
a('')
|
||||
a(render_block(self.long_text))
|
||||
a('')
|
||||
return ans
|
||||
|
||||
def as_rst(self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str, level: int = 0) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
a(f'.. opt:: {conf_name}.{self.name}')
|
||||
documented = tuple(x for x in self.items if x.documented)
|
||||
if any(k.defval_as_str for k in documented):
|
||||
defaults = tuple(x for x in documented if x.add_to_default)
|
||||
if defaults:
|
||||
a('.. code-block:: conf')
|
||||
a('')
|
||||
for k in defaults:
|
||||
a(f' {self.name:s} {k.defval_as_str}'.rstrip())
|
||||
else:
|
||||
a('')
|
||||
a('Has no default values. Example values are shown below:')
|
||||
a('')
|
||||
a('.. code-block:: conf')
|
||||
a('')
|
||||
for k in self.items:
|
||||
a(f' {self.name:s} {k.defval_as_str}'.rstrip())
|
||||
a('')
|
||||
if self.long_text:
|
||||
a(expand_opt_references(conf_name, self.long_text))
|
||||
a('')
|
||||
return ans
|
||||
|
||||
|
||||
class Mapping:
|
||||
add_to_default: bool
|
||||
short_text: str
|
||||
long_text: str
|
||||
documented: bool
|
||||
setting_name: str
|
||||
name: str
|
||||
only: Only
|
||||
|
||||
@property
|
||||
def parseable_text(self) -> str:
|
||||
return ''
|
||||
|
||||
@property
|
||||
def key_text(self) -> str:
|
||||
return ''
|
||||
|
||||
def as_conf(self, commented: bool = False, level: int = 0, action_group: list['Mapping'] = []) -> list[str]:
|
||||
ans: list[str] = []
|
||||
if not self.documented:
|
||||
return ans
|
||||
a = ans.append
|
||||
if self.short_text:
|
||||
a(render_block(self.short_text.strip())), a('')
|
||||
for sc in [self] + action_group:
|
||||
if sc.documented:
|
||||
prefix = '' if sc.add_to_default else '#:: E.g. '
|
||||
a(f'{prefix}{sc.setting_name} {sc.parseable_text}')
|
||||
if self.long_text:
|
||||
a(''), a(render_block(self.long_text.strip(), '#:: '))
|
||||
a('')
|
||||
return ans
|
||||
|
||||
def as_rst(
|
||||
self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str, level: int = 0, action_group: list['Mapping'] = []
|
||||
) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
if not self.documented:
|
||||
return ans
|
||||
if not self.short_text:
|
||||
raise ValueError(f'The shortcut for {self.name} has no short_text')
|
||||
sc_text = f'{conf_name}.{self.short_text}'
|
||||
shortcut_slugs[f'{conf_name}.{self.name}'] = (sc_text, self.key_text.replace('kitty_mod', kitty_mod))
|
||||
a(f'.. shortcut:: {sc_text}')
|
||||
block_started = False
|
||||
for sc in [self] + action_group:
|
||||
if sc.add_to_default and sc.documented:
|
||||
if not block_started:
|
||||
a('.. code-block:: conf')
|
||||
a('')
|
||||
block_started = True
|
||||
suffix = ''
|
||||
if sc.only == 'macos':
|
||||
suffix = ' 🍎'
|
||||
elif sc.only == 'linux':
|
||||
suffix = ' 🐧'
|
||||
a(f' {sc.setting_name} {sc.parseable_text.replace("kitty_mod", kitty_mod)}{suffix}')
|
||||
a('')
|
||||
if self.long_text:
|
||||
a('')
|
||||
a(expand_opt_references(conf_name, self.long_text))
|
||||
a('')
|
||||
|
||||
return ans
|
||||
|
||||
|
||||
class ShortcutMapping(Mapping):
|
||||
setting_name: str = 'map'
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
raw_definition: str,
|
||||
short_text: str,
|
||||
long_text: str,
|
||||
add_to_default: bool,
|
||||
documented: bool,
|
||||
group: 'Group',
|
||||
only: Only,
|
||||
):
|
||||
self.name = name
|
||||
self.only = only
|
||||
self._raw_definition = raw_definition
|
||||
self.short_text = short_text
|
||||
self.long_text = long_text
|
||||
self.documented = documented
|
||||
self.add_to_default = add_to_default
|
||||
self.group = group
|
||||
from kitty.options.utils import parse_options_for_map
|
||||
|
||||
_, remainder = parse_options_for_map(raw_definition)
|
||||
parts = remainder.split(maxsplit=1)
|
||||
self.key = parts[0]
|
||||
self.action_def = parts[1] if len(parts) > 1 else ''
|
||||
|
||||
@property
|
||||
def parseable_text(self) -> str:
|
||||
return self._raw_definition
|
||||
|
||||
@property
|
||||
def key_text(self) -> str:
|
||||
return self.key
|
||||
|
||||
|
||||
class MouseMapping(Mapping):
|
||||
setting_name: str = 'mouse_map'
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
button: str,
|
||||
event: str,
|
||||
modes: str,
|
||||
action_def: str,
|
||||
short_text: str,
|
||||
long_text: str,
|
||||
add_to_default: bool,
|
||||
documented: bool,
|
||||
group: 'Group',
|
||||
only: Only,
|
||||
):
|
||||
self.name = name
|
||||
self.only = only
|
||||
self.button = button
|
||||
self.event = event
|
||||
self.modes = modes
|
||||
self.action_def = action_def
|
||||
self.short_text = short_text
|
||||
self.long_text = long_text
|
||||
self.documented = documented
|
||||
self.add_to_default = add_to_default
|
||||
self.group = group
|
||||
|
||||
@property
|
||||
def parseable_text(self) -> str:
|
||||
return f'{self.button} {self.event} {self.modes} {self.action_def}'
|
||||
|
||||
@property
|
||||
def key_text(self) -> str:
|
||||
return self.button
|
||||
|
||||
|
||||
NonGroups = Union[Option, MultiOption, ShortcutMapping, MouseMapping]
|
||||
GroupItem = Union[NonGroups, 'Group']
|
||||
|
||||
|
||||
class Group:
|
||||
def __init__(self, name: str, title: str, coalesced_iterator_data: CoalescedIteratorData, start_text: str = '', parent: Optional['Group'] = None):
|
||||
self.name = name
|
||||
self.coalesced_iterator_data = coalesced_iterator_data
|
||||
self.title = title
|
||||
self.start_text = start_text
|
||||
self.end_text = ''
|
||||
self.items: list[GroupItem] = []
|
||||
self.parent = parent
|
||||
|
||||
def append(self, item: GroupItem) -> None:
|
||||
self.items.append(item)
|
||||
|
||||
def __iter__(self) -> Iterator[GroupItem]:
|
||||
return iter(self.items)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.items)
|
||||
|
||||
def iter_with_coalesced_options(self) -> Iterator[GroupItem]:
|
||||
for item in self:
|
||||
if id(item) not in self.coalesced_iterator_data.coalesced:
|
||||
yield item
|
||||
|
||||
def iter_all(self) -> Iterator[GroupItem]:
|
||||
for x in self:
|
||||
yield x
|
||||
if isinstance(x, Group):
|
||||
yield from x.iter_all()
|
||||
|
||||
def iter_all_non_groups(self) -> Iterator[NonGroups]:
|
||||
for x in self:
|
||||
if isinstance(x, Group):
|
||||
yield from x.iter_all_non_groups()
|
||||
else:
|
||||
yield x
|
||||
|
||||
def as_rst(self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str = 'kitty_mod', level: int = 0) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
if level:
|
||||
a('')
|
||||
a(f'.. _conf-{conf_name}-{self.name}:')
|
||||
a('')
|
||||
a(self.title)
|
||||
heading_level = '+' if level > 1 else '-'
|
||||
a(heading_level * (len(self.title) + 20))
|
||||
a('')
|
||||
if self.start_text:
|
||||
a(self.start_text)
|
||||
a('')
|
||||
else:
|
||||
ans.extend(('.. default-domain:: conf', ''))
|
||||
|
||||
kitty_mod = self.coalesced_iterator_data.kitty_mod
|
||||
for item in self.iter_with_coalesced_options():
|
||||
if isinstance(item, Option):
|
||||
lines = item.as_rst(conf_name, shortcut_slugs, kitty_mod, option_group=self.coalesced_iterator_data.option_group_for_option(item))
|
||||
elif isinstance(item, Mapping):
|
||||
lines = item.as_rst(conf_name, shortcut_slugs, kitty_mod, level + 1, action_group=self.coalesced_iterator_data.action_group_for_action(item))
|
||||
else:
|
||||
lines = item.as_rst(conf_name, shortcut_slugs, kitty_mod, level + 1)
|
||||
ans.extend(lines)
|
||||
|
||||
if level:
|
||||
if self.end_text:
|
||||
a('')
|
||||
a(self.end_text)
|
||||
return ans
|
||||
|
||||
def as_conf(self, commented: bool = False, level: int = 0) -> list[str]:
|
||||
ans: list[str] = []
|
||||
a = ans.append
|
||||
if level:
|
||||
a('#: ' + self.title + ' {{{')
|
||||
a('')
|
||||
if self.start_text:
|
||||
a(render_block(self.start_text))
|
||||
a('')
|
||||
else:
|
||||
ans.extend(('# vim:fileencoding=utf-8:foldmethod=marker', ''))
|
||||
|
||||
for item in self.iter_with_coalesced_options():
|
||||
if isinstance(item, Option):
|
||||
lines = item.as_conf(option_group=self.coalesced_iterator_data.option_group_for_option(item))
|
||||
elif isinstance(item, Mapping):
|
||||
lines = item.as_conf(commented, level + 1, action_group=self.coalesced_iterator_data.action_group_for_action(item))
|
||||
else:
|
||||
lines = item.as_conf(commented, level + 1)
|
||||
ans.extend(lines)
|
||||
|
||||
if level:
|
||||
if self.end_text:
|
||||
a('')
|
||||
a(render_block(self.end_text))
|
||||
a('#: }}}')
|
||||
a('')
|
||||
else:
|
||||
map_groups = []
|
||||
start: int | None = None
|
||||
count: int | None = None
|
||||
for i, line in enumerate(ans):
|
||||
if line.startswith('map ') or line.startswith('mouse_map '):
|
||||
if start is None:
|
||||
start = i
|
||||
count = 1
|
||||
else:
|
||||
if count is not None:
|
||||
count += 1
|
||||
else:
|
||||
if start is not None and count is not None:
|
||||
map_groups.append((start, count))
|
||||
start = count = None
|
||||
for start, count in map_groups:
|
||||
r = range(start, start + count)
|
||||
sz = max(len(ans[i].split(' ', 3)[1]) for i in r)
|
||||
for i in r:
|
||||
line = ans[i]
|
||||
parts = line.split(' ', 3)
|
||||
parts[1] = parts[1].ljust(sz)
|
||||
ans[i] = ' '.join(parts)
|
||||
|
||||
if commented:
|
||||
ans = [x if x.startswith('#') or not x.strip() else (f'# {x}') for x in ans]
|
||||
else:
|
||||
# Comment out any invalid options that have no value
|
||||
ans = [f'# {x}' if not x.startswith('#') and len(x.strip().split()) == 1 else x for x in ans]
|
||||
|
||||
return ans
|
||||
|
||||
|
||||
def resolve_import(name: str, module: Any = None) -> ParserFuncType:
|
||||
ans = None
|
||||
if name.count('.') > 1:
|
||||
m = import_module(name.rpartition('.')[0])
|
||||
ans = getattr(m, name.rpartition('.')[2])
|
||||
else:
|
||||
ans = getattr(builtins, name, None)
|
||||
if not callable(ans):
|
||||
ans = getattr(generic_parsers, name, None)
|
||||
if not callable(ans):
|
||||
ans = getattr(module, name)
|
||||
if not callable(ans):
|
||||
raise TypeError(f'{name} is not a function')
|
||||
return cast(ParserFuncType, ans)
|
||||
|
||||
|
||||
class Action:
|
||||
def __init__(self, name: str, option_type: str, fields: dict[str, str], imports: Iterable[str]):
|
||||
self.name = name
|
||||
self._parser_func = option_type
|
||||
self.fields = fields
|
||||
self.imports = frozenset(imports)
|
||||
|
||||
def resolve_imports(self, module: Any) -> 'Action':
|
||||
self.parser_func = resolve_import(self._parser_func, module)
|
||||
return self
|
||||
|
||||
|
||||
class Definition:
|
||||
def __init__(self, package: str, *actions: Action, has_color_table: bool = False) -> None:
|
||||
if package.startswith('!'):
|
||||
self.module_for_parsers = import_module(package[1:])
|
||||
else:
|
||||
self.module_for_parsers = import_module(f'{package}.options.utils')
|
||||
self.has_color_table = has_color_table
|
||||
self.coalesced_iterator_data = CoalescedIteratorData()
|
||||
self.root_group = Group('', '', self.coalesced_iterator_data)
|
||||
self.current_group = self.root_group
|
||||
self.option_map: dict[str, Option] = {}
|
||||
self.multi_option_map: dict[str, MultiOption] = {}
|
||||
self.shortcut_map: dict[str, list[ShortcutMapping]] = {}
|
||||
self.mouse_map: dict[str, list[MouseMapping]] = {}
|
||||
self.actions = {a.name: a.resolve_imports(self.module_for_parsers) for a in actions}
|
||||
self.deprecations: dict[ParserFuncType, tuple[str, ...]] = {}
|
||||
|
||||
def iter_all_non_groups(self) -> Iterator[NonGroups]:
|
||||
yield from self.root_group.iter_all_non_groups()
|
||||
|
||||
def iter_all_options(self) -> Iterator[Option | MultiOption]:
|
||||
for x in self.iter_all_non_groups():
|
||||
if isinstance(x, (Option, MultiOption)):
|
||||
yield x
|
||||
|
||||
def iter_all_maps(self, which: str = 'map') -> Iterator[ShortcutMapping | MouseMapping]:
|
||||
for x in self.iter_all_non_groups():
|
||||
if isinstance(x, ShortcutMapping) and which in ('map', '*'):
|
||||
yield x
|
||||
elif isinstance(x, MouseMapping) and which in ('mouse_map', '*'):
|
||||
yield x
|
||||
|
||||
def parser_func(self, name: str) -> ParserFuncType:
|
||||
ans = getattr(builtins, name, None)
|
||||
if callable(ans):
|
||||
return cast(ParserFuncType, ans)
|
||||
ans = getattr(generic_parsers, name, None)
|
||||
if callable(ans):
|
||||
return cast(ParserFuncType, ans)
|
||||
ans = getattr(self.module_for_parsers, name)
|
||||
if not callable(ans):
|
||||
raise TypeError(f'{name} is not a function')
|
||||
return cast(ParserFuncType, ans)
|
||||
|
||||
def add_group(self, name: str, title: str = '', start_text: str = '') -> None:
|
||||
self.current_group = Group(name, title or name, self.coalesced_iterator_data, start_text.strip(), self.current_group)
|
||||
if self.current_group.parent is not None:
|
||||
self.current_group.parent.append(self.current_group)
|
||||
|
||||
def end_group(self, end_text: str = '') -> None:
|
||||
self.current_group.end_text = end_text.strip()
|
||||
if self.current_group.parent is not None:
|
||||
self.current_group = self.current_group.parent
|
||||
|
||||
def add_option(
|
||||
self,
|
||||
name: str,
|
||||
defval: str | float | int | bool,
|
||||
option_type: str = 'str',
|
||||
long_text: str = '',
|
||||
documented: bool = True,
|
||||
add_to_default: bool = False,
|
||||
only: Only = '',
|
||||
macos_default: Unset | str = unset,
|
||||
choices: tuple[str, ...] = (),
|
||||
ctype: str = '',
|
||||
has_secret: bool = False,
|
||||
) -> None:
|
||||
if isinstance(defval, bool):
|
||||
defval = 'yes' if defval else 'no'
|
||||
else:
|
||||
defval = str(defval)
|
||||
is_multiple = name.startswith('+')
|
||||
long_text = long_text.strip()
|
||||
if is_multiple:
|
||||
name = name[1:]
|
||||
if macos_default is not unset:
|
||||
raise TypeError(f'Cannot specify macos_default for is_multiple option: {name} use only instead')
|
||||
is_new = name not in self.multi_option_map
|
||||
if is_new:
|
||||
self.multi_option_map[name] = MultiOption(name, self.parser_func(option_type), long_text, self.current_group, ctype, has_secret)
|
||||
mopt = self.multi_option_map[name]
|
||||
if is_new:
|
||||
self.current_group.append(mopt)
|
||||
mopt.add_value(defval, add_to_default, documented, only)
|
||||
return
|
||||
opt = Option(name, defval, macos_default, self.parser_func(option_type), long_text, documented, self.current_group, choices, ctype, has_secret)
|
||||
self.current_group.append(opt)
|
||||
self.option_map[name] = opt
|
||||
|
||||
def add_map(self, short_text: str, defn: str, long_text: str = '', add_to_default: bool = True, documented: bool = True, only: Only = '') -> None:
|
||||
name, rest = defn.split(maxsplit=1)
|
||||
sc = ShortcutMapping(name, rest, short_text, long_text.strip(), add_to_default, documented, self.current_group, only)
|
||||
self.current_group.append(sc)
|
||||
self.shortcut_map.setdefault(name, []).append(sc)
|
||||
|
||||
def add_mouse_map(self, short_text: str, defn: str, long_text: str = '', add_to_default: bool = True, documented: bool = True, only: Only = '') -> None:
|
||||
name, button, event, modes, action_def = defn.split(maxsplit=4)
|
||||
mm = MouseMapping(name, button, event, modes, action_def, short_text, long_text.strip(), add_to_default, documented, self.current_group, only)
|
||||
self.current_group.append(mm)
|
||||
self.mouse_map.setdefault(name, []).append(mm)
|
||||
|
||||
def add_deprecation(self, parser_name: str, *aliases: str) -> None:
|
||||
self.deprecations[self.parser_func(parser_name)] = aliases
|
||||
|
||||
def as_conf(self, commented: bool = False) -> list[str]:
|
||||
self.coalesced_iterator_data.initialize(self.root_group)
|
||||
return self.root_group.as_conf(commented)
|
||||
|
||||
def as_rst(self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]]) -> list[str]:
|
||||
self.coalesced_iterator_data.initialize(self.root_group)
|
||||
return self.root_group.as_rst(conf_name, shortcut_slugs)
|
||||
@@ -0,0 +1,574 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
|
||||
from contextlib import contextmanager
|
||||
from typing import (
|
||||
Any,
|
||||
Generic,
|
||||
Literal,
|
||||
NamedTuple,
|
||||
TypeVar,
|
||||
)
|
||||
|
||||
from ..constants import _plat, is_macos
|
||||
from ..fast_data_types import Color
|
||||
from ..rgb import to_color as as_color
|
||||
from ..types import ConvertibleToNumbers, ParsedShortcut, run_once
|
||||
from ..typing_compat import Protocol
|
||||
from ..utils import expandvars, log_error, shlex_split
|
||||
|
||||
key_pat = re.compile(r'([a-zA-Z][a-zA-Z0-9_-]*)\s+(.+)$')
|
||||
number_unit_pat = re.compile(r'\s*([-+]?\d+\.?\d*)\s*([^\d\s]*)?')
|
||||
ItemParser = Callable[[str, str, dict[str, Any]], bool]
|
||||
T = TypeVar('T')
|
||||
|
||||
|
||||
class OptionsProtocol(Protocol):
|
||||
def _asdict(self) -> dict[str, Any]:
|
||||
pass
|
||||
|
||||
|
||||
class BadLine(NamedTuple):
|
||||
number: int
|
||||
line: str
|
||||
exception: Exception
|
||||
file: str
|
||||
|
||||
|
||||
def positive_int(x: ConvertibleToNumbers) -> int:
|
||||
return max(0, int(x))
|
||||
|
||||
|
||||
def positive_float(x: ConvertibleToNumbers) -> float:
|
||||
return max(0, float(x))
|
||||
|
||||
|
||||
def percent(x: str) -> float:
|
||||
return float(x.rstrip('%')) / 100.0
|
||||
|
||||
|
||||
def to_color(x: str) -> Color:
|
||||
ans = as_color(x, validate=True)
|
||||
if ans is None: # this is only for type-checking
|
||||
ans = Color(0, 0, 0)
|
||||
return ans
|
||||
|
||||
|
||||
def to_color_or_none(x: str) -> Color | None:
|
||||
return None if x.lower() == 'none' else to_color(x)
|
||||
|
||||
|
||||
def unit_float(x: ConvertibleToNumbers) -> float:
|
||||
return max(0, min(float(x), 1))
|
||||
|
||||
|
||||
def signed_unit_float(x: ConvertibleToNumbers) -> float:
|
||||
return max(-1, min(float(x), 1))
|
||||
|
||||
|
||||
def number_with_unit(x: str, default_unit: str, *extra_units: str) -> tuple[float, str]:
|
||||
if (mat := number_unit_pat.match(x)) is not None:
|
||||
try:
|
||||
value = float(mat.group(1))
|
||||
except Exception as e:
|
||||
raise ValueError(f'Not a number: {x} with error: {e}')
|
||||
unit = mat.group(2) or default_unit
|
||||
if unit != default_unit and unit not in extra_units:
|
||||
raise ValueError(f'Not a valid unit: {x}. Allowed units are: {default_unit}, {", ".join(extra_units)}')
|
||||
return value, unit
|
||||
raise ValueError(f'Invalid number with unit: {x}')
|
||||
|
||||
|
||||
def to_bool(x: str) -> bool:
|
||||
return x.lower() in ('y', 'yes', 'true')
|
||||
|
||||
|
||||
class ToCmdline:
|
||||
def __init__(self) -> None:
|
||||
self.override_env: dict[str, str] | None = None
|
||||
|
||||
def __enter__(self) -> 'ToCmdline':
|
||||
return self
|
||||
|
||||
def __exit__(self, *a: Any) -> None:
|
||||
self.override_env = None
|
||||
|
||||
def filter_env_vars(self, *a: str, **override: str) -> 'ToCmdline':
|
||||
remove = frozenset(a)
|
||||
self.override_env = {k: v for k, v in os.environ.items() if k not in remove}
|
||||
self.override_env.update(override)
|
||||
return self
|
||||
|
||||
def __call__(self, x: str, expand: bool = True) -> list[str]:
|
||||
if expand:
|
||||
ans = list(
|
||||
map(
|
||||
lambda y: expandvars(os.path.expanduser(y), os.environ if self.override_env is None else self.override_env, fallback_to_os_env=False),
|
||||
shlex_split(x),
|
||||
)
|
||||
)
|
||||
else:
|
||||
ans = list(shlex_split(x))
|
||||
return ans
|
||||
|
||||
|
||||
to_cmdline_implementation = ToCmdline()
|
||||
|
||||
|
||||
def to_cmdline(x: str, expand: bool = True) -> list[str]:
|
||||
return to_cmdline_implementation(x, expand)
|
||||
|
||||
|
||||
def python_string(text: str) -> str:
|
||||
from ast import literal_eval
|
||||
|
||||
text = (text[:-1] + "\\'") if text.endswith("'") else text
|
||||
ans: str = literal_eval("'''" + text.replace("'''", "'\\''") + "'''")
|
||||
return ans
|
||||
|
||||
|
||||
class Choice:
|
||||
def __init__(self, choices: Sequence[str]):
|
||||
self.defval = choices[0]
|
||||
self.all_choices = frozenset(choices)
|
||||
|
||||
def __call__(self, x: str) -> str:
|
||||
x = x.lower()
|
||||
if x not in self.all_choices:
|
||||
raise ValueError(f'The value {x} is not a known choice')
|
||||
return x
|
||||
|
||||
|
||||
def choices(*choices: str) -> Choice:
|
||||
return Choice(choices)
|
||||
|
||||
|
||||
class CurrentlyParsing:
|
||||
__slots__ = 'line', 'number', 'file'
|
||||
|
||||
def __init__(self, line: str = '', number: int = -1, file: str = ''):
|
||||
self.line = line
|
||||
self.number = number
|
||||
self.file = file
|
||||
|
||||
def __copy__(self) -> 'CurrentlyParsing':
|
||||
return CurrentlyParsing(self.line, self.number, self.file)
|
||||
|
||||
@contextmanager
|
||||
def set_line(self, line: str, number: int) -> Generator['CurrentlyParsing', None, None]:
|
||||
orig = self.line, self.number
|
||||
self.line = line
|
||||
self.number = number
|
||||
try:
|
||||
yield self
|
||||
finally:
|
||||
self.line, self.number = orig
|
||||
|
||||
@contextmanager
|
||||
def set_file(self, file: str) -> Generator['CurrentlyParsing', None, None]:
|
||||
orig = self.file
|
||||
self.file = file
|
||||
try:
|
||||
yield self
|
||||
finally:
|
||||
self.file = orig
|
||||
|
||||
|
||||
currently_parsing = CurrentlyParsing()
|
||||
OSNames = Literal['macos', 'bsd', 'linux', 'unknown']
|
||||
|
||||
|
||||
@run_once
|
||||
def os_name() -> OSNames:
|
||||
if is_macos:
|
||||
return 'macos'
|
||||
if 'bsd' in _plat:
|
||||
return 'bsd'
|
||||
if 'linux' in _plat:
|
||||
return 'linux'
|
||||
return 'unknown'
|
||||
|
||||
|
||||
class NamedLineIterator:
|
||||
def __init__(self, name: str, lines: Iterator[str]):
|
||||
self.lines = lines
|
||||
self.name = name
|
||||
|
||||
def __iter__(self) -> Iterator[str]:
|
||||
return self.lines
|
||||
|
||||
|
||||
class GenincludeError(Exception): ...
|
||||
|
||||
|
||||
def pygeninclude(path: str) -> list[str]:
|
||||
import io
|
||||
import runpy
|
||||
|
||||
before = sys.stdout
|
||||
buf = sys.stdout = io.StringIO()
|
||||
try:
|
||||
runpy.run_path(path, run_name='__main__')
|
||||
except FileNotFoundError:
|
||||
raise
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
tb = traceback.format_exc()
|
||||
raise GenincludeError(f'Running the geninclude program: {path} failed with the error:\n{tb}')
|
||||
finally:
|
||||
sys.stdout = before
|
||||
return buf.getvalue().splitlines()
|
||||
|
||||
|
||||
def geninclude(path: str) -> list[str]:
|
||||
old = os.environ.get('KITTY_OS')
|
||||
os.environ['KITTY_OS'] = os_name()
|
||||
try:
|
||||
if path.endswith('.py'):
|
||||
return pygeninclude(path)
|
||||
import subprocess
|
||||
|
||||
cp = subprocess.run([path], capture_output=True, text=True)
|
||||
if cp.returncode != 0:
|
||||
raise GenincludeError(f'Running the geninclude program: {path} failed with exit code: {cp.returncode} and STDERR:\n{cp.stderr}')
|
||||
return cp.stdout.splitlines()
|
||||
finally:
|
||||
if old is None:
|
||||
os.environ.pop('KITTY_OS', None)
|
||||
else:
|
||||
os.environ['KITTY_OS'] = old
|
||||
|
||||
|
||||
include_keys = 'include', 'globinclude', 'envinclude', 'geninclude'
|
||||
|
||||
|
||||
class RecursiveInclude(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Memory:
|
||||
def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None:
|
||||
self.s: set[str] = set()
|
||||
if accumulate_bad_lines is None:
|
||||
accumulate_bad_lines = []
|
||||
self.accumulate_bad_lines = accumulate_bad_lines
|
||||
|
||||
def seen(self, path: str) -> bool:
|
||||
key = os.path.normpath(path)
|
||||
if key in self.s:
|
||||
self.accumulate_bad_lines.append(
|
||||
BadLine(
|
||||
currently_parsing.number,
|
||||
currently_parsing.line.rstrip(),
|
||||
RecursiveInclude(f'The file {path} has already been included, ignoring'),
|
||||
currently_parsing.file,
|
||||
)
|
||||
)
|
||||
return True
|
||||
self.s.add(key)
|
||||
return False
|
||||
|
||||
|
||||
def parse_line(
|
||||
line: str,
|
||||
parse_conf_item: ItemParser,
|
||||
ans: dict[str, Any],
|
||||
base_path_for_includes: str,
|
||||
effective_config_lines: Callable[[str, str], None],
|
||||
memory: Memory,
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
) -> None:
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
return
|
||||
m = key_pat.match(line)
|
||||
if m is None:
|
||||
log_error(f'Ignoring invalid config line: {line!r}')
|
||||
return
|
||||
key, val = m.groups()
|
||||
if key.endswith('include') and key in include_keys:
|
||||
val = expandvars(os.path.expanduser(val.strip()), {'KITTY_OS': os_name()})
|
||||
if key == 'globinclude':
|
||||
from pathlib import Path
|
||||
|
||||
vals = tuple(map(lambda x: str(os.fspath(x)), sorted(Path(base_path_for_includes).glob(val))))
|
||||
elif key == 'envinclude':
|
||||
from fnmatch import fnmatchcase
|
||||
|
||||
for x in os.environ:
|
||||
if fnmatchcase(x, val):
|
||||
with currently_parsing.set_file(f'<env var: {x}>'):
|
||||
_parse(
|
||||
NamedLineIterator(os.path.join(base_path_for_includes, ''), iter(os.environ[x].splitlines())),
|
||||
parse_conf_item,
|
||||
ans,
|
||||
memory,
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
)
|
||||
return
|
||||
elif key == 'geninclude':
|
||||
if not allow_geninclude:
|
||||
log_error('Ignoring geninclude directive for security')
|
||||
return
|
||||
if not os.path.isabs(val):
|
||||
val = os.path.join(base_path_for_includes, val)
|
||||
if not memory.seen(val):
|
||||
try:
|
||||
lines = geninclude(val)
|
||||
except FileNotFoundError as e:
|
||||
if e.filename == val:
|
||||
log_error(f'Could not find the geninclude file: {val}, ignoring')
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
with currently_parsing.set_file(f'<get: {val}>'):
|
||||
_parse(
|
||||
NamedLineIterator(os.path.join(base_path_for_includes, ''), iter(lines)),
|
||||
parse_conf_item,
|
||||
ans,
|
||||
memory,
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
)
|
||||
return
|
||||
else:
|
||||
if not os.path.isabs(val):
|
||||
val = os.path.join(base_path_for_includes, val)
|
||||
vals = (val,)
|
||||
for val in vals:
|
||||
if memory.seen(val):
|
||||
continue
|
||||
try:
|
||||
with open(val, encoding='utf-8', errors='replace') as include:
|
||||
with currently_parsing.set_file(val):
|
||||
_parse(include, parse_conf_item, ans, memory, accumulate_bad_lines, effective_config_lines, allow_geninclude=allow_geninclude)
|
||||
except FileNotFoundError:
|
||||
log_error(f'Could not find included config file: {val}, ignoring')
|
||||
except OSError:
|
||||
log_error('Could not read from included config file: {}, ignoring'.format(val))
|
||||
return
|
||||
if parse_conf_item(key, val, ans):
|
||||
effective_config_lines(key, line)
|
||||
else:
|
||||
log_error(f'Ignoring unknown config key: {key}')
|
||||
|
||||
|
||||
def _parse(
|
||||
lines: Iterable[str],
|
||||
parse_conf_item: ItemParser,
|
||||
ans: dict[str, Any],
|
||||
memory: Memory,
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
) -> None:
|
||||
name = getattr(lines, 'name', None)
|
||||
effective_config_lines = effective_config_lines or (lambda a, b: None)
|
||||
if name:
|
||||
base_path_for_includes = os.path.abspath(name) if name.endswith(os.path.sep) else os.path.dirname(os.path.abspath(name))
|
||||
else:
|
||||
from ..constants import config_dir
|
||||
|
||||
base_path_for_includes = config_dir
|
||||
|
||||
it = iter(lines)
|
||||
line = ''
|
||||
next_line: str = ''
|
||||
next_line_num = 0
|
||||
|
||||
while True:
|
||||
try:
|
||||
if next_line:
|
||||
line = next_line
|
||||
else:
|
||||
line = next(it).lstrip()
|
||||
next_line_num += 1
|
||||
line_num = next_line_num
|
||||
|
||||
try:
|
||||
next_line = next(it).lstrip()
|
||||
next_line_num += 1
|
||||
|
||||
while next_line.startswith('\\'):
|
||||
line = line.rstrip('\n') + next_line[1:]
|
||||
try:
|
||||
next_line = next(it).lstrip()
|
||||
next_line_num += 1
|
||||
except StopIteration:
|
||||
next_line = ''
|
||||
break
|
||||
except StopIteration:
|
||||
next_line = ''
|
||||
try:
|
||||
with currently_parsing.set_line(line, line_num):
|
||||
parse_line(line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude)
|
||||
except Exception as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
accumulate_bad_lines.append(BadLine(line_num, line.rstrip(), e, currently_parsing.file))
|
||||
except StopIteration:
|
||||
break
|
||||
|
||||
|
||||
def parse_config_base(
|
||||
lines: Iterable[str],
|
||||
parse_conf_item: ItemParser,
|
||||
ans: dict[str, Any],
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
) -> None:
|
||||
_parse(lines, parse_conf_item, ans, Memory(accumulate_bad_lines), accumulate_bad_lines, effective_config_lines, allow_geninclude)
|
||||
|
||||
|
||||
def merge_dicts(defaults: dict[str, Any], newvals: dict[str, Any]) -> dict[str, Any]:
|
||||
ans = defaults.copy()
|
||||
ans.update(newvals)
|
||||
return ans
|
||||
|
||||
|
||||
def resolve_config(SYSTEM_CONF: str, defconf: str, config_files_on_cmd_line: Sequence[str] = ()) -> Generator[str, None, None]:
|
||||
if config_files_on_cmd_line:
|
||||
if 'NONE' not in config_files_on_cmd_line:
|
||||
yield SYSTEM_CONF
|
||||
yield from config_files_on_cmd_line
|
||||
else:
|
||||
yield SYSTEM_CONF
|
||||
yield defconf
|
||||
|
||||
|
||||
def load_config(
|
||||
defaults: OptionsProtocol,
|
||||
parse_config: Callable[[Iterable[str]], dict[str, Any]],
|
||||
merge_configs: Callable[[dict[str, Any], dict[str, Any]], dict[str, Any]],
|
||||
*paths: str,
|
||||
overrides: Iterable[str] | None = None,
|
||||
initialize_defaults: Callable[[dict[str, Any]], dict[str, Any]] = lambda x: x,
|
||||
) -> tuple[dict[str, Any], tuple[str, ...]]:
|
||||
ans = initialize_defaults(defaults._asdict())
|
||||
found_paths = []
|
||||
for path in paths:
|
||||
if not path:
|
||||
continue
|
||||
if path == '-':
|
||||
path = '/dev/stdin'
|
||||
with currently_parsing.set_file(path):
|
||||
vals = parse_config(sys.stdin)
|
||||
else:
|
||||
try:
|
||||
with open(path, encoding='utf-8', errors='replace') as f:
|
||||
with currently_parsing.set_file(path):
|
||||
vals = parse_config(f)
|
||||
except (FileNotFoundError, PermissionError):
|
||||
continue
|
||||
found_paths.append(path)
|
||||
ans = merge_configs(ans, vals)
|
||||
if overrides is not None:
|
||||
with currently_parsing.set_file('<override>'):
|
||||
vals = parse_config(overrides)
|
||||
ans = merge_configs(ans, vals)
|
||||
return ans, tuple(found_paths)
|
||||
|
||||
|
||||
ReturnType = TypeVar('ReturnType')
|
||||
KeyFunc = Callable[[str, str], ReturnType]
|
||||
|
||||
|
||||
class KeyFuncWrapper(Generic[ReturnType]):
|
||||
def __init__(self) -> None:
|
||||
self.args_funcs: dict[str, KeyFunc[ReturnType]] = {}
|
||||
|
||||
def __call__(self, *names: str) -> Callable[[KeyFunc[ReturnType]], KeyFunc[ReturnType]]:
|
||||
|
||||
def w(f: KeyFunc[ReturnType]) -> KeyFunc[ReturnType]:
|
||||
for name in names:
|
||||
if self.args_funcs.setdefault(name, f) is not f:
|
||||
raise ValueError(f'the args_func {name} is being redefined')
|
||||
return f
|
||||
|
||||
return w
|
||||
|
||||
def get(self, name: str) -> KeyFunc[ReturnType] | None:
|
||||
return self.args_funcs.get(name)
|
||||
|
||||
|
||||
class KeyAction(NamedTuple):
|
||||
func: str
|
||||
args: tuple[str | float | bool | int | None, ...] = ()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
if self.args:
|
||||
return f'KeyAction({self.func!r}, {self.args!r})'
|
||||
return f'KeyAction({self.func!r})'
|
||||
|
||||
def pretty(self) -> str:
|
||||
ans = self.func
|
||||
for x in self.args:
|
||||
ans += f' {x}'
|
||||
return ans
|
||||
|
||||
|
||||
def parse_kittens_func_args(action: str, args_funcs: dict[str, KeyFunc[tuple[str, Any]]]) -> KeyAction:
|
||||
parts = action.strip().split(' ', 1)
|
||||
func = parts[0]
|
||||
if len(parts) == 1:
|
||||
return KeyAction(func, ())
|
||||
rest = parts[1]
|
||||
|
||||
try:
|
||||
parser = args_funcs[func]
|
||||
except KeyError as e:
|
||||
raise KeyError(f'Unknown action: {func}. Check if map action: {action} is valid') from e
|
||||
|
||||
try:
|
||||
func, args = parser(func, rest)
|
||||
except Exception:
|
||||
raise ValueError(f'Unknown key action: {action}')
|
||||
|
||||
if not isinstance(args, (list, tuple)):
|
||||
args = (args,)
|
||||
|
||||
return KeyAction(func, tuple(args))
|
||||
|
||||
|
||||
KittensKeyDefinition = tuple[ParsedShortcut, KeyAction]
|
||||
KittensKeyMap = dict[ParsedShortcut, KeyAction]
|
||||
|
||||
|
||||
def parse_kittens_key(val: str, funcs_with_args: dict[str, KeyFunc[tuple[str, Any]]]) -> KittensKeyDefinition | None:
|
||||
from ..key_encoding import parse_shortcut
|
||||
|
||||
sc, action = val.partition(' ')[::2]
|
||||
if not sc or not action:
|
||||
return None
|
||||
ans = parse_kittens_func_args(action, funcs_with_args)
|
||||
return parse_shortcut(sc), ans
|
||||
|
||||
|
||||
def uniq(vals: Iterable[T]) -> list[T]:
|
||||
seen: set[T] = set()
|
||||
seen_add = seen.add
|
||||
return [x for x in vals if x not in seen and not seen_add(x)] # ty: ignore[redundant-condition]
|
||||
|
||||
|
||||
def save_type_stub(text: str, fpath: str) -> None:
|
||||
fpath += 'i'
|
||||
preamble = '# Update this file by running: ./test.py type-check\n\n'
|
||||
try:
|
||||
with open(fpath) as fs:
|
||||
existing = fs.read()
|
||||
except FileNotFoundError:
|
||||
existing = ''
|
||||
current = preamble + text
|
||||
if existing != current:
|
||||
with open(fpath, 'w') as f:
|
||||
f.write(current)
|
||||
Reference in new issue
Block a user