Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,15 @@ repos:
name: format-sh
entry: mise exec -- shfmt -w
language: system
files: ^(.*\.(sh|sh\.tmpl|bash|zsh)|(managed/)?dot_(bash|zsh)rc|(managed/)?dot_config/tmux/tmux\.conf\.tmpl|(managed/)?dot_config/zsh/completions/_.*|(managed/)?dot_local/bin/executable_.*)$
files: ^(.*\.(sh|sh\.tmpl|bash|zsh)|(managed/)?dot_(bash|zsh)rc|(managed/)?dot_config/tmux/tmux\.conf\.tmpl|(managed/)?dot_config/zsh/completions/_.*|(managed/)?dot_local/bin/(work/)?executable_.*)$
exclude: ^managed/dot_local/bin/executable_(dotfiles|generate-completions|tmx|vscode-extensions-update)$
stages: [pre-commit]

- id: format-sh-check
name: format-sh-check
entry: mise exec -- shfmt -d
language: system
files: ^(.*\.(sh|sh\.tmpl|bash|zsh)|(managed/)?dot_(bash|zsh)rc|(managed/)?dot_config/tmux/tmux\.conf\.tmpl|(managed/)?dot_config/zsh/completions/_.*|(managed/)?dot_local/bin/executable_.*)$
files: ^(.*\.(sh|sh\.tmpl|bash|zsh)|(managed/)?dot_(bash|zsh)rc|(managed/)?dot_config/tmux/tmux\.conf\.tmpl|(managed/)?dot_config/zsh/completions/_.*|(managed/)?dot_local/bin/(work/)?executable_.*)$
exclude: ^managed/dot_local/bin/executable_(dotfiles|generate-completions|tmx|vscode-extensions-update)$
stages: [manual]

Expand All @@ -120,7 +120,7 @@ repos:
name: lint-sh
entry: mise exec -- shellcheck
language: system
files: ^(.*\.(sh|sh\.tmpl|bash)|(managed/)?dot_bashrc|(managed/)?dot_local/bin/executable_.*)$
files: ^(.*\.(sh|sh\.tmpl|bash)|(managed/)?dot_bashrc|(managed/)?dot_local/bin/(work/)?executable_.*)$
exclude: ^managed/dot_local/bin/executable_(dotfiles|generate-completions|tmx|vscode-extensions-update)$
stages: [pre-commit]

Expand Down
7 changes: 7 additions & 0 deletions managed/dot_config/fish/conf.d/20-work.fish
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# The work dotfiles source applies its executables and shims here. Prepend it so
# its shims shadow the real binaries; it is absent on personal machines.
set -l work_bin "$HOME/.local/bin/work"
if test -d $work_bin
fish_add_path --move --prepend --path $work_bin
end

set -l work_root "$__fish_config_dir/work"

