refactor: migrar comando new para que utilice metodos usando questionary

This commit is contained in:
jt
2026-07-14 00:22:22 -03:00
parent 4968667dad
commit a5a753f429
6 changed files with 104 additions and 55 deletions
+37 -8
View File
@@ -13,10 +13,10 @@ from git_flow.remote.gitea import GiteaRemoteAPI
from git_flow.io import *
from os.path import isfile
TYPE_SUCCESS = 0
TYPE_WARNING = 1
TYPE_ERROR = 2
TYPE_INFO = 3
from typing import Optional
import rich
import rich.panel
import questionary
flowconfig = Git.get_config(FLOWCONFIG_FILENAME) if isfile(FLOWCONFIG_FILENAME) else {}
@@ -48,7 +48,7 @@ def ensure_right_branch():
if branch == "HEAD":
raise GitFlowError("No se encuentra parado sobre una rama.")
elif confirm(f"Se encuentra sobre la rama '{branch}'. ¿Es correcto?"):
elif io_confirm(f"Se encuentra sobre la rama '{branch}'. ¿Es correcto?"):
return branch
else:
raise GitFlowError("Ejecución cancelada.")
@@ -102,11 +102,11 @@ def ensure_clean_worktree(has_remote: bool):
if not_empty:
if not has_remote:
warning("Existen cambios en tu entorno de trabajo sin commitear.")
io_warning("Existen cambios en tu entorno de trabajo sin commitear.")
else:
raise GitFlowError("No se puede continuar con cambios pendientes.")
if not confirm("¿Desea continuar?", False):
if not io_confirm("¿Desea continuar?", False):
raise GitFlowError("Ejecución abortada")
@@ -137,4 +137,33 @@ def is_valid_ticket(ticket: str) -> bool:
ticket_project = components[0]
ticket_number = components[1]
return ticket_project.isalpha() and ticket_project.isupper() and ticket_number.isnumeric()
return ticket_project.isalpha() and ticket_project.isupper() and ticket_number.isnumeric()
def io_error(message: str, title: Optional[str] = None):
_io_status(message, "❌ Error: ", "red", title)
def io_warning(message: str, title: Optional[str] = None):
_io_status(message, "⚠️ Warning: ", "yellow", title)
def io_info(message: str, title: Optional[str] = None):
_io_status(message, "️ Info: ", "blue", title)
def _io_status(message: str, prefix: str, style: str, title: Optional[str] = None):
if title:
rich.print(rich.panel.Panel(message, title=prefix + title, style=style, expand=False, title_align="left"))
else:
rich.print(f"[{style}]{prefix}{message}[/{style}]")
def io_confirm(question: str, default: bool = True) -> bool:
return questionary.confirm(question, default=default, auto_enter=False).ask()
def io_choice(prompt: str, options: list[str]) -> str:
return questionary.select(prompt, options, instruction="Usar flechas").ask()
def io_prompt(message: str, default: str = "", persistent: bool = False, strip: bool = False, validator = None) -> str:
if persistent and not validator:
validator = lambda s: len(s.strip()) > 0
value = questionary.text(message, default, validate=validator).ask()
return value.strip() if strip else value
+18 -25
View File
@@ -1,6 +1,6 @@
import typer
from git_flow import BRANCH_TYPES
from git_flow.command.base import *
import git_flow.command.base as base
from git_flow.git import Git
from typing import Optional
@@ -11,52 +11,45 @@ app = typer.Typer()
def new():
"""Crea una nueva rama siguiendo Conventional Branches"""
ensure_initialized()
branch = ensure_right_branch()
base.ensure_initialized()
branch = base.ensure_right_branch()
if branch not in environments:
warning("La rama actual no corresponde a un entorno configurado.")
if branch not in base.environments:
base.io_warning("La rama actual no corresponde a un entorno configurado.")
info("Se creará una nueva rama de trabajo sobre la rama actual.")
info("Debe seleccionar el tipo de cambio a realizar.")
base.io_info("Se creará una nueva rama de trabajo sobre la rama actual.\n"
"Debe seleccionar el tipo de cambio a realizar.", title="Tipo de cambio")
branch_type = choice("Tipos de cambio", BRANCH_TYPES)
branch_type = base.io_choice("Tipos de cambio", BRANCH_TYPES)
ticket = _get_optional_ticket()
new_branch = _get_unique_branch_name(branch_type, ticket)
if "flow.remote" in flowconfig and Git.get_tracking_branch(branch):
if "flow.remote" in base.flowconfig and Git.get_tracking_branch(branch):
Git("pull").exec(print="Actualizando rama actual")
if confirm(f"¿Crear rama '{new_branch}' sobre la rama actual?"):
if base.io_confirm(f"¿Crear rama '{new_branch}' sobre la rama actual?"):
Git("switch", new_branch, create=True).exec(print="Creando nueva rama")
def _get_optional_ticket() -> Optional[str]:
ticket = prompt("[Opcional] Ticket que respalda el cambio (en formato ABC-123)")
if not ticket:
return None
if not is_valid_ticket(ticket):
warning("Formato de ticket inválido, ignorando.")
return None
return ticket
return base.io_prompt(
"Ticket que respalda el cambio (en formato ABC-123)",
validator=lambda x: len(x.strip()) == 0 or base.is_valid_ticket(x)
)
def _get_unique_branch_name(branch_type: str, ticket: Optional[str]) -> str:
info(f"Ingrese las palabras clave que describan el cambio de tipo '{branch_type}'.")
base.io_info(f"Ingrese las palabras clave que describan el cambio de tipo '{branch_type}'.\n"
"Las mismas se utilizaran para generar el nombre de la rama.", title="Nombre de rama")
branch = None
branches = Git.get_branches()
while branch is None:
keywords = prompt(
"Palabras clave del cambio (por ejemplo: 'create worker form')",
persistent=True,
)
keywords = base.io_prompt("Palabras clave", persistent=True)
keywords = filter(lambda k: len(k) > 0, keywords.split(" "))
branch = branch_type + "/" + (ticket + "-" if ticket else "") + "-".join(keywords)
if branch in branches:
error(
base.io_error(
f"La rama '{branch}' ya existe, cambie las palabras claves para generar otra"
)
branch = None
+4 -14
View File
@@ -140,17 +140,7 @@ class Git:
return process
def _run(self, print: str | None = None, check: bool = True):
process = subprocess.run(
self.command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
if print is not None:
self._print_process("", "", title=print)
if check:
process.check_returncode()
return process
return self._get(print, check)
def _print_process(self, stdout: str, stderr: str, title: str):
command = []
@@ -164,12 +154,12 @@ class Git:
command.append(arg)
text = f"[yellow]$ {" ".join(command)}[/yellow]"
text = f"[green]$ {" ".join(command)}[/green]"
for line in stdout.splitlines():
text += "\n\\[out] " + line
text += "\n" + line
for line in stderr.splitlines():
text += "\n[red]\\[err][/red] " + line
text += "\n[red]" + line + "[/red]"
panel(title or "Ejecutando", text)
+7 -7
View File
@@ -3,7 +3,7 @@
import typer
from git_flow import GitFlowError
from git_flow.command.base import *
import git_flow.command.base as base
from git_flow.command import init, new, commit, merge, tag, release, branch
REPOSITORY_TOKEN_PATH = ".repository-token"
@@ -23,10 +23,10 @@ app.add_typer(branch.app)
def main():
try:
app()
except GitFlowError as e:
error(str(e))
except Exception as e:
error("Ocurrió un error inesperado: " + str(e))
except KeyboardInterrupt as e:
print()
error("Ejecución abortada")
except GitFlowError as e:
base.io_error(str(e), title="Git Flow")
except Exception as e:
base.io_error(str(e), title="Inesperado")
except KeyboardInterrupt as e:
base.io_error("Ejecución abortada")