Implementación inicial de Nucleo Docs
This commit is contained in:
152
.claude/hooks/README.md
Normal file
152
.claude/hooks/README.md
Normal file
@@ -0,0 +1,152 @@
|
||||
# Gitea Actions Monitor Hook
|
||||
|
||||
Este hook monitorea automáticamente tus Gitea Actions después de hacer `git push` y te notifica cuando terminan.
|
||||
|
||||
## Configuración
|
||||
|
||||
### 1. Crear un token de acceso en Gitea
|
||||
|
||||
1. Ve a: https://gitea.nucleoriofrio.com/user/settings/applications
|
||||
2. En la sección **"Generate New Token"**:
|
||||
- **Token Name**: `claude-code-monitor` (o el nombre que prefieras)
|
||||
- **Select Permissions**: Marca `read:repository` o `repo` (lectura de repositorio)
|
||||
3. Click en **"Generate Token"**
|
||||
4. **IMPORTANTE**: Copia el token inmediatamente (solo se muestra una vez)
|
||||
|
||||
### 2. Configurar la variable de entorno
|
||||
|
||||
Agrega el token a tu archivo de configuración de shell:
|
||||
|
||||
**Para Bash** (`~/.bashrc`):
|
||||
```bash
|
||||
export GITEA_TOKEN='tu_token_aqui'
|
||||
```
|
||||
|
||||
**Para Zsh** (`~/.zshrc`):
|
||||
```bash
|
||||
export GITEA_TOKEN='tu_token_aqui'
|
||||
```
|
||||
|
||||
**Para Fish** (`~/.config/fish/config.fish`):
|
||||
```fish
|
||||
set -x GITEA_TOKEN 'tu_token_aqui'
|
||||
```
|
||||
|
||||
Luego recarga la configuración:
|
||||
```bash
|
||||
source ~/.bashrc # o ~/.zshrc o reinicia la terminal
|
||||
```
|
||||
|
||||
### 3. Verificar que funciona
|
||||
|
||||
Verifica que la variable está configurada:
|
||||
```bash
|
||||
echo $GITEA_TOKEN
|
||||
```
|
||||
|
||||
Deberías ver tu token.
|
||||
|
||||
## Uso
|
||||
|
||||
Una vez configurado, el hook se activa automáticamente cuando Claude Code ejecuta `git push`:
|
||||
|
||||
1. Claude ejecuta `git push`
|
||||
2. El hook verifica que Actions estén habilitadas
|
||||
3. El hook se activa automáticamente y comienza a monitorear
|
||||
4. **Claude se congela** mientras espera a que termine la Gitea Action (máximo 10 minutos)
|
||||
5. Puedes presionar **Ctrl+C** para interrumpir la espera si es necesario
|
||||
6. Cuando termine, Claude te muestra información detallada:
|
||||
|
||||
**Ejemplo de action exitosa:**
|
||||
```
|
||||
✅ Gitea Action completada: EXITOSO
|
||||
|
||||
📋 Detalles:
|
||||
• Workflow: build-and-deploy (build-and-deploy.yml)
|
||||
• Run #3
|
||||
• Evento: push
|
||||
• Branch: master
|
||||
• Commit: a1b2c3d4
|
||||
• Título: Update README: Add Claude Code hooks feature
|
||||
• Duración: 5m 23s
|
||||
• Iniciado: 2025-10-12T14:30:05Z
|
||||
• Finalizado: 2025-10-12T14:35:28Z
|
||||
|
||||
🔗 Ver logs completos:
|
||||
https://gitea.nucleoriofrio.com/nucleo000/plantillaNuxtAuthentikProxy/actions/runs/123
|
||||
```
|
||||
|
||||
**Si las Actions no están habilitadas:**
|
||||
```
|
||||
⚠️ Git push exitoso, pero las Gitea Actions NO están habilitadas en este repositorio.
|
||||
|
||||
📝 Para habilitar Actions:
|
||||
1. Ve a: https://gitea.nucleoriofrio.com/nucleo000/plantillaNuxtAuthentikProxy/settings
|
||||
2. Busca la sección 'Actions' o 'Workflows'
|
||||
3. Activa las Actions
|
||||
```
|
||||
|
||||
## Configuración Avanzada
|
||||
|
||||
### Cambiar el timeout
|
||||
|
||||
Edita `.claude/settings.local.json` y modifica el valor `timeout` (en segundos):
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/monitor-gitea-action.sh",
|
||||
"timeout": 300 // 5 minutos en lugar de 10
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Cambiar el intervalo de polling
|
||||
|
||||
Edita `.claude/hooks/monitor-gitea-action.sh` y modifica:
|
||||
|
||||
```bash
|
||||
POLL_INTERVAL=10 # Consultar cada 10 segundos (puedes cambiar a 5, 15, 30, etc.)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### El hook no se activa
|
||||
|
||||
1. Verifica que el archivo de configuración es correcto: `cat .claude/settings.local.json`
|
||||
2. Reinicia Claude Code para que recargue la configuración
|
||||
3. Revisa los logs con `claude --debug`
|
||||
|
||||
### Error "falta GITEA_TOKEN"
|
||||
|
||||
El token no está configurado. Sigue los pasos de configuración arriba.
|
||||
|
||||
### Timeout: La action todavía está corriendo
|
||||
|
||||
La action tardó más de 10 minutos. Puedes:
|
||||
- Aumentar el `timeout` en la configuración
|
||||
- Verificar el estado manualmente en Gitea
|
||||
- Optimizar tu Gitea Action para que sea más rápida
|
||||
|
||||
### El script no puede conectarse a la API
|
||||
|
||||
1. Verifica que puedes acceder a Gitea: `curl https://gitea.nucleoriofrio.com`
|
||||
2. Verifica que el token es válido:
|
||||
```bash
|
||||
curl -H "Authorization: token $GITEA_TOKEN" \
|
||||
https://gitea.nucleoriofrio.com/api/v1/repos/nucleo000/plantillaNuxtAuthentikProxy/actions/tasks?limit=1
|
||||
```
|
||||
|
||||
## Desactivar el hook
|
||||
|
||||
Si quieres desactivar temporalmente el hook, comenta o elimina la sección `hooks` en `.claude/settings.local.json`.
|
||||
197
.claude/hooks/monitor-gitea-action.sh
Executable file
197
.claude/hooks/monitor-gitea-action.sh
Executable file
@@ -0,0 +1,197 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Monitor Gitea Action after git push
|
||||
# Este script se ejecuta después de un git push y espera a que termine la Gitea Action
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Configuración
|
||||
GITEA_URL="https://gitea.nucleoriofrio.com"
|
||||
OWNER="nucleo000"
|
||||
REPO="nucleoDocs"
|
||||
|
||||
# Intentar cargar el token desde el entorno o desde ~/.bashrc
|
||||
GITEA_TOKEN="${GITEA_TOKEN:-}"
|
||||
if [ -z "$GITEA_TOKEN" ] && [ -f "$HOME/.bashrc" ]; then
|
||||
# Intentar extraer el token de .bashrc
|
||||
GITEA_TOKEN=$(grep -oP "export GITEA_TOKEN=['\"]?\K[^'\"]*" "$HOME/.bashrc" 2>/dev/null || echo "")
|
||||
fi
|
||||
|
||||
MAX_WAIT_SECONDS=600 # 10 minutos
|
||||
POLL_INTERVAL=10 # Consultar cada 10 segundos
|
||||
|
||||
# Leer el input JSON del hook
|
||||
INPUT=$(cat)
|
||||
|
||||
# Verificar si el comando fue un git push
|
||||
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""')
|
||||
if [[ ! "$COMMAND" =~ git[[:space:]]+push ]]; then
|
||||
# No fue un git push, salir sin hacer nada
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Verificar que existe el token
|
||||
if [ -z "$GITEA_TOKEN" ]; then
|
||||
cat <<EOF
|
||||
{
|
||||
"decision": "block",
|
||||
"reason": "⚠️ Git push exitoso, pero no puedo monitorear la Gitea Action: falta GITEA_TOKEN.\n\nConfigura el token en ~/.bashrc o ~/.zshrc:\nexport GITEA_TOKEN='tu_token_aqui'"
|
||||
}
|
||||
EOF
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Función para verificar si las actions están habilitadas
|
||||
check_actions_enabled() {
|
||||
local repo_info=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
|
||||
"$GITEA_URL/api/v1/repos/$OWNER/$REPO")
|
||||
echo "$repo_info" | jq -r '.has_actions // false'
|
||||
}
|
||||
|
||||
# Función para consultar el estado de la última action
|
||||
get_latest_action_status() {
|
||||
local response=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
|
||||
"$GITEA_URL/api/v1/repos/$OWNER/$REPO/actions/tasks?limit=1")
|
||||
|
||||
# Verificar si hay un error de permisos
|
||||
if echo "$response" | jq -e '.message' > /dev/null 2>&1; then
|
||||
echo "ERROR: $(echo "$response" | jq -r '.message')" >&2
|
||||
echo ""
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "$response" | jq -r '.workflow_runs[0] // .data[0] // empty'
|
||||
}
|
||||
|
||||
# Función para formatear el resultado
|
||||
format_result() {
|
||||
local status="$1"
|
||||
local task_data="$2"
|
||||
|
||||
local id=$(echo "$task_data" | jq -r '.id // "N/A"')
|
||||
local workflow_name=$(echo "$task_data" | jq -r '.name // "N/A"')
|
||||
local workflow_file=$(echo "$task_data" | jq -r '.workflow_id // "N/A"')
|
||||
local run_number=$(echo "$task_data" | jq -r '.run_number // "N/A"')
|
||||
local event=$(echo "$task_data" | jq -r '.event // "N/A"')
|
||||
local branch=$(echo "$task_data" | jq -r '.head_branch // "N/A"')
|
||||
local title=$(echo "$task_data" | jq -r '.display_title // "N/A"')
|
||||
local created=$(echo "$task_data" | jq -r '.created_at // "N/A"')
|
||||
local started=$(echo "$task_data" | jq -r '.run_started_at // .started_at // "N/A"')
|
||||
local updated=$(echo "$task_data" | jq -r '.updated_at // .stopped_at // "N/A"')
|
||||
local commit=$(echo "$task_data" | jq -r '.head_sha[0:8] // "N/A"')
|
||||
local run_url=$(echo "$task_data" | jq -r '.url // ""')
|
||||
|
||||
# Calcular duración si es posible
|
||||
local duration="N/A"
|
||||
if [[ "$started" != "N/A" && "$updated" != "N/A" ]]; then
|
||||
local start_ts=$(date -d "$started" +%s 2>/dev/null || echo "0")
|
||||
local end_ts=$(date -d "$updated" +%s 2>/dev/null || echo "0")
|
||||
if [[ $start_ts -gt 0 && $end_ts -gt 0 ]]; then
|
||||
local diff=$((end_ts - start_ts))
|
||||
if [[ $diff -lt 60 ]]; then
|
||||
duration="${diff}s"
|
||||
else
|
||||
local mins=$((diff / 60))
|
||||
local secs=$((diff % 60))
|
||||
duration="${mins}m ${secs}s"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
case "$status" in
|
||||
success)
|
||||
local emoji="✅"
|
||||
local msg="EXITOSO"
|
||||
;;
|
||||
failure)
|
||||
local emoji="❌"
|
||||
local msg="FALLÓ"
|
||||
;;
|
||||
cancelled)
|
||||
local emoji="🚫"
|
||||
local msg="CANCELADO"
|
||||
;;
|
||||
*)
|
||||
local emoji="⚠️"
|
||||
local msg="DESCONOCIDO ($status)"
|
||||
;;
|
||||
esac
|
||||
|
||||
# Construir URL de logs si no está disponible
|
||||
if [[ -z "$run_url" || "$run_url" == "null" ]]; then
|
||||
run_url="$GITEA_URL/$OWNER/$REPO/actions/runs/$id"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
{
|
||||
"decision": "block",
|
||||
"reason": "$emoji Gitea Action completada: $msg\n\n📋 Detalles:\n • Workflow: $workflow_name ($workflow_file)\n • Run #$run_number\n • Evento: $event\n • Branch: $branch\n • Commit: $commit\n • Título: $title\n • Duración: $duration\n • Iniciado: $started\n • Finalizado: $updated\n\n🔗 Ver logs completos:\n $run_url"
|
||||
}
|
||||
EOF
|
||||
}
|
||||
|
||||
# Verificar si las actions están habilitadas
|
||||
echo "🔍 Verificando si Actions están habilitadas..." >&2
|
||||
ACTIONS_ENABLED=$(check_actions_enabled)
|
||||
|
||||
if [[ "$ACTIONS_ENABLED" != "true" ]]; then
|
||||
cat <<EOF
|
||||
{
|
||||
"decision": "block",
|
||||
"reason": "⚠️ Git push exitoso, pero las Gitea Actions NO están habilitadas en este repositorio.\n\n📝 Para habilitar Actions:\n1. Ve a: $GITEA_URL/$OWNER/$REPO/settings\n2. Busca la sección 'Actions' o 'Workflows'\n3. Activa las Actions\n\nLuego podrás ver tus workflows en:\n$GITEA_URL/$OWNER/$REPO/actions"
|
||||
}
|
||||
EOF
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Notificar que empezamos a monitorear
|
||||
echo "🔄 Monitoreando Gitea Action (máximo ${MAX_WAIT_SECONDS}s)..." >&2
|
||||
|
||||
# Esperar un poco antes de la primera consulta (dar tiempo a que Gitea cree la action)
|
||||
sleep 5
|
||||
|
||||
# Polling loop
|
||||
elapsed=0
|
||||
while [ $elapsed -lt $MAX_WAIT_SECONDS ]; do
|
||||
# Consultar el estado
|
||||
TASK_DATA=$(get_latest_action_status)
|
||||
|
||||
if [ -z "$TASK_DATA" ]; then
|
||||
echo "⏳ Esperando que Gitea cree la action... (${elapsed}s)" >&2
|
||||
sleep $POLL_INTERVAL
|
||||
elapsed=$((elapsed + POLL_INTERVAL))
|
||||
continue
|
||||
fi
|
||||
|
||||
STATUS=$(echo "$TASK_DATA" | jq -r '.status // "unknown"')
|
||||
|
||||
echo "📊 Estado actual: $STATUS (${elapsed}s)" >&2
|
||||
|
||||
# Verificar si terminó
|
||||
case "$STATUS" in
|
||||
success|failure|cancelled)
|
||||
# Action terminó!
|
||||
format_result "$STATUS" "$TASK_DATA"
|
||||
exit 0
|
||||
;;
|
||||
running|pending|waiting)
|
||||
# Todavía corriendo
|
||||
sleep $POLL_INTERVAL
|
||||
elapsed=$((elapsed + POLL_INTERVAL))
|
||||
;;
|
||||
*)
|
||||
# Estado desconocido
|
||||
echo "⚠️ Estado desconocido: $STATUS" >&2
|
||||
sleep $POLL_INTERVAL
|
||||
elapsed=$((elapsed + POLL_INTERVAL))
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Timeout alcanzado
|
||||
cat <<EOF
|
||||
{
|
||||
"decision": "block",
|
||||
"reason": "⏱️ Timeout: La Gitea Action todavía está corriendo después de ${MAX_WAIT_SECONDS}s.\n\n🔗 Verifica el estado manualmente en:\n$GITEA_URL/$OWNER/$REPO/actions"
|
||||
}
|
||||
EOF
|
||||
16
.claude/settings.json
Normal file
16
.claude/settings.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/monitor-gitea-action.sh",
|
||||
"timeout": 600
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user