Skip to content

Commit

Permalink
Refactor git util
Browse files Browse the repository at this point in the history
  • Loading branch information
goFrendiAsgard committed Dec 11, 2024
1 parent 0eded06 commit 6b6ae92
Show file tree
Hide file tree
Showing 4 changed files with 148 additions and 138 deletions.
14 changes: 7 additions & 7 deletions src/zrb/builtin/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,14 @@ async def get_git_diff(ctx: AnyContext):
)
async def prune_local_branches(ctx: AnyContext):
repo_dir = await get_repo_dir(log_method=ctx.print)
branches = get_branches(repo_dir)
current_branch = get_current_branch(repo_dir)
branches = await get_branches(repo_dir, log_method=ctx.print)
current_branch = await get_current_branch(repo_dir, log_method=ctx.print)
for branch in branches:
if branch == current_branch or branch == "main" or branch == "master":
continue
ctx.print(stylize_yellow(f"Removing local branch: {branch}"))
try:
delete_branch(repo_dir, branch)
await delete_branch(repo_dir, branch, log_method=ctx.print)
except Exception as e:
ctx.log_error(e)

Expand Down Expand Up @@ -135,9 +135,9 @@ async def git_commit(ctx: AnyContext):
async def git_pull(ctx: AnyContext):
repo_dir = await get_repo_dir(log_method=ctx.print)
remote = ctx.input.remote
current_branch = get_current_branch(repo_dir)
current_branch = await get_current_branch(repo_dir, log_method=ctx.print)
ctx.print(f"Pulling from {remote}/{current_branch}")
pull(repo_dir, remote, current_branch)
await pull(repo_dir, remote, current_branch, log_method=ctx.print)