if test -d $work_root
Expand Down
7 changes: 7 additions & 0 deletions managed/dot_config/zsh/conf.d/20-work.zsh
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# The work dotfiles source applies its executables and shims here. Prepend it so
# its shims shadow the real binaries; it is absent on personal machines.
zsh_work_bin="$HOME/.local/bin/work"
if [[ -d $zsh_work_bin ]]; then
path=("$zsh_work_bin" ${path:#$zsh_work_bin})
fi

ZSH_WORK_ROOT="${ZSH_WORK_ROOT:-$ZSH_CONFIG_DIR/work}"

_source_zsh_globbed_files "$ZSH_WORK_ROOT/functions"
Expand Down
37 changes: 22 additions & 15 deletions managed/dot_local/bin/executable_generate-completions
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ thin wrapper shims stay POSIX sh.
Configuration lives in ~/.config/generate-completions/:

- config.json: chezmoi-managed base registry.
- config.local.json: optional machine-local overlay (e.g. work-only tools).
- config.d/*.json: optional drop-ins, applied in name order, for registries
that other sources manage (e.g. a work dotfiles source).
- config.local.json: optional machine-local overlay, applied last.

Both files share the same shape:
All files share the same shape:

{
"commands": {
Expand All @@ -25,7 +27,7 @@ Both files share the same shape:
}
}

Overlay commands merge over the base by name; a null entry removes the
Later files' commands merge over earlier ones by name; a null entry removes the
command. "{shell}" in generator arguments is replaced with the shell being
generated for. "shells" defaults to fish and zsh, and "targets" overrides the
conventional per-shell target paths.
Expand All @@ -42,7 +44,9 @@ from pathlib import Path
from typing import Any

DEFAULT_SHELLS = ("fish", "zsh")
CONFIG_FILES = ("config.json", "config.local.json")
BASE_CONFIG = "config.json"
DROP_IN_DIR = "config.d"
LOCAL_CONFIG = "config.local.json"

CommandEntry = dict[str, Any]

Expand All @@ -61,17 +65,20 @@ def config_dir() -> Path:
return config_home() / "generate-completions"


def config_files() -> list[Path]:
"""Return the existing config files in merge order: base, drop-ins, local."""
directory = config_dir()
drop_ins = sorted((directory / DROP_IN_DIR).glob("*.json"))
candidates = [directory / BASE_CONFIG, *drop_ins, directory / LOCAL_CONFIG]
return [path for path in candidates if path.is_file()]


def load_commands() -> dict[str, CommandEntry]:
"""Merge the base and local config files into a command registry."""
"""Merge the config files into a command registry."""
commands: dict[str, CommandEntry] = {}
found = False

for filename in CONFIG_FILES:
path = config_dir() / filename
if not path.is_file():
continue
found = True
paths = config_files()

for path in paths:
try:
data = json.loads(path.read_text())
except (OSError, json.JSONDecodeError) as error:
Expand All @@ -89,7 +96,7 @@ def load_commands() -> dict[str, CommandEntry]:
else:
raise ConfigError(f"{path}: command {name!r} must be an object or null")

if not found:
if not paths:
raise ConfigError(
f"no config found under {config_dir()} (is the chezmoi-managed config.json applied?)"
)
Expand Down Expand Up @@ -178,8 +185,8 @@ def main(argv: list[str] | None = None) -> int:
description="Regenerate fish and zsh completions for supported commands.",
epilog=(
"When no commands are provided, regenerate all supported completions."
" Supported commands come from config.json and config.local.json under"
" ~/.config/generate-completions/."
" Supported commands come from config.json, config.d/*.json, and"
" config.local.json under ~/.config/generate-completions/."
),
)
parser.add_argument("commands", nargs="*", metavar="COMMAND", help="commands to regenerate")
Expand Down
62 changes: 62 additions & 0 deletions tests/test_generate_completions.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,68 @@ def test_load_commands_merges_local_over_base(config_home):
assert commands["chezmoi"]["generator"][0] == "work-chezmoi"


def write_drop_in(config_home, filename, commands):
drop_ins = config_home / "generate-completions" / "config.d"
drop_ins.mkdir(exist_ok=True)
path = drop_ins / filename
path.write_text(json.dumps({"commands": commands}))
return path


def test_load_commands_merges_drop_ins_between_base_and_local(config_home):
write_config(
config_home,
"config.json",
{"base": {"generator": ["base"]}, "shared": {"generator": ["from-base"]}},
)
write_drop_in(
config_home,
"work.json",
{
"base": None,
"shared": {"generator": ["from-drop-in"]},
"work-tool": {"generator": ["work-tool"]},
},
)
write_config(config_home, "config.local.json", {"work-tool": {"generator": ["from-local"]}})

commands = gc.load_commands()

assert sorted(commands) == ["shared", "work-tool"]
assert commands["shared"]["generator"] == ["from-drop-in"]
assert commands["work-tool"]["generator"] == ["from-local"]


def test_load_commands_applies_drop_ins_in_name_order(config_home):
write_config(config_home, "config.json", {})
write_drop_in(config_home, "20-later.json", {"tool": {"generator": ["later"]}})
write_drop_in(config_home, "10-earlier.json", {"tool": {"generator": ["earlier"]}})

assert gc.load_commands()["tool"]["generator"] == ["later"]


def test_load_commands_ignores_drop_ins_without_json_suffix(config_home):
write_config(config_home, "config.json", {})
write_drop_in(config_home, "work.json.bak", {"stale": {"generator": ["stale"]}})

assert gc.load_commands() == {}


def test_load_commands_accepts_a_drop_in_without_base_config(config_home):
write_drop_in(config_home, "work.json", {"tool": {"generator": ["tool"]}})

assert sorted(gc.load_commands()) == ["tool"]


def test_load_commands_names_a_malformed_drop_in(config_home):
write_config(config_home, "config.json", {})
drop_in = write_drop_in(config_home, "work.json", {})
drop_in.write_text("{not json")

with pytest.raises(gc.ConfigError, match=r"config\.d/work\.json"):
gc.load_commands()


@pytest.mark.usefixtures("config_home")
def test_load_commands_without_any_config_fails():
with pytest.raises(gc.ConfigError, match="no config found"):
Expand Down
Loading