feat(config): add named configuration profiles
Profiles declared as `profile <name> { ... }` in kitty.conf are now collected
while the configuration is read and applied only when selected, so switching
between projects no longer requires duplicating or editing kitty.conf.
The selected profile is layered over the global configuration, meaning it only
overrides the options it declares. Selection happens with --profile or
KITTY_PROFILE, reloading keeps the active profile, and an unknown or malformed
profile is reported without blocking startup.
This commit is contained in:
9 files changed
+303
-9
No files matched your search
+1
-1
@@ -3700,7 +3700,7 @@ class Boss:
|
||||
final_overrides = old_opts.config_overrides if apply_overrides else ()
|
||||
if overrides:
|
||||
final_overrides += tuple(overrides)
|
||||
opts = load_config(*paths, overrides=final_overrides or None, accumulate_bad_lines=bad_lines)
|
||||
opts = load_config(*paths, overrides=final_overrides or None, accumulate_bad_lines=bad_lines, profile=old_opts.profile_name or None)
|
||||
if bad_lines:
|
||||
self.show_bad_config_lines(bad_lines)
|
||||
from .fonts.render import clear_font_caches
|
||||
|
||||
+1
-1
@@ -737,7 +737,7 @@ def create_opts(args: CLIOptions, accumulate_bad_lines: list[BadLineType] | None
|
||||
|
||||
config = default_config_paths(args.config)
|
||||
overrides = map(parse_override, args.override or ())
|
||||
opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines)
|
||||
opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines, profile=getattr(args, 'profile', ''))
|
||||
return opts
|
||||
|
||||
|
||||
|
||||
@@ -215,6 +215,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
||||
a(' config_paths: tuple[str, ...] = ()')
|
||||
a(' all_config_paths: tuple[str, ...] = ()')
|
||||
a(' config_overrides: tuple[str, ...] = ()')
|
||||
a(" profile_name: str = ''")
|
||||
a('')
|
||||
a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:')
|
||||
if defn.has_color_table:
|
||||
|
||||
+95
-3
@@ -245,12 +245,67 @@ def geninclude(path: str) -> list[str]:
|
||||
|
||||
|
||||
include_keys = 'include', 'globinclude', 'envinclude', 'geninclude'
|
||||
profile_start_pat = re.compile(r'^profile\s+([A-Za-z0-9_.-]+)\s*\{$')
|
||||
ProfileLines = list[tuple[str, int, str]]
|
||||
|
||||
|
||||
class RecursiveInclude(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ProfileCollector:
|
||||
"""Gathers the contents of ``profile <name> { ... }`` blocks instead of parsing them.
|
||||
|
||||
Blocks are buffered so that the caller can parse them separately, after the
|
||||
rest of the configuration, which is what allows a profile to only override
|
||||
the options it declares. One collector is used per file, so a block cannot
|
||||
span an include.
|
||||
"""
|
||||
|
||||
__slots__ = ('profiles', 'current', 'start')
|
||||
|
||||
def __init__(self, profiles: dict[str, ProfileLines]) -> None:
|
||||
self.profiles = profiles
|
||||
self.current: str | None = None
|
||||
self.start: tuple[str, int] = ('', 0)
|
||||
|
||||
def handle(self, line: str, file: str, line_num: int) -> bool:
|
||||
stripped = line.strip()
|
||||
if self.current is None:
|
||||
m = profile_start_pat.match(stripped)
|
||||
if m is not None:
|
||||
self.current = m.group(1)
|
||||
self.start = (file, line_num)
|
||||
self.profiles.setdefault(self.current, [])
|
||||
return True
|
||||
if stripped == '}':
|
||||
raise ValueError('Unexpected "}" outside of a profile block')
|
||||
return False
|
||||
if stripped == '}':
|
||||
self.current = None
|
||||
return True
|
||||
if profile_start_pat.match(stripped) is not None:
|
||||
raise ValueError(f'Profile blocks cannot be nested, found one inside the profile {self.current!r}')
|
||||
self.profiles[self.current].append((file, line_num, line))
|
||||
return True
|
||||
|
||||
def finish(self) -> None:
|
||||
if self.current is not None:
|
||||
file, line_num = self.start
|
||||
where = file or 'the configuration'
|
||||
raise ValueError(f'The profile {self.current!r} opened on line {line_num} of {where} was never closed')
|
||||
|
||||
|
||||
def handle_profile_line(collector: ProfileCollector, line: str, line_num: int, accumulate_bad_lines: list[BadLine] | None) -> bool:
|
||||
try:
|
||||
return collector.handle(line, currently_parsing.file, line_num)
|
||||
except ValueError as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
accumulate_bad_lines.append(BadLine(line_num, line.rstrip(), e, currently_parsing.file))
|
||||
return True
|
||||
|
||||
|
||||
class Memory:
|
||||
def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None:
|
||||
self.s: set[str] = set()
|
||||
@@ -283,6 +338,7 @@ def parse_line(
|
||||
memory: Memory,
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> None:
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
@@ -312,6 +368,7 @@ def parse_line(
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
return
|
||||
elif key == 'geninclude':
|
||||
@@ -338,6 +395,7 @@ def parse_line(
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
return
|
||||
else:
|
||||
@@ -350,7 +408,16 @@ def parse_line(
|
||||
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)
|
||||
_parse(
|
||||
include,
|
||||
parse_conf_item,
|
||||
ans,
|
||||
memory,
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
log_error(f'Could not find included config file: {val}, ignoring')
|
||||
except OSError:
|
||||
@@ -370,8 +437,10 @@ def _parse(
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> None:
|
||||
name = getattr(lines, 'name', None)
|
||||
collector = ProfileCollector(profiles) if profiles is not None else 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))
|
||||
@@ -410,7 +479,11 @@ def _parse(
|
||||
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)
|
||||
if collector is not None and handle_profile_line(collector, line, line_num, accumulate_bad_lines):
|
||||
continue
|
||||
parse_line(
|
||||
line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude, profiles
|
||||
)
|
||||
except Exception as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
@@ -418,6 +491,15 @@ def _parse(
|
||||
except StopIteration:
|
||||
break
|
||||
|
||||
if collector is not None:
|
||||
try:
|
||||
collector.finish()
|
||||
except ValueError as e:
|
||||
if accumulate_bad_lines is None:
|
||||
raise
|
||||
file, line_num = collector.start
|
||||
accumulate_bad_lines.append(BadLine(line_num, '', e, file))
|
||||
|
||||
|
||||
def parse_config_base(
|
||||
lines: Iterable[str],
|
||||
@@ -426,8 +508,18 @@ def parse_config_base(
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> None:
|
||||
_parse(lines, parse_conf_item, ans, Memory(accumulate_bad_lines), accumulate_bad_lines, effective_config_lines, allow_geninclude)
|
||||
_parse(
|
||||
lines,
|
||||
parse_conf_item,
|
||||
ans,
|
||||
Memory(accumulate_bad_lines),
|
||||
accumulate_bad_lines,
|
||||
effective_config_lines,
|
||||
allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
|
||||
|
||||
def merge_dicts(defaults: dict[str, Any], newvals: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
+68
-4
@@ -3,12 +3,12 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Callable, Generator, Iterable
|
||||
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
|
||||
from contextlib import contextmanager, suppress
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
from .conf.utils import BadLine, parse_config_base
|
||||
from .conf.utils import BadLine, NamedLineIterator, ProfileLines, currently_parsing, parse_config_base
|
||||
from .conf.utils import load_config as _load_config
|
||||
from .constants import cache_dir, defconf
|
||||
from .options.types import Options, defaults, option_names
|
||||
@@ -162,6 +162,7 @@ def parse_config(
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
allow_geninclude: bool = True,
|
||||
profiles: dict[str, ProfileLines] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from .options.parse import create_result_dict, parse_conf_item
|
||||
|
||||
@@ -173,14 +174,66 @@ def parse_config(
|
||||
accumulate_bad_lines=accumulate_bad_lines,
|
||||
effective_config_lines=effective_config_lines,
|
||||
allow_geninclude=allow_geninclude,
|
||||
profiles=profiles,
|
||||
)
|
||||
return ans
|
||||
|
||||
|
||||
def resolve_profile_name(profile: str | None = None) -> str:
|
||||
"""The explicitly requested profile wins over the environment variable."""
|
||||
ans = profile if profile else os.environ.get('KITTY_PROFILE', '')
|
||||
return ans.strip()
|
||||
|
||||
|
||||
def _lines_by_file(lines: Sequence[tuple[str, int, str]]) -> Iterator[tuple[str, list[str]]]:
|
||||
"""Group consecutive lines read from the same file, padding them so that
|
||||
their line numbers stay the ones of the original configuration file."""
|
||||
group: list[str] = []
|
||||
current = ''
|
||||
for file, line_num, line in lines:
|
||||
if group and file != current:
|
||||
yield current, group
|
||||
group = []
|
||||
current = file
|
||||
while len(group) < line_num - 1:
|
||||
group.append('')
|
||||
group.append(line)
|
||||
if group:
|
||||
yield current, group
|
||||
|
||||
|
||||
def parse_profile_lines(
|
||||
lines: Sequence[tuple[str, int, str]],
|
||||
accumulate_bad_lines: list[BadLine] | None = None,
|
||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from .options.parse import actions, create_result_dict
|
||||
|
||||
ans = create_result_dict()
|
||||
for file, group in _lines_by_file(lines):
|
||||
# Lines read from STDIN or from the command line have no directory to
|
||||
# resolve includes against, so let the parser fall back to config_dir.
|
||||
name = file if file and file != '-' and not file.startswith('<') else ''
|
||||
with currently_parsing.set_file(name):
|
||||
vals = parse_config(
|
||||
NamedLineIterator(name, iter(group)), accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=effective_config_lines
|
||||
)
|
||||
for k, v in vals.items():
|
||||
if isinstance(v, dict):
|
||||
ans.setdefault(k, {}).update(v)
|
||||
elif k in actions:
|
||||
ans.setdefault(k, []).extend(v)
|
||||
else:
|
||||
ans[k] = v
|
||||
return ans
|
||||
|
||||
|
||||
effective_config_lines: list[str] = []
|
||||
|
||||
|
||||
def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None) -> Options:
|
||||
def load_config(
|
||||
*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None, profile: str | None = None
|
||||
) -> Options:
|
||||
from .options.parse import merge_result_dicts
|
||||
from .options.types import secret_options
|
||||
|
||||
@@ -191,14 +244,24 @@ def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_
|
||||
effective_config_lines.append(line)
|
||||
|
||||
overrides = tuple(overrides) if overrides is not None else ()
|
||||
profiles: dict[str, ProfileLines] = {}
|
||||
|
||||
opts_dict, found_paths = _load_config(
|
||||
defaults,
|
||||
partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line),
|
||||
partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line, profiles=profiles),
|
||||
merge_result_dicts,
|
||||
*paths,
|
||||
overrides=overrides,
|
||||
)
|
||||
active_profile = resolve_profile_name(profile)
|
||||
if active_profile:
|
||||
profile_lines = profiles.get(active_profile)
|
||||
if profile_lines is None:
|
||||
log_error(f'The configuration profile {active_profile!r} is not defined, ignoring it')
|
||||
else:
|
||||
# Parsed after the global configuration so that it is layered on top
|
||||
# of it and only needs to list the options it changes.
|
||||
opts_dict = merge_result_dicts(opts_dict, parse_profile_lines(profile_lines, accumulate_bad_lines, add_effective_config_line))
|
||||
opts = Options(opts_dict)
|
||||
|
||||
opts.alias_map = build_action_aliases(opts.kitten_alias, 'kitten')
|
||||
@@ -213,6 +276,7 @@ def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_
|
||||
opts.config_paths = found_paths
|
||||
opts.all_config_paths = paths
|
||||
opts.config_overrides = overrides
|
||||
opts.profile_name = active_profile
|
||||
return opts
|
||||
|
||||
|
||||
|
||||
Generated
+1
@@ -803,6 +803,7 @@ class Options:
|
||||
config_paths: tuple[str, ...] = ()
|
||||
all_config_paths: tuple[str, ...] = ()
|
||||
config_overrides: tuple[str, ...] = ()
|
||||
profile_name: str = ''
|
||||
|
||||
def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:
|
||||
self.color_table = array(self.color_table.typecode, self.color_table)
|
||||
|
||||
@@ -416,6 +416,13 @@ completion=type:file ext:conf group:"Config files" kwds:none,NONE
|
||||
{config_help}
|
||||
|
||||
|
||||
--profile
|
||||
Apply the named configuration profile on top of the loaded configuration.
|
||||
Profiles are declared in :file:`kitty.conf` with
|
||||
:code:`profile <name> {{ ... }}` blocks. This overrides the
|
||||
:envvar:`KITTY_PROFILE` environment variable.
|
||||
|
||||
|
||||
--override -o
|
||||
type=list
|
||||
completion=type:special group:complete_kitty_override
|
||||
|
||||
Reference in new issue
Block a user