-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
586 lines (503 loc) · 18.1 KB
/
Copy pathindex.js
File metadata and controls
586 lines (503 loc) · 18.1 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
#!/usr/bin/env node
import { program } from 'commander';
import simpleGit from 'simple-git';
import { GoogleGenerativeAI } from '@google/generative-ai';
import chalk from 'chalk';
import inquirerPkg from 'inquirer';
import Conf from 'conf';
import fs from 'node:fs/promises';
import path from 'node:path';
const config = new Conf({ projectName: 'git-mood' });
const git = simpleGit();
// Inquirer has changed module shapes across versions (ESM/CJS interop).
// Normalize to a single `prompt()` function to avoid runtime "prompt is not a function".
const inquirer = (inquirerPkg && typeof inquirerPkg === 'object' && 'default' in inquirerPkg)
? inquirerPkg.default
: inquirerPkg;
const inqPrompt = (inquirer && typeof inquirer === 'object' && typeof inquirer.prompt === 'function')
? inquirer.prompt.bind(inquirer)
: (typeof inquirer === 'function' ? inquirer : undefined);
if (typeof inqPrompt !== 'function') {
throw new Error("Inquirer failed to load: expected a 'prompt' function.");
}
const MODELS = [
// Gemini 3.5 Series (Latest Frontier Models)
{ id: 'gemini-3.5-flash', name: 'Gemini 3.5 Flash (Agentic & High-Speed)' },
// Gemini 3.1 Series (Advanced Core Performance)
{ id: 'gemini-3.1-pro-preview', name: 'Gemini 3.1 Pro (Flagship Reasoning - Paid)' },
{ id: 'gemini-3.1-flash-lite', name: 'Gemini 3.1 Flash-Lite (High-Volume Automation)' },
// Gemini 3 Series (Stable Infrastructure)
{ id: 'gemini-3-flash', name: 'Gemini 3 Flash (Fast Modulated Reasoning)' },
{ id: 'gemini-3-pro', name: 'Gemini 3 Pro (Paid Complex Reasoning)' },
// Gemini 2.5 Series (Stable Long-Context)
{ id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro (Paid Deep Reasoning)' },
{ id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash (Balanced Price-Performance)' },
{ id: 'gemini-2.5-flash-lite', name: 'Gemini 2.5 Flash-Lite (Low Latency)' },
];
const DEFAULT_MODEL = 'gemini-3.5-flash';
function getModelId() {
return config.get('model_id') ?? DEFAULT_MODEL;
}
function parseCommitSuggestion(text) {
const trimmed = (text ?? '').trim();
if (!trimmed) return { subject: '', body: '' };
const firstBrace = trimmed.indexOf('{');
const lastBrace = trimmed.lastIndexOf('}');
if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
const jsonSlice = trimmed.slice(firstBrace, lastBrace + 1);
try {
const parsed = JSON.parse(jsonSlice);
return {
subject: String(parsed.subject ?? '').trim(),
body: String(parsed.body ?? '').trim(),
};
} catch {
}
}
const lines = trimmed.split(/\r?\n/);
const subject = (lines.shift() ?? '').trim();
const body = lines.join('\n').trim();
return { subject, body };
}
async function fileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
async function safeReadText(filePath, maxChars) {
try {
const content = await fs.readFile(filePath, 'utf8');
if (typeof maxChars === 'number' && maxChars > 0 && content.length > maxChars) {
return content.slice(0, maxChars);
}
return content;
} catch {
return '';
}
}
async function buildFileTree(rootDir, options) {
const ignore = new Set(options?.ignore ?? ['node_modules', '.git']);
const maxDepth = options?.maxDepth ?? 6;
const maxEntries = options?.maxEntries ?? 500;
let entriesCount = 0;
const lines = [];
async function walk(currentDir, depth) {
if (depth > maxDepth) return;
if (entriesCount >= maxEntries) return;
let dirents;
try {
dirents = await fs.readdir(currentDir, { withFileTypes: true });
} catch {
return;
}
dirents.sort((a, b) => a.name.localeCompare(b.name));
for (const d of dirents) {
if (entriesCount >= maxEntries) return;
if (ignore.has(d.name)) continue;
const full = path.join(currentDir, d.name);
const rel = path.relative(rootDir, full).replace(/\\/g, '/');
lines.push(rel + (d.isDirectory() ? '/' : ''));
entriesCount += 1;
if (d.isDirectory()) {
await walk(full, depth + 1);
}
}
}
await walk(rootDir, 0);
return lines.join('\n');
}
async function collectProjectContext(rootDir, scope) {
const packageJsonPath = path.join(rootDir, 'package.json');
const packageJson = await safeReadText(packageJsonPath, 12000);
const cliCommands = `
git-mood setup
git-mood model
git-mood commit
git-mood review
git-mood readme
`.trim();
if (scope === 'package') {
return `PACKAGE.JSON:\n${packageJson}\n\nCLI COMMANDS:\n${cliCommands}`;
}
const tree = await buildFileTree(rootDir, { ignore: ['node_modules', '.git'], maxDepth: 6, maxEntries: 500 });
if (scope === 'tree_key') {
const indexPath = path.join(rootDir, 'index.js');
const indexJs = await safeReadText(indexPath, 20000);
return `PACKAGE.JSON:\n${packageJson}\n\nCLI COMMANDS:\n${cliCommands}\n\nFILE TREE:\n${tree}\n\nKEY SOURCE FILES:\n\n--- index.js ---\n${indexJs}`;
}
const readmePath = path.join(rootDir, 'README.md');
const existingReadme = await safeReadText(readmePath, 20000);
const packageLockPath = path.join(rootDir, 'package-lock.json');
const packageLock = await safeReadText(packageLockPath, 12000);
const indexPath = path.join(rootDir, 'index.js');
const indexJs = await safeReadText(indexPath, 20000);
return `PACKAGE.JSON:\n${packageJson}\n\nPACKAGE-LOCK.JSON (TRUNCATED):\n${packageLock}\n\nCLI COMMANDS:\n${cliCommands}\n\nFILE TREE:\n${tree}\n\nEXISTING README (IF ANY):\n${existingReadme}\n\nSOURCE FILES:\n\n--- index.js ---\n${indexJs}`;
}
async function generateReadme() {
try {
const rootDir = process.cwd();
const readmePath = path.join(rootDir, 'README.md');
const hasReadme = await fileExists(readmePath);
const scopeAnswer = await inqPrompt([
{
type: 'select',
name: 'scope',
message: 'Choose context for README generation:',
choices: [
{ name: 'Only package.json + CLI commands (fast)', value: 'package' },
{ name: 'File tree + key source files (recommended)', value: 'tree_key' },
{ name: 'Everything (can be slow / token-heavy)', value: 'all' },
],
default: 0,
},
]);
if (hasReadme) {
const overwriteAnswer = await inqPrompt([
{
type: 'confirm',
name: 'overwrite',
message: 'README.md already exists. Overwrite it?',
default: false,
},
]);
if (!overwriteAnswer.overwrite) {
console.log(chalk.yellow('❌ Cancelled.'));
return;
}
}
process.stdout.write(chalk.blue('🧠 Writing README...'));
const model = getAI();
const context = await collectProjectContext(rootDir, scopeAnswer.scope);
const prompt = `
You are an expert technical writer.
Generate a high-quality README.md for this project in Markdown.
Output Markdown ONLY.
Include these sections (if applicable):
- Title
- Description
- Features
- Installation
- Setup (including Gemini API key configuration)
- Usage (show CLI commands and examples)
- Configuration
- Requirements
- License
Keep it concise and accurate. Do not invent features.
PROJECT CONTEXT:
${context}
`;
const result = await model.generateContent(prompt);
const markdown = (result?.response?.text?.() ?? '').trim();
console.log("\r" + " ".repeat(50) + "\r");
if (!markdown) {
console.log(chalk.red('❌ Failed to generate README content.'));
return;
}
await fs.writeFile(readmePath, markdown + '\n', 'utf8');
console.log(chalk.green('✅ README.md generated!'));
console.log(chalk.cyan('📄 Saved locally to: ') + chalk.white(readmePath));
console.log(chalk.yellow('ℹ️ This only writes the file locally. It does NOT commit or push to GitHub yet.'));
let isRepo = false;
try {
isRepo = await git.checkIsRepo();
} catch {
isRepo = false;
}
if (isRepo) {
const stageAnswer = await inqPrompt([
{
type: 'confirm',
name: 'stage',
message: 'Stage README.md now (git add README.md)?',
default: false,
},
]);
if (stageAnswer.stage) {
await git.add(['README.md']);
console.log(chalk.green('✅ Staged README.md'));
const commitNowAnswer = await inqPrompt([
{
type: 'confirm',
name: 'commitNow',
message: 'Generate commit message and commit now?',
default: false,
},
]);
if (commitNowAnswer.commitNow) {
await generateCommit();
} else {
console.log(chalk.gray('Next: run `git-mood commit` when you are ready.'));
}
} else {
console.log(chalk.gray('Next: `git add README.md` then `git-mood commit` to publish it.'));
}
}
} catch (e) {
console.error(chalk.red('Error:'), e.message);
}
}
// --- HELPER: GET AI MODEL ---
function getAI() {
const apiKey = config.get('gemini_key');
if (!apiKey) {
console.log(chalk.red("❌ No API Key found! Run 'git-mood setup' first."));
cleanupAndExit(1);
}
const genAI = new GoogleGenerativeAI(apiKey);
const modelId = getModelId();
return genAI.getGenerativeModel({ model: modelId });
}
// --- COMMAND 1: AUTO COMMIT & PUSH ---
async function generateCommit(options = {}) {
try {
// 1. Check staged files
const diff = await git.diff(['--staged']);
if (!diff) {
console.log(chalk.yellow("⚠️ No staged changes found. Did you run 'git add .'?"));
return;
}
process.stdout.write(chalk.blue("🧠 Analyzing changes..."));
const model = getAI();
// Prompt asking for a conventional commit message
const aiPrompt = `
You are an expert developer. Generate a git commit subject and an extended description for these changes.
The subject MUST follow "Conventional Commits" format (e.g., 'feat: add login', 'fix: resolve crash').
Keep the subject <= 72 characters and do not wrap it in quotes.
The body should be 1-6 short lines explaining what changed and why (no code blocks).
Return STRICT JSON only, with exactly these keys:
{"subject":"...","body":"..."}
THE DIFF:
${diff.substring(0, 5000)}
`;
const result = await model.generateContent(aiPrompt);
const suggestion = parseCommitSuggestion(result.response.text());
const subject = suggestion.subject;
const body = suggestion.body;
console.log("\r" + " ".repeat(50) + "\r"); // Clear spinner
console.log(chalk.bold.cyan('\n─ Suggested Commit ─\n'));
console.log(chalk.green('Subject: ') + chalk.bold.white(subject));
if (body) {
console.log(chalk.green('Description:\n') + chalk.white(body));
}
console.log(chalk.gray('─'.repeat(50)));
let finalSubject = subject;
let finalBody = body;
if (options.interactive) {
const edited = await inqPrompt([
{
type: 'input',
name: 'subject',
message: 'Edit commit subject:',
default: finalSubject,
},
{
type: 'editor',
name: 'body',
message: 'Edit commit description (body):',
default: finalBody,
},
]);
finalSubject = String(edited.subject ?? '').trim();
finalBody = String(edited.body ?? '').trim();
} else {
const nextAction = await inqPrompt([
{
type: 'select',
name: 'action',
message: 'What do you want to do?',
choices: [
{ name: 'Commit as-is', value: 'commit' },
{ name: 'Edit then commit', value: 'edit_commit' },
{ name: 'Cancel', value: 'cancel' },
],
default: 0,
},
]);
if (nextAction.action === 'cancel') {
console.log(chalk.yellow('❌ Cancelled.'));
return;
}
if (nextAction.action === 'edit_commit') {
const edited = await inqPrompt([
{
type: 'input',
name: 'subject',
message: 'Edit commit subject:',
default: finalSubject,
},
{
type: 'editor',
name: 'body',
message: 'Edit commit description (body):',
default: finalBody,
},
]);
finalSubject = String(edited.subject ?? '').trim();
finalBody = String(edited.body ?? '').trim();
}
}
if (!finalSubject) {
console.log(chalk.red('❌ Commit subject cannot be empty.'));
return;
}
const fullMessage = finalBody ? `${finalSubject}\n\n${finalBody}` : finalSubject;
await git.commit(fullMessage);
console.log(chalk.green("✅ Committed locally!"));
// 3. NEW STEP: Ask user to PUSH
const pushAnswer = await inqPrompt([
{
type: 'confirm',
name: 'shouldPush',
message: '🚀 Do you want to push to GitHub now?',
default: true
},
]);
if (pushAnswer.shouldPush) {
process.stdout.write(chalk.yellow("🚀 Pushing code..."));
try {
await git.push();
console.log("\r" + " ".repeat(50) + "\r");
console.log(chalk.green.bold("🎉 Pushed to GitHub successfully!"));
} catch (pushError) {
// Check if the error is because we need to pull
if (pushError.message.includes('fetch first') || pushError.message.includes('rejected')) {
console.log(chalk.yellow("\n⚠️ GitHub is ahead of your computer."));
const pullAnswer = await inqPrompt([
{
type: 'confirm',
name: 'shouldPull',
message: 'Do you want to PULL (download) changes and try pushing again?',
default: true
},
]);
if (pullAnswer.shouldPull) {
try {
console.log(chalk.blue("⬇️ Pulling changes..."));
await git.pull();
console.log(chalk.blue("⬆️ Pushing again..."));
await git.push();
console.log(chalk.green.bold("🎉 Pushed to GitHub successfully!"));
} catch (pullError) {
console.error(chalk.red("\n❌ Auto-fix failed. You likely have merge conflicts. Fix them manually."));
}
}
} else {
console.error(chalk.red("\n❌ Push failed:"), pushError.message);
}
}
}
} catch (e) {
console.error(chalk.red("Error:"), e.message);
}
}
// --- COMMAND 2: CODE REVIEW ---
async function codeReview() {
try {
// Look at unstaged AND staged changes
const diff = await git.diff();
if (!diff) {
console.log(chalk.green("✨ No changes to review. Working directory clean."));
return;
}
process.stdout.write(chalk.magenta("🕵️ Scanning code for bugs and smell..."));
const model = getAI();
const aiPrompt = `
Review this code diff like a Senior Engineer.
1. Identify potential bugs (logic errors, memory leaks).
2. Point out security risks (exposed keys, unsafe inputs).
3. Suggest 1 clean code improvement.
Format output as a bulleted list. Be helpful but strict.
THE DIFF:
${diff.substring(0, 8000)}
`;
const result = await model.generateContent(aiPrompt);
console.log("\r" + " ".repeat(50) + "\r");
console.log(chalk.bold.magenta("\n🛡️ AI CODE REVIEW REPORT 🛡️"));
console.log(result.response.text());
} catch (e) {
console.error(chalk.red("Error:"), e.message);
}
}
// --- COMMAND 3: SETUP ---
async function setupCLI() {
const answers = await inqPrompt([
{
type: 'input',
name: 'apiKey',
message: 'Paste your Google Gemini API Key:',
},
{
type: 'select',
name: 'modelId',
message: 'Choose Gemini model (↑/↓ arrows, Enter to select):',
choices: MODELS.map((m) => ({ name: m.name, value: m.id })),
default: Math.max(0, MODELS.findIndex((m) => m.id === getModelId())),
},
]);
config.set('gemini_key', answers.apiKey);
config.set('model_id', answers.modelId);
console.log(chalk.green("✅ API Key and model saved."));
}
// --- COMMAND 4: MODEL (change model) ---
async function modelCLI() {
const answer = await inqPrompt([
{
type: 'select',
name: 'modelId',
message: 'Choose Gemini model (↑/↓ arrows, Enter to select):',
choices: MODELS.map((m) => ({ name: m.name, value: m.id })),
default: Math.max(0, MODELS.findIndex((m) => m.id === getModelId())),
},
]);
config.set('model_id', answer.modelId);
const label = MODELS.find((m) => m.id === answer.modelId)?.name ?? answer.modelId;
console.log(chalk.green("✅ Model set to: " + label));
}
// --- CLI CONFIG ---
program
.name('git-mood')
.description('AI-Powered Git Assistant — conventional commits & code review')
.version('2.1.0');
program.command('setup').description('Set Gemini API key and model').action(setupCLI);
program.command('model').description('Change Gemini model').action(modelCLI);
program
.command('commit')
.description('Generates a commit message from your staged changes and commits it')
.option('-i, --interactive', 'Edit subject/body before committing')
.action((options) => generateCommit(options));
program
.command('review')
.description('Scans your current changes for bugs before you commit')
.action(codeReview);
program
.command('readme')
.description('Generates a README.md for your current project using AI')
.action(generateReadme);
function cleanupAndExit(code) {
try {
if (process.stdin.isTTY) {
try {
process.stdin.setRawMode(false);
} catch {
// ignore
}
}
} catch {
// ignore
}
// Delay the exit slightly to allow libuv handles/threads (e.g., keep-alive fetch connections)
// to clean up and close gracefully, preventing Windows assertion crashes.
setTimeout(() => {
process.exit(code);
}, 100);
}
await program
.parseAsync(process.argv)
.then(() => cleanupAndExit(0))
.catch((err) => {
console.error(chalk.red('Error:'), err?.message ?? String(err));
cleanupAndExit(1);
});