Skip to content

Commit

Permalink
feat: allow diff to take a branch name as origin using worktree (#655)
Browse files Browse the repository at this point in the history
Following the discussion on discord, I've extended the behaviour of
`create_worktree` to use a branch and not be detached. This allows us to
compare two branch, the current and `main` for example easily.
  • Loading branch information
Alexsaphir authored May 10, 2024
1 parent b468913 commit 6db2bfc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
10 changes: 7 additions & 3 deletions flux_local/git_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,17 +772,21 @@ async def update_kustomization(cluster: Cluster) -> None:


@contextlib.contextmanager
def create_worktree(repo: git.repo.Repo) -> Generator[Path, None, None]:
def create_worktree(repo: git.repo.Repo, existing_branch: str | None = None) -> Generator[Path, None, None]:
"""Create a ContextManager for a new git worktree in the current repo.
This is used to get a fork of the current repo without any local changes
in order to produce a diff.
Specifying existing_branch allows to compare the current state with the existing branch.
"""
orig = os.getcwd()
with tempfile.TemporaryDirectory() as tmp_dir:
_LOGGER.debug("Creating worktree in %s", tmp_dir)
# Add --detach to avoid creating a branch since we will not make modifications
repo.git.worktree("add", "--detach", str(tmp_dir))
if existing_branch is None:
# Add --detach to avoid creating a branch since we will not make modifications
repo.git.worktree("add", "--detach", str(tmp_dir))
else:
repo.git.worktree("add", str(tmp_dir), existing_branch)
os.chdir(tmp_dir)
yield Path(tmp_dir)
_LOGGER.debug("Restoring to %s", orig)
Expand Down
11 changes: 10 additions & 1 deletion flux_local/tool/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,15 @@ def add_diff_flags(args: ArgumentParser) -> None:
default=None,
nargs="?",
)

args.add_argument(
"--branch-orig",
help="Branch to compare against using worktree",
type=str,
default=None,
nargs="?",
)

args.add_argument(
"--strip-attrs",
help="Labels or annotations to strip from the diff",
Expand Down Expand Up @@ -225,7 +234,7 @@ def create_diff_path(
yield git_repo.PathSelector(path_orig, sources=kwargs.get("sources"))
return

with git_repo.create_worktree(selector.repo) as worktree:
with git_repo.create_worktree(selector.repo, existing_branch=kwargs.get("branch_orig")) as worktree:
yield git_repo.PathSelector(pathlib.Path(worktree) / selector.relative_path)


Expand Down

0 comments on commit 6db2bfc

Please sign in to comment.