-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
193 lines (175 loc) · 5.68 KB
/
cli.ts
File metadata and controls
193 lines (175 loc) · 5.68 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
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import chalk from 'chalk';
import sade from 'sade';
import { ZodError } from 'zod';
import { initCommand } from './cli/commands/init';
import {
displayCommitMessage,
displayGenerationStatus,
displayStagedChanges,
executeCommit,
getGitStatus,
} from './cli/helpers';
import { formatValidationError, validateCliOptions } from './cli/schemas';
import { CommitMessageGenerator } from './generator';
import type { GitStatus } from './utils/git-schemas';
import { ConsoleLogger, SilentLogger } from './utils/logger';
// Read version from package.json
const Filename = fileURLToPath(import.meta.url);
const Dirname = dirname(Filename);
const packageJson = JSON.parse(readFileSync(join(Dirname, '../package.json'), 'utf-8'));
const version = packageJson.version;
/**
* Generate commit command (default action)
*/
async function generateCommitCommand(rawOptions: {
agent?: string;
cwd: string;
dryRun?: boolean;
messageOnly?: boolean;
quiet?: boolean;
verbose?: boolean;
}): Promise<void> {
const options = validateOptionsOrExit(rawOptions);
const agentName = options.agent ?? 'claude';
// --message-only implies --quiet (pure message output with no progress)
const quiet = options.quiet === true || options.messageOnly === true;
const verbose = options.verbose === true;
// Create logger based on --quiet and --verbose flags
const logger = quiet ? new SilentLogger() : new ConsoleLogger({ verbose });
try {
const gitStatus = await checkGitStatusOrExit(options.cwd, logger);
displayStagedChanges(gitStatus, logger);
displayGenerationStatus(agentName, logger);
const task = {
description: 'Analyze git diff to generate appropriate commit message',
produces: gitStatus.stagedFiles,
title: 'Code changes',
};
// Pass logger to Generator via config
const generator = new CommitMessageGenerator({
agent: agentName,
logger,
});
const message = await generator.generateCommitMessage(task, {
files: gitStatus.stagedFiles,
workdir: options.cwd,
});
displayCommitMessage(message, options.messageOnly === true, logger);
await executeCommit(
message,
options.cwd,
options.dryRun === true,
options.messageOnly === true,
logger
);
} catch (error) {
console.error(chalk.red('❌ Error:'), error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
/**
* Validate CLI options or exit with error
*/
function validateOptionsOrExit(
rawOptions: Parameters<typeof validateCliOptions>[0]
): ReturnType<typeof validateCliOptions> {
try {
return validateCliOptions(rawOptions);
} catch (error) {
if (error instanceof ZodError) {
console.error(chalk.red('❌ Invalid CLI options:'));
console.error(chalk.yellow(formatValidationError(error)));
console.log(chalk.gray('\nPlease check your command-line flags and try again.'));
process.exit(1);
}
throw error;
}
}
/**
* Check git status and exit if no changes
*
* Returns a simplified GitStatus-like object with just the fields we need
*/
async function checkGitStatusOrExit(
cwd: string,
logger: ConsoleLogger | SilentLogger
): Promise<GitStatus> {
const gitStatus = await getGitStatus(cwd);
if (!gitStatus.hasChanges) {
logger.warn('No staged changes to commit');
logger.info('Run `git add` to stage changes first');
process.exit(1);
}
// Return full GitStatus from getGitStatus which already has all required fields
return gitStatus;
}
/**
* Main CLI setup
*/
const prog = sade('commitment');
prog.version(version);
// Init command - setup git hooks
prog
.command('init')
.describe('Initialize commitment hooks in your project')
.option('--hook-manager', 'Hook manager to use: husky, simple-git-hooks, plain')
.option('--agent', 'Default AI agent for hooks: claude, codex, gemini')
.option('--cwd', 'Working directory', process.cwd())
.action(
async (options: {
cwd: string;
'hook-manager'?: 'husky' | 'simple-git-hooks' | 'plain';
agent?: 'claude' | 'codex' | 'gemini';
}) => {
// Init command always uses console logger (never quiet)
const logger = new ConsoleLogger();
await initCommand(
{
agent: options.agent,
cwd: options.cwd,
hookManager: options['hook-manager'],
},
logger
);
}
);
// Default command - generate commit message
prog
.command('generate', '', { default: true })
.describe(
'Generate commit message and create commit\n\n' +
'Available agents:\n' +
' claude - Claude CLI (default)\n' +
' codex - OpenAI Codex CLI\n' +
' gemini - Google Gemini CLI\n\n' +
'Example: commitment --agent claude --dry-run --quiet'
)
.option('--agent', 'AI agent to use (claude, codex, gemini)', 'claude')
.option('--dry-run', 'Generate message without creating commit')
.option('--message-only', 'Output only the commit message (no commit)')
.option('--quiet', 'Suppress progress messages (useful for scripting)')
.option('--verbose', 'Show detailed debug output')
.option('--cwd', 'Working directory', process.cwd())
.action(
async (options: {
agent?: string;
cwd: string;
'dry-run'?: boolean;
'message-only'?: boolean;
quiet?: boolean;
verbose?: boolean;
}) => {
await generateCommitCommand({
agent: options.agent,
cwd: options.cwd,
dryRun: options['dry-run'],
messageOnly: options['message-only'],
quiet: options.quiet,
verbose: options.verbose,
});
}
);
prog.parse(process.argv);