@make_task(
Expand All @@ -156,6 +156,6 @@ async def git_pull(ctx: AnyContext):
async def git_push(ctx: AnyContext):
repo_dir = await get_repo_dir(log_method=ctx.print)
remote = ctx.input.remote
current_branch = get_current_branch(repo_dir)
current_branch = await get_current_branch(repo_dir, log_method=ctx.print)
ctx.print(f"Pushing to {remote}/{current_branch}")
push(repo_dir, remote, current_branch)
await push(repo_dir, remote, current_branch, log_method=ctx.print)
9 changes: 6 additions & 3 deletions src/zrb/builtin/git_subtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@
)
async def git_add_subtree(ctx: AnyContext):
repo_dir = await get_repo_dir(log_method=ctx.print)
add_subtree(
await add_subtree(
repo_dir=repo_dir,
name=ctx.input.name,
repo_url=ctx.input["repo-url"],
branch=ctx.input["repo-branch"],
prefix=ctx.input["repo-prefix"],
log_method=ctx.print,
)


Expand All @@ -59,11 +60,12 @@ async def git_pull_subtree(ctx: AnyContext):
for name, detail in config.data.items():
try:
ctx.print(f"Pull from subtree {name}")
pull_subtree(
await pull_subtree(
repo_dir=repo_dir,
prefix=detail.prefix,
repo_url=detail.repo_url,
branch=detail.branch,
log_method=ctx.print,
)
except Exception as e:
if first_err is None:
Expand All @@ -89,11 +91,12 @@ async def git_push_subtree(ctx: AnyContext):
for name, detail in config.data.items():
try:
ctx.print(f"Push to subtree {name}")
push_subtree(
await push_subtree(
repo_dir=repo_dir,
prefix=detail.prefix,
repo_url=detail.repo_url,
branch=detail.branch,
log_method=ctx.print,
)
except Exception as e:
if first_err is None:
Expand Down
135 changes: 62 additions & 73 deletions src/zrb/util/git.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import subprocess
from collections.abc import Callable
from typing import Any

Expand Down Expand Up @@ -27,7 +26,7 @@ async def get_diff(
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")
lines = cmd_result.ouptput.strip().split("\n")
lines = cmd_result.output.strip().split("\n")
diff: dict[str, dict[str, bool]] = {}
for line in lines:
if not line.startswith("---") and not line.startswith("+++"):
Expand Down Expand Up @@ -65,51 +64,45 @@ async def get_repo_dir(log_method: Callable[..., Any] = print) -> str:
return os.path.abspath(cmd_result.output.strip())


def get_current_branch(repo_dir: str) -> str:
try:
result = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)


def get_branches(repo_dir: str) -> list[str]:
try:
result = subprocess.run(
["git", "branch"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
return [
branch.lstrip("*").strip() for branch in result.stdout.strip().split("\n")
]
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)


def delete_branch(repo_dir: str, branch_name: str) -> str:
try:
result = subprocess.run(
["git", "branch", "-D", branch_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)
async def get_current_branch(
repo_dir: str, log_method: Callable[..., Any] = print
) -> str:
cmd_result, exit_code = await run_command(
cmd=["git", "rev-parse", "--abbrev-ref", "HEAD"],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")
return cmd_result.output.strip()


async def get_branches(
repo_dir: str, log_method: Callable[..., Any] = print
) -> list[str]:
cmd_result, exit_code = await run_command(
cmd=["git", "rev-parse", "--abbrev-ref", "HEAD"],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")
return [
branch.lstrip("*").strip() for branch in cmd_result.output.strip().split("\n")
]


async def delete_branch(
repo_dir: str, branch_name: str, log_method: Callable[..., Any] = print
) -> str:
cmd_result, exit_code = await run_command(
cmd=["git", "branch", "-D", branch_name],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")
return cmd_result.output.strip()


async def add(repo_dir: str, log_method: Callable[..., Any] = print):
Expand Down Expand Up @@ -139,29 +132,25 @@ async def commit(
raise Exception(f"Non zero exit code: {exit_code}")


def pull(repo_dir: str, remote: str, branch: str) -> str:
try:
subprocess.run(
["git", "pull", remote, branch],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)


def push(repo_dir: str, remote: str, branch: str) -> str:
try:
subprocess.run(
["git", "push", "-u", remote, branch],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)
async def pull(
repo_dir: str, remote: str, branch: str, log_method: Callable[..., Any] = print
) -> str:
_, exit_code = await run_command(
cmd=["git", "pull", remote, branch],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")


async def push(
repo_dir: str, remote: str, branch: str, log_method: Callable[..., Any] = print
) -> str:
_, exit_code = await run_command(
cmd=["git", "push", "-u", remote, branch],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")
128 changes: 73 additions & 55 deletions src/zrb/util/git_subtree.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import os
import subprocess
from collections.abc import Callable
from typing import Any

from pydantic import BaseModel

from zrb.util.cmd.command import run_command


class SingleSubTreeConfig(BaseModel):
repo_url: str
Expand All @@ -28,68 +31,83 @@ def save_config(repo_dir: str, config: SubTreeConfig):
f.write(config.model_dump_json(indent=2))


def add_subtree(repo_dir: str, name: str, repo_url: str, branch: str, prefix: str):
async def add_subtree(
repo_dir: str,
name: str,
repo_url: str,
branch: str,
prefix: str,
log_method: Callable[..., Any] = print,
):
config = load_config()
if os.path.isdir(prefix):
raise ValueError(f"Directory exists: {prefix}")
if name in config.data:
raise ValueError(f"Subtree config already exists: {name}")
try:
subprocess.run(
["git", "subtree", "add", "--prefix", prefix, repo_url, branch],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)
_, exit_code = await run_command(
cmd=[
"git",
"subtree",
"add",
"--prefix",
prefix,
repo_url,
branch,
],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")
config.data[name] = SingleSubTreeConfig(
repo_url=repo_url, branch=branch, prefix=prefix
)
save_config(repo_dir, config)


def pull_subtree(repo_dir: str, prefix: str, repo_url: str, branch: str):
try:
subprocess.run(
[
"git",
"subtree",
"pull",
"--prefix",
prefix,
repo_url,
branch,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)


def push_subtree(repo_dir: str, prefix: str, repo_url: str, branch: str):
try:
subprocess.run(
[
"git",
"subtree",
"push",
"--prefix",
prefix,
repo_url,
branch,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
raise Exception(e.stderr or e.stdout)
async def pull_subtree(
repo_dir: str,
prefix: str,
repo_url: str,
branch: str,
log_method: Callable[..., Any] = print,
):
_, exit_code = await run_command(
cmd=[
"git",
"subtree",
"pull",
"--prefix",
prefix,
repo_url,
branch,
],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")


async def push_subtree(
repo_dir: str,
prefix: str,
repo_url: str,
branch: str,
log_method: Callable[..., Any] = print,
):
_, exit_code = await run_command(
cmd=[
"git",
"subtree",
"push",
"--prefix",
prefix,
repo_url,
branch,
],
cwd=repo_dir,
log_method=log_method,
)
if exit_code != 0:
raise Exception(f"Non zero exit code: {exit_code}")

0 comments on commit 6b6ae92

Please sign in to comment.