[IMPROVED] Refactorizado script como cversion_token.sh con enfoque simplificado

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Mauro Rosero P. 2025-03-15 12:25:19 -05:00
parent b7be96d03c
commit 92dd54059f
Signed by: mrosero
GPG key ID: 83BD2A5F674B7E26
2 changed files with 113 additions and 209 deletions

View file

@ -67,7 +67,7 @@ bin/update.sh
| `bin/ghcli_install.sh` | Instala GitHub CLI (gh) con soporte multiplataforma | | `bin/ghcli_install.sh` | Instala GitHub CLI (gh) con soporte multiplataforma |
| `bin/glcli_install.sh` | Instala GitLab CLI (glab) con múltiples métodos de instalación | | `bin/glcli_install.sh` | Instala GitLab CLI (glab) con múltiples métodos de instalación |
| `bin/fjcli_install.sh` | Instala Forgejo/Codeberg CLI vía Cargo | | `bin/fjcli_install.sh` | Instala Forgejo/Codeberg CLI vía Cargo |
| `bin/version_cli.sh` | Menú para gestionar herramientas de control de versiones y sus tokens | | `bin/cversion_token.sh` | Menú para gestionar tokens de control de versiones cifrados con SOPS |
### Seguridad y Acceso ### Seguridad y Acceso
@ -185,19 +185,19 @@ El script instala la CLI mediante Cargo (el gestor de paquetes de Rust):
- Verifica si Cargo está instalado y lo instala si es necesario - Verifica si Cargo está instalado y lo instala si es necesario
- Instala codeberg-cli que es compatible con servidores Forgejo - Instala codeberg-cli que es compatible con servidores Forgejo
#### Gestor unificado de CLIs de control de versiones #### Gestor de tokens de control de versiones
```bash ```bash
# Menú interactivo para gestión de CLIs # Menú interactivo para gestión de tokens
bin/version_cli.sh bin/cversion_token.sh
``` ```
Este script proporciona un menú interactivo para gestionar todas las CLIs de control de versiones: Este script proporciona un menú interactivo para gestionar los tokens de acceso para plataformas de control de versiones:
- Selección sencilla del tipo de plataforma (GitHub, GitLab o Forgejo/Codeberg)
- Verifica si las CLIs están instaladas y ofrece instalarlas si faltan - Verifica si las CLIs están instaladas y ofrece instalarlas si faltan
- Configura y almacena tokens de acceso cifrados con SOPS - Configura y almacena tokens de acceso cifrados con SOPS en ~/.developer
- Verifica el estado de configuración de las herramientas - Ofrece la opción de probar la conectividad con cada servicio
- Prueba la conectividad con los servicios respectivos - Permite configurar múltiples tokens secuencialmente
- Compatible con GitHub, GitLab y Forgejo/Codeberg
Para aprender a usar Codeberg CLI (compatible con Forgejo), consulta la [documentación en el repositorio de Codeberg CLI](https://codeberg.org/RobWalt/codeberg-cli). Para aprender a usar Codeberg CLI (compatible con Forgejo), consulta la [documentación en el repositorio de Codeberg CLI](https://codeberg.org/RobWalt/codeberg-cli).

View file

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# [Author] Cortana Rosero One <cortana@rosero.one> # [Author] Cortana Rosero One <cortana@rosero.one>
# [Title] version_cli.sh - Gestor de CLIs de Control de Versiones # [Title] cversion_token.sh - Gestor de Tokens de Control de Versiones
# [Generated] Created by Claude Code (claude-3-7-sonnet-20250219) # [Generated] Created by Claude Code (claude-3-7-sonnet-20250219)
# #
# AGPL License # AGPL License
@ -22,11 +22,8 @@ source "$LIB_DIR/console.lib"
source "$MSG_DIR/head.es" source "$MSG_DIR/head.es"
# Variables globales # Variables globales
title="GESTOR DE CLIs DE CONTROL DE VERSIONES" title="GESTOR DE TOKENS DE CONTROL DE VERSIONES"
apps_title="Gestión de CLIs Git" apps_title="Configuración de Tokens Git"
SELECTED_CLI=""
TOKEN_FILE=""
SELECTED_CLI_NAME=""
SOPS_CONFIG_DIR="$DEVELOPER_DIR" SOPS_CONFIG_DIR="$DEVELOPER_DIR"
# Verificar que SOPS esté instalado # Verificar que SOPS esté instalado
@ -45,55 +42,6 @@ check_dialog() {
fi fi
} }
# Verificar si un CLI está instalado
check_cli_installed() {
local cli_name="$1"
local command_name="$2"
if ! command -v "$command_name" &> /dev/null; then
dialog_yesno "El CLI de $cli_name no está instalado.\n¿Desea instalarlo ahora?" 8 60
if [ $? -eq 0 ]; then
install_cli "$cli_name"
return $?
else
return 1
fi
fi
return 0
}
# Instalar un CLI específico
install_cli() {
local cli_name="$1"
local install_script=""
case "$cli_name" in
"GitHub")
install_script="$SCRIPT_DIR/ghcli_install.sh"
;;
"GitLab")
install_script="$SCRIPT_DIR/glcli_install.sh"
;;
"Forgejo")
install_script="$SCRIPT_DIR/fjcli_install.sh"
;;
esac
if [ -f "$install_script" ]; then
clear
echo "Instalando CLI de $cli_name..."
bash "$install_script"
local result=$?
echo "Presione Enter para continuar..."
read
return $result
else
dialog --backtitle "${title}" --title "${head_error}" --msgbox "No se encontró el script de instalación para $cli_name" 7 50
return 1
fi
}
# Crear directorio para tokens si no existe # Crear directorio para tokens si no existe
check_token_directory() { check_token_directory() {
if [ ! -d "$SOPS_CONFIG_DIR" ]; then if [ ! -d "$SOPS_CONFIG_DIR" ]; then
@ -104,115 +52,94 @@ check_token_directory() {
chmod 700 "$SOPS_CONFIG_DIR" chmod 700 "$SOPS_CONFIG_DIR"
} }
# Menú principal # Verificar e instalar CLI según tipo seleccionado
show_main_menu() { manage_version_token() {
local vcs_type=""
local cli_command=""
local token_file=""
local install_script=""
local token_prompt=""
local token_helper=""
local token_stored=0
# Mostrar menú para seleccionar tipo de control de versiones
dialog_input_menu "Seleccione la plataforma de control de versiones:" \ dialog_input_menu "Seleccione la plataforma de control de versiones:" \
"Seleccione la plataforma para la cual desea configurar el CLI" \ "Seleccione la plataforma para la cual desea configurar el token" \
"1 GitHub 2 GitLab 3 Forgejo" \ "1 GitHub 2 GitLab 3 Forgejo" \
12 70 12 70
if [ $codex -ne 0 ]; then if [ $codex -ne 0 ]; then
exit 0 return 1
fi fi
# Configurar variables según la selección
case "$value" in case "$value" in
"1") "1")
SELECTED_CLI="gh" vcs_type="GitHub"
SELECTED_CLI_NAME="GitHub" cli_command="gh"
TOKEN_FILE="$SOPS_CONFIG_DIR/github.sops.yaml" token_file="$SOPS_CONFIG_DIR/github.sops.yaml"
install_script="$SCRIPT_DIR/ghcli_install.sh"
token_prompt="Ingrese su token de acceso personal de GitHub:"
token_helper="Puede generar un nuevo token en: https://github.com/settings/tokens\nAsegúrese de incluir los permisos necesarios (repo, workflow, etc.)"
;; ;;
"2") "2")
SELECTED_CLI="glab" vcs_type="GitLab"
SELECTED_CLI_NAME="GitLab" cli_command="glab"
TOKEN_FILE="$SOPS_CONFIG_DIR/gitlab.sops.yaml" token_file="$SOPS_CONFIG_DIR/gitlab.sops.yaml"
install_script="$SCRIPT_DIR/glcli_install.sh"
token_prompt="Ingrese su token de acceso personal de GitLab:"
token_helper="Puede generar un nuevo token en: https://gitlab.com/-/profile/personal_access_tokens\nAsegúrese de incluir los permisos necesarios (api, read_repository, etc.)"
;; ;;
"3") "3")
SELECTED_CLI="berg" vcs_type="Forgejo"
SELECTED_CLI_NAME="Forgejo" cli_command="berg"
TOKEN_FILE="$SOPS_CONFIG_DIR/forgejo.sops.yaml" token_file="$SOPS_CONFIG_DIR/forgejo.sops.yaml"
install_script="$SCRIPT_DIR/fjcli_install.sh"
token_prompt="Ingrese su token de acceso personal de Forgejo/Codeberg:"
token_helper="Puede generar un nuevo token en su perfil de usuario, en la sección 'Aplicaciones'\nAsegúrese de incluir los permisos necesarios"
;; ;;
*) *)
exit 0 return 1
;; ;;
esac esac
handle_cli_selection # Verificar si el CLI está instalado
} if ! command -v "$cli_command" &> /dev/null; then
dialog_yesno "El CLI de $vcs_type ($cli_command) no está instalado.\n¿Desea instalarlo ahora?" 8 60
# Manejar la selección de CLI if [ $? -eq 0 ]; then
handle_cli_selection() { # Instalar el CLI si el usuario lo confirma
# Verificar si el CLI seleccionado está instalado if [ -f "$install_script" ]; then
check_cli_installed "$SELECTED_CLI_NAME" "$SELECTED_CLI" clear
if [ $? -ne 0 ]; then echo "Instalando CLI de $vcs_type..."
# Si el usuario no quiere instalar el CLI, volver al menú principal bash "$install_script"
show_main_menu if [ $? -ne 0 ]; then
return dialog --backtitle "${title}" --title "${head_error}" --msgbox "No se pudo instalar el CLI de $vcs_type. Verifique los mensajes de error e intente nuevamente." 8 70
return 1
fi
echo "Presione Enter para continuar..."
read
else
dialog --backtitle "${title}" --title "${head_error}" --msgbox "No se encontró el script de instalación para $vcs_type en: $install_script" 8 70
return 1
fi
else
dialog --backtitle "${title}" --title "${head_info}" --msgbox "El CLI es necesario para interactuar con $vcs_type.\nEl token se guardará de todas formas, pero no podrá verificar la conexión." 8 70
fi
fi fi
# Mostrar menú de acciones para el CLI seleccionado
dialog_input_menu "Acciones para $SELECTED_CLI_NAME CLI:" \
"Seleccione la acción que desea realizar" \
"1 'Configurar token de acceso' 2 'Verificar configuración' 3 'Probar conexión' 4 'Volver al menú principal'" \
12 70
if [ $codex -ne 0 ]; then
show_main_menu
return
fi
case "$value" in
"1")
configure_token
;;
"2")
verify_configuration
;;
"3")
test_connection
;;
"4")
show_main_menu
;;
*)
exit 0
;;
esac
}
# Configurar token de acceso
configure_token() {
# Verificar si ya existe un token configurado # Verificar si ya existe un token configurado
if [ -f "$TOKEN_FILE" ]; then if [ -f "$token_file" ]; then
dialog_yesno "Ya existe un token configurado para $SELECTED_CLI_NAME.\n¿Desea reemplazarlo?" 8 60 token_stored=1
dialog_yesno "Ya existe un token configurado para $vcs_type.\n¿Desea reemplazarlo?" 8 60
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
handle_cli_selection return 0
return
fi fi
fi fi
# Solicitar token de acceso # Solicitar token de acceso
local token_prompt=""
local token_helper=""
case "$SELECTED_CLI_NAME" in
"GitHub")
token_prompt="Ingrese su token de acceso personal de GitHub:"
token_helper="Puede generar un nuevo token en: https://github.com/settings/tokens\nAsegúrese de incluir los permisos necesarios (repo, workflow, etc.)"
;;
"GitLab")
token_prompt="Ingrese su token de acceso personal de GitLab:"
token_helper="Puede generar un nuevo token en: https://gitlab.com/-/profile/personal_access_tokens\nAsegúrese de incluir los permisos necesarios (api, read_repository, etc.)"
;;
"Forgejo")
token_prompt="Ingrese su token de acceso personal de Forgejo/Codeberg:"
token_helper="Puede generar un nuevo token en su perfil de usuario, en la sección 'Aplicaciones'\nAsegúrese de incluir los permisos necesarios"
;;
esac
dialog_input_pass "$token_prompt" "$token_helper" dialog_input_pass "$token_prompt" "$token_helper"
if [ $codex -ne 0 ]; then if [ $codex -ne 0 ]; then
handle_cli_selection return 1
return
fi fi
local token="$value" local token="$value"
@ -220,87 +147,56 @@ configure_token() {
# Validar el token # Validar el token
if [ -z "$token" ]; then if [ -z "$token" ]; then
dialog --backtitle "${title}" --title "${head_error}" --msgbox "${npm_055}" 7 50 dialog --backtitle "${title}" --title "${head_error}" --msgbox "${npm_055}" 7 50
configure_token return 1
return
fi fi
if [ ${#token} -lt 20 ]; then if [ ${#token} -lt 20 ]; then
dialog --backtitle "${title}" --title "${head_warning}" --msgbox "${npm_056}" 7 60 dialog_yesno "${npm_056}\n\n¿Desea continuar de todas formas?" 8 70
if [ $? -ne 0 ]; then
return 1
fi
fi fi
# Crear archivo YAML y encriptarlo con SOPS # Crear archivo YAML y encriptarlo con SOPS
echo "creating_token: \"$token\"" > "/tmp/token_temp.yaml" echo "creating_token: \"$token\"" > "/tmp/token_temp.yaml"
encrypt_token "/tmp/token_temp.yaml" "$TOKEN_FILE" "$SELECTED_CLI_NAME" sops --encrypt "/tmp/token_temp.yaml" > "$token_file" 2>/dev/null
# Eliminar archivo temporal # Eliminar archivo temporal
rm -f "/tmp/token_temp.yaml" rm -f "/tmp/token_temp.yaml"
handle_cli_selection # Verificar resultado de la encriptación
}
# Encriptar token con SOPS
encrypt_token() {
local temp_file="$1"
local target_file="$2"
local cli_name="$3"
sops --encrypt "$temp_file" > "$target_file" 2>/dev/null
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
dialog --backtitle "${title}" --title "${npm_052}" --msgbox "El token de $cli_name ha sido encriptado exitosamente en\n$target_file" 8 70
# Establecer permisos adecuados # Establecer permisos adecuados
chmod 600 "$target_file" chmod 600 "$token_file"
else
dialog --backtitle "${title}" --title "${head_error}" --msgbox "Falló la encriptación del token de $cli_name." 7 50
fi
}
# Verificar configuración
verify_configuration() {
local status_message=""
if [ ! -f "$TOKEN_FILE" ]; then
status_message="No se encontró un token configurado para $SELECTED_CLI_NAME.\nEl archivo $TOKEN_FILE no existe."
else
local config_status=""
case "$SELECTED_CLI_NAME" in dialog --backtitle "${title}" --title "${npm_052}" --msgbox "El token de $vcs_type ha sido encriptado exitosamente en:\n$token_file" 8 70
"GitHub")
if command -v gh &> /dev/null; then
config_status=$(gh auth status 2>&1 || echo "No autenticado")
else
config_status="CLI de GitHub no está instalado."
fi
;;
"GitLab")
if command -v glab &> /dev/null; then
config_status=$(glab auth status 2>&1 || echo "No autenticado")
else
config_status="CLI de GitLab no está instalado."
fi
;;
"Forgejo")
if command -v berg &> /dev/null; then
config_status="Token almacenado en: $TOKEN_FILE\nCifrado con SOPS."
else
config_status="CLI de Forgejo/Codeberg no está instalado."
fi
;;
esac
status_message="Estado de configuración para $SELECTED_CLI_NAME:\n\n$config_status" # Probar conexión si el CLI está instalado
if command -v "$cli_command" &> /dev/null; then
dialog_yesno "¿Desea probar la conexión con $vcs_type usando el token configurado?" 8 60
if [ $? -eq 0 ]; then
test_connection "$vcs_type" "$cli_command" "$token_file"
fi
fi
else
dialog --backtitle "${title}" --title "${head_error}" --msgbox "Falló la encriptación del token de $vcs_type." 7 50
return 1
fi fi
dialog --backtitle "${title}" --title "Verificación de configuración" --msgbox "$status_message" 15 70 return 0
handle_cli_selection
} }
# Probar conexión # Probar conexión con el servicio
test_connection() { test_connection() {
local vcs_type="$1"
local cli_command="$2"
local token_file="$3"
local connection_status="" local connection_status=""
local connection_message="" local connection_message=""
case "$SELECTED_CLI_NAME" in dialog --backtitle "${title}" --title "Prueba de conexión" --infobox "Probando conexión con $vcs_type..." 5 60
case "$vcs_type" in
"GitHub") "GitHub")
if command -v gh &> /dev/null; then if command -v gh &> /dev/null; then
connection_status=$(gh api user 2>&1) connection_status=$(gh api user 2>&1)
@ -330,8 +226,8 @@ test_connection() {
"Forgejo") "Forgejo")
if command -v berg &> /dev/null; then if command -v berg &> /dev/null; then
# Intentar usar el token de SOPS para la autenticación # Intentar usar el token de SOPS para la autenticación
if [ -f "$TOKEN_FILE" ]; then if [ -f "$token_file" ]; then
local token=$(sops --decrypt "$TOKEN_FILE" 2>/dev/null | grep 'creating_token' | cut -d'"' -f2) local token=$(sops --decrypt "$token_file" 2>/dev/null | grep 'creating_token' | cut -d'"' -f2)
if [ -n "$token" ]; then if [ -n "$token" ]; then
connection_status=$(curl -s -H "Authorization: token $token" "https://codeberg.org/api/v1/user" 2>&1) connection_status=$(curl -s -H "Authorization: token $token" "https://codeberg.org/api/v1/user" 2>&1)
if echo "$connection_status" | grep -q '"username"'; then if echo "$connection_status" | grep -q '"username"'; then
@ -352,8 +248,7 @@ test_connection() {
;; ;;
esac esac
dialog --backtitle "${title}" --title "Prueba de conexión" --msgbox "$connection_message" 15 70 dialog --backtitle "${title}" --title "Resultado de la prueba" --msgbox "$connection_message" 15 70
handle_cli_selection
} }
# Función principal # Función principal
@ -363,8 +258,17 @@ main() {
check_sops check_sops
check_token_directory check_token_directory
# Mostrar menú principal # Ejecutar la función principal
show_main_menu manage_version_token
# Preguntar si desea configurar otro token
while true; do
dialog_yesno "¿Desea configurar otro token de control de versiones?" 7 60
if [ $? -ne 0 ]; then
break
fi
manage_version_token
done
} }
# Ejecutar función principal # Ejecutar función principal