Compare commits

..

5 Commits

Author SHA1 Message Date
史悦
8e1f3d8259 优化 generatePrompt 函数,通过注释添加提示,以确保仅输出Git提交信息。
Some checks failed
Test / Test (ubuntu-latest) (push) Has been cancelled
Test / Test (windows-latest) (push) Has been cancelled
2025-10-21 10:12:03 +08:00
史悦
35372013a1 ``refactor(prompt): 优化并规范化生成提交信息的提示词- 将 conventional 类型的提示词从 JSON 格式更改为更简洁的列表格式。- 将通用规则格式化为项目列表,并增加“使用动词开头”的祈使句要求,以提高生成消息的一致性和质量。``
Some checks failed
Test / Test (ubuntu-latest) (push) Has been cancelled
Test / Test (windows-latest) (push) Has been cancelled
2025-10-21 10:02:56 +08:00
史悦
65da1dc301 feat: 在aicommits中添加提交、推送、重写和取消操作选项
Some checks failed
Test / Test (ubuntu-latest) (push) Has been cancelled
Test / Test (windows-latest) (push) Has been cancelled
2025-08-28 10:53:49 +08:00
史悦
69d3ef5040 文档: 在README.md中增加baseURL配置项说明 2025-08-27 17:50:39 +08:00
史悦
b01e7fe566 docs: 将README.md翻译为中文
Some checks failed
Test / Test (ubuntu-latest) (push) Has been cancelled
Test / Test (windows-latest) (push) Has been cancelled
2025-08-27 16:56:47 +08:00
4 changed files with 220 additions and 124 deletions

160
README.md
View File

