Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
296 lines (276 loc) · 12.5 KB
/
Copy pathindex.ts
File metadata and controls
296 lines (276 loc) · 12.5 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
#!/usr/bin/env node
import child_process from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import util from 'node:util'
import { intro, outro, autocomplete, text, isCancel, cancel, note, spinner } from '@clack/prompts'
import chalk from 'chalk'
const exec = util.promisify(child_process.exec)
function parseJsonc(source: string): unknown {
const stripped = source
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/(^|[^:])\/\/.*$/gm, '$1')
.replace(/,(\s*[}\]])/g, '$1')
return JSON.parse(stripped)
}
async function main() {
intro(chalk.bgCyan.black('Conventional Commit CLI'))
const spin = spinner()
spin.start('Loading context')
const mostUpdatedPackage = await getMostUpdatedPackage()
// --- 1. Load Scopes from Workspace ---
let scopes: { value: string; label: string; hint?: string }[] = [
{ value: '', label: 'None', hint: 'No scope' }
]
const findWorkspaceFile = (vscodeDir: string) => {
try {
const workspaceFileName = fs
.readdirSync(vscodeDir)
.find((file) => file.endsWith('.code-workspace'))
return workspaceFileName ? path.join(vscodeDir, workspaceFileName) : null
} catch {
return null
}
}
const workspaceFile =
findWorkspaceFile(path.join(process.cwd(), '.vscode')) ??
findWorkspaceFile(path.join(process.cwd(), '..', '..', '.vscode'))
if (workspaceFile) {
try {
const content = parseJsonc(fs.readFileSync(workspaceFile, 'utf8')) as {
folders?: { name?: string; path: string }[]
}
for (const f of content.folders ?? []) {
const name = f.name || path.basename(f.path)
if (name !== '/')
scopes.push({ value: name, label: name, hint: 'From workspace configuration' })
}
} catch (e) {
console.log(e)
// Ignore parsing errors
}
}
spin.stop(
`Context loaded (${scopes.length === 1 ? 'no scopes found' : `${scopes.length - 1} scopes loaded`})`
)
// --- 2. Type Selection ---
const type = await autocomplete({
message: 'Select change type:',
options: [
{ value: 'feat', label: 'feat - A new feature' },
{ value: 'fix', label: 'fix - A bug fix' },
{ value: 'docs', label: 'docs - Documentation only' },
{ value: 'style', label: 'style - Formatting, missing semi-colons, etc.' },
{ value: 'refactor', label: 'refactor - Code restructuring' },
{ value: 'perf', label: 'perf - Performance improvements' },
{ value: 'test', label: 'test - Adding missing tests' },
{ value: 'build', label: 'build - Build system or external dependencies' },
{ value: 'ci', label: 'ci - CI configuration files and scripts' },
{ value: 'chore', label: "chore - Other changes that don't modify src or test" },
{ value: 'revert', label: 'revert - Reverts a previous commit' }
]
})
if (isCancel(type)) return cancel('Commit aborted.')
// --- 3. Scope Selection ---
const scope =
scopes.length === 1
? scopes[0]!.value
: await autocomplete({
message: 'Select scope (from workspace):',
initialValue: mostUpdatedPackage,
options: scopes
})
if (isCancel(scope)) return cancel('Commit aborted.')
const emojiByType: Record<string, string | undefined> = {
feat: ':sparkles:',
fix: ':bug:',
docs: ':memo:',
refactor: ':recycle:',
perf: ':zap:',
test: ':white_check_mark:',
ci: ':green_heart:',
revert: ':rewind:'
}
// --- 4. Gitmoji Selection (Textual Values) ---
const gitmoji = await autocomplete({
message: 'Choose a gitmoji:',
initialValue: emojiByType[type],
options: [
{ value: '', label: 'None' },
{ value: ':art:', label: ':art: 🎨 - Improve structure / format of the code' },
{ value: ':zap:', label: ':zap: ⚡️ - Improve performance' },
{ value: ':fire:', label: ':fire: 🔥 - Remove code or files' },
{ value: ':bug:', label: ':bug: 🐛 - Fix a bug' },
{ value: ':ambulance:', label: ':ambulance: 🚑 - Critical hotfix' },
{ value: ':sparkles:', label: ':sparkles: ✨ - Introduce new features' },
{ value: ':memo:', label: ':memo: 📝 - Add or update documentation' },
{ value: ':rocket:', label: ':rocket: 🚀 - Deploy stuff' },
{ value: ':lipstick:', label: ':lipstick: 💄 - Add or update UI and style files' },
{ value: ':tada:', label: ':tada: 🎉 - Begin a project' },
{ value: ':white_check_mark:', label: ':white_check_mark: ✅ - Add, update, or pass tests' },
{ value: ':lock:', label: ':lock: 🔒 - Fix security issues' },
{
value: ':closed_lock_with_key:',
label: ':closed_lock_with_key: 🔐 - Add or update secrets'
},
{ value: ':bookmark:', label: ':bookmark: 🔖 - Release / Version tags' },
{ value: ':rotating_light:', label: ':rotating_light: 🚨 - Fix compiler / linter warnings' },
{ value: ':construction:', label: ':construction: 🚧 - Work in progress' },
{ value: ':green_heart:', label: ':green_heart: 💚 - Fix CI Build' },
{ value: ':arrow_down:', label: ':arrow_down: ⬇️ - Downgrade dependencies' },
{ value: ':arrow_up:', label: ':arrow_up: ⬆️ - Upgrade dependencies' },
{ value: ':pushpin:', label: ':pushpin: 📌 - Pin dependencies to specific versions' },
{
value: ':construction_worker:',
label: ':construction_worker: 👷 - Add or update CI build system'
},
{
value: ':chart_with_upwards_trend:',
label: ':chart_with_upwards_trend: 📈 - Add analytics'
},
{ value: ':recycle:', label: ':recycle: ♻️ - Refactor code' },
{ value: ':heavy_plus_sign:', label: ':heavy_plus_sign: ➕ - Add a dependency' },
{ value: ':heavy_minus_sign:', label: ':heavy_minus_sign: ➖ - Remove a dependency' },
{ value: ':wrench:', label: ':wrench: 🔧 - Add or update configuration files' },
{ value: ':hammer:', label: ':hammer: 🔨 - Add or update development scripts' },
{
value: ':globe_with_meridians:',
label: ':globe_with_meridians: 🌐 - Internationalization'
},
{ value: ':pencil2:', label: ':pencil2: ✏️ - Fix typos' },
{ value: ':poop:', label: ':poop: 💩 - Write bad code that needs improvement' },
{ value: ':rewind:', label: ':rewind: ⏪ - Revert changes' },
{
value: ':twisted_rightwards_arrows:',
label: ':twisted_rightwards_arrows: 🔀 - Merge branches'
},
{ value: ':package:', label: ':package: 📦 - Add or update compiled files/packages' },
{ value: ':alien:', label: ':alien: 👽 - Update code due to external API changes' },
{ value: ':page_facing_up:', label: ':page_facing_up: 📄 - Add or update license' },
{ value: ':truck:', label: ':truck: 🚚 - Move or rename resources' },
{ value: ':boom:', label: ':boom: 💥 - Introduce breaking changes' },
{ value: ':bento:', label: ':bento: 🍱 - Add or update assets' },
{ value: ':wheelchair:', label: '♿:wheelchair: ️ - Improve accessibility' },
{ value: ':bulb:', label: ':bulb: 💡 - Add or update source code documentation' },
{ value: ':beers:', label: ':beers: 🍻 - Write code drunkenly' },
{ value: ':speech_balloon:', label: ':speech_balloon: 💬 - Add or update text/literals' },
{ value: ':card_file_box:', label: ':card_file_box: 🗃️ - Database related changes' },
{ value: ':loud_sound:', label: ':loud_sound: 🔊 - Add or update logs' },
{ value: ':mute:', label: ':mute: 🔇 - Remove logs' },
{
value: ':busts_in_silhouette:',
label: ':busts_in_silhouette: 👥 - Add or update contributor(s)'
},
{ value: ':children_crossing:', label: ':children_crossing: 🚸 - Improve UX/usability' },
{
value: ':building_construction:',
label: ':building_construction: 🏗️ - Architectural changes'
},
{ value: ':iphone:', label: ':iphone: 📱 - Responsive design' },
{ value: ':clown_face:', label: ':clown_face: 🤡 - Mock things' },
{ value: ':egg:', label: ':egg: 🥚 - Add or update an easter egg' },
{ value: ':see_no_evil:', label: ':see_no_evil: 🙈 - Add or update a .gitignore file' },
{ value: ':camera_flash:', label: ':camera_flash: 📸 - Add or update snapshots' },
{ value: ':alembic:', label: ':alembic: ⚗️ - Perform experiments' },
{ value: ':mag:', label: ':mag: 🔍 - Improve SEO' },
{ value: ':label:', label: ':label: 🏷️ - Add or update types' },
{ value: ':seedling:', label: ':seedling: 🌱 - Add or update seed files' },
{ value: ':triangular_flag_on_post:', label: ':triangular_flag_on_post: 🚩 - Feature flags' },
{ value: ':goal_net:', label: ':goal_net: 🥅 - Catch errors' },
{ value: ':animation:', label: ':animation: 💫 - Animations and transitions' },
{ value: ':wastebasket:', label: ':wastebasket: 🗑️ - Deprecate code' },
{
value: ':passport_control:',
label:
':passport_control: 🛂 - Work on code related to authorization, roles and permissions.'
},
{
value: ':adhesive_bandage:',
label: ':adhesive_bandage: 🩹 - Simple fix for a non-critical issue.'
},
{ value: ':monocle_face:', label: ':monocle_face: 🧐 - Data exploration/inspection.' },
{ value: ':coffin:', label: ':coffin: ⚰️ - Remove dead code.' },
{ value: ':test_tube:', label: ':test_tube: 🧪 - Add a failing test.' },
{ value: ':necktie:', label: ':necktie: 👔 - Add or update business logic.' },
{ value: ':stethoscope:', label: ':stethoscope: 🩺 - Add or update healthcheck.' },
{ value: ':bricks:', label: ':bricks: 🧱 - Infrastructure related changes.' },
{ value: ':technologist:', label: ':technologist: 👨💻 - Improve developer experience.' },
{
value: ':money_with_wings:',
label: ':money_with_wings: 💸 - Add sponsorships or money related infrastructure.'
},
{
value: ':thread:',
label: ':thread: 🧵 - Add or update code related to multithreading or concurrency.'
},
{
value: ':safety_vest:',
label: ':safety_vest: 🦺 - Add or update code related to validation.'
},
{ value: ':whale:', label: ':whale: 🐳 - Add or update code related to Docker.' }
]
})
if (isCancel(gitmoji)) return cancel('Commit aborted.')
// --- 5. Descriptions ---
const subject = await text({
message: 'Short description :',
validate: (v) =>
!v?.match(/^(?:[a-zA-Z0-9]|`)[^\n]{0,64}$/)
? 'Invalid description, must match (?:[a-zA-Z0-9]|`)[^\n]{0,64}'
: undefined
})
if (isCancel(subject)) return cancel('Commit aborted.')
const body = await text({
message: 'Longer description (optional):',
placeholder: 'Details about this change...'
})
if (isCancel(body)) return cancel('Commit aborted.')
const breaking = await text({
message: 'Breaking changes (optional):',
placeholder: 'Describe what broke...'
})
if (isCancel(breaking)) return cancel('Commit aborted.')
// --- 6. Assemble & Execute ---
const s = scope ? `(${scope})` : ''
const b = breaking ? '!' : ''
const g = gitmoji ? `${gitmoji} ` : ''
let msg = `${type}${s}${b}: ${g}${subject}`
if (body) msg += `\n\n${body}`
if (breaking) msg += `\n\nBREAKING CHANGE: ${breaking}`
note(msg, 'Final Commit Message')
try {
const cmd = `git commit -m "${msg.replace(/"/g, '\\"')}"`
spin.start(cmd)
// Shell execution
await exec(cmd)
spin.stop(cmd)
outro(chalk.green('✔ Git commit created successfully!'))
} catch {
outro(chalk.red('✘ Error: Failed to commit. Make sure your changes are staged.'))
}
}
async function getMostUpdatedPackage() {
const stagedOutput = (await exec('git diff --cached --name-only')).toString()
const stagedFiles = stagedOutput
.split('\n')
.map((f) => f.trim())
.filter(Boolean)
const packageCounts: Record<string, number> = {}
for (const file of stagedFiles) {
if (!file.startsWith(`packages/`)) continue
const parts = file.split('/') // extract the package name: packages/<name>/...
if (parts.length < 2) continue
const packageName = parts[1]!
packageCounts[packageName] = (packageCounts[packageName] || 0) + 1
}
let maxCount = 0
let mostUpdatedPackage: string | undefined = undefined
for (const [pkg, count] of Object.entries(packageCounts)) {
if (count > maxCount) {
maxCount = count
mostUpdatedPackage = pkg
}
}
return mostUpdatedPackage
}
main()