mirror of
https://github.com/di-sukharev/opencommit.git
synced 2026-01-13 07:38:01 -05:00
Compare commits
61 Commits
github-act
...
v2.4.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a7f2d69e7 | ||
|
|
f240d35231 | ||
|
|
04ee73ca9d | ||
|
|
91885cdd1c | ||
|
|
b7a2cd46b3 | ||
|
|
028c0bc518 | ||
|
|
897eb73cd7 | ||
|
|
e7ce40a8d1 | ||
|
|
18d25672d7 | ||
|
|
79b1008e02 | ||
|
|
3c0a271bf8 | ||
|
|
ccfd24a9e5 | ||
|
|
0c8bf5562d | ||
|
|
96c7676a13 | ||
|
|
90f64d5475 | ||
|
|
a70b831f9d | ||
|
|
cad179953a | ||
|
|
8979841010 | ||
|
|
1e974086d3 | ||
|
|
792ab67ef1 | ||
|
|
a7af55df37 | ||
|
|
5c540abae9 | ||
|
|
f69e716dcc | ||
|
|
1d8d8e57c2 | ||
|
|
fdc638cd86 | ||
|
|
56e02f2604 | ||
|
|
b926a627a8 | ||
|
|
32f3e176f0 | ||
|
|
cf4212016f | ||
|
|
c491fa4bad | ||
|
|
f10fc37fe7 | ||
|
|
f7b1a6358f | ||
|
|
5f9f29c467 | ||
|
|
0ec5dab80a | ||
|
|
8d47a1bb0f | ||
|
|
fad05e0757 | ||
|
|
12f7e7eaf9 | ||
|
|
6490532818 | ||
|
|
e0e953dab8 | ||
|
|
75fa04efd4 | ||
|
|
93019139fb | ||
|
|
ce47c1fe81 | ||
|
|
a880dd6bd2 | ||
|
|
f193bb1d96 | ||
|
|
4cc34dfa5f | ||
|
|
d034238505 | ||
|
|
25acb1c219 | ||
|
|
44c9d48eae | ||
|
|
702eab9ec0 | ||
|
|
e8be3858ab | ||
|
|
50e7cd3576 | ||
|
|
4f57201e98 | ||
|
|
009462f92c | ||
|
|
34775e9e69 | ||
|
|
3f3043c48e | ||
|
|
820422760a | ||
|
|
b40657c1a7 | ||
|
|
dcd8f52be3 | ||
|
|
0eff198eb9 | ||
|
|
b345eee815 | ||
|
|
cba599337d |
2
.github/CONTRIBUTING.md
vendored
2
.github/CONTRIBUTING.md
vendored
@@ -9,7 +9,7 @@ Thanks for considering contributing to the project.
|
||||
3. Create a new branch for your changes.
|
||||
4. Make your changes and commit them with descriptive commit messages.
|
||||
5. Push your changes to your forked repository.
|
||||
6. Create a pull request from your branch to the `dev` branch.
|
||||
6. Create a pull request from your branch to the `dev` branch. Not `master` branch, PR to `dev` branch, please.
|
||||
|
||||
## Getting started
|
||||
|
||||
|
||||
BIN
.github/github-mark-white.png
vendored
Normal file
BIN
.github/github-mark-white.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
135
README.md
135
README.md
@@ -3,11 +3,12 @@
|
||||
<img src=".github/logo-grad.svg" alt="OpenCommit logo"/>
|
||||
<h1 align="center">OpenCommit</h1>
|
||||
<h4 align="center">Follow the bird <a href="https://twitter.com/io_Y_oi"><img src="https://img.shields.io/twitter/follow/io_Y_oi?style=flat&label=io_Y_oi&logo=twitter&color=0bf&logoColor=fff" align="center"></a>
|
||||
</h4>
|
||||
</div>
|
||||
<h2>Auto-generate meaningful commits in 1 second</h2>
|
||||
<p>Killing lame commits with AI 🤯🔫</p>
|
||||
<a href="https://www.npmjs.com/package/opencommit"><img src="https://img.shields.io/npm/v/opencommit" alt="Current version"></a>
|
||||
<h4 align="center">🪩 Winner of GitHub 2023 HACKATHON <a href="https://twitter.com/io_Y_oi"><img style="width:18px; height:18px;" src=".github/github-mark-white.png" align="center"></a>
|
||||
</h4>
|
||||
</div>
|
||||
|
||||
---
|
||||
@@ -16,15 +17,35 @@
|
||||
<img src=".github/opencommit-example.png" alt="OpenCommit example"/>
|
||||
</div>
|
||||
|
||||
All the commits in this repo are done with OpenCommit — look into [the commits](https://github.com/di-sukharev/opencommit/commit/eae7618d575ee8d2e9fff5de56da79d40c4bc5fc) to see how OpenCommit works. Emoji and long commit description text is configurable.
|
||||
All the commits in this repo are authored by OpenCommit — look at [the commits](https://github.com/di-sukharev/opencommit/commit/eae7618d575ee8d2e9fff5de56da79d40c4bc5fc) to see how OpenCommit works. Emojis and long commit descriptions are configurable.
|
||||
|
||||
## Setup OpenCommit as a Github Action 🔥
|
||||
## Setup OpenCommit as a CLI tool
|
||||
|
||||
You can use OpenCommit by simply running it via the CLI like this `oco`. 2 seconds and your staged changes are committed with a meaningful message.
|
||||
|
||||
1. Install OpenCommit globally to use in any repository:
|
||||
|
||||
```sh
|
||||
npm install -g opencommit
|
||||
```
|
||||
|
||||
2. Get your API key from [OpenAI](https://platform.openai.com/account/api-keys). Make sure that you add your payment details, so the API works.
|
||||
|
||||
3. Set the key to OpenCommit config:
|
||||
|
||||
```sh
|
||||
opencommit config set OCO_OPENAI_API_KEY=<your_api_key>
|
||||
```
|
||||
|
||||
Your API key is stored locally in the `~/.opencommit` config file.
|
||||
|
||||
## Setup OpenCommit as a GitHub Action 🔥
|
||||
|
||||
OpenCommit is now available as a GitHub Action which automatically improves all new commits messages when you push to remote!
|
||||
|
||||
This is great if you want to make sure all of the commits in all of repository branches are meaningful and not lame like `fix1` or `done2`.
|
||||
This is great if you want to make sure all of the commits in all of your repository branches are meaningful and not lame like `fix1` or `done2`.
|
||||
|
||||
Create a file `.github/workflows/opencommit.yml` with contents below:
|
||||
Create a file `.github/workflows/opencommit.yml` with the contents below:
|
||||
|
||||
```yml
|
||||
name: 'OpenCommit Action'
|
||||
@@ -37,6 +58,7 @@ on:
|
||||
|
||||
jobs:
|
||||
opencommit:
|
||||
timeout-minutes: 10
|
||||
name: OpenCommit
|
||||
runs-on: ubuntu-latest
|
||||
permissions: write-all
|
||||
@@ -67,31 +89,11 @@ jobs:
|
||||
OCO_LANGUAGE: en
|
||||
```
|
||||
|
||||
That is it. Now when you push to any branch in your repo — all NEW commits are being improved by never-tired-AI.
|
||||
That is it. Now when you push to any branch in your repo — all NEW commits are being improved by your never-tired AI.
|
||||
|
||||
Make sure you exclude public collaboration branches (`main`, `dev`, `etc`) in `branches-ignore`, so OpenCommit does not rebase commits there when improving the messages.
|
||||
Make sure you exclude public collaboration branches (`main`, `dev`, `etc`) in `branches-ignore`, so OpenCommit does not rebase commits there while improving the messages.
|
||||
|
||||
Interactive rebase (`rebase -i`) changes commit SHA, so commit history in remote becomes different with your local branch history. It's ok when you work on the branch alone, but may be inconvenient for other collaborators.
|
||||
|
||||
## Setup OpenCommit as a CLI
|
||||
|
||||
You can use OpenCommit by simply running it via CLI like this `oc`. 2 seconds and your staged changes are committed with a meaningful message.
|
||||
|
||||
1. Install OpenCommit globally to use in any repository:
|
||||
|
||||
```sh
|
||||
npm install -g opencommit
|
||||
```
|
||||
|
||||
2. Get your API key from [OpenAI](https://platform.openai.com/account/api-keys). Make sure you add payment details, so API works.
|
||||
|
||||
3. Set the key to OpenCommit config:
|
||||
|
||||
```sh
|
||||
opencommit config set OCO_OPENAI_API_KEY=<your_api_key>
|
||||
```
|
||||
|
||||
Your api key is stored locally in `~/.opencommit` config file.
|
||||
Interactive rebase (`rebase -i`) changes commits' SHA, so the commit history in remote becomes different from your local branch history. This is okay if you work on the branch alone, but may be inconvenient for other collaborators.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -102,62 +104,69 @@ git add <files...>
|
||||
opencommit
|
||||
```
|
||||
|
||||
You can also use the `oc` shortcut:
|
||||
You can also use the `oco` shortcut:
|
||||
|
||||
```sh
|
||||
git add <files...>
|
||||
oc
|
||||
oco
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Local per repo configuration
|
||||
|
||||
Create an `.env` file and add OpenCommit config variables there like this:
|
||||
Create a `.env` file and add OpenCommit config variables there like this:
|
||||
|
||||
```env
|
||||
OCO_OPENAI_API_KEY=<your openAI API token>
|
||||
OCO_OPENAI_MAX_TOKENS=<max response tokens from openAI API>
|
||||
OCO_OPENAI_BASE_PATH=<may be used to set proxy path to openAI api>
|
||||
OCO_OPENAI_API_KEY=<your OpenAI API token>
|
||||
OCO_OPENAI_MAX_TOKENS=<max response tokens from OpenAI API>
|
||||
OCO_OPENAI_BASE_PATH=<may be used to set proxy path to OpenAI api>
|
||||
OCO_DESCRIPTION=<postface a message with ~3 sentences description>
|
||||
OCO_EMOJI=<add GitMoji>
|
||||
OCO_MODEL=<either gpt-3.5-turbo or gpt-4>
|
||||
OCO_LANGUAGE=<locale, scroll to the bottom to see options>
|
||||
OCO_MESSAGE_TEMPLATE_PLACEHOLDER=<message template placeholder, example: '$msg'>
|
||||
```
|
||||
|
||||
### Global config for all repos
|
||||
|
||||
Local config still has more priority as Global config, but you may set `OCO_MODEL` and `OCO_LOCALE` globally and set local configs for `OCO_EMOJI` and `OCO_DESCRIPTION` per repo which is more convenient.
|
||||
Local config still has more priority than Global config, but you may set `OCO_MODEL` and `OCO_LOCALE` globally and set local configs for `OCO_EMOJI` and `OCO_DESCRIPTION` per repo which is more convenient.
|
||||
|
||||
Simply run any of the variable above like this:
|
||||
Simply set any of the variables above like this:
|
||||
|
||||
```sh
|
||||
oc config set OCO_OPENAI_API_KEY=gpt-4
|
||||
oco config set OCO_OPENAI_API_KEY=gpt-4
|
||||
```
|
||||
|
||||
Configure [GitMoji](https://gitmoji.dev/) to preface a message.
|
||||
|
||||
```sh
|
||||
oc config set OCO_EMOJI=true
|
||||
oco config set OCO_EMOJI=true
|
||||
```
|
||||
|
||||
To remove preface emoji:
|
||||
To remove preface emojis:
|
||||
|
||||
```sh
|
||||
oc config set OCO_EMOJI=false
|
||||
oco config set OCO_EMOJI=false
|
||||
```
|
||||
|
||||
### Switch to GPT-4
|
||||
### Switch to GPT-4 or other models
|
||||
|
||||
By default OpenCommit uses GPT-3.5-turbo (ChatGPT).
|
||||
By default, OpenCommit uses `gpt-3.5-turbo-16k` model.
|
||||
|
||||
You may switch to GPT-4 which performs better, but costs ~x15 times more 🤠
|
||||
|
||||
```sh
|
||||
oc config set OCO_MODEL=gpt-4
|
||||
oco config set OCO_MODEL=gpt-4
|
||||
```
|
||||
|
||||
Make sure you do lowercase `gpt-4` and you have API access to the 4th model. Even if you have ChatGPT+ it doesn't necessarily mean that you have API access to GPT-4.
|
||||
or for as a cheaper option:
|
||||
|
||||
```sh
|
||||
oco config set OCO_MODEL=gpt-3.5-turbo
|
||||
```
|
||||
|
||||
Make sure that you spell it `gpt-4` (lowercase) and that you have API access to the 4th model. Even if you have ChatGPT+, that doesn't necessarily mean that you have API access to GPT-4.
|
||||
|
||||
## Locale configuration
|
||||
|
||||
@@ -165,25 +174,25 @@ To globally specify the language used to generate commit messages:
|
||||
|
||||
```sh
|
||||
# de, German ,Deutsch
|
||||
oc config set OCO_LANGUAGE=de
|
||||
oc config set OCO_LANGUAGE=German
|
||||
oc config set OCO_LANGUAGE=Deutsch
|
||||
oco config set OCO_LANGUAGE=de
|
||||
oco config set OCO_LANGUAGE=German
|
||||
oco config set OCO_LANGUAGE=Deutsch
|
||||
|
||||
# fr, French, française
|
||||
oc config set OCO_LANGUAGE=fr
|
||||
oc config set OCO_LANGUAGE=French
|
||||
oc config set OCO_LANGUAGE=française
|
||||
oco config set OCO_LANGUAGE=fr
|
||||
oco config set OCO_LANGUAGE=French
|
||||
oco config set OCO_LANGUAGE=française
|
||||
```
|
||||
|
||||
The default language set is **English**
|
||||
The default language setting is **English**
|
||||
All available languages are currently listed in the [i18n](https://github.com/di-sukharev/opencommit/tree/master/src/i18n) folder
|
||||
|
||||
### Git flags
|
||||
|
||||
The `opencommit` or `oc` commands can be used in place of the `git commit -m "${generatedMessage}"` command. This means that any regular flags that are used with the `git commit` command will also be applied when using `opencommit` or `oc`.
|
||||
The `opencommit` or `oco` commands can be used in place of the `git commit -m "${generatedMessage}"` command. This means that any regular flags that are used with the `git commit` command will also be applied when using `opencommit` or `oco`.
|
||||
|
||||
```sh
|
||||
oc --no-verify
|
||||
oco --no-verify
|
||||
```
|
||||
|
||||
is translated to :
|
||||
@@ -192,33 +201,41 @@ is translated to :
|
||||
git commit -m "${generatedMessage}" --no-verify
|
||||
```
|
||||
|
||||
To include a message in the generated message, you can utilize the template function! For instance:
|
||||
|
||||
```sh
|
||||
oco '$msg #205’
|
||||
```
|
||||
|
||||
> opencommit examines placeholders in the parameters, allowing you to append additional information before and after the placeholders, such as the relevant Issue or Pull Request. Similarly, you have the option to customize the OCO_MESSAGE_TEMPLATE_PLACEHOLDER configuration item, for example, simplifying it to $m!"
|
||||
|
||||
### Ignore files
|
||||
|
||||
You can ignore files from submission to OpenAI by creating a `.opencommitignore` file. For example:
|
||||
You can remove files from being sent to OpenAI by creating a `.opencommitignore` file. For example:
|
||||
|
||||
```ignorelang
|
||||
path/to/large-asset.zip
|
||||
**/*.jpg
|
||||
```
|
||||
|
||||
This is useful for preventing opencommit from uploading artifacts and large files.
|
||||
This helps prevent opencommit from uploading artifacts and large files.
|
||||
|
||||
By default, opencommit ignores files matching: `*-lock.*` and `*.lock`
|
||||
|
||||
## Git hook (KILLER FEATURE)
|
||||
|
||||
You can set OpenCommit as Git [`prepare-commit-msg`](https://git-scm.com/docs/githooks#_prepare_commit_msg) hook. Hook integrates with you IDE Source Control and allows you edit the message before commit.
|
||||
You can set OpenCommit as Git [`prepare-commit-msg`](https://git-scm.com/docs/githooks#_prepare_commit_msg) hook. Hook integrates with your IDE Source Control and allows you to edit the message before committing.
|
||||
|
||||
To set the hook:
|
||||
|
||||
```sh
|
||||
oc hook set
|
||||
oco hook set
|
||||
```
|
||||
|
||||
To unset the hook:
|
||||
|
||||
```sh
|
||||
oc hook unset
|
||||
oco hook unset
|
||||
```
|
||||
|
||||
To use the hook:
|
||||
@@ -232,4 +249,4 @@ Or follow the process of your IDE Source Control feature, when it calls `git com
|
||||
|
||||
## Payments
|
||||
|
||||
You pay for your own requests to OpenAI API. OpenCommit uses ChatGPT (3.5-turbo) official model, that is ~15x times cheaper than GPT-4.
|
||||
You pay for your requests to OpenAI API. OpenCommit uses ChatGPT (3.5-turbo) official model, which is ~15x times cheaper than GPT-4.
|
||||
|
||||
1071
out/cli.cjs
1071
out/cli.cjs
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
5
package-lock.json
generated
5
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opencommit",
|
||||
"version": "2.0.17",
|
||||
"version": "2.4.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opencommit",
|
||||
"version": "2.0.17",
|
||||
"version": "2.4.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.0",
|
||||
@@ -26,7 +26,6 @@
|
||||
"openai": "^3.2.1"
|
||||
},
|
||||
"bin": {
|
||||
"oc": "out/cli.cjs",
|
||||
"oco": "out/cli.cjs",
|
||||
"opencommit": "out/cli.cjs"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "opencommit",
|
||||
"version": "2.0.17",
|
||||
"version": "2.4.1",
|
||||
"description": "Auto-generate impressive commits in 1 second. Killing lame commits with AI 🤯🔫",
|
||||
"keywords": [
|
||||
"git",
|
||||
@@ -17,7 +17,6 @@
|
||||
"main": "cli.js",
|
||||
"bin": {
|
||||
"opencommit": "./out/cli.cjs",
|
||||
"oc": "./out/cli.cjs",
|
||||
"oco": "./out/cli.cjs"
|
||||
},
|
||||
"repository": {
|
||||
@@ -42,7 +41,7 @@
|
||||
"start": "node ./out/cli.cjs",
|
||||
"dev": "ts-node ./src/cli.ts",
|
||||
"build": "rimraf out && node esbuild.config.js",
|
||||
"deploy": "npm run build && npm version patch && npm publish --tag latest",
|
||||
"deploy": "npm run build:push && npm version patch && git push --tags && npm publish --tag latest",
|
||||
"build:push": "npm run build && git add . && git commit -m 'build' && git push",
|
||||
"lint": "eslint src --ext ts && tsc --noEmit",
|
||||
"format": "prettier --write src"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export enum COMMANDS {
|
||||
hook = 'hook',
|
||||
config = 'config'
|
||||
config = 'config',
|
||||
hook = 'hook'
|
||||
}
|
||||
|
||||
25
src/api.ts
25
src/api.ts
@@ -7,7 +7,14 @@ import {
|
||||
OpenAIApi
|
||||
} from 'openai';
|
||||
|
||||
import { CONFIG_MODES, getConfig } from './commands/config';
|
||||
import {
|
||||
CONFIG_MODES,
|
||||
DEFAULT_MODEL_TOKEN_LIMIT,
|
||||
getConfig
|
||||
} from './commands/config';
|
||||
import { tokenCount } from './utils/tokenCount';
|
||||
import { GenerateCommitMessageErrorEnum } from './generateCommitMessageFromGitDiff';
|
||||
import { execa } from 'execa';
|
||||
|
||||
const config = getConfig();
|
||||
|
||||
@@ -21,7 +28,7 @@ if (!apiKey && command !== 'config' && mode !== CONFIG_MODES.set) {
|
||||
intro('opencommit');
|
||||
|
||||
outro(
|
||||
'OCO_OPENAI_API_KEY is not set, please run `oc config set OCO_OPENAI_API_KEY=<your token>. Make sure you add payment details, so API works.`'
|
||||
'OCO_OPENAI_API_KEY is not set, please run `oco config set OCO_OPENAI_API_KEY=<your token>. Make sure you add payment details, so API works.`'
|
||||
);
|
||||
outro(
|
||||
'For help look into README https://github.com/di-sukharev/opencommit#setup'
|
||||
@@ -56,6 +63,14 @@ class OpenAi {
|
||||
max_tokens: maxTokens || 500
|
||||
};
|
||||
try {
|
||||
const REQUEST_TOKENS = messages
|
||||
.map((msg) => tokenCount(msg.content) + 4)
|
||||
.reduce((a, b) => a + b, 0);
|
||||
|
||||
if (REQUEST_TOKENS > DEFAULT_MODEL_TOKEN_LIMIT - maxTokens) {
|
||||
throw new Error(GenerateCommitMessageErrorEnum.tooMuchTokens);
|
||||
}
|
||||
|
||||
const { data } = await this.openAI.createChatCompletion(params);
|
||||
|
||||
const message = data.choices[0].message;
|
||||
@@ -88,10 +103,8 @@ export const getOpenCommitLatestVersion = async (): Promise<
|
||||
string | undefined
|
||||
> => {
|
||||
try {
|
||||
const { data } = await axios.get(
|
||||
'https://unpkg.com/opencommit/package.json'
|
||||
);
|
||||
return data.version;
|
||||
const { stdout } = await execa('npm', ['view', 'opencommit', 'version']);
|
||||
return stdout;
|
||||
} catch (_) {
|
||||
outro('Error while getting the latest version of opencommit');
|
||||
return undefined;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { configCommand } from './commands/config';
|
||||
import { hookCommand, isHookCalled } from './commands/githook.js';
|
||||
import { prepareCommitMessageHook } from './commands/prepare-commit-msg-hook';
|
||||
import { commit } from './commands/commit';
|
||||
// import { checkIsLatestVersion } from './utils/checkIsLatestVersion';
|
||||
import { checkIsLatestVersion } from './utils/checkIsLatestVersion';
|
||||
|
||||
const extraArgs = process.argv.slice(2);
|
||||
|
||||
@@ -21,7 +21,7 @@ cli(
|
||||
help: { description: packageJSON.description }
|
||||
},
|
||||
async () => {
|
||||
// await checkIsLatestVersion();
|
||||
await checkIsLatestVersion();
|
||||
|
||||
if (await isHookCalled()) {
|
||||
prepareCommitMessageHook();
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { execa } from 'execa';
|
||||
import {
|
||||
GenerateCommitMessageErrorEnum,
|
||||
generateCommitMessageByDiff
|
||||
} from '../generateCommitMessageFromGitDiff';
|
||||
import { generateCommitMessageByDiff } from '../generateCommitMessageFromGitDiff';
|
||||
import {
|
||||
assertGitRepo,
|
||||
getChangedFiles,
|
||||
@@ -19,25 +16,44 @@ import {
|
||||
multiselect,
|
||||
select
|
||||
} from '@clack/prompts';
|
||||
import { getConfig } from '../commands/config';
|
||||
import chalk from 'chalk';
|
||||
import { trytm } from '../utils/trytm';
|
||||
|
||||
const config = getConfig();
|
||||
|
||||
const getGitRemotes = async () => {
|
||||
const { stdout } = await execa('git', ['remote']);
|
||||
return stdout.split('\n').filter((remote) => Boolean(remote.trim()));
|
||||
};
|
||||
|
||||
// Check for the presence of message templates
|
||||
const checkMessageTemplate = (extraArgs: string[]): string | false => {
|
||||
for (const key in extraArgs) {
|
||||
if (extraArgs[key].includes(config?.OCO_MESSAGE_TEMPLATE_PLACEHOLDER))
|
||||
return extraArgs[key];
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const generateCommitMessageFromGitDiff = async (
|
||||
diff: string,
|
||||
extraArgs: string[]
|
||||
): Promise<void> => {
|
||||
const messageTemplate = checkMessageTemplate(extraArgs);
|
||||
await assertGitRepo();
|
||||
|
||||
const commitSpinner = spinner();
|
||||
commitSpinner.start('Generating the commit message');
|
||||
try {
|
||||
const commitMessage = await generateCommitMessageByDiff(diff);
|
||||
let commitMessage = await generateCommitMessageByDiff(diff);
|
||||
|
||||
if (typeof messageTemplate === 'string') {
|
||||
commitMessage = messageTemplate.replace(
|
||||
config?.OCO_MESSAGE_TEMPLATE_PLACEHOLDER,
|
||||
commitMessage
|
||||
);
|
||||
}
|
||||
commitSpinner.stop('📝 Commit message generated');
|
||||
|
||||
outro(
|
||||
@@ -139,7 +155,7 @@ export async function commit(
|
||||
|
||||
if (changedFiles) await gitAdd({ files: changedFiles });
|
||||
else {
|
||||
outro('No changes detected, write some code and run `oc` again');
|
||||
outro('No changes detected, write some code and run `oco` again');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { command } from 'cleye';
|
||||
import { join as pathJoin } from 'path';
|
||||
import { parse as iniParse, stringify as iniStringify } from 'ini';
|
||||
import { existsSync, writeFileSync, readFileSync } from 'fs';
|
||||
import { homedir } from 'os';
|
||||
import { intro, outro } from '@clack/prompts';
|
||||
import chalk from 'chalk';
|
||||
import { command } from 'cleye';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { parse as iniParse, stringify as iniStringify } from 'ini';
|
||||
import { homedir } from 'os';
|
||||
import { join as pathJoin } from 'path';
|
||||
import { COMMANDS } from '../CommandsEnum';
|
||||
import { getI18nLocal } from '../i18n';
|
||||
|
||||
@@ -19,9 +19,12 @@ export enum CONFIG_KEYS {
|
||||
OCO_DESCRIPTION = 'OCO_DESCRIPTION',
|
||||
OCO_EMOJI = 'OCO_EMOJI',
|
||||
OCO_MODEL = 'OCO_MODEL',
|
||||
OCO_LANGUAGE = 'OCO_LANGUAGE'
|
||||
OCO_LANGUAGE = 'OCO_LANGUAGE',
|
||||
OCO_MESSAGE_TEMPLATE_PLACEHOLDER = 'OCO_MESSAGE_TEMPLATE_PLACEHOLDER'
|
||||
}
|
||||
|
||||
export const DEFAULT_MODEL_TOKEN_LIMIT = 4096;
|
||||
|
||||
export enum CONFIG_MODES {
|
||||
get = 'get',
|
||||
set = 'set'
|
||||
@@ -80,7 +83,7 @@ export const configValidators = {
|
||||
}
|
||||
validateConfig(
|
||||
CONFIG_KEYS.OCO_OPENAI_MAX_TOKENS,
|
||||
typeof value === 'number',
|
||||
value ? typeof value === 'number' : undefined,
|
||||
'Must be a number'
|
||||
);
|
||||
|
||||
@@ -117,9 +120,22 @@ export const configValidators = {
|
||||
|
||||
[CONFIG_KEYS.OCO_MODEL](value: any) {
|
||||
validateConfig(
|
||||
CONFIG_KEYS.OCO_OPENAI_BASE_PATH,
|
||||
value === 'gpt-3.5-turbo' || value === 'gpt-4',
|
||||
`${value} is not supported yet, use 'gpt-4' or 'gpt-3.5-turbo' (default)`
|
||||
CONFIG_KEYS.OCO_MODEL,
|
||||
[
|
||||
'gpt-3.5-turbo',
|
||||
'gpt-4',
|
||||
'gpt-3.5-turbo-16k',
|
||||
'gpt-3.5-turbo-0613'
|
||||
].includes(value),
|
||||
`${value} is not supported yet, use 'gpt-4', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-0613' or 'gpt-3.5-turbo' (default)`
|
||||
);
|
||||
return value;
|
||||
},
|
||||
[CONFIG_KEYS.OCO_MESSAGE_TEMPLATE_PLACEHOLDER](value: any) {
|
||||
validateConfig(
|
||||
CONFIG_KEYS.OCO_MESSAGE_TEMPLATE_PLACEHOLDER,
|
||||
value.startsWith('$'),
|
||||
`${value} must start with $, for example: '$msg'`
|
||||
);
|
||||
return value;
|
||||
}
|
||||
@@ -134,12 +150,16 @@ const configPath = pathJoin(homedir(), '.opencommit');
|
||||
export const getConfig = (): ConfigType | null => {
|
||||
const configFromEnv = {
|
||||
OCO_OPENAI_API_KEY: process.env.OCO_OPENAI_API_KEY,
|
||||
OCO_OPENAI_MAX_TOKENS: Number(process.env.OCO_OPENAI_MAX_TOKENS),
|
||||
OCO_OPENAI_MAX_TOKENS: process.env.OCO_OPENAI_MAX_TOKENS
|
||||
? Number(process.env.OCO_OPENAI_MAX_TOKENS)
|
||||
: undefined,
|
||||
OCO_OPENAI_BASE_PATH: process.env.OCO_OPENAI_BASE_PATH,
|
||||
OCO_DESCRIPTION: process.env.OCO_DESCRIPTION === 'true' ? true : false,
|
||||
OCO_EMOJI: process.env.OCO_EMOJI === 'true' ? true : false,
|
||||
OCO_MODEL: process.env.OCO_MODEL,
|
||||
OCO_LANGUAGE: process.env.OCO_LANGUAGE
|
||||
OCO_MODEL: process.env.OCO_MODEL || 'gpt-3.5-turbo-16k',
|
||||
OCO_LANGUAGE: process.env.OCO_LANGUAGE || 'en',
|
||||
OCO_MESSAGE_TEMPLATE_PLACEHOLDER:
|
||||
process.env.OCO_MESSAGE_TEMPLATE_PLACEHOLDER || '$msg'
|
||||
};
|
||||
|
||||
const configExists = existsSync(configPath);
|
||||
@@ -149,6 +169,13 @@ export const getConfig = (): ConfigType | null => {
|
||||
const config = iniParse(configFile);
|
||||
|
||||
for (const configKey of Object.keys(config)) {
|
||||
if (
|
||||
!config[configKey] ||
|
||||
['null', 'undefined'].includes(config[configKey])
|
||||
) {
|
||||
config[configKey] = undefined;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const validator = configValidators[configKey as CONFIG_KEYS];
|
||||
const validValue = validator(
|
||||
|
||||
@@ -24,7 +24,7 @@ export const prepareCommitMessageHook = async (
|
||||
|
||||
if (changedFiles) await gitAdd({ files: changedFiles });
|
||||
else {
|
||||
outro('No changes detected, write some code and run `oc` again');
|
||||
outro('No changes detected, write some code and run `oco` again');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
ChatCompletionRequestMessageRoleEnum
|
||||
} from 'openai';
|
||||
import { api } from './api';
|
||||
import { getConfig } from './commands/config';
|
||||
import { DEFAULT_MODEL_TOKEN_LIMIT, getConfig } from './commands/config';
|
||||
import { mergeDiffs } from './utils/mergeDiffs';
|
||||
import { i18n, I18nLocals } from './i18n';
|
||||
import { tokenCount } from './utils/tokenCount';
|
||||
@@ -16,8 +16,8 @@ const INIT_MESSAGES_PROMPT: Array<ChatCompletionRequestMessage> = [
|
||||
role: ChatCompletionRequestMessageRoleEnum.System,
|
||||
// prettier-ignore
|
||||
content: `You are to act as the author of a commit message in git. Your mission is to create clean and comprehensive commit messages in the conventional commit convention and explain WHAT were the changes and WHY the changes were done. I'll send you an output of 'git diff --staged' command, and you convert it into a commit message.
|
||||
${config?.OCO_EMOJI ? 'Use GitMoji convention to preface the commit.': 'Do not preface the commit with anything.'}
|
||||
${config?.OCO_DESCRIPTION ? 'Add a short description of WHY the changes are done after the commit message. Don\'t start it with "This commit", just describe the changes.': "Don't add any descriptions to the commit, only commit message."}
|
||||
${config?.OCO_EMOJI ? 'Use GitMoji convention to preface the commit.' : 'Do not preface the commit with anything.'}
|
||||
${config?.OCO_DESCRIPTION ? 'Add a short description of WHY the changes are done after the commit message. Don\'t start it with "This commit", just describe the changes.' : "Don't add any descriptions to the commit, only commit message."}
|
||||
Use the present tense. Lines must not be longer than 74 characters. Use ${translation.localLanguage} to answer.`
|
||||
},
|
||||
{
|
||||
@@ -74,27 +74,33 @@ export enum GenerateCommitMessageErrorEnum {
|
||||
emptyMessage = 'EMPTY_MESSAGE'
|
||||
}
|
||||
|
||||
interface GenerateCommitMessageError {
|
||||
error: GenerateCommitMessageErrorEnum;
|
||||
}
|
||||
|
||||
const INIT_MESSAGES_PROMPT_LENGTH = INIT_MESSAGES_PROMPT.map(
|
||||
(msg) => tokenCount(msg.content) + 4
|
||||
).reduce((a, b) => a + b, 0);
|
||||
|
||||
const MAX_REQ_TOKENS = 3000 - INIT_MESSAGES_PROMPT_LENGTH;
|
||||
const ADJUSTMENT_FACTOR = 20;
|
||||
|
||||
export const generateCommitMessageByDiff = async (
|
||||
diff: string
|
||||
): Promise<string> => {
|
||||
try {
|
||||
if (tokenCount(diff) >= MAX_REQ_TOKENS) {
|
||||
const MAX_REQUEST_TOKENS =
|
||||
DEFAULT_MODEL_TOKEN_LIMIT -
|
||||
ADJUSTMENT_FACTOR -
|
||||
INIT_MESSAGES_PROMPT_LENGTH -
|
||||
config?.OCO_OPENAI_MAX_TOKENS;
|
||||
|
||||
if (tokenCount(diff) >= MAX_REQUEST_TOKENS) {
|
||||
const commitMessagePromises = getCommitMsgsPromisesFromFileDiffs(
|
||||
diff,
|
||||
MAX_REQ_TOKENS
|
||||
MAX_REQUEST_TOKENS
|
||||
);
|
||||
|
||||
const commitMessages = await Promise.all(commitMessagePromises);
|
||||
const commitMessages = [];
|
||||
for (const promise of commitMessagePromises) {
|
||||
commitMessages.push(await promise);
|
||||
await delay(2000);
|
||||
}
|
||||
|
||||
return commitMessages.join('\n\n');
|
||||
} else {
|
||||
@@ -126,9 +132,17 @@ function getMessagesPromisesByChangesInFile(
|
||||
maxChangeLength
|
||||
);
|
||||
|
||||
const lineDiffsWithHeader = mergedChanges.map(
|
||||
(change) => fileHeader + change
|
||||
);
|
||||
const lineDiffsWithHeader = [];
|
||||
for (const change of mergedChanges) {
|
||||
const totalChange = fileHeader + change;
|
||||
if (tokenCount(totalChange) > maxChangeLength) {
|
||||
// If the totalChange is too large, split it into smaller pieces
|
||||
const splitChanges = splitDiff(totalChange, maxChangeLength);
|
||||
lineDiffsWithHeader.push(...splitChanges);
|
||||
} else {
|
||||
lineDiffsWithHeader.push(totalChange);
|
||||
}
|
||||
}
|
||||
|
||||
const commitMsgsFromFileLineDiffs = lineDiffsWithHeader.map((lineDiff) => {
|
||||
const messages = generateCommitMessageChatCompletionPrompt(
|
||||
@@ -141,6 +155,38 @@ function getMessagesPromisesByChangesInFile(
|
||||
return commitMsgsFromFileLineDiffs;
|
||||
}
|
||||
|
||||
function splitDiff(diff: string, maxChangeLength: number) {
|
||||
const lines = diff.split('\n');
|
||||
const splitDiffs = [];
|
||||
let currentDiff = '';
|
||||
|
||||
for (let line of lines) {
|
||||
// If a single line exceeds maxChangeLength, split it into multiple lines
|
||||
while (tokenCount(line) > maxChangeLength) {
|
||||
const subLine = line.substring(0, maxChangeLength);
|
||||
line = line.substring(maxChangeLength);
|
||||
splitDiffs.push(subLine);
|
||||
}
|
||||
|
||||
// Check the tokenCount of the currentDiff and the line separately
|
||||
if (tokenCount(currentDiff) + tokenCount('\n' + line) > maxChangeLength) {
|
||||
// If adding the next line would exceed the maxChangeLength, start a new diff
|
||||
splitDiffs.push(currentDiff);
|
||||
currentDiff = line;
|
||||
} else {
|
||||
// Otherwise, add the line to the current diff
|
||||
currentDiff += '\n' + line;
|
||||
}
|
||||
}
|
||||
|
||||
// Add the last diff
|
||||
if (currentDiff) {
|
||||
splitDiffs.push(currentDiff);
|
||||
}
|
||||
|
||||
return splitDiffs;
|
||||
}
|
||||
|
||||
export function getCommitMsgsPromisesFromFileDiffs(
|
||||
diff: string,
|
||||
maxDiffLength: number
|
||||
@@ -172,5 +218,10 @@ export function getCommitMsgsPromisesFromFileDiffs(
|
||||
commitMessagePromises.push(api.generateCommitMessage(messages));
|
||||
}
|
||||
}
|
||||
|
||||
return commitMessagePromises;
|
||||
}
|
||||
|
||||
function delay(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export enum I18nLocals {
|
||||
'id_ID' = 'id_ID',
|
||||
'pl' = 'pl',
|
||||
'tr' = 'tr',
|
||||
'th' = 'th',
|
||||
'th' = 'th'
|
||||
}
|
||||
|
||||
export const i18n = {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { getOpenCommitLatestVersion } from '../api';
|
||||
import currentPackage from '../../package.json' assert { type: 'json' };
|
||||
import chalk from 'chalk';
|
||||
import { outro } from '@clack/prompts';
|
||||
|
||||
export const checkIsLatestVersion = async () => {
|
||||
const latestVersion = await getOpenCommitLatestVersion();
|
||||
@@ -9,7 +10,7 @@ export const checkIsLatestVersion = async () => {
|
||||
const currentVersion = currentPackage.version;
|
||||
|
||||
if (currentVersion !== latestVersion) {
|
||||
console.warn(
|
||||
outro(
|
||||
chalk.yellow(
|
||||
`
|
||||
You are not using the latest stable version of OpenCommit with new features and bug fixes.
|
||||
|
||||
@@ -25,13 +25,11 @@ export const getOpenCommitIgnore = (): Ignore => {
|
||||
return ig;
|
||||
};
|
||||
|
||||
export const getCoreHooksPath = async(): Promise<string> => {
|
||||
const { stdout } = await execa('git', [
|
||||
'config',
|
||||
'core.hooksPath']);
|
||||
export const getCoreHooksPath = async (): Promise<string> => {
|
||||
const { stdout } = await execa('git', ['config', 'core.hooksPath']);
|
||||
|
||||
return stdout;
|
||||
}
|
||||
};
|
||||
|
||||
export const getStagedFiles = async (): Promise<string[]> => {
|
||||
const { stdout: gitDir } = await execa('git', [
|
||||
@@ -83,12 +81,20 @@ export const gitAdd = async ({ files }: { files: string[] }) => {
|
||||
|
||||
export const getDiff = async ({ files }: { files: string[] }) => {
|
||||
const lockFiles = files.filter(
|
||||
(file) => file.includes('.lock') || file.includes('-lock.')
|
||||
(file) =>
|
||||
file.includes('.lock') ||
|
||||
file.includes('-lock.') ||
|
||||
file.includes('.svg') ||
|
||||
file.includes('.png') ||
|
||||
file.includes('.jpg') ||
|
||||
file.includes('.jpeg') ||
|
||||
file.includes('.webp') ||
|
||||
file.includes('.gif')
|
||||
);
|
||||
|
||||
if (lockFiles.length) {
|
||||
outro(
|
||||
`Some files are '.lock' files which are excluded by default from 'git diff'. No commit messages are generated for this files:\n${lockFiles.join(
|
||||
`Some files are excluded by default from 'git diff'. No commit messages are generated for this files:\n${lockFiles.join(
|
||||
'\n'
|
||||
)}`
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user