@@ -3,193 +3,193 @@
<img src=".github/screenshot.png" alt="AI Commits"/>
<h1 align="center">AI Commits</h1>
</div>
<p>A CLI that writes your git commit messages for you with AI. Never write a commit message again.</p>
<a href="https://www.npmjs.com/package/aicommits"><img src="https://img.shields.io/npm/v/aicommits" alt="Current version"></a>
<p>一个使用 AI 为您编写 git 提交消息的 CLI 工具。再也不用手写提交消息了。</p>
<a href="https://www.npmjs.com/package/aicommits"><img src="https://img.shields.io/npm/v/aicommits" alt="当前版本"></a>
</div>
---
## Setup
## 设置
> The minimum supported version of Node.js is the latest v14. Check your Node.js version with `node --version`.
> 支持的最低 Node.js 版本是最新的 v14。使用 `node --version` 检查您的 Node.js 版本。
1. Install _aicommits_:
1. 安装 _aicommits_
```sh
npm install -g aicommits
```
2. Retrieve your API key from [OpenAI](https://platform.openai.com/account/api-keys)
2. [OpenAI](https://platform.openai.com/account/api-keys) 获取您的 API 密钥
> Note: If you haven't already, you'll have to create an account and set up billing.
> 注意:如果您还没有账户,您需要创建一个账户并设置计费。
3. Set the key so aicommits can use it:
3. 设置密钥以便 aicommits 可以使用它:
```sh
aicommits config set OPENAI_KEY=<your token>
```
This will create a `.aicommits` file in your home directory.
这将在您的主目录中创建一个 `.aicommits` 文件。
### Upgrading
### 升级
Check the installed version with:
使用以下命令检查已安装的版本:
```
aicommits --version
```
If it's not the [latest version](https://github.com/Nutlope/aicommits/releases/latest), run:
如果它不是[最新版本](https://github.com/Nutlope/aicommits/releases/latest),请运行:
```sh
npm update -g aicommits
```
## Usage
## 使用方法
### CLI mode
### CLI 模式
You can call `aicommits` directly to generate a commit message for your staged changes:
您可以直接调用 `aicommits` 来为您的暂存更改生成提交消息:
```sh
git add <files...>
aicommits
```
`aicommits` passes down unknown flags to `git commit`, so you can pass in [`commit` flags](https://git-scm.com/docs/git-commit).
`aicommits` 会将未知标志传递给 `git commit`,因此您可以传入 [`commit` 标志](https://git-scm.com/docs/git-commit)
For example, you can stage all changes in tracked files with as you commit:
例如,您可以在提交时暂存所有跟踪文件中的更改:
```sh
aicommits --all # or -a
aicommits --all # -a
```
> 👉 **Tip:** Use the `aic` alias if `aicommits` is too long for you.
> 👉 **提示:** 如果 `aicommits` 对您来说太长,可以使用 `aic` 别名。
#### Generate multiple recommendations
#### 生成多个建议
Sometimes the recommended commit message isn't the best so you want it to generate a few to pick from. You can generate multiple commit messages at once by passing in the `--generate <i>` flag, where 'i' is the number of generated messages:
有时推荐的提交消息不是最好的,所以您希望它生成几个以供选择。您可以通过传入 `--generate <i>` 标志来一次生成多个提交消息,其中 'i' 是生成的消息数量:
```sh
aicommits --generate <i> # or -g <i>
aicommits --generate <i> # -g <i>
```
> Warning: this uses more tokens, meaning it costs more.
> 警告:这会使用更多的令牌,意味着成本更高。
#### Generating Conventional Commits
#### 生成约定式提交
If you'd like to generate [Conventional Commits](https://conventionalcommits.org/), you can use the `--type` flag followed by `conventional`. This will prompt `aicommits` to format the commit message according to the Conventional Commits specification:
如果您想生成[约定式提交](https://conventionalcommits.org/),可以使用 `--type` 标志,后跟 `conventional`。这将提示 `aicommits` 根据约定式提交规范格式化提交消息:
```sh
aicommits --type conventional # or -t conventional
aicommits --type conventional # -t conventional
```
This feature can be useful if your project follows the Conventional Commits standard or if you're using tools that rely on this commit format.
如果您的项目遵循约定式提交标准,或者您使用依赖此提交格式的工具,此功能会很有用。
### Git hook
### Git 钩子
You can also integrate _aicommits_ with Git via the [`prepare-commit-msg`](https://git-scm.com/docs/githooks#_prepare_commit_msg) hook. This lets you use Git like you normally would, and edit the commit message before committing.
您还可以通过 [`prepare-commit-msg`](https://git-scm.com/docs/githooks#_prepare_commit_msg) 钩子将 _aicommits_ 与 Git 集成。这让您可以像平常一样使用 Git并在提交之前编辑提交消息。
#### Install
#### 安装
In the Git repository you want to install the hook in:
在您要安装钩子的 Git 仓库中:
```sh
aicommits hook install
```
#### Uninstall
#### 卸载
In the Git repository you want to uninstall the hook from:
在您要卸载钩子的 Git 仓库中:
```sh
aicommits hook uninstall
```
#### Usage
#### 使用方法
1. Stage your files and commit:
1. 暂存您的文件并提交:
```sh
git add <files...>
git commit # Only generates a message when it's not passed in
git commit # 仅在未传入消息时生成消息
```
> If you ever want to write your own message instead of generating one, you can simply pass one in: `git commit -m "My message"`
> 如果您想自己编写消息而不是生成消息,可以简单地传入一个:`git commit -m "My message"`
2. Aicommits will generate the commit message for you and pass it back to Git. Git will open it with the [configured editor](https://docs.github.com/en/get-started/getting-started-with-git/associating-text-editors-with-git) for you to review/edit it.
2. Aicommits 将为您生成提交消息并将其传递回 GitGit 将使用[配置的编辑器](https://docs.github.com/en/get-started/getting-started-with-git/associating-text-editors-with-git)打开它供您查看/编辑。
3. Save and close the editor to commit!
3. 保存并关闭编辑器以提交!
## Configuration
## 配置
### Reading a configuration value
### 读取配置值
To retrieve a configuration option, use the command:
要检索配置选项,请使用命令:
```sh
aicommits config get <key>
```
For example, to retrieve the API key, you can use:
例如,要检索 API 密钥,您可以使用:
```sh
aicommits config get OPENAI_KEY
```
You can also retrieve multiple configuration options at once by separating them with spaces:
您还可以通过用空格分隔它们来一次检索多个配置选项:
```sh
aicommits config get OPENAI_KEY generate
```
### Setting a configuration value
### 设置配置值
To set a configuration option, use the command:
要设置配置选项,请使用命令:
```sh
aicommits config set <key>=<value>
```
For example, to set the API key, you can use:
例如,要设置 API 密钥,您可以使用:
```sh
aicommits config set OPENAI_KEY=<your-api-key>
```
You can also set multiple configuration options at once by separating them with spaces, like
您还可以通过用空格分隔它们来一次设置多个配置选项,例如
```sh
aicommits config set OPENAI_KEY=<your-api-key> generate=3 locale=en
```
### Options
### 选项
#### OPENAI_KEY
Required
必需
The OpenAI API key. You can retrieve it from [OpenAI API Keys page](https://platform.openai.com/account/api-keys).
OpenAI API 密钥。您可以从 [OpenAI API 密钥页面](https://platform.openai.com/account/api-keys) 检索它。
#### locale
Default: `en`
默认值:`en`
The locale to use for the generated commit messages. Consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes.
用于生成提交消息的语言环境。请参阅以下列表中的代码:https://wikipedia.org/wiki/List_of_ISO_639-1_codes
#### generate
Default: `1`
默认值:`1`
The number of commit messages to generate to pick from.
要生成的提交消息数量以供选择。
Note, this will use more tokens as it generates more results.
注意,这会使用更多的令牌,因为它会生成更多的结果。
#### proxy
Set a HTTP/HTTPS proxy to use for requests.
设置用于请求的 HTTP/HTTPS 代理。
To clear the proxy option, you can use the command (note the empty value after the equals sign):
要清除代理选项,您可以使用命令(注意等号后的空值):
```sh
aicommits config set proxy=
@@ -197,17 +197,17 @@ aicommits config set proxy=
#### model
Default: `gpt-3.5-turbo`
默认值:`gpt-3.5-turbo`
The Chat Completions (`/v1/chat/completions`) model to use. Consult the list of models available in the [OpenAI Documentation](https://platform.openai.com/docs/models/model-endpoint-compatibility).
要使用的聊天完成(`/v1/chat/completions`)模型。请参阅 [OpenAI 文档](https://platform.openai.com/docs/models/model-endpoint-compatibility)中可用模型的列表。
> Tip: If you have access, try upgrading to [`gpt-4`](https://platform.openai.com/docs/models/gpt-4) for next-level code analysis. It can handle double the input size, but comes at a higher cost. Check out OpenAI's website to learn more.
> 提示:如果您有权限,尝试升级到 [`gpt-4`](https://platform.openai.com/docs/models/gpt-4) 以获得更高级的代码分析。它可以处理双倍的输入大小,但成本更高。请访问 OpenAI 的网站了解更多信息。
#### timeout
The timeout for network requests to the OpenAI API in milliseconds.
向 OpenAI API 发出网络请求的超时时间(以毫秒为单位)。
Default: `10000` (10 seconds)
默认值:`10000`10 秒)
```sh
aicommits config set timeout=20000 # 20s
@@ -215,9 +215,9 @@ aicommits config set timeout=20000 # 20s
#### max-length
The maximum character length of the generated commit message.
生成的提交消息的最大字符长度。
Default: `50`
默认值:`50`
```sh
aicommits config set max-length=100
@@ -225,32 +225,44 @@ aicommits config set max-length=100
#### type
Default: `""` (Empty string)
默认值:`""`(空字符串)
The type of commit message to generate. Set this to "conventional" to generate commit messages that follow the Conventional Commits specification:
要生成的提交消息类型。将其设置为 "conventional" 以生成遵循约定式提交规范的提交消息:
```sh
aicommits config set type=conventional
```
You can clear this option by setting it to an empty string:
您可以通过将其设置为空字符串来清除此选项:
```sh
aicommits config set type=
```
## How it works
#### baseURL
This CLI tool runs `git diff` to grab all your latest code changes, sends them to OpenAI's GPT-3, then returns the AI generated commit message.
默认值:`https://api.openai.com`
Video coming soon where I rebuild it from scratch to show you how to easily build your own CLI tools powered by AI.
用于设置 OpenAI API 的基础 URL。如果您使用的是 OpenAI 的代理服务或其他兼容的 API 端点,可以通过此选项进行配置:
## Maintainers
```sh
aicommits config set baseURL=https://your-proxy-url.com
```
这对于使用自定义 API 端点或代理服务的用户非常有用。
## 工作原理
这个 CLI 工具运行 `git diff` 来获取您所有的最新代码更改,将它们发送到 OpenAI 的 GPT-3然后返回 AI 生成的提交消息。
视频即将推出,我将从头开始重建它,向您展示如何轻松构建由 AI 驱动的自己的 CLI 工具。
## 维护者
- **Hassan El Mghari**: [@Nutlope](https://github.com/Nutlope) [<img src="https://img.shields.io/twitter/follow/nutlope?style=flat&label=nutlope&logo=twitter&color=0bf&logoColor=fff" align="center">](https://twitter.com/nutlope)
- **Hiroki Osame**: [@privatenumber](https://github.com/privatenumber) [<img src="https://img.shields.io/twitter/follow/privatenumbr?style=flat&label=privatenumbr&logo=twitter&color=0bf&logoColor=fff" align="center">](https://twitter.com/privatenumbr)
## Contributing
## 贡献
If you want to help fix a bug or implement a feature in [Issues](https://github.com/Nutlope/aicommits/issues), checkout the [Contribution Guide](CONTRIBUTING.md) to learn how to setup and test the project
如果您想在 [Issues](https://github.com/Nutlope/aicommits/issues) 中帮助修复错误或实现功能,请查看 [贡献指南](CONTRIBUTING.md) 以了解如何设置和测试项目。

View File

@@ -61,7 +61,7 @@ export default async (
});
const s = spinner();
s.start('The AI is analyzing your changes');
s.start('正在分析您的更改');
let messages: string[];
try {
messages = await generateCommitMessage(
@@ -84,34 +84,126 @@ export default async (
throw new KnownError('No commit messages were generated. Try again.');
}
let message: string;
if (messages.length === 1) {
[message] = messages;
const confirmed = await confirm({
message: `Use this commit message?\n\n ${message}\n`,
// 处理单个或多个提交消息的函数
const handleCommitAction = async (msg: string, isSingleMessage: boolean = true) => {
const action = await select({
message: isSingleMessage ? `使用此提交消息?\n\n ${msg}\n` : '选择操作:',
options: [
{ label: '提交', value: 'commit' },
{ label: '提交并推送', value: 'commit-and-push' },
{ label: '重写', value: 'rewrite' },
{ label: '取消', value: 'cancel' },
],
});
if (!confirmed || isCancel(confirmed)) {
outro('Commit cancelled');
return;
if (isCancel(action) || action === 'cancel') {
outro('提交已取消');
return false;
}
} 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;
if (action === 'rewrite') {
return 'rewrite';
}
if (action === 'commit') {
await execa('git', ['commit', '-m', msg, ...rawArgv]);
outro(`${green('✔')} 提交成功!`);
return true;
} else if (action === 'commit-and-push') {
await execa('git', ['commit', '-m', msg, ...rawArgv]);
const pushSpinner = spinner();
pushSpinner.start('正在推送到远程仓库...');
try {
await execa('git', ['push']);
pushSpinner.stop('推送成功');
outro(`${green('✔')} 提交并推送成功!`);
return true;
} catch (error) {
pushSpinner.stop('推送失败');
outro(`${red('✖')} 提交成功但推送失败: ${(error as Error).message}`);
return true;
}
}
return false;
};
// 重新生成提交消息的函数
const regenerateMessages = async () => {
const s = spinner();
s.start('正在重新生成提交消息...');
try {
const config = await getConfig({
OPENAI_KEY: env.OPENAI_KEY || env.OPENAI_API_KEY,
proxy:
env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY,
generate: generate?.toString(),
type: commitType?.toString(),
});
const newMessages = await generateCommitMessage(
config.OPENAI_KEY,
config.model,
config.locale,
staged.diff,
config.generate,
config['max-length'],
config.type,
config.timeout,
config.proxy,
config.baseURL
);
s.stop('已重新生成提交消息');
if (newMessages.length === 0) {
throw new KnownError('没有重新生成提交消息。请重试。');
}
return newMessages;
} catch (error) {
s.stop('重新生成失败');
throw error;
}
};
// 处理消息选择和提交的主循环
let currentMessages = messages;
while (true) {
let message: string;
if (currentMessages.length === 1) {
[message] = currentMessages;
const result = await handleCommitAction(message, true);
if (result === 'rewrite') {
currentMessages = await regenerateMessages();
continue;
} else if (result === true || result === false) {
return;
}
} else {
const selected = await select({
message: `选择一个提交消息: ${dim('(Ctrl+c 退出)')}`,
options: currentMessages.map((value) => ({ label: value, value })),
});
if (isCancel(selected)) {
outro('提交已取消');
return;
}
message = selected as string;
const result = await handleCommitAction(message, false);
if (result === 'rewrite') {
currentMessages = await regenerateMessages();
continue;
} else if (result === true || result === false) {
return;
}
}
message = selected as string;
}
await execa('git', ['commit', '-m', message, ...rawArgv]);
outro(`${green('✔')} Successfully committed!`);
})().catch((error) => {
outro(`${red('✖')} ${error.message}`);
handleCliError(error);

View File

@@ -36,7 +36,7 @@ export default () =>
});
const s = spinner();
s.start('The AI is analyzing your changes');
s.start('正在分析您的更改');
let messages: string[];
try {
messages = await generateCommitMessage(

View File

@@ -18,24 +18,14 @@ const commitTypes: Record<CommitType, string> = {
* Conventional Changelog:
* https://github.com/conventional-changelog/conventional-changelog/blob/d0e5d5926c8addba74bc962553dd8bcfba90e228/packages/conventional-changelog-conventionalcommits/writer-opts.js#L182-L193
*/
conventional: `从下面的类型到描述的JSON中选择最能描述git差异的类型\n${JSON.stringify(
{
docs: '仅文档更改',
style:
'不影响代码含义的更改(空格、格式、缺少分号等)',
refactor: '既不修复错误也不添加功能的代码更改',
perf: '提高性能的代码更改',
test: '添加缺失的测试或更正现有测试',
build: '影响构建系统或外部依赖的更改',
ci: '对我们的CI配置文件和脚本的更改',
chore: '不修改src或测试文件的其他更改',
revert: '恢复之前的提交',
feat: '新功能',
fix: '错误修复',
},
null,
2
)}`,
conventional: `从下面的类型到描述的JSON中选择最能描述git差异的类型(中文即可,注意后面加冒号)\n
\n- feat: 新功能
\n- fix: 修复 bug
\n- docs: 更新文档
\n- style: 格式调整(不影响代码执行)
\n- refactor: 重构(非功能更新)
\n- test: 测试相关内容
\n- chore: 构建或工具变更`,
};
export const generatePrompt = (
@@ -45,14 +35,16 @@ export const generatePrompt = (
) =>
[
'为以下代码差异生成一个简洁的、使用现在时态的中文git提交消息并遵循以下规范',
`提交消息使用中文编写。`,
`提交消息最多${maxLength}个字符。`,
'提交消息包含具体的类名、方法名或其他关键信息,不能过于笼统。',
'对于功能添加,应该指明具体的类或模块,如"在UserController中添加了用户权限验证功能"。',
'对于代码重构,应该指明重构的具体类或方法,如"重构了PaymentProcessor类的金额计算逻辑"。',
'排除任何不必要的内容如翻译。您的整个响应将直接传递到git提交中。',
`- 提交消息使用中文编写。`,
`- 提交消息最多${maxLength}个字符。`,
`- 使用动词作开头(祈使句形式)`,
'- 提交消息包含具体的类名、方法名或其他关键信息,不能过于笼统。',
'- 对于功能添加,应该指明具体类或模块,如"在UserController中添加了用户权限验证功能"。',
'- 对于代码重构,应该指明重构的具体类或方法,如"重构了PaymentProcessor类的金额计算逻辑"。',
'- 排除任何不必要的内容如翻译。您的整个响应将直接传递到git提交中。',
commitTypes[type],
specifyCommitFormat(type),
//`只输出Git的提交信息即可不要输出其他任何信息`,
]
.filter(Boolean)
.join('\n');