refactor: hooks to be called via aicommits (#99)

This commit is contained in:
hiroki osame
2023-02-22 00:01:11 -05:00
committed by GitHub
parent 09013af5fc
commit 13b06e8c16
7 changed files with 124 additions and 107 deletions

View File

@@ -1,21 +1,9 @@
import { execa } from 'execa';
import {
black, dim, green, red, bgCyan,
} from 'kolorist';
import {
intro, outro, spinner, select, confirm, isCancel,
} from '@clack/prompts';
import { cli } from 'cleye';
import { description, version } from '../package.json';
import {
assertGitRepo,
getStagedDiff,
getDetectedMessage,
} from './utils/git.js';
import { getConfig } from './utils/config.js';
import { generateCommitMessage } from './utils/openai.js';
import aicommits from './commands/aicommits.js';
import prepareCommitMessageHook from './commands/prepare-commit-msg-hook.js';
import configCommand from './commands/config.js';
import hookCommand from './commands/hook.js';
import hookCommand, { isCalledFromGitHook } from './commands/hook.js';
const rawArgv = process.argv.slice(2);
@@ -51,70 +39,14 @@ cli(
ignoreArgv: type => type === 'unknown-flag' || type === 'argument',
},
(argv) => {
(async () => {
intro(bgCyan(black(' aicommits ')));
await assertGitRepo();
const detectingFiles = spinner();
detectingFiles.start('Detecting staged files');
const staged = await getStagedDiff();
if (!staged) {
throw new Error('No staged changes found. Make sure to stage your changes with `git add`.');
}
detectingFiles.stop(`${getDetectedMessage(staged.files)}:\n${
staged.files.map(file => ` ${file}`).join('\n')
}`);
const config = await getConfig();
const OPENAI_KEY = process.env.OPENAI_KEY ?? process.env.OPENAI_API_KEY ?? config.OPENAI_KEY;
if (!OPENAI_KEY) {
throw new Error('Please set your OpenAI API key in ~/.aicommits');
}
const s = spinner();
s.start('The AI is analyzing your changes');
const messages = await generateCommitMessage(
OPENAI_KEY,
staged.diff,
if (isCalledFromGitHook) {
prepareCommitMessageHook();
} else {
aicommits(
argv.flags.generate,
rawArgv,
);
s.stop('Changes analyzed');
let message;
if (messages.length === 1) {
[message] = messages;
const confirmed = await confirm({
message: `Use this commit message?\n\n ${message}\n`,
});
if (!confirmed || isCancel(confirmed)) {
outro('Commit cancelled');
return;
}
} else {
const selected = await select({
message: `Pick a commit message to use: ${dim('(Ctrl+c to exit)')}`,
options: messages.map(value => ({ label: value, value })),
});
if (isCancel(selected)) {
outro('Commit cancelled');
return;
}
message = selected;
}
await execa('git', ['commit', '-m', message, ...rawArgv]);
outro(`${green('✔')} Successfully committed!`);
})().catch((error) => {
outro(`${red('✖')} ${error.message}`);
process.exit(1);
});
}
},
rawArgv,
);