-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathprepare-commit-msg-hook.ts
More file actions
51 lines (39 loc) · 1.44 KB
/
prepare-commit-msg-hook.ts
File metadata and controls
51 lines (39 loc) · 1.44 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
import fs from 'fs/promises';
import chalk from 'chalk';
import { intro, outro } from '@clack/prompts';
import { getStagedGitDiff } from '../utils/git';
import { getConfig } from './config';
import { generateCommitMessageWithChatCompletion } from '../generateCommitMessageFromGitDiff';
const [messageFilePath, commitSource] = process.argv.slice(2);
export const prepareCommitMessageHook = async () => {
try {
if (!messageFilePath) {
throw new Error(
'Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook'
);
}
const config = getConfig();
// Skip commit message check if the user has set the skipCommitMessageCheck flag to true
if (!config?.skipCommitMessageCheck && commitSource) return;
const staged = await getStagedGitDiff();
if (!staged) return;
intro('opencommit');
if (!config?.OPENAI_API_KEY) {
throw new Error(
'No OPEN_AI_API exists. Set your OPEN_AI_API=<key> in ~/.opencommit'
);
}
const commitMessage = await generateCommitMessageWithChatCompletion(
staged.diff
);
if (typeof commitMessage !== 'string') throw new Error(commitMessage.error);
const fileContent = await fs.readFile(messageFilePath);
await fs.writeFile(
messageFilePath,
commitMessage + '\n' + fileContent.toString()
);
} catch (error) {
outro(`${chalk.red('✖')} ${error}`);
process.exit(1);
}
};