diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a26b56..0322f97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - `git workspace cache get|set|exists ` — 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 `/.workspace/.cache//` with a self-managed `.gitignore`. The hook runner injects `GIT_WORKSPACE_CACHE_NAMESPACE=hooks/` for bin-script hooks. - `GIT_WORKSPACE_CACHE_DIR` environment variable injected into hook execution environments — points to `/.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 diff --git a/README.md b/README.md index 9a28703..c9b56cc 100644 --- a/README.md +++ b/README.md @@ -380,10 +380,10 @@ overwrite = false
-Placeholders +Templating
-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 @@ -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.
@@ -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.* diff --git a/pyproject.toml b/pyproject.toml index a31412d..cfe6b93 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/src/git_workspace/assets.py b/src/git_workspace/assets.py index 34291c5..1dcf26e 100644 --- a/src/git_workspace/assets.py +++ b/src/git_workspace/assets.py @@ -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 @@ -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" @@ -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 diff --git a/src/git_workspace/doctor.py b/src/git_workspace/doctor.py index 23d3975..4c179f3 100644 --- a/src/git_workspace/doctor.py +++ b/src/git_workspace/doctor.py @@ -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 @@ -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 @@ -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", diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index a45719f..72b112b 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -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") diff --git a/tests/integration/fixtures/configs/with-jinja-copies/assets/template.txt b/tests/integration/fixtures/configs/with-jinja-copies/assets/template.txt new file mode 100644 index 0000000..83c04d0 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/assets/template.txt @@ -0,0 +1 @@ +{% if GIT_WORKSPACE_BRANCH == "main" %}env=prod{% else %}env=dev{% endif %} diff --git a/tests/integration/fixtures/configs/with-jinja-copies/bin/.keep b/tests/integration/fixtures/configs/with-jinja-copies/bin/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/COMMIT_EDITMSG b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/COMMIT_EDITMSG new file mode 100644 index 0000000..e79c5e8 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/COMMIT_EDITMSG @@ -0,0 +1 @@ +initial diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/HEAD b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/HEAD new file mode 100644 index 0000000..b870d82 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/HEAD @@ -0,0 +1 @@ +ref: refs/heads/main diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/MERGE_RR b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/MERGE_RR new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/config b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/config new file mode 100644 index 0000000..a5f1957 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/config @@ -0,0 +1,10 @@ +[core] + repositoryformatversion = 0 + filemode = true + bare = false + logallrefupdates = true + ignorecase = true + precomposeunicode = true +[user] + email = fixture@test.com + name = fixture diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/description b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/description new file mode 100644 index 0000000..498b267 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/description @@ -0,0 +1 @@ +Unnamed repository; edit this file 'description' to name the repository. diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/applypatch-msg.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/applypatch-msg.sample new file mode 100755 index 0000000..a5d7b84 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/applypatch-msg.sample @@ -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+"$@"} +: diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/commit-msg.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/commit-msg.sample new file mode 100755 index 0000000..b58d118 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/commit-msg.sample @@ -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 +} diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/fsmonitor-watchman.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/fsmonitor-watchman.sample new file mode 100755 index 0000000..23e856f --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/fsmonitor-watchman.sample @@ -0,0 +1,174 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use IPC::Open2; + +# An example hook script to integrate Watchman +# (https://facebook.github.io/watchman/) with git to speed up detecting +# new and modified files. +# +# The hook is passed a version (currently 2) and last update token +# formatted as a string and outputs to stdout a new update token and +# all files that have been modified since the update token. Paths must +# be relative to the root of the working tree and separated by a single NUL. +# +# To enable this hook, rename this file to "query-watchman" and set +# 'git config core.fsmonitor .git/hooks/query-watchman' +# +my ($version, $last_update_token) = @ARGV; + +# Uncomment for debugging +# print STDERR "$0 $version $last_update_token\n"; + +# Check the hook interface version +if ($version ne 2) { + die "Unsupported query-fsmonitor hook version '$version'.\n" . + "Falling back to scanning...\n"; +} + +my $git_work_tree = get_working_dir(); + +my $retry = 1; + +my $json_pkg; +eval { + require JSON::XS; + $json_pkg = "JSON::XS"; + 1; +} or do { + require JSON::PP; + $json_pkg = "JSON::PP"; +}; + +launch_watchman(); + +sub launch_watchman { + my $o = watchman_query(); + if (is_work_tree_watched($o)) { + output_result($o->{clock}, @{$o->{files}}); + } +} + +sub output_result { + my ($clockid, @files) = @_; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # binmode $fh, ":utf8"; + # print $fh "$clockid\n@files\n"; + # close $fh; + + binmode STDOUT, ":utf8"; + print $clockid; + print "\0"; + local $, = "\0"; + print @files; +} + +sub watchman_clock { + my $response = qx/watchman clock "$git_work_tree"/; + die "Failed to get clock id on '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + + return $json_pkg->new->utf8->decode($response); +} + +sub watchman_query { + my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') + or die "open2() failed: $!\n" . + "Falling back to scanning...\n"; + + # In the query expression below we're asking for names of files that + # changed since $last_update_token but not from the .git folder. + # + # To accomplish this, we're using the "since" generator to use the + # recency index to select candidate nodes and "fields" to limit the + # output to file names only. Then we're using the "expression" term to + # further constrain the results. + my $last_update_line = ""; + if (substr($last_update_token, 0, 1) eq "c") { + $last_update_token = "\"$last_update_token\""; + $last_update_line = qq[\n"since": $last_update_token,]; + } + my $query = <<" END"; + ["query", "$git_work_tree", {$last_update_line + "fields": ["name"], + "expression": ["not", ["dirname", ".git"]] + }] + END + + # Uncomment for debugging the watchman query + # open (my $fh, ">", ".git/watchman-query.json"); + # print $fh $query; + # close $fh; + + print CHLD_IN $query; + close CHLD_IN; + my $response = do {local $/; }; + + # Uncomment for debugging the watch response + # open ($fh, ">", ".git/watchman-response.json"); + # print $fh $response; + # close $fh; + + die "Watchman: command returned no output.\n" . + "Falling back to scanning...\n" if $response eq ""; + die "Watchman: command returned invalid output: $response\n" . + "Falling back to scanning...\n" unless $response =~ /^\{/; + + return $json_pkg->new->utf8->decode($response); +} + +sub is_work_tree_watched { + my ($output) = @_; + my $error = $output->{error}; + if ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) { + $retry--; + my $response = qx/watchman watch "$git_work_tree"/; + die "Failed to make watchman watch '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + $output = $json_pkg->new->utf8->decode($response); + $error = $output->{error}; + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # close $fh; + + # Watchman will always return all files on the first query so + # return the fast "everything is dirty" flag to git and do the + # Watchman query just to get it over with now so we won't pay + # the cost in git to look up each individual file. + my $o = watchman_clock(); + $error = $output->{error}; + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + output_result($o->{clock}, ("/")); + $last_update_token = $o->{clock}; + + eval { launch_watchman() }; + return 0; + } + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + return 1; +} + +sub get_working_dir { + my $working_dir; + if ($^O =~ 'msys' || $^O =~ 'cygwin') { + $working_dir = Win32::GetCwd(); + $working_dir =~ tr/\\/\//; + } else { + require Cwd; + $working_dir = Cwd::cwd(); + } + + return $working_dir; +} diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/post-update.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/post-update.sample new file mode 100755 index 0000000..ec17ec1 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/post-update.sample @@ -0,0 +1,8 @@ +#!/bin/sh +# +# An example hook script to prepare a packed repository for use over +# dumb transports. +# +# To enable this hook, rename this file to "post-update". + +exec git update-server-info diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-applypatch.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-applypatch.sample new file mode 100755 index 0000000..4142082 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-applypatch.sample @@ -0,0 +1,14 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed +# 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. +# +# To enable this hook, rename this file to "pre-applypatch". + +. git-sh-setup +precommit="$(git rev-parse --git-path hooks/pre-commit)" +test -x "$precommit" && exec "$precommit" ${1+"$@"} +: diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-commit.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-commit.sample new file mode 100755 index 0000000..29ed5ee --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-commit.sample @@ -0,0 +1,49 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git commit" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message if +# it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-commit". + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=$(git hash-object -t tree /dev/null) +fi + +# If you want to allow non-ASCII filenames set this variable to true. +allownonascii=$(git config --type=bool hooks.allownonascii) + +# Redirect output to stderr. +exec 1>&2 + +# Cross platform projects tend to avoid non-ASCII filenames; prevent +# them from being added to the repository. We exploit the fact that the +# printable range starts at the space character and ends with tilde. +if [ "$allownonascii" != "true" ] && + # Note that the use of brackets around a tr range is ok here, (it's + # even required, for portability to Solaris 10's /usr/bin/tr), since + # the square bracket bytes happen to fall in the designated range. + test $(git diff-index --cached --name-only --diff-filter=A -z $against | + LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 +then + cat <<\EOF +Error: Attempt to add a non-ASCII file name. + +This can cause problems if you want to work with people on other platforms. + +To be portable it is advisable to rename the file. + +If you know what you are doing you can disable this check using: + + git config hooks.allownonascii true +EOF + exit 1 +fi + +# If there are whitespace errors, print the offending file names and fail. +exec git diff-index --check --cached $against -- diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-merge-commit.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-merge-commit.sample new file mode 100755 index 0000000..399eab1 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-merge-commit.sample @@ -0,0 +1,13 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git merge" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message to +# stderr if it wants to stop the merge commit. +# +# To enable this hook, rename this file to "pre-merge-commit". + +. git-sh-setup +test -x "$GIT_DIR/hooks/pre-commit" && + exec "$GIT_DIR/hooks/pre-commit" +: diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-push.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-push.sample new file mode 100755 index 0000000..4ce688d --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-push.sample @@ -0,0 +1,53 @@ +#!/bin/sh + +# An example hook script to verify what is about to be pushed. Called by "git +# push" after it has checked the remote status, but before anything has been +# pushed. If this script exits with a non-zero status nothing will be pushed. +# +# This hook is called with the following parameters: +# +# $1 -- Name of the remote to which the push is being done +# $2 -- URL to which the push is being done +# +# If pushing without using a named remote those arguments will be equal. +# +# Information about the commits which are being pushed is supplied as lines to +# the standard input in the form: +# +# +# +# This sample shows how to prevent push of commits where the log message starts +# with "WIP" (work in progress). + +remote="$1" +url="$2" + +zero=$(git hash-object --stdin &2 "Found WIP commit in $local_ref, not pushing" + exit 1 + fi + fi +done + +exit 0 diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-rebase.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-rebase.sample new file mode 100755 index 0000000..6cbef5c --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-rebase.sample @@ -0,0 +1,169 @@ +#!/bin/sh +# +# Copyright (c) 2006, 2008 Junio C Hamano +# +# The "pre-rebase" hook is run just before "git rebase" starts doing +# its job, and can prevent the command from running by exiting with +# non-zero status. +# +# The hook is called with the following parameters: +# +# $1 -- the upstream the series was forked from. +# $2 -- the branch being rebased (or empty when rebasing the current branch). +# +# This sample shows how to prevent topic branches that are already +# merged to 'next' branch from getting rebased, because allowing it +# would result in rebasing already published history. + +publish=next +basebranch="$1" +if test "$#" = 2 +then + topic="refs/heads/$2" +else + topic=`git symbolic-ref HEAD` || + exit 0 ;# we do not interrupt rebasing detached HEAD +fi + +case "$topic" in +refs/heads/??/*) + ;; +*) + exit 0 ;# we do not interrupt others. + ;; +esac + +# Now we are dealing with a topic branch being rebased +# on top of master. Is it OK to rebase it? + +# Does the topic really exist? +git show-ref -q "$topic" || { + echo >&2 "No such branch $topic" + exit 1 +} + +# Is topic fully merged to master? +not_in_master=`git rev-list --pretty=oneline ^master "$topic"` +if test -z "$not_in_master" +then + echo >&2 "$topic is fully merged to master; better remove it." + exit 1 ;# we could allow it, but there is no point. +fi + +# Is topic ever merged to next? If so you should not be rebasing it. +only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` +only_next_2=`git rev-list ^master ${publish} | sort` +if test "$only_next_1" = "$only_next_2" +then + not_in_topic=`git rev-list "^$topic" master` + if test -z "$not_in_topic" + then + echo >&2 "$topic is already up to date with master" + exit 1 ;# we could allow it, but there is no point. + else + exit 0 + fi +else + not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` + /usr/bin/perl -e ' + my $topic = $ARGV[0]; + my $msg = "* $topic has commits already merged to public branch:\n"; + my (%not_in_next) = map { + /^([0-9a-f]+) /; + ($1 => 1); + } split(/\n/, $ARGV[1]); + for my $elem (map { + /^([0-9a-f]+) (.*)$/; + [$1 => $2]; + } split(/\n/, $ARGV[2])) { + if (!exists $not_in_next{$elem->[0]}) { + if ($msg) { + print STDERR $msg; + undef $msg; + } + print STDERR " $elem->[1]\n"; + } + } + ' "$topic" "$not_in_next" "$not_in_master" + exit 1 +fi + +<<\DOC_END + +This sample hook safeguards topic branches that have been +published from being rewound. + +The workflow assumed here is: + + * Once a topic branch forks from "master", "master" is never + merged into it again (either directly or indirectly). + + * Once a topic branch is fully cooked and merged into "master", + it is deleted. If you need to build on top of it to correct + earlier mistakes, a new topic branch is created by forking at + the tip of the "master". This is not strictly necessary, but + it makes it easier to keep your history simple. + + * Whenever you need to test or publish your changes to topic + branches, merge them into "next" branch. + +The script, being an example, hardcodes the publish branch name +to be "next", but it is trivial to make it configurable via +$GIT_DIR/config mechanism. + +With this workflow, you would want to know: + +(1) ... if a topic branch has ever been merged to "next". Young + topic branches can have stupid mistakes you would rather + clean up before publishing, and things that have not been + merged into other branches can be easily rebased without + affecting other people. But once it is published, you would + not want to rewind it. + +(2) ... if a topic branch has been fully merged to "master". + Then you can delete it. More importantly, you should not + build on top of it -- other people may already want to + change things related to the topic as patches against your + "master", so if you need further changes, it is better to + fork the topic (perhaps with the same name) afresh from the + tip of "master". + +Let's look at this example: + + o---o---o---o---o---o---o---o---o---o "next" + / / / / + / a---a---b A / / + / / / / + / / c---c---c---c B / + / / / \ / + / / / b---b C \ / + / / / / \ / + ---o---o---o---o---o---o---o---o---o---o---o "master" + + +A, B and C are topic branches. + + * A has one fix since it was merged up to "next". + + * B has finished. It has been fully merged up to "master" and "next", + and is ready to be deleted. + + * C has not merged to "next" at all. + +We would want to allow C to be rebased, refuse A, and encourage +B to be deleted. + +To compute (1): + + git rev-list ^master ^topic next + git rev-list ^master next + + if these match, topic has not merged in next at all. + +To compute (2): + + git rev-list master..topic + + if this is empty, it is fully merged to "master". + +DOC_END diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-receive.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-receive.sample new file mode 100755 index 0000000..a1fd29e --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/pre-receive.sample @@ -0,0 +1,24 @@ +#!/bin/sh +# +# An example hook script to make use of push options. +# The example simply echoes all push options that start with 'echoback=' +# and rejects all pushes when the "reject" push option is used. +# +# To enable this hook, rename this file to "pre-receive". + +if test -n "$GIT_PUSH_OPTION_COUNT" +then + i=0 + while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" + do + eval "value=\$GIT_PUSH_OPTION_$i" + case "$value" in + echoback=*) + echo "echo from the pre-receive-hook: ${value#*=}" >&2 + ;; + reject) + exit 1 + esac + i=$((i + 1)) + done +fi diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/prepare-commit-msg.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/prepare-commit-msg.sample new file mode 100755 index 0000000..10fa14c --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/prepare-commit-msg.sample @@ -0,0 +1,42 @@ +#!/bin/sh +# +# An example hook script to prepare the commit log message. +# Called by "git commit" with the name of the file that has the +# commit message, followed by the description of the commit +# message's source. The hook's purpose is to edit the commit +# message file. If the hook fails with a non-zero status, +# the commit is aborted. +# +# To enable this hook, rename this file to "prepare-commit-msg". + +# This hook includes three examples. The first one removes the +# "# Please enter the commit message..." help message. +# +# The second includes the output of "git diff --name-status -r" +# into the message, just before the "git status" output. It is +# commented because it doesn't cope with --amend or with squashed +# commits. +# +# The third example adds a Signed-off-by line to the message, that can +# still be edited. This is rarely a good idea. + +COMMIT_MSG_FILE=$1 +COMMIT_SOURCE=$2 +SHA1=$3 + +/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" + +# case "$COMMIT_SOURCE,$SHA1" in +# ,|template,) +# /usr/bin/perl -i.bak -pe ' +# print "\n" . `git diff --cached --name-status -r` +# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; +# *) ;; +# esac + +# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" +# if test -z "$COMMIT_SOURCE" +# then +# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" +# fi diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/push-to-checkout.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/push-to-checkout.sample new file mode 100755 index 0000000..af5a0c0 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/push-to-checkout.sample @@ -0,0 +1,78 @@ +#!/bin/sh + +# An example hook script to update a checked-out tree on a git push. +# +# This hook is invoked by git-receive-pack(1) when it reacts to git +# push and updates reference(s) in its repository, and when the push +# tries to update the branch that is currently checked out and the +# receive.denyCurrentBranch configuration variable is set to +# updateInstead. +# +# By default, such a push is refused if the working tree and the index +# of the remote repository has any difference from the currently +# checked out commit; when both the working tree and the index match +# the current commit, they are updated to match the newly pushed tip +# of the branch. This hook is to be used to override the default +# behaviour; however the code below reimplements the default behaviour +# as a starting point for convenient modification. +# +# The hook receives the commit with which the tip of the current +# branch is going to be updated: +commit=$1 + +# It can exit with a non-zero status to refuse the push (when it does +# so, it must not modify the index or the working tree). +die () { + echo >&2 "$*" + exit 1 +} + +# Or it can make any necessary changes to the working tree and to the +# index to bring them to the desired state when the tip of the current +# branch is updated to the new commit, and exit with a zero status. +# +# For example, the hook can simply run git read-tree -u -m HEAD "$1" +# in order to emulate git fetch that is run in the reverse direction +# with git push, as the two-tree form of git read-tree -u -m is +# essentially the same as git switch or git checkout that switches +# branches while keeping the local changes in the working tree that do +# not interfere with the difference between the branches. + +# The below is a more-or-less exact translation to shell of the C code +# for the default behaviour for git's push-to-checkout hook defined in +# the push_to_deploy() function in builtin/receive-pack.c. +# +# Note that the hook will be executed from the repository directory, +# not from the working tree, so if you want to perform operations on +# the working tree, you will have to adapt your code accordingly, e.g. +# by adding "cd .." or using relative paths. + +if ! git update-index -q --ignore-submodules --refresh +then + die "Up-to-date check failed" +fi + +if ! git diff-files --quiet --ignore-submodules -- +then + die "Working directory has unstaged changes" +fi + +# This is a rough translation of: +# +# head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX +if git cat-file -e HEAD 2>/dev/null +then + head=HEAD +else + head=$(git hash-object -t tree --stdin &2 + exit 1 +} + +unset GIT_DIR GIT_WORK_TREE +cd "$worktree" && + +if grep -q "^diff --git " "$1" +then + validate_patch "$1" +else + validate_cover_letter "$1" +fi && + +if test "$GIT_SENDEMAIL_FILE_COUNTER" = "$GIT_SENDEMAIL_FILE_TOTAL" +then + git config --unset-all sendemail.validateWorktree && + trap 'git worktree remove -ff "$worktree"' EXIT && + validate_series +fi diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/update.sample b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/update.sample new file mode 100755 index 0000000..c4d426b --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/hooks/update.sample @@ -0,0 +1,128 @@ +#!/bin/sh +# +# An example hook script to block unannotated tags from entering. +# Called by "git receive-pack" with arguments: refname sha1-old sha1-new +# +# To enable this hook, rename this file to "update". +# +# Config +# ------ +# hooks.allowunannotated +# This boolean sets whether unannotated tags will be allowed into the +# repository. By default they won't be. +# hooks.allowdeletetag +# This boolean sets whether deleting tags will be allowed in the +# repository. By default they won't be. +# hooks.allowmodifytag +# This boolean sets whether a tag may be modified after creation. By default +# it won't be. +# hooks.allowdeletebranch +# This boolean sets whether deleting branches will be allowed in the +# repository. By default they won't be. +# hooks.denycreatebranch +# This boolean sets whether remotely creating branches will be denied +# in the repository. By default this is allowed. +# + +# --- Command line +refname="$1" +oldrev="$2" +newrev="$3" + +# --- Safety check +if [ -z "$GIT_DIR" ]; then + echo "Don't run this script from the command line." >&2 + echo " (if you want, you could supply GIT_DIR then run" >&2 + echo " $0 )" >&2 + exit 1 +fi + +if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +# --- Config +allowunannotated=$(git config --type=bool hooks.allowunannotated) +allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch) +denycreatebranch=$(git config --type=bool hooks.denycreatebranch) +allowdeletetag=$(git config --type=bool hooks.allowdeletetag) +allowmodifytag=$(git config --type=bool hooks.allowmodifytag) + +# check for no description +projectdesc=$(sed -e '1q' "$GIT_DIR/description") +case "$projectdesc" in +"Unnamed repository"* | "") + echo "*** Project description file hasn't been set" >&2 + exit 1 + ;; +esac + +# --- Check types +# if $newrev is 0000...0000, it's a commit to delete a ref. +zero=$(git hash-object --stdin &2 + echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 + exit 1 + fi + ;; + refs/tags/*,delete) + # delete tag + if [ "$allowdeletetag" != "true" ]; then + echo "*** Deleting a tag is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/tags/*,tag) + # annotated tag + if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 + then + echo "*** Tag '$refname' already exists." >&2 + echo "*** Modifying a tag is not allowed in this repository." >&2 + exit 1 + fi + ;; + refs/heads/*,commit) + # branch + if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then + echo "*** Creating a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/heads/*,delete) + # delete branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/remotes/*,commit) + # tracking branch + ;; + refs/remotes/*,delete) + # delete tracking branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a tracking branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + *) + # Anything else (is there anything else?) + echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 + exit 1 + ;; +esac + +# --- Finished +exit 0 diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/index b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/index new file mode 100644 index 0000000..65d6751 Binary files /dev/null and b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/index differ diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/info/exclude b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/info/exclude new file mode 100644 index 0000000..a5196d1 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/info/exclude @@ -0,0 +1,6 @@ +# git ls-files --others --exclude-from=.git/info/exclude +# Lines that start with '#' are comments. +# For a project mostly in C, the following would be a good set of +# exclude patterns (uncomment them if you want to use them): +# *.[oa] +# *~ diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/logs/HEAD b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/logs/HEAD new file mode 100644 index 0000000..02c12ac --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/logs/HEAD @@ -0,0 +1 @@ +0000000000000000000000000000000000000000 6e20999a113f29e1b82dc63fb91d203a34bcb07a fixture 1776136782 -0300 commit (initial): initial diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/logs/refs/heads/main b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/logs/refs/heads/main new file mode 100644 index 0000000..02c12ac --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/logs/refs/heads/main @@ -0,0 +1 @@ +0000000000000000000000000000000000000000 6e20999a113f29e1b82dc63fb91d203a34bcb07a fixture 1776136782 -0300 commit (initial): initial diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/objects/4b/825dc642cb6eb9a060e54bf8d69288fbee4904 b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/objects/4b/825dc642cb6eb9a060e54bf8d69288fbee4904 new file mode 100644 index 0000000..adf6411 Binary files /dev/null and b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/objects/4b/825dc642cb6eb9a060e54bf8d69288fbee4904 differ diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/objects/6e/20999a113f29e1b82dc63fb91d203a34bcb07a b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/objects/6e/20999a113f29e1b82dc63fb91d203a34bcb07a new file mode 100644 index 0000000..2ca0543 --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/objects/6e/20999a113f29e1b82dc63fb91d203a34bcb07a @@ -0,0 +1,3 @@ +x•�Q +!@ûös�btÝq„ˆ®¢îHB&Ø,tüö£ ô÷xðxeôÞ,áI§øÌnÝ +yW2IŽ eõ¹òFÑ1×,â#z“v}Œ µ}tŸ×ÜUÞz)£ßÀ†@v¡Àθ šÃ/•ÿ*Ó^M[zš/Ú�4® \ No newline at end of file diff --git a/tests/integration/fixtures/configs/with-jinja-copies/dotgit/refs/heads/main b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/refs/heads/main new file mode 100644 index 0000000..5fa614c --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/dotgit/refs/heads/main @@ -0,0 +1 @@ +6e20999a113f29e1b82dc63fb91d203a34bcb07a diff --git a/tests/integration/fixtures/configs/with-jinja-copies/manifest.toml b/tests/integration/fixtures/configs/with-jinja-copies/manifest.toml new file mode 100644 index 0000000..7df100d --- /dev/null +++ b/tests/integration/fixtures/configs/with-jinja-copies/manifest.toml @@ -0,0 +1,7 @@ +version = 1 + +base_branch = "main" + +[[copy]] +source = "template.txt" +target = "template.txt" diff --git a/tests/integration/test_copying.py b/tests/integration/test_copying.py index e85e4b8..fba64d1 100644 --- a/tests/integration/test_copying.py +++ b/tests/integration/test_copying.py @@ -176,3 +176,23 @@ def test_copy_is_independent_of_source(workspace_with_copies: Workspace) -> None original_content = source.read_text() target.write_text("modified") assert source.read_text() == original_content + + +def test_jinja_if_block_renders_branch_main( + workspace_with_jinja_copies: Workspace, +) -> None: + up(branch="main", workspace_dir=str(workspace_with_jinja_copies.dir)) + target = workspace_with_jinja_copies.dir / "main" / "template.txt" + assert target.read_text() == "env=prod\n" + + +def test_jinja_if_block_renders_other_branch( + workspace_with_jinja_copies: Workspace, +) -> None: + up( + branch="feature/x", + base_branch="main", + workspace_dir=str(workspace_with_jinja_copies.dir), + ) + target = workspace_with_jinja_copies.dir / "feature" / "x" / "template.txt" + assert target.read_text() == "env=dev\n" diff --git a/tests/unit/test_copier.py b/tests/unit/test_copier.py index c954471..1dca2ff 100644 --- a/tests/unit/test_copier.py +++ b/tests/unit/test_copier.py @@ -521,3 +521,116 @@ def test_apply_returns_zero_when_skipped(self, copier: Copier, fs: FakeFilesyste copy = Copy(source="template.txt", target="template.txt", overwrite=False) assert copier._apply(copy) == 0 + + +class TestJinjaTemplating: + ASSETS_DIR = Path("/workspace/.workspace/assets") + WORKTREE_DIR = Path("/workspace/feat/GWS-001") + ENV = { + "GIT_WORKSPACE_BRANCH": "main", + "GIT_WORKSPACE_VAR_ENV": "staging", + "PATH": "/usr/bin", # non-prefixed env should not be exposed to templates + } + + @pytest.fixture + def copier(self, mocker: MockerFixture) -> Copier: + worktree = mocker.MagicMock() + worktree.dir = self.WORKTREE_DIR + worktree.workspace.paths.assets = self.ASSETS_DIR + worktree.workspace.manifest.copies = [] + ignore = mocker.MagicMock(spec=IgnoreManager) + return Copier(worktree, ignore, env=self.ENV) + + def test_renders_if_block_when_condition_true(self, copier: Copier, fs: FakeFilesystem) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file( + str(source), + contents='{% if GIT_WORKSPACE_BRANCH == "main" %}prod{% else %}dev{% endif %}', + ) + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "prod" + + def test_renders_if_block_when_condition_false( + self, copier: Copier, fs: FakeFilesystem + ) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file( + str(source), + contents='{% if GIT_WORKSPACE_BRANCH == "release" %}prod{% else %}dev{% endif %}', + ) + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "dev" + + def test_supports_filters(self, copier: Copier, fs: FakeFilesystem) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file(str(source), contents="{{ GIT_WORKSPACE_BRANCH | upper }}") + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "MAIN" + + def test_supports_for_loop(self, copier: Copier, fs: FakeFilesystem) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file( + str(source), + contents="{% for c in GIT_WORKSPACE_BRANCH %}{{ c }}-{% endfor %}", + ) + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "m-a-i-n-" + + def test_unknown_variable_renders_verbatim(self, copier: Copier, fs: FakeFilesystem) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file(str(source), contents="{{ GIT_WORKSPACE_TYPO }}") + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "{{ GIT_WORKSPACE_TYPO }}" + + def test_does_not_expose_non_prefixed_env_to_templates( + self, copier: Copier, fs: FakeFilesystem + ) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file(str(source), contents="{{ PATH }}") + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "{{ PATH }}" + + def test_preserves_trailing_newline(self, copier: Copier, fs: FakeFilesystem) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file(str(source), contents="branch={{ GIT_WORKSPACE_BRANCH }}\n") + fs.create_dir(str(self.WORKTREE_DIR)) + + copier._copy_with_substitution(source, target) + + assert target.read_text() == "branch=main\n" + + def test_template_syntax_error_is_wrapped(self, copier: Copier, fs: FakeFilesystem) -> None: + source = self.ASSETS_DIR / "template.txt" + target = self.WORKTREE_DIR / "template.txt" + fs.create_file(str(source), contents="{% if GIT_WORKSPACE_BRANCH %}oops") + fs.create_dir(str(self.WORKTREE_DIR)) + + with pytest.raises(WorkspaceCopyError) as exc: + copier._copy_with_substitution(source, target) + + assert "template.txt" in str(exc.value) diff --git a/tests/unit/test_doctor_checks.py b/tests/unit/test_doctor_checks.py index 4aaa979..e888516 100644 --- a/tests/unit/test_doctor_checks.py +++ b/tests/unit/test_doctor_checks.py @@ -906,6 +906,40 @@ def test_warns_for_fingerprint_placeholder_when_fingerprint_not_declared( assert len(findings) == 1 assert "GIT_WORKSPACE_FINGERPRINT_DEPS" in findings[0].message + def test_returns_error_for_invalid_template_syntax( + self, workspace: MagicMock, tmp_path: Path + ) -> None: + assets = tmp_path / "assets" + assets.mkdir() + (assets / "template.txt").write_text("{% if GIT_WORKSPACE_BRANCH %}oops") + workspace.paths.assets = assets + workspace.manifest.copies = [Copy(source="template.txt", target="template.txt")] + workspace.manifest.vars = {} + + findings = [] + _check_copy_placeholders(workspace, findings) + + assert len(findings) == 1 + assert findings[0].level == "error" + assert "template.txt" in findings[0].message + assert "invalid template syntax" in findings[0].message + + def test_skips_placeholder_check_when_template_invalid( + self, workspace: MagicMock, tmp_path: Path + ) -> None: + assets = tmp_path / "assets" + assets.mkdir() + (assets / "template.txt").write_text("{% if %}{{ GIT_WORKSPACE_TYPO }}") + workspace.paths.assets = assets + workspace.manifest.copies = [Copy(source="template.txt", target="template.txt")] + workspace.manifest.vars = {} + + findings = [] + _check_copy_placeholders(workspace, findings) + + assert len(findings) == 1 + assert findings[0].level == "error" + class TestCheckFingerprintNameClashes: def test_returns_no_findings_for_unique_names(self, workspace: MagicMock) -> None: diff --git a/uv.lock b/uv.lock index 665529a..3043b4b 100644 --- a/uv.lock +++ b/uv.lock @@ -64,6 +64,7 @@ name = "git-workspace-cli" version = "0.7.0b1" source = { editable = "." } dependencies = [ + { name = "jinja2" }, { name = "tomlkit" }, { name = "typer" }, ] @@ -80,6 +81,7 @@ dev = [ [package.metadata] requires-dist = [ + { name = "jinja2", specifier = ">=3.1" }, { name = "tomlkit", specifier = ">=0.13" }, { name = "typer", specifier = ">=0.24.1" }, ] @@ -112,6 +114,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + [[package]] name = "markdown-it-py" version = "4.0.0" @@ -124,6 +138,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" }, ] +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + [[package]] name = "mdurl" version = "0.1.2"