-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-commit.js
More file actions
310 lines (272 loc) Β· 9.77 KB
/
git-commit.js
File metadata and controls
310 lines (272 loc) Β· 9.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/**
* Git Commit Specialist Plugin
* Provides advanced git commit functionality with conventional commit support
* and safety validations for the git-commit-specialist agent
*/
export const GitCommitPlugin = async ({ $ }) => {
// Conventional commit types and their descriptions
const COMMIT_TYPES = {
feat: 'New feature or functionality',
fix: 'Bug fix',
docs: 'Documentation changes',
style: 'Code style changes (formatting, semicolons, etc.)',
refactor: 'Code refactoring without functionality changes',
test: 'Adding or updating tests',
chore: 'Maintenance tasks, dependency updates, etc.',
perf: 'Performance improvements',
ci: 'CI/CD pipeline changes',
build: 'Build system or tooling changes',
revert: 'Reverting previous commits',
}
// Sensitive data patterns to detect
const SENSITIVE_PATTERNS = [
/api[_-]?key/i,
/token/i,
/secret/i,
/password/i,
/-----BEGIN.*PRIVATE KEY-----/i,
/\.env/i,
/email.*@/i,
/phone.*\d{3}/i,
/ssn|social.*security/i,
]
// File organization patterns
const FILE_PATTERNS = {
domain: /^src\/domains\/[^\/]+\/(components|hooks|services|types|utils|__tests__)/,
shared: /^src\/domains\/shared\//,
core: /^src\/core\/(config|types|utils)/,
ui: /^src\/ui\/(components|layouts|theme|assets)/,
tests: /^tests\/unit\//,
}
// Analyze changes and suggest commit type
const analyzeChanges = async files => {
const analysis = {
type: 'chore',
scope: null,
breaking: false,
confidence: 0,
}
for (const file of files) {
// Detect scope from domain structure
const domainMatch = file.match(/src\/domains\/([^\/]+)/)
if (domainMatch && !analysis.scope) {
analysis.scope = domainMatch[1]
}
// Suggest commit type based on file patterns
if (file.includes('__tests__') || file.includes('.test.')) {
analysis.type = 'test'
analysis.confidence = Math.max(analysis.confidence, 0.9)
} else if (file.includes('README') || file.includes('docs/') || file.includes('.md')) {
analysis.type = 'docs'
analysis.confidence = Math.max(analysis.confidence, 0.8)
} else if (file.includes('components/') || file.includes('hooks/')) {
analysis.type = 'feat'
analysis.confidence = Math.max(analysis.confidence, 0.7)
} else if (file.includes('services/') || file.includes('api/')) {
analysis.type = 'refactor'
analysis.confidence = Math.max(analysis.confidence, 0.6)
}
}
return analysis
}
// Validate file organization
const validateFileOrganization = async files => {
const violations = []
for (const file of files) {
// Skip non-source files
if (!file.startsWith('src/') && !file.startsWith('tests/')) {
continue
}
const isValid = Object.values(FILE_PATTERNS).some(pattern => pattern.test(file))
if (!isValid) {
violations.push({
file,
suggestion: getOrganizationSuggestion(file),
})
}
}
return violations
}
// Get organization suggestion for misplaced files
const getOrganizationSuggestion = file => {
if (file.includes('component') || file.includes('Component')) {
return 'src/domains/{domain}/components/'
} else if (file.includes('hook') || file.includes('Hook')) {
return 'src/domains/{domain}/hooks/'
} else if (file.includes('service') || file.includes('Service')) {
return 'src/domains/{domain}/services/'
} else if (file.includes('util') || file.includes('Util')) {
return 'src/domains/{domain}/utils/'
} else if (file.includes('test') || file.includes('spec')) {
return 'src/domains/{domain}/__tests__/'
} else if (file.includes('config')) {
return 'src/core/config/'
} else if (file.includes('type') || file.includes('interface')) {
return 'src/domains/{domain}/types/'
} else {
return 'src/domains/{domain}/components/'
}
}
// Detect sensitive data in files
const detectSensitiveData = async files => {
const findings = []
for (const file of files) {
try {
const { stdout: content } = await $`cat ${file}`
const lines = content.split('\n')
lines.forEach((line, index) => {
SENSITIVE_PATTERNS.forEach(pattern => {
if (pattern.test(line)) {
findings.push({
file,
line: index + 1,
content: line.trim(),
pattern: pattern.toString(),
})
}
})
})
} catch (error) {
// File might not exist or be binary, skip
continue
}
}
return findings
}
// Generate conventional commit message
const generateCommitMessage = (type, scope, description, breaking = false) => {
const prefix = breaking ? `${type}!` : type
const scopeStr = scope ? `(${scope})` : ''
return `${prefix}${scopeStr}: ${description}`
}
// Validate commit message format
const validateCommitMessage = message => {
const pattern =
/^(feat|fix|docs|style|refactor|test|chore|perf|ci|build|revert)(\(.+\))?: .{1,}/
return pattern.test(message)
}
// Get staged files
const getStagedFiles = async () => {
try {
const { stdout } = await $`git diff --cached --name-only`
return stdout.trim().split('\n').filter(Boolean)
} catch {
return []
}
}
// Get unstaged changes
const getUnstagedChanges = async () => {
try {
const { stdout } = await $`git diff --name-only`
return stdout.trim().split('\n').filter(Boolean)
} catch {
return []
}
}
// Check current branch
const getCurrentBranch = async () => {
try {
const { stdout } = await $`git branch --show-current`
return stdout.trim()
} catch {
return 'unknown'
}
}
return {
tool: {
execute: {
before: async (input, output) => {
// Intercept git commit commands for validation
if (input.tool === 'bash' && output.args.command) {
const command = output.args.command
if (command.includes('git commit')) {
console.log('π Git Commit Specialist: Validating commit...')
// Get staged files for validation
const stagedFiles = await getStagedFiles()
if (stagedFiles.length === 0) {
throw new Error(
'β No staged files found. Stage your changes first with `git add`.'
)
}
// Validate file organization
const violations = await validateFileOrganization(stagedFiles)
if (violations.length > 0) {
console.error('β File organization violations detected:')
violations.forEach(v => {
console.error(` π ${v.file} β ${v.suggestion}`)
})
throw new Error('Fix file organization before committing.')
}
// Detect sensitive data
const sensitiveFindings = await detectSensitiveData(stagedFiles)
if (sensitiveFindings.length > 0) {
console.error('π¨ Sensitive data detected:')
sensitiveFindings.forEach(f => {
console.error(` π ${f.file}:${f.line} - ${f.content.substring(0, 50)}...`)
})
throw new Error('Remove sensitive data before committing.')
}
// Validate commit message if provided
if (command.includes('-m')) {
const messageMatch = command.match(/-m\s+["']([^"']+)["']/)
if (messageMatch) {
const message = messageMatch[1]
if (!validateCommitMessage(message)) {
throw new Error(
'β Invalid commit message format. Use: type(scope): description\n' +
'Example: feat(auth): add user login functionality'
)
}
}
}
console.log('β
Commit validation passed!')
}
}
},
after: async (input, output) => {
// Post-commit actions
if (input.tool === 'bash' && output.args.command && !output.error) {
const command = output.args.command
if (command.includes('git commit')) {
console.log('π Commit created successfully!')
// Suggest next steps
const branch = await getCurrentBranch()
if (['main', 'master'].includes(branch)) {
console.log('π‘ Consider creating a feature branch for future changes.')
} else {
console.log('π‘ Ready to push? Run: git push origin', branch)
}
}
}
},
},
},
// Custom functions for the git-commit-specialist agent
functions: {
analyzeChanges,
validateFileOrganization,
detectSensitiveData,
generateCommitMessage,
validateCommitMessage,
getStagedFiles,
getUnstagedChanges,
getCurrentBranch,
getCommitTypes: () => COMMIT_TYPES,
},
event: async ({ event }) => {
if (event.type === 'session.start') {
// Initialize git commit specialist
const branch = await getCurrentBranch()
const stagedFiles = await getStagedFiles()
const unstagedFiles = await getUnstagedChanges()
console.log(`π Git Commit Specialist initialized on branch: ${branch}`)
if (stagedFiles.length > 0) {
console.log(`π ${stagedFiles.length} staged file(s) ready for commit`)
}
if (unstagedFiles.length > 0) {
console.log(`π ${unstagedFiles.length} unstaged file(s)`)
}
}
},
}
}