claude-git-hooks 2.1.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/README.md +280 -78
  3. package/bin/claude-hooks +295 -119
  4. package/lib/config.js +164 -0
  5. package/lib/hooks/pre-commit.js +180 -67
  6. package/lib/hooks/prepare-commit-msg.js +47 -41
  7. package/lib/utils/claude-client.js +107 -16
  8. package/lib/utils/claude-diagnostics.js +266 -0
  9. package/lib/utils/file-operations.js +1 -65
  10. package/lib/utils/file-utils.js +65 -0
  11. package/lib/utils/installation-diagnostics.js +145 -0
  12. package/lib/utils/package-info.js +75 -0
  13. package/lib/utils/preset-loader.js +214 -0
  14. package/lib/utils/prompt-builder.js +83 -67
  15. package/lib/utils/resolution-prompt.js +12 -2
  16. package/package.json +49 -50
  17. package/templates/ANALYZE_DIFF.md +33 -0
  18. package/templates/COMMIT_MESSAGE.md +24 -0
  19. package/templates/CUSTOMIZATION_GUIDE.md +656 -0
  20. package/templates/SUBAGENT_INSTRUCTION.md +1 -0
  21. package/templates/config.example.json +41 -0
  22. package/templates/pre-commit +40 -2
  23. package/templates/prepare-commit-msg +40 -2
  24. package/templates/presets/ai/ANALYSIS_PROMPT.md +133 -0
  25. package/templates/presets/ai/PRE_COMMIT_GUIDELINES.md +176 -0
  26. package/templates/presets/ai/config.json +12 -0
  27. package/templates/presets/ai/preset.json +42 -0
  28. package/templates/presets/backend/ANALYSIS_PROMPT.md +85 -0
  29. package/templates/presets/backend/PRE_COMMIT_GUIDELINES.md +87 -0
  30. package/templates/presets/backend/config.json +12 -0
  31. package/templates/presets/backend/preset.json +49 -0
  32. package/templates/presets/database/ANALYSIS_PROMPT.md +114 -0
  33. package/templates/presets/database/PRE_COMMIT_GUIDELINES.md +143 -0
  34. package/templates/presets/database/config.json +12 -0
  35. package/templates/presets/database/preset.json +38 -0
  36. package/templates/presets/default/config.json +12 -0
  37. package/templates/presets/default/preset.json +53 -0
  38. package/templates/presets/frontend/ANALYSIS_PROMPT.md +99 -0
  39. package/templates/presets/frontend/PRE_COMMIT_GUIDELINES.md +95 -0
  40. package/templates/presets/frontend/config.json +12 -0
  41. package/templates/presets/frontend/preset.json +50 -0
  42. package/templates/presets/fullstack/ANALYSIS_PROMPT.md +107 -0
  43. package/templates/presets/fullstack/CONSISTENCY_CHECKS.md +147 -0
  44. package/templates/presets/fullstack/PRE_COMMIT_GUIDELINES.md +125 -0
  45. package/templates/presets/fullstack/config.json +12 -0
  46. package/templates/presets/fullstack/preset.json +55 -0
  47. package/templates/shared/ANALYSIS_PROMPT.md +103 -0
  48. package/templates/shared/ANALYZE_DIFF.md +33 -0
  49. package/templates/shared/COMMIT_MESSAGE.md +24 -0
  50. package/templates/shared/PRE_COMMIT_GUIDELINES.md +145 -0
  51. package/templates/shared/RESOLUTION_PROMPT.md +32 -0
  52. package/templates/check-version.sh +0 -266
