refactor: migrate from class commands to scripts commands

This commit is contained in:
jt
2026-05-17 11:19:30 -03:00
parent 9ffefafad0
commit 0ac04aee84
10 changed files with 775 additions and 812 deletions
+81 -79
View File
@@ -1,111 +1,113 @@
from argparse import Namespace
import typer
from git_flow import GitFlowError
from git_flow.changelog import Changelog
from git_flow.command.base import Command
from git_flow.command.base import *
from git_flow.git import Git
app = typer.Typer()
class MergeCommand(Command):
def name(self) -> str:
return "merge"
def description(self) -> str:
return """Realiza el merge de la rama, o crea el PR para hacerlo si tiene un remoto configurado"""
@app.command()
def merge():
"""Realiza el merge de la rama, o crea el PR para hacerlo si tiene un remoto configurado"""
ensure_initialized()
def run(self, args: Namespace = Namespace()):
self.ensure_initialized()
branch = ensure_right_branch()
target, _ = get_branch_env_and_type(branch)
branch = self.ensure_right_branch()
(target, _) = self.get_branch_env_and_type(branch)
if "flow.remote" in flowconfig:
remote = flowconfig["flow.remote"]
token = ensure_repository_token()
run_remote(remote, token, branch, target)
else:
run_local(branch, target)
if "flow.remote" in self.flowconfig:
remote = self.flowconfig["flow.remote"]
token = self.ensure_repository_token()
self.run_remote(remote, token, branch, target)
else:
self.run_local(branch, target)
def run_remote(self, remote: str, token: str, branch: str, target: str):
self.ensure_clean_worktree(True)
def run_remote(remote: str, token: str, branch: str, target: str):
ensure_clean_worktree(True)
Git("switch", target).exec(print="Cambiando a rama destino")
Git("pull").exec(print="Obteniendo ultimos cambios del remoto")
Git("switch", "-").exec(print="Volviendo a rama a mergear")
check_merge_conflicts(target)
show_commits_to_merge(target)
if confirm(f"¿Crear PR de '{branch}' a '{target}'?"):
Git("push", remote, branch, set_upstream=True).exec(
print="Subiendo rama al remoto para crear PR"
)
create_pull_request(token, branch, target)
def run_local(branch: str, target: str):
ensure_clean_worktree(False)
check_merge_conflicts(target)
show_commits_to_merge(target)
if confirm(f"¿Mergear rama '{branch}' a '{target}'?"):
Git("switch", target).exec(print="Cambiando a rama destino")
Git("pull").exec(print="Obteniendo ultimos cambios del remoto")
Git("switch", "-").exec(print="Volviendo a rama a mergear")
Git("merge", branch, ff=False).exec(print="Mergeando")
self.check_merge_conflicts(target)
self.show_commits_to_merge(target)
if self.confirm(f"¿Crear PR de '{branch}' a '{target}'?"):
Git("push", remote, branch, set_upstream=True).exec(
print="Subiendo rama al remoto para crear PR"
)
def show_commits_to_merge(target):
commits = Git("log", target + "..", format="%s").lines()
self.create_pull_request(token, branch, target)
if not commits:
raise GitFlowError("No hay cambios a mergear.")
def run_local(self, branch: str, target: str):
self.ensure_clean_worktree(False)
self.check_merge_conflicts(target)
self.show_commits_to_merge(target)
print("Cambios a mergear:")
if self.confirm(f"¿Mergear rama '{branch}' a '{target}'?"):
Git("switch", target).exec(print="Cambiando a rama destino")
Git("merge", branch, ff=False).exec(print="Mergeando")
for commit in commits:
print("- " + commit)
def show_commits_to_merge(self, target):
commits = Git("log", target + "..", format="%s").lines()
if not commits:
raise GitFlowError("No hay cambios a mergear.")
def check_merge_conflicts(target: str):
merge_conflicts = Git("merge", target, ff=False, commit=False).code(
print="Realizando merge de prueba para verificar conflictos"
)
print("Cambios a mergear:")
Git("merge", abort=True).exec(print="Abortando merge de prueba", check=False)
for commit in commits:
print("- " + commit)
def check_merge_conflicts(self, target: str):
merge_conflicts = Git("merge", target, ff=False, commit=False).code(
print="Realizando merge de prueba para verificar conflictos"
if merge_conflicts:
error(f"La rama actual tiene conflictos con {target}")
info(
f"""Se recomienda mergear {target} a la rama actual, resolver los conflictos localmente, y ejecutar nuevamente este comando"""
)
raise GitFlowError("Ejecución abortada.")
else:
success("No se detectaron merge conflicts.")
Git("merge", abort=True).exec(print="Abortando merge de prueba", check=False)
if merge_conflicts:
self.error(f"La rama actual tiene conflictos con {target}")
self.info(
f"""Se recomienda mergear {target} a la rama actual, resolver los conflictos localmente, y ejecutar nuevamente este comando"""
)
raise GitFlowError("Ejecución abortada.")
else:
self.success("No se detectaron merge conflicts.")
def create_pull_request(token: str, branch: str, target: str):
changelog = Changelog()
commits = Git("log", target + "..", format="%s").lines()
def create_pull_request(self, token: str, branch: str, target: str):
changelog = Changelog()
commits = Git("log", target + "..", format="%s").lines()
if len(commits) == 1:
title = commits[0]
else:
title = branch.replace("/", ": ").replace("-", " ")
if len(commits) == 1:
title = commits[0]
else:
title = branch.replace("/", ": ").replace("-", " ")
if title.startswith("release: "):
title = title[title.index(" ", title.index(" ") + 1) + 1 :]
if title.startswith("release: "):
title = title[title.index(' ', title.index(' ') + 1) + 1:]
info("Título del PR por defecto: " + title)
self.info("Título del PR por defecto: " + title)
opt_title = prompt("[Opcional] Ingrese otro titulo para el PR")
opt_title = self.prompt("[Opcional] Ingrese otro titulo para el PR")
if opt_title:
title = opt_title
if opt_title:
title = opt_title
message = get_remote_api(token).create_pull_request(
branch,
target,
title,
changelog.generate_content(target, branch),
)
message = self.get_remote_api(token).create_pull_request(
branch,
target,
title,
changelog.generate_content(target, branch),
)
success(message)
self.success(message)
if self.confirm("¿Desea cambiar a la rama objetivo y bajar los cambios?"):
Git("switch", target).exec(print="Cambiando a rama objetivo")
Git("pull").exec(print="Obteniendo cambios")
if confirm("¿Desea cambiar a la rama objetivo y bajar los cambios?"):
Git("switch", target).exec(print="Cambiando a rama objetivo")
Git("pull").exec(print="Obteniendo cambios")