Merge pull request 'feat(config): add named configuration profiles' (#33) from feat/config-profiles into main
Reviewed-on: #33
This commit was merged in pull request #33.
This commit is contained in:
commit
ea29472b27
9 files changed
+303
-9
No files matched your search
@@ -70,6 +70,37 @@ dynamiquement la configuration en exécutant un programme avec
|
|||||||
geninclude dynamic.py
|
geninclude dynamic.py
|
||||||
|
|
||||||
|
|
||||||
|
.. _config-profiles:
|
||||||
|
|
||||||
|
Profils de configuration
|
||||||
|
------------------------
|
||||||
|
|
||||||
|
Vous pouvez regrouper des réglages dans des profils nommés, à l'intérieur de
|
||||||
|
:file:`kitty.conf`, et n'en appliquer qu'un seul au démarrage. Un profil est un
|
||||||
|
bloc de configuration ordinaire délimité par des accolades ::
|
||||||
|
|
||||||
|
font_size 11
|
||||||
|
|
||||||
|
profile work {
|
||||||
|
font_size 9
|
||||||
|
background_opacity 1
|
||||||
|
}
|
||||||
|
|
||||||
|
Les lignes d'un bloc :code:`profile` ne sont appliquées que si ce profil est
|
||||||
|
sélectionné. La priorité est la suivante : profil, puis configuration globale,
|
||||||
|
puis valeurs par défaut. Un profil ne surcharge donc que les options qu'il
|
||||||
|
contient ; les autres conservent leur valeur habituelle.
|
||||||
|
|
||||||
|
Sélectionnez un profil avec l'option :option:`kitty --profile` ou avec la
|
||||||
|
variable d'environnement :envvar:`KITTY_PROFILE`, qui permet de lier un profil à
|
||||||
|
un projet dans un script de lancement. Si le profil demandé est inconnu, ou si
|
||||||
|
l'une de ses lignes est invalide, l'erreur est signalée mais |kitty| démarre
|
||||||
|
quand même avec le reste de la configuration.
|
||||||
|
|
||||||
|
Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser
|
||||||
|
:code:`include` et les autres directives d'inclusion.
|
||||||
|
|
||||||
|
|
||||||
.. include:: /generated/conf-kitty.rst
|
.. include:: /generated/conf-kitty.rst
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -3700,7 +3700,7 @@ class Boss:
|
|||||||
final_overrides = old_opts.config_overrides if apply_overrides else ()
|
final_overrides = old_opts.config_overrides if apply_overrides else ()
|
||||||
if overrides:
|
if overrides:
|
||||||
final_overrides += tuple(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:
|
if bad_lines:
|
||||||
self.show_bad_config_lines(bad_lines)
|
self.show_bad_config_lines(bad_lines)
|
||||||
from .fonts.render import clear_font_caches
|
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)
|
config = default_config_paths(args.config)
|
||||||
overrides = map(parse_override, args.override or ())
|
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
|
return opts
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -215,6 +215,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
|
|||||||
a(' config_paths: tuple[str, ...] = ()')
|
a(' config_paths: tuple[str, ...] = ()')
|
||||||
a(' all_config_paths: tuple[str, ...] = ()')
|
a(' all_config_paths: tuple[str, ...] = ()')
|
||||||
a(' config_overrides: tuple[str, ...] = ()')
|
a(' config_overrides: tuple[str, ...] = ()')
|
||||||
|
a(" profile_name: str = ''")
|
||||||
a('')
|
a('')
|
||||||
a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:')
|
a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:')
|
||||||
if defn.has_color_table:
|
if defn.has_color_table:
|
||||||
|
|||||||
+95
-3
@@ -245,12 +245,67 @@ def geninclude(path: str) -> list[str]:
|
|||||||
|
|
||||||
|
|
||||||
include_keys = 'include', 'globinclude', 'envinclude', 'geninclude'
|
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):
|
class RecursiveInclude(Exception):
|
||||||
pass
|
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:
|
class Memory:
|
||||||
def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None:
|
def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None:
|
||||||
self.s: set[str] = set()
|
self.s: set[str] = set()
|
||||||
@@ -283,6 +338,7 @@ def parse_line(
|
|||||||
memory: Memory,
|
memory: Memory,
|
||||||
accumulate_bad_lines: list[BadLine] | None = None,
|
accumulate_bad_lines: list[BadLine] | None = None,
|
||||||
allow_geninclude: bool = True,
|
allow_geninclude: bool = True,
|
||||||
|
profiles: dict[str, ProfileLines] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if not line or line.startswith('#'):
|
if not line or line.startswith('#'):
|
||||||
@@ -312,6 +368,7 @@ def parse_line(
|
|||||||
accumulate_bad_lines,
|
accumulate_bad_lines,
|
||||||
effective_config_lines,
|
effective_config_lines,
|
||||||
allow_geninclude=allow_geninclude,
|
allow_geninclude=allow_geninclude,
|
||||||
|
profiles=profiles,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
elif key == 'geninclude':
|
elif key == 'geninclude':
|
||||||
@@ -338,6 +395,7 @@ def parse_line(
|
|||||||
accumulate_bad_lines,
|
accumulate_bad_lines,
|
||||||
effective_config_lines,
|
effective_config_lines,
|
||||||
allow_geninclude=allow_geninclude,
|
allow_geninclude=allow_geninclude,
|
||||||
|
profiles=profiles,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
@@ -350,7 +408,16 @@ def parse_line(
|
|||||||
try:
|
try:
|
||||||
with open(val, encoding='utf-8', errors='replace') as include:
|
with open(val, encoding='utf-8', errors='replace') as include:
|
||||||
with currently_parsing.set_file(val):
|
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:
|
except FileNotFoundError:
|
||||||
log_error(f'Could not find included config file: {val}, ignoring')
|
log_error(f'Could not find included config file: {val}, ignoring')
|
||||||
except OSError:
|
except OSError:
|
||||||
@@ -370,8 +437,10 @@ def _parse(
|
|||||||
accumulate_bad_lines: list[BadLine] | None = None,
|
accumulate_bad_lines: list[BadLine] | None = None,
|
||||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||||
allow_geninclude: bool = True,
|
allow_geninclude: bool = True,
|
||||||
|
profiles: dict[str, ProfileLines] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
name = getattr(lines, 'name', 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)
|
effective_config_lines = effective_config_lines or (lambda a, b: None)
|
||||||
if name:
|
if name:
|
||||||
base_path_for_includes = os.path.abspath(name) if name.endswith(os.path.sep) else os.path.dirname(os.path.abspath(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 = ''
|
next_line = ''
|
||||||
try:
|
try:
|
||||||
with currently_parsing.set_line(line, line_num):
|
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:
|
except Exception as e:
|
||||||
if accumulate_bad_lines is None:
|
if accumulate_bad_lines is None:
|
||||||
raise
|
raise
|
||||||
@@ -418,6 +491,15 @@ def _parse(
|
|||||||
except StopIteration:
|
except StopIteration:
|
||||||
break
|
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(
|
def parse_config_base(
|
||||||
lines: Iterable[str],
|
lines: Iterable[str],
|
||||||
@@ -426,8 +508,18 @@ def parse_config_base(
|
|||||||
accumulate_bad_lines: list[BadLine] | None = None,
|
accumulate_bad_lines: list[BadLine] | None = None,
|
||||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||||
allow_geninclude: bool = True,
|
allow_geninclude: bool = True,
|
||||||
|
profiles: dict[str, ProfileLines] | None = 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]:
|
def merge_dicts(defaults: dict[str, Any], newvals: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
|||||||
+68
-4
@@ -3,12 +3,12 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from collections.abc import Callable, Generator, Iterable
|
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
|
||||||
from contextlib import contextmanager, suppress
|
from contextlib import contextmanager, suppress
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from typing import Any
|
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 .conf.utils import load_config as _load_config
|
||||||
from .constants import cache_dir, defconf
|
from .constants import cache_dir, defconf
|
||||||
from .options.types import Options, defaults, option_names
|
from .options.types import Options, defaults, option_names
|
||||||
@@ -162,6 +162,7 @@ def parse_config(
|
|||||||
accumulate_bad_lines: list[BadLine] | None = None,
|
accumulate_bad_lines: list[BadLine] | None = None,
|
||||||
effective_config_lines: Callable[[str, str], None] | None = None,
|
effective_config_lines: Callable[[str, str], None] | None = None,
|
||||||
allow_geninclude: bool = True,
|
allow_geninclude: bool = True,
|
||||||
|
profiles: dict[str, ProfileLines] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
from .options.parse import create_result_dict, parse_conf_item
|
from .options.parse import create_result_dict, parse_conf_item
|
||||||
|
|
||||||
@@ -173,14 +174,66 @@ def parse_config(
|
|||||||
accumulate_bad_lines=accumulate_bad_lines,
|
accumulate_bad_lines=accumulate_bad_lines,
|
||||||
effective_config_lines=effective_config_lines,
|
effective_config_lines=effective_config_lines,
|
||||||
allow_geninclude=allow_geninclude,
|
allow_geninclude=allow_geninclude,
|
||||||
|
profiles=profiles,
|
||||||
)
|
)
|
||||||
return ans
|
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] = []
|
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.parse import merge_result_dicts
|
||||||
from .options.types import secret_options
|
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)
|
effective_config_lines.append(line)
|
||||||
|
|
||||||
overrides = tuple(overrides) if overrides is not None else ()
|
overrides = tuple(overrides) if overrides is not None else ()
|
||||||
|
profiles: dict[str, ProfileLines] = {}
|
||||||
|
|
||||||
opts_dict, found_paths = _load_config(
|
opts_dict, found_paths = _load_config(
|
||||||
defaults,
|
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,
|
merge_result_dicts,
|
||||||
*paths,
|
*paths,
|
||||||
overrides=overrides,
|
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 = Options(opts_dict)
|
||||||
|
|
||||||
opts.alias_map = build_action_aliases(opts.kitten_alias, 'kitten')
|
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.config_paths = found_paths
|
||||||
opts.all_config_paths = paths
|
opts.all_config_paths = paths
|
||||||
opts.config_overrides = overrides
|
opts.config_overrides = overrides
|
||||||
|
opts.profile_name = active_profile
|
||||||
return opts
|
return opts
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Generated
+1
@@ -803,6 +803,7 @@ class Options:
|
|||||||
config_paths: tuple[str, ...] = ()
|
config_paths: tuple[str, ...] = ()
|
||||||
all_config_paths: tuple[str, ...] = ()
|
all_config_paths: tuple[str, ...] = ()
|
||||||
config_overrides: tuple[str, ...] = ()
|
config_overrides: tuple[str, ...] = ()
|
||||||
|
profile_name: str = ''
|
||||||
|
|
||||||
def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:
|
def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:
|
||||||
self.color_table = array(self.color_table.typecode, self.color_table)
|
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}
|
{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
|
--override -o
|
||||||
type=list
|
type=list
|
||||||
completion=type:special group:complete_kitty_override
|
completion=type:special group:complete_kitty_override
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from kitty.config import load_config
|
||||||
|
from kitty.utils import log_error
|
||||||
|
|
||||||
|
from .base import BaseTest
|
||||||
|
|
||||||
|
|
||||||
|
class TestConfigProfiles(BaseTest):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.error_messages: list[str] = []
|
||||||
|
log_error.redirect = self.error_messages.append
|
||||||
|
self.tdir = tempfile.mkdtemp()
|
||||||
|
self.conf = os.path.join(self.tdir, 'kitty.conf')
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
del log_error.redirect
|
||||||
|
shutil.rmtree(self.tdir)
|
||||||
|
super().tearDown()
|
||||||
|
|
||||||
|
def write_conf(self, text: str) -> str:
|
||||||
|
with open(self.conf, 'w', encoding='utf-8') as f:
|
||||||
|
f.write(text)
|
||||||
|
return self.conf
|
||||||
|
|
||||||
|
def test_profile_overrides_only_the_options_it_declares(self):
|
||||||
|
self.write_conf('font_size 13\n\nprofile work {\n font_size 9\n cursor_shape beam\n}\n')
|
||||||
|
base = load_config(self.conf)
|
||||||
|
self.ae(base.font_size, 13)
|
||||||
|
self.ae(base.profile_name, '')
|
||||||
|
work = load_config(self.conf, profile='work')
|
||||||
|
self.ae(work.profile_name, 'work')
|
||||||
|
self.ae(work.font_size, 9)
|
||||||
|
self.assertNotEqual(work.cursor_shape, base.cursor_shape)
|
||||||
|
# Options absent from the profile keep the global value
|
||||||
|
self.ae(work.background_opacity, base.background_opacity)
|
||||||
|
|
||||||
|
def test_profile_is_selected_by_environment_variable(self):
|
||||||
|
self.write_conf('font_size 13\nprofile dark {\n font_size 21\n}\n')
|
||||||
|
with patch.dict(os.environ, {'KITTY_PROFILE': 'dark'}):
|
||||||
|
self.ae(load_config(self.conf).font_size, 21)
|
||||||
|
# An explicitly requested profile wins over the environment
|
||||||
|
with patch.dict(os.environ, {'KITTY_PROFILE': 'dark'}):
|
||||||
|
self.ae(load_config(self.conf, profile='').font_size, 21)
|
||||||
|
self.write_conf('font_size 13\nprofile dark {\n font_size 21\n}\nprofile light {\n font_size 17\n}\n')
|
||||||
|
self.ae(load_config(self.conf, profile='light').font_size, 17)
|
||||||
|
|
||||||
|
def test_unknown_profile_is_reported_without_blocking_startup(self):
|
||||||
|
self.write_conf('font_size 13\n')
|
||||||
|
opts = load_config(self.conf, profile='missing')
|
||||||
|
self.ae(opts.font_size, 13)
|
||||||
|
self.ae(opts.profile_name, 'missing')
|
||||||
|
self.assertTrue(any('missing' in msg for msg in self.error_messages), self.error_messages)
|
||||||
|
|
||||||
|
def test_invalid_line_in_profile_does_not_block_startup(self):
|
||||||
|
self.write_conf('font_size 12\nprofile work {\n font_size not-a-number\n background_opacity 0.5\n}\n')
|
||||||
|
bad_lines = []
|
||||||
|
opts = load_config(self.conf, profile='work', accumulate_bad_lines=bad_lines)
|
||||||
|
self.ae(opts.font_size, 12)
|
||||||
|
self.ae(opts.background_opacity, 0.5)
|
||||||
|
self.ae(len(bad_lines), 1)
|
||||||
|
self.assertIn('font_size not-a-number', bad_lines[0].line)
|
||||||
|
self.ae(bad_lines[0].file, self.conf)
|
||||||
|
|
||||||
|
def test_unterminated_profile_is_reported(self):
|
||||||
|
self.write_conf('profile work {\n font_size 9\n')
|
||||||
|
bad_lines = []
|
||||||
|
opts = load_config(self.conf, accumulate_bad_lines=bad_lines)
|
||||||
|
self.ae(len(bad_lines), 1)
|
||||||
|
self.assertIn('never closed', str(bad_lines[0].exception))
|
||||||
|
self.assertNotEqual(opts.font_size, 9)
|
||||||
|
|
||||||
|
def test_profile_in_included_file(self):
|
||||||
|
with open(os.path.join(self.tdir, 'extra.conf'), 'w', encoding='utf-8') as f:
|
||||||
|
f.write('profile extra {\n font_size 30\n}\n')
|
||||||
|
self.write_conf('include extra.conf\nfont_size 13\n')
|
||||||
|
self.ae(load_config(self.conf, profile='extra').font_size, 30)
|
||||||
|
self.ae(load_config(self.conf).font_size, 13)
|
||||||
|
|
||||||
|
def test_mappings_from_profile_are_added(self):
|
||||||
|
self.write_conf('map ctrl+a new_tab\n\nprofile work {\n map ctrl+b new_window\n}\n')
|
||||||
|
base = load_config(self.conf)
|
||||||
|
work = load_config(self.conf, profile='work')
|
||||||
|
self.ae(len(work.keyboard_modes[''].keymap), len(base.keyboard_modes[''].keymap) + 1)
|
||||||
|
|
||||||
|
def test_profile_name_on_command_line(self):
|
||||||
|
from kitty.cli import parse_args
|
||||||
|
|
||||||
|
args, rest = parse_args(['--profile', 'work'])
|
||||||
|
self.ae(args.profile, 'work')
|
||||||
|
self.ae(rest, [])
|
||||||
Reference in new issue
Block a user