@@ -0,0 +1,145 @@
1
+ # General Code Quality Guidelines
2
+
3
+ ## Security Fundamentals
4
+
5
+ ### Input Validation
6
+ ✅ Validate all user input
7
+ ✅ Sanitize data before use
8
+ ✅ Use parameterized queries
9
+ ✅ Escape output properly
10
+ ✅ Validate file paths
11
+
12
+ ### Credentials and Secrets
13
+ ✅ Never hardcode credentials
14
+ ✅ Use environment variables or secure vaults
15
+ ✅ Don't log sensitive data
16
+ ✅ Rotate keys regularly
17
+ ✅ Use secure random generators
18
+
19
+ ### Authentication & Authorization
20
+ ✅ Implement proper authentication
21
+ ✅ Check permissions before operations
22
+ ✅ Use secure session management
23
+ ✅ Implement rate limiting
24
+ ✅ Log security events
25
+
26
+ ## Reliability
27
+
28
+ ### Error Handling
29
+ ✅ Handle all error cases
30
+ ✅ Provide meaningful error messages
31
+ ✅ Clean up resources in finally blocks
32
+ ✅ Don't swallow exceptions silently
33
+ ✅ Log errors appropriately
34
+
35
+ ### Null Safety
36
+ ✅ Check for null/undefined values
37
+ ✅ Use optional chaining where supported
38
+ ✅ Provide default values
39
+ ✅ Document when null is valid
40
+ ✅ Avoid null pointer exceptions
41
+
42
+ ### Resource Management
43
+ ✅ Close files and connections
44
+ ✅ Free allocated memory
45
+ ✅ Use try-with-resources patterns
46
+ ✅ Implement proper cleanup
47
+ ✅ Avoid resource leaks
48
+
49
+ ## Maintainability
50
+
51
+ ### Code Organization
52
+ ✅ Keep functions small and focused
53
+ ✅ Use descriptive names
54
+ ✅ Follow consistent naming conventions
55
+ ✅ Organize code logically
56
+ ✅ Limit nesting depth
57
+
58
+ ### Documentation
59
+ ✅ Document complex logic
60
+ ✅ Explain non-obvious decisions
61
+ ✅ Keep comments up to date
62
+ ✅ Use inline documentation
63
+ ✅ Document public APIs
64
+
65
+ ### Code Duplication
66
+ ✅ Extract common code into functions
67
+ ✅ Use appropriate design patterns
68
+ ✅ Don't copy-paste code
69
+ ✅ Refactor when you see duplication
70
+ ✅ Keep DRY (Don't Repeat Yourself)
71
+
72
+ ## Performance
73
+
74
+ ### General Guidelines
75
+ ✅ Choose appropriate data structures
76
+ ✅ Avoid unnecessary loops
77
+ ✅ Cache expensive computations
78
+ ✅ Use lazy loading when appropriate
79
+ ✅ Profile before optimizing
80
+
81
+ ### Resource Usage
82
+ ✅ Limit memory allocations
83
+ ✅ Use streaming for large data
84
+ ✅ Implement pagination
85
+ ✅ Clean up resources promptly
86
+ ✅ Avoid memory leaks
87
+
88
+ ## Common Issues to Avoid
89
+
90
+ ### Critical Issues (BLOCKER)
91
+ ❌ Security vulnerabilities (SQL injection, XSS, etc.)
92
+ ❌ Exposed credentials or secrets
93
+ ❌ Data loss risks
94
+ ❌ Critical bugs that crash the application
95
+
96
+ ### Major Issues (CRITICAL/MAJOR)
97
+ ❌ Unhandled exceptions
98
+ ❌ Resource leaks
99
+ ❌ Missing input validation
100
+ ❌ Poor error handling
101
+ ❌ Performance bottlenecks
102
+
103
+ ### Minor Issues (MINOR/INFO)
104
+ ❌ Code duplication
105
+ ❌ Poor naming
106
+ ❌ Missing documentation
107
+ ❌ Style inconsistencies
108
+ ❌ Unused code
109
+
110
+ ## Testing
111
+
112
+ ✅ Write tests for new functionality
113
+ ✅ Test error scenarios
114
+ ✅ Test edge cases
115
+ ✅ Mock external dependencies
116
+ ✅ Aim for reasonable coverage
117
+
118
+ ## Version Control
119
+
120
+ ✅ Write clear commit messages
121
+ ✅ Keep commits focused and atomic
122
+ ✅ Don't commit sensitive data
123
+ ✅ Review your own changes first
124
+ ✅ Rebase/clean up before pushing
125
+
126
+ ## Language-Specific
127
+
128
+ Different languages have specific best practices:
129
+
130
+ - **JavaScript/Node.js**: Use strict mode, handle promises, avoid callback hell
131
+ - **Python**: Follow PEP 8, use virtual environments, handle exceptions
132
+ - **Java**: Follow naming conventions, use proper access modifiers, handle checked exceptions
133
+ - **SQL**: Use parameterized queries, optimize for performance, maintain data integrity
134
+ - **Shell scripts**: Quote variables, check exit codes, handle errors
135
+
136
+ ## Quality Standards
137
+
138
+ Strive for:
139
+ - **Reliability**: A or B
140
+ - **Security**: A or B
141
+ - **Maintainability**: A or B
142
+ - **Coverage**: 70%+ for new code
143
+ - **Complexity**: Keep cyclomatic complexity low
144
+
145
+ Remember: The goal is to write code that is secure, reliable, maintainable, and performs well.
@@ -0,0 +1,32 @@
1
+ # FIX_CRITICAL_ISSUES
2
+
3
+ CONTEXT:
4
+ repo:{{REPO_NAME}}
5
+ branch:{{BRANCH_NAME}}
6
+ commit:{{COMMIT_SHA}}
7
+ files:{{FILE_COUNT}}
8
+
9
+ CRITICAL_ISSUES:
10
+ {{BLOCKING_ISSUES}}
11
+
12
+ AFFECTED_FILES:
13
+ {{FILE_CONTENTS}}
14
+
15
+ INSTRUCTIONS:
16
+ 1.Navigate→exact_file:line
17
+ 2.Apply_minimal_fix
18
+ 3.Maintain_style/conventions
19
+ 4.No_unrelated_refactoring
20
+
21
+ OUTPUT:
22
+ - diff_format
23
+ - one_line_explanation_max
24
+
25
+ PRIORITY:
26
+ 1.security_vulns
27
+ 2.null_ptr/runtime
28
+ 3.logic_errors
29
+ 4.performance
30
+ 5.code_quality
31
+
32
+ START_FIXING:
@@ -1,266 +0,0 @@
1
- #!/bin/bash
2
-
3
- # Script compartido para verificar versión de claude-git-hooks
4
- # Este script puede ser invocado desde cualquier hook
5
-
6
- # Colores para output
7
- RED='\033[0;31m'
8
- GREEN='\033[0;32m'
9
- YELLOW='\033[1;33m'
10
- BLUE='\033[0;34m'
11
- NC='\033[0m' # No Color
12
-
13
- # Función para logging
14
- log() {
15
- echo -e "${GREEN}[VERSION-CHECK]${NC} $1"
16
- }
17
-
18
- error() {
19
- echo -e "${RED}[ERROR]${NC} $1"
20
- }
21
-
22
- warning() {
23
- echo -e "${YELLOW}[WARNING]${NC} $1"
24
- }
25
-
26
- info() {
27
- echo -e "${BLUE}[INFO]${NC} $1"
28
- }
29
-
30
- # Función compartida para comparar versiones semánticas
31
- # Retorna: 1 si v1 > v2, 2 si v1 < v2, 0 si son iguales
32
- compare_versions() {
33
- local v1="$1"
34
- local v2="$2"
35
-
36
- if [ -n "$DEBUG_VERSION" ]; then
37
- echo "[DEBUG] compare_versions: comparando '$v1' con '$v2'"
38
- fi
39
-
40
- # Si son exactamente iguales
41
- if [ "$v1" = "$v2" ]; then
42
- if [ -n "$DEBUG_VERSION" ]; then
43
- echo "[DEBUG] compare_versions: versiones iguales, retornando 0"
44
- fi
45
- return 0
46
- fi
47
-
48
- # Usar sort -V que entiende versiones semánticas correctamente
49
- local sorted=$(printf "%s\n%s" "$v1" "$v2" | sort -V)
50
- local smaller=$(echo "$sorted" | head -1)
51
- local larger=$(echo "$sorted" | tail -1)
52
-
53
- if [ -n "$DEBUG_VERSION" ]; then
54
- echo "[DEBUG] compare_versions: sorted='$sorted', smaller='$smaller', larger='$larger'"
55
- fi
56
-
57
- if [ "$v1" = "$larger" ]; then
58
- if [ -n "$DEBUG_VERSION" ]; then
59
- echo "[DEBUG] compare_versions: v1 es mayor, retornando 1"
60
- fi
61
- return 1 # v1 es mayor que v2
62
- else
63
- if [ -n "$DEBUG_VERSION" ]; then
64
- echo "[DEBUG] compare_versions: v1 es menor, retornando 2"
65
- fi
66
- return 2 # v1 es menor que v2 (cambié de 255 a 2 para evitar problemas con set -e)
67
- fi
68
- }
69
-
70
- # Función principal de verificación
71
- check_version() {
72
- # Debug mode si está activado
73
- if [ -n "$DEBUG_VERSION" ]; then
74
- echo "[DEBUG] Iniciando verificación de versión..."
75
- fi
76
-
77
- info "Verificando versión instalada..."
78
-
79
- # Intentar obtener versión actual desde package.json global
80
- CURRENT_VERSION=""
81
- NPM_PREFIX=$(npm prefix -g 2>/dev/null || echo "/usr/local")
82
- PACKAGE_JSON_PATHS=(
83
- "$NPM_PREFIX/lib/node_modules/claude-git-hooks/package.json"
84
- "/usr/lib/node_modules/claude-git-hooks/package.json"
85
- "/usr/local/lib/node_modules/claude-git-hooks/package.json"
86
- "$HOME/.npm-global/lib/node_modules/claude-git-hooks/package.json"
87
- )
88
-
89
- for path in "${PACKAGE_JSON_PATHS[@]}"; do
90
- if [ -f "$path" ]; then
91
- CURRENT_VERSION=$(grep '"version"' "$path" 2>/dev/null | sed 's/.*"version".*"\(.*\)".*/\1/')
92
- break
93
- fi
94
- done
95
-
96
- if [ -z "$CURRENT_VERSION" ]; then
97
- warning "No se pudo determinar la versión actual"
98
- return 0 # Continuar sin bloquear
99
- fi
100
-
101
- if [ -n "$DEBUG_VERSION" ]; then
102
- echo "[DEBUG] Versión actual encontrada: $CURRENT_VERSION"
103
- fi
104
-
105
- # Obtener última versión desde NPM (usando npm view que es más confiable)
106
- info "Verificando última versión disponible..."
107
-
108
- # Método principal: usar npm view que es más confiable
109
- if [ -n "$DEBUG_VERSION" ]; then
110
- echo "[DEBUG] Ejecutando: npm view claude-git-hooks version"
111
- fi
112
-
113
- LATEST_VERSION=$(npm view claude-git-hooks version 2>/dev/null || echo "")
114
-
115
- if [ -n "$DEBUG_VERSION" ]; then
116
- echo "[DEBUG] npm view retornó: '$LATEST_VERSION'"
117
- echo "[DEBUG] Longitud de LATEST_VERSION: ${#LATEST_VERSION}"
118
- fi
119
-
120
- # Si npm view falla, intentar con la API de NPM
121
- if [ -z "$LATEST_VERSION" ]; then
122
- # Obtener el JSON completo y extraer dist-tags.latest con jq si está disponible
123
- if command -v jq &> /dev/null; then
124
- LATEST_VERSION=$(curl -s https://registry.npmjs.org/claude-git-hooks 2>/dev/null | jq -r '."dist-tags".latest' 2>/dev/null || echo "")
125
- if [ -n "$DEBUG_VERSION" ]; then
126
- echo "[DEBUG] jq parsing retornó: '$LATEST_VERSION'"
127
- fi
128
- else
129
- # Sin jq, usar método más robusto con sed
130
- LATEST_VERSION=$(curl -s https://registry.npmjs.org/claude-git-hooks 2>/dev/null | sed -n 's/.*"dist-tags":{[^}]*"latest":"\([^"]*\)".*/\1/p' | head -1)
131
- if [ -n "$DEBUG_VERSION" ]; then
132
- echo "[DEBUG] sed parsing retornó: '$LATEST_VERSION'"
133
- fi
134
- fi
135
- fi
136
-
137
- # Validar que lo obtenido parece una versión (formato X.Y.Z)
138
- if [ -n "$DEBUG_VERSION" ]; then
139
- echo "[DEBUG] Validando versión: '$LATEST_VERSION'"
140
- fi
141
-
142
- if ! echo "$LATEST_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+' ; then
143
- if [ -n "$DEBUG_VERSION" ]; then
144
- echo "[DEBUG] Versión obtenida no es válida: '$LATEST_VERSION'"
145
- fi
146
- warning "No se pudo obtener una versión válida del registro NPM"
147
- return 0
148
- fi
149
-
150
- if [ -n "$DEBUG_VERSION" ]; then
151
- echo "[DEBUG] Versión válida confirmada: '$LATEST_VERSION'"
152
- fi
153
-
154
- if [ -z "$LATEST_VERSION" ]; then
155
- # Si no se puede obtener la versión, continuar sin bloquear
156
- return 0
157
- fi
158
-
159
- if [ "$CURRENT_VERSION" = "$LATEST_VERSION" ]; then
160
- log "Versión actual ($CURRENT_VERSION) está actualizada ✓"
161
- return 0
162
- fi
163
-
164
- # Comparar versiones usando la función compartida
165
- if [ -n "$DEBUG_VERSION" ]; then
166
- echo "[DEBUG] Comparando versiones: '$CURRENT_VERSION' vs '$LATEST_VERSION'"
167
- fi
168
-
169
- # Deshabilitar set -e temporalmente para capturar el código de retorno
170
- set +e
171
- compare_versions "$CURRENT_VERSION" "$LATEST_VERSION"
172
- comparison_result=$?
173
- set -e
174
-
175
- if [ -n "$DEBUG_VERSION" ]; then
176
- echo "[DEBUG] Resultado de comparación: $comparison_result"
177
- fi
178
-
179
- if [ $comparison_result -eq 0 ]; then
180
- # Las versiones son iguales
181
- if [ -n "$DEBUG_VERSION" ]; then
182
- echo "[DEBUG] Las versiones son iguales"
183
- fi
184
- log "Versión actual ($CURRENT_VERSION) está actualizada ✓"
185
- return 0
186
- elif [ $comparison_result -eq 1 ]; then
187
- # La versión actual es mayor que la publicada (desarrollo local)
188
- if [ -n "$DEBUG_VERSION" ]; then
189
- echo "[DEBUG] Versión local ($CURRENT_VERSION) es más nueva que la publicada ($LATEST_VERSION)"
190
- fi
191
- log "Versión de desarrollo ($CURRENT_VERSION) > versión publicada ($LATEST_VERSION) ✓"
192
- return 0
193
- elif [ $comparison_result -eq 2 ]; then
194
- # La versión publicada es mayor, continuar con prompt de actualización
195
- if [ -n "$DEBUG_VERSION" ]; then
196
- echo "[DEBUG] La versión publicada ($LATEST_VERSION) es más nueva que la local ($CURRENT_VERSION)"
197
- fi
198
- # Continuar con el prompt de actualización (no return aquí)
199
- fi
200
-
201
- if [ -n "$DEBUG_VERSION" ]; then
202
- echo "[DEBUG] La versión publicada es más nueva, procediendo con prompt de actualización"
203
- fi
204
-
205
- # Solo mostrar actualización si la versión publicada es realmente más nueva
206
- echo
207
- warning "Nueva versión disponible: $LATEST_VERSION (actual: $CURRENT_VERSION)"
208
- echo -e "${YELLOW}╭─────────────────────────────────────────────╮${NC}"
209
- echo -e "${YELLOW}│${NC} Una nueva versión de claude-git-hooks está ${YELLOW}│${NC}"
210
- echo -e "${YELLOW}│${NC} disponible con mejoras y correcciones ${YELLOW}│${NC}"
211
- echo -e "${YELLOW}╰─────────────────────────────────────────────╯${NC}"
212
- echo
213
-
214
- # Leer respuesta del usuario de forma compatible con todas las consolas
215
- echo -n "¿Deseas actualizar ahora? (s/n): "
216
-
217
- # Intentar varios métodos de lectura para máxima compatibilidad
218
- REPLY=""
219
-
220
- # Método 1: Leer desde /dev/tty si existe
221
- if [ -c /dev/tty ]; then
222
- read -r REPLY </dev/tty 2>/dev/null || REPLY=""
223
- fi
224
-
225
- # Método 2: Si falla, intentar leer desde stdin estándar
226
- if [ -z "$REPLY" ]; then
227
- read -r REPLY 2>/dev/null || REPLY=""
228
- fi
229
-
230
- # Método 3: Si aún no tenemos respuesta, usar bash -c
231
- if [ -z "$REPLY" ]; then
232
- REPLY=$(bash -c 'read -r reply && echo "$reply"' 2>/dev/null || echo "")
233
- fi
234
-
235
- # Si ningún método funcionó, informar y continuar
236
- if [ -z "$REPLY" ]; then
237
- echo
238
- info "No se pudo leer la respuesta. Continuando sin actualizar."
239
- info "Para actualizar manualmente, ejecuta: claude-hooks update"
240
- return 0
241
- fi
242
-
243
- if [ "$REPLY" = "s" ] || [ "$REPLY" = "S" ] || [ "$REPLY" = "si" ] || [ "$REPLY" = "SI" ] || [ "$REPLY" = "sí" ] || [ "$REPLY" = "SÍ" ] || [ "$REPLY" = "y" ] || [ "$REPLY" = "Y" ] || [ "$REPLY" = "yes" ] || [ "$REPLY" = "YES" ]; then
244
- echo
245
- info "Actualizando claude-git-hooks..."
246
-
247
- if npm install -g claude-git-hooks@latest; then
248
- echo
249
- log "✅ Actualización completada exitosamente"
250
- info "Por favor, vuelve a ejecutar tu comando git commit"
251
- exit 0 # Salir para que el usuario reinicie con la nueva versión
252
- else
253
- error "Error al actualizar. Intenta manualmente con: npm install -g claude-git-hooks@latest"
254
- return 1
255
- fi
256
- else
257
- info "Actualización pospuesta. Puedes actualizar más tarde con: claude-hooks update"
258
- echo
259
- return 0
260
- fi
261
- }
262
-
263
- # Si se ejecuta directamente (no como source), ejecutar la verificación
264
- if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
265
- check_version
266
- fi