|
| 1 | +import os |
| 2 | +import shutil |
| 3 | +import uuid |
| 4 | + |
| 5 | +import click |
| 6 | +import git |
| 7 | + |
| 8 | +from gitflow_toolbox.common.gitlab import CurrentGitlab, RemoteGitlab |
| 9 | +from gitflow_toolbox.common.is_main_call import is_main_call |
| 10 | + |
| 11 | + |
| 12 | +@click.command() |
| 13 | +@click.option("--from-gitlab", type=click.Choice(["current", "remote"], case_sensitive=False)) |
| 14 | +@click.argument("source_branch", type=str) |
| 15 | +@click.option("--to-gitlab", type=click.Choice(["current", "remote"], case_sensitive=False)) |
| 16 | +@click.argument("target_branch", type=str) |
| 17 | +@click.pass_context |
| 18 | +def diff( |
| 19 | + ctx: click.Context, |
| 20 | + from_gitlab: tuple[str], |
| 21 | + source_branch: str, |
| 22 | + to_gitlab: tuple[str], |
| 23 | + target_branch: str, |
| 24 | +): |
| 25 | + """Returns the 'git diff' between two branches |
| 26 | +
|
| 27 | + Args: |
| 28 | + from_gitlab (str): source gitlab [current/remote] |
| 29 | + source_branch (str): source branch |
| 30 | + to_gitlab (str): destination gitlab [current/remote] |
| 31 | + target_branch (str): destination branch |
| 32 | +
|
| 33 | + Returns: |
| 34 | + str: the 'git diff' between two branches, or an empty string (line return) if no diff |
| 35 | + """ |
| 36 | + |
| 37 | + gitlab_from = CurrentGitlab() if from_gitlab == "current" else RemoteGitlab() |
| 38 | + gitlab_to = CurrentGitlab() if to_gitlab == "current" else RemoteGitlab() |
| 39 | + |
| 40 | + project_from_clone_dir = os.path.join("/tmp", f"gf_{uuid.uuid4()}") |
| 41 | + |
| 42 | + try: |
| 43 | + # Clone |
| 44 | + repo_from = git.Repo.clone_from( |
| 45 | + gitlab_from.project_authenticated_url, project_from_clone_dir, branch=source_branch |
| 46 | + ) |
| 47 | + # Add remote |
| 48 | + repo_from.create_remote("target", gitlab_to.project_authenticated_url) |
| 49 | + # Diff |
| 50 | + repo_from.remotes.target.fetch(target_branch) |
| 51 | + diff_output = str(repo_from.git.diff(f"target/{target_branch}")) |
| 52 | + if diff_output and is_main_call(ctx): |
| 53 | + click.echo(diff_output) |
| 54 | + return diff_output |
| 55 | + finally: |
| 56 | + # Clean |
| 57 | + if os.path.isdir(project_from_clone_dir): |
| 58 | + shutil.rmtree(project_from_clone_dir) |
0 commit comments