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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
- `git workspace cache get|set|exists <key>` — file-based cache scoped by the `GIT_WORKSPACE_CACHE_NAMESPACE` env var; intended for use inside hook scripts to skip already-completed work (e.g. paired with `GIT_WORKSPACE_FINGERPRINT_*` to gate `uv sync`). Cache lives at `<root>/.workspace/.cache/<namespace>/<key>` with a self-managed `.gitignore`. The hook runner injects `GIT_WORKSPACE_CACHE_NAMESPACE=hooks/<hook_name>` for bin-script hooks.
- `GIT_WORKSPACE_CACHE_DIR` environment variable injected into hook execution environments — points to `<root>/.workspace/.cache`, useful for direct cache manipulation (e.g. invalidation via `rm -rf "$GIT_WORKSPACE_CACHE_DIR"`).

### Changed
- Copy assets are now rendered as [Jinja2](https://jinja.palletsprojects.com/) templates instead of regex placeholder substitution; existing `{{ GIT_WORKSPACE_* }}` files render identically, but `{% if %}` / `{% for %}` / filters are now supported for richer control over the output. Unknown variables still render verbatim; only `GIT_WORKSPACE_*` keys are exposed to templates. `git workspace doctor` flags malformed templates as errors.

## [0.6.0] - 2026-04-26

### Added
Expand Down
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,10 +380,10 @@ overwrite = false
</details>

<details>
<summary><i>Placeholders</i></summary>
<summary><i>Templating</i></summary>
<br/>

Text files in `.workspace/assets/` can contain `{{ GIT_WORKSPACE_* }}` placeholders. When the file is copied, each placeholder is replaced with the corresponding value from the environment — the same variables available to hooks, including manifest, runtime, and fingerprint vars.
Text files in `.workspace/assets/` are rendered as [Jinja2](https://jinja.palletsprojects.com/) templates. Every `GIT_WORKSPACE_*` variable available to hooks — base, manifest, runtime, and fingerprint vars — is exposed by name, so `{{ GIT_WORKSPACE_BRANCH }}` substitution works exactly as it always has.

```
# .workspace/assets/config.local.yaml
Expand All @@ -400,7 +400,17 @@ worktree: /path/to/workspace/feature/my-feature
env: staging
```

Unknown placeholders are left verbatim. Binary files are copied as-is without substitution. When the source is a directory, substitution is applied to every text file inside it.
Beyond simple substitution, you also get conditionals, loops, and filters — useful when a single asset needs to differ across branches:

```
{% if GIT_WORKSPACE_BRANCH == "main" %}
log_level: warn
{% else %}
log_level: debug
{% endif %}
```

Unknown variables are left verbatim (e.g. `{{ GIT_WORKSPACE_TYPO }}` is written as-is so typos are obvious). Only `GIT_WORKSPACE_*` keys are exposed — the host process environment is not. Binary files are copied as-is without rendering. When the source is a directory, every text file inside it is rendered. `git workspace doctor` flags both unknown variables and template syntax errors.

</details>

Expand Down Expand Up @@ -634,4 +644,4 @@ If it turns out to be useful to you too, [consider supporting the project](https

---

*Built with [Typer](https://typer.tiangolo.com), [Rich](https://rich.readthedocs.io), and a deep appreciation for git worktrees.*
*Built with [Typer](https://typer.tiangolo.com), [Rich](https://rich.readthedocs.io), [Jinja2](https://jinja.palletsprojects.com), and a deep appreciation for git worktrees.*
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ classifiers = [
"Programming Language :: Python :: 3.15",
"Topic :: Software Development :: Version Control :: Git",
]
dependencies = ["tomlkit>=0.13", "typer>=0.24.1"]
dependencies = ["jinja2>=3.1", "tomlkit>=0.13", "typer>=0.24.1"]

[project.urls]
Homepage = "https://github.com/ewilazarus/git-workspace"
Expand Down
52 changes: 30 additions & 22 deletions src/git_workspace/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from pathlib import Path
from types import TracebackType

from jinja2 import DebugUndefined, Environment, TemplateError

from git_workspace import git
from git_workspace.errors import WorkspaceCopyError, WorkspaceLinkError
from git_workspace.manifest import Asset, Copy, Link
Expand Down Expand Up @@ -180,9 +182,11 @@ class Copier(AssetManager[Copy]):
overwrite existing files on reapplication. The only error case is
attempting to copy over an existing symlink.

Text files are inspected for ``{{ GIT_WORKSPACE_* }}`` placeholders and
values are substituted from the provided environment dict. Binary files
are copied as-is.
Text files are rendered as Jinja2 templates with ``GIT_WORKSPACE_*``
variables from the provided environment dict; this supports
``{{ var }}`` substitution as well as ``{% if %}`` / ``{% for %}`` and
filters. Undefined variables render verbatim as ``{{ name }}``.
Binary files are copied as-is.
"""

asset_name = "copy"
Expand All @@ -192,34 +196,38 @@ class Copier(AssetManager[Copy]):

def __init__(self, worktree: Worktree, ignore: IgnoreManager, env: dict[str, str]) -> None:
super().__init__(worktree, ignore, worktree.workspace.manifest.copies)
self._env = env

def _resolve_placeholders(self, content: str) -> tuple[str, int]:
count = 0

def replace(m: re.Match) -> str:
nonlocal count

value = self._env.get(m.group(1))
if value is not None:
count += 1
return value

return m.group(0)

return self.PLACEHOLDER_RE.sub(replace, content), count
self._template_vars = {k: v for k, v in env.items() if k.startswith("GIT_WORKSPACE_")}
self._jinja_env = Environment(
undefined=DebugUndefined,
autoescape=False,
keep_trailing_newline=True,
)

def _count_resolved(self, content: str) -> int:
return sum(
1 for m in self.PLACEHOLDER_RE.finditer(content) if m.group(1) in self._template_vars
)

def _render(self, source: Path, content: str) -> tuple[str, int]:
try:
template = self._jinja_env.from_string(content)
rendered = template.render(self._template_vars)
except TemplateError as e:
raise WorkspaceCopyError(f"Failed to render template {source!r}: {e}") from e
return rendered, self._count_resolved(content)

def _copy_with_substitution(self, source: Path, target: Path) -> int:
try:
content = source.read_text(encoding="utf-8")
new_content, count = self._resolve_placeholders(content)
target.write_text(new_content, encoding="utf-8")
return count
except UnicodeDecodeError, ValueError:
logger.debug("copying %s as binary (not valid UTF-8 text)", source)
shutil.copy2(source, target)
return 0

new_content, count = self._render(source, content)
target.write_text(new_content, encoding="utf-8")
return count

def _copy_dir_with_substitution(self, source: Path, target: Path) -> int:
total = 0

Expand Down
18 changes: 17 additions & 1 deletion src/git_workspace/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import TYPE_CHECKING, Literal

import tomlkit
from jinja2 import Environment, TemplateSyntaxError

from git_workspace import git
from git_workspace.assets import Copier
Expand Down Expand Up @@ -499,6 +500,7 @@ def _check_copy_placeholders(workspace: Workspace, findings: list[Finding]) -> N
}
)
assets_dir = workspace.paths.assets
jinja_env = Environment()

for copy in workspace.manifest.copies:
source = assets_dir / copy.source
Expand All @@ -513,12 +515,26 @@ def _check_copy_placeholders(workspace: Workspace, findings: list[Finding]) -> N
content = file.read_text(encoding="utf-8")
except UnicodeDecodeError, OSError:
continue

rel = file.relative_to(assets_dir)

try:
jinja_env.parse(content)
except TemplateSyntaxError as e:
findings.append(
Finding(
"error",
f"Copy asset '{rel}' has invalid template syntax"
f" on line {e.lineno}: {e.message}",
)
)
continue

seen: set[str] = set()
for match in Copier.PLACEHOLDER_RE.finditer(content):
key = match.group(1)
if key not in known and key not in seen:
seen.add(key)
rel = file.relative_to(assets_dir)
findings.append(
Finding(
"warning",
Expand Down
10 changes: 10 additions & 0 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,16 @@ def workspace_with_placeholder_copies(setup: Setup, tmp_path: Path) -> Workspace
)


@pytest.fixture
def workspace_with_jinja_copies(setup: Setup, tmp_path: Path) -> Workspace:
setup(config="with-jinja-copies")
return Workspace.clone(
workspace_dir=str(tmp_path / "workspace"),
url=str(tmp_path / "repo"),
config_url=str(tmp_path / "configs" / "with-jinja-copies"),
)


@pytest.fixture
def workspace_with_prune(setup: Setup, tmp_path: Path) -> Workspace:
setup(config="with-prune")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{% if GIT_WORKSPACE_BRANCH == "main" %}env=prod{% else %}env=dev{% endif %}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
initial
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ref: refs/heads/main
Empty file.
10 changes: 10 additions & 0 deletions tests/integration/fixtures/configs/with-jinja-copies/dotgit/config
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[user]
email = fixture@test.com
name = fixture
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Unnamed repository; edit this file 'description' to name the repository.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/sh
#
# An example hook script to check the commit log message taken by
# applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit. The hook is
# allowed to edit the commit message file.
#
# To enable this hook, rename this file to "applypatch-msg".

. git-sh-setup
commitmsg="$(git rev-parse --git-path hooks/commit-msg)"
test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"}
:
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message. The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit. The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".

# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"

# This example catches duplicate Signed-off-by lines.

test "" = "$(grep '^Signed-off-by: ' "$1" |
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
echo >&2 Duplicate Signed-off-by lines.
exit 1
}
Loading
Loading