mirror of
https://github.com/di-sukharev/opencommit.git
synced 2026-01-13 07:38:01 -05:00
Compare commits
12 Commits
v3.2.8
...
refactorin
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88d6a92567 | ||
|
|
36aab60393 | ||
|
|
ba3c0b7e0b | ||
|
|
5209610236 | ||
|
|
d1f03f1105 | ||
|
|
3df5b241dc | ||
|
|
5ddf2cb21a | ||
|
|
c6b6b2f3fd | ||
|
|
e1ce774538 | ||
|
|
f1ea54cf1c | ||
|
|
ccb7cd99e5 | ||
|
|
ce6ae0b514 |
4
.github/CONTRIBUTING.md
vendored
4
.github/CONTRIBUTING.md
vendored
@@ -18,7 +18,7 @@ To get started, follow these steps:
|
||||
1. Clone the project repository locally.
|
||||
2. Install dependencies with `npm install`.
|
||||
3. Run the project with `npm run dev`.
|
||||
4. See [issues](https://github.com/di-sukharev/opencommit/issues) or [TODO.md](TODO.md) to help the project.
|
||||
4. See [issues](https://github.com/di-sukharev/open-commit/issues) or [TODO.md](../TODO.md) to help the project.
|
||||
|
||||
## Commit message guidelines
|
||||
|
||||
@@ -30,7 +30,7 @@ If you encounter any issues while using the project, please report them on the G
|
||||
|
||||
## Contacts
|
||||
|
||||
If you have any questions about contributing to the project, please contact by [creating an issue](https://github.com/di-sukharev/opencommit/issues) on the GitHub issue tracker.
|
||||
If you have any questions about contributing to the project, please contact by [creating an issue](https://github.com/di-sukharev/open-commit/issues) on the GitHub issue tracker.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
8
.github/workflows/codeql.yml
vendored
8
.github/workflows/codeql.yml
vendored
@@ -40,11 +40,11 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
uses: github/codeql-action/init@v2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v3
|
||||
uses: github/codeql-action/autobuild@v2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
@@ -71,6 +71,6 @@ jobs:
|
||||
# ./location_of_script_within_repo/buildscript.sh
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
uses: github/codeql-action/analyze@v2
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
|
||||
4
.github/workflows/dependency-review.yml
vendored
4
.github/workflows/dependency-review.yml
vendored
@@ -15,6 +15,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 'Checkout Repository'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v3
|
||||
- name: 'Dependency Review'
|
||||
uses: actions/dependency-review-action@v3
|
||||
uses: actions/dependency-review-action@v2
|
||||
|
||||
17
.github/workflows/test.yml
vendored
17
.github/workflows/test.yml
vendored
@@ -1,11 +1,6 @@
|
||||
name: Testing
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- main
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
unit-test:
|
||||
@@ -14,12 +9,11 @@ jobs:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v2
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
- name: Run Unit Tests
|
||||
@@ -30,12 +24,11 @@ jobs:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v2
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
- name: Install git
|
||||
run: |
|
||||
sudo apt-get update
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -11,5 +11,4 @@ uncaughtExceptions.log
|
||||
src/*.json
|
||||
.idea
|
||||
test.ts
|
||||
notes.md
|
||||
.nvmrc
|
||||
notes.md
|
||||
17
README.md
17
README.md
@@ -106,15 +106,14 @@ Create a `.env` file and add OpenCommit config variables there like this:
|
||||
|
||||
```env
|
||||
...
|
||||
OCO_AI_PROVIDER=<openai (default), anthropic, azure, ollama, gemini, flowise, deepseek>
|
||||
OCO_AI_PROVIDER=<openai (default), anthropic, azure, ollama, gemini, flowise>
|
||||
OCO_API_KEY=<your OpenAI API token> // or other LLM provider API token
|
||||
OCO_API_URL=<may be used to set proxy path to OpenAI api>
|
||||
OCO_API_CUSTOM_HEADERS=<JSON string of custom HTTP headers to include in API requests>
|
||||
OCO_TOKENS_MAX_INPUT=<max model token limit (default: 4096)>
|
||||
OCO_TOKENS_MAX_OUTPUT=<max response tokens (default: 500)>
|
||||
OCO_DESCRIPTION=<postface a message with ~3 sentences description of the changes>
|
||||
OCO_EMOJI=<boolean, add GitMoji>
|
||||
OCO_MODEL=<either 'gpt-4o-mini' (default), 'gpt-4o', 'gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0125', 'gpt-4-1106-preview', 'gpt-4-turbo-preview' or 'gpt-4-0125-preview' or any Anthropic or Ollama model or any string basically, but it should be a valid model name>
|
||||
OCO_MODEL=<either 'gpt-4o', 'gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo' (default), 'gpt-3.5-turbo-0125', 'gpt-4-1106-preview', 'gpt-4-turbo-preview' or 'gpt-4-0125-preview' or any Anthropic or Ollama model or any string basically, but it should be a valid model name>
|
||||
OCO_LANGUAGE=<locale, scroll to the bottom to see options>
|
||||
OCO_MESSAGE_TEMPLATE_PLACEHOLDER=<message template placeholder, default: '$msg'>
|
||||
OCO_PROMPT_MODULE=<either conventional-commit or @commitlint, default: conventional-commit>
|
||||
@@ -133,18 +132,6 @@ Simply set any of the variables above like this:
|
||||
oco config set OCO_MODEL=gpt-4o-mini
|
||||
```
|
||||
|
||||
To see all available configuration parameters and their accepted values:
|
||||
|
||||
```sh
|
||||
oco config describe
|
||||
```
|
||||
|
||||
To see details for a specific parameter:
|
||||
|
||||
```sh
|
||||
oco config describe OCO_MODEL
|
||||
```
|
||||
|
||||
Configure [GitMoji](https://gitmoji.dev/) to preface a message.
|
||||
|
||||
```sh
|
||||
|
||||
@@ -9,33 +9,19 @@ const config: Config = {
|
||||
testTimeout: 100_000,
|
||||
coverageProvider: 'v8',
|
||||
moduleDirectories: ['node_modules', 'src'],
|
||||
preset: 'ts-jest/presets/default-esm',
|
||||
preset: 'ts-jest/presets/js-with-ts-esm',
|
||||
setupFilesAfterEnv: ['<rootDir>/test/jest-setup.ts'],
|
||||
testEnvironment: 'node',
|
||||
testRegex: ['.*\\.test\\.ts$'],
|
||||
// Tell Jest to ignore the specific duplicate package.json files
|
||||
// that are causing Haste module naming collisions
|
||||
modulePathIgnorePatterns: [
|
||||
'<rootDir>/test/e2e/prompt-module/data/'
|
||||
],
|
||||
transformIgnorePatterns: [
|
||||
'node_modules/(?!(cli-testing-library|@clack|cleye)/.*)'
|
||||
],
|
||||
transformIgnorePatterns: ['node_modules/(?!cli-testing-library)'],
|
||||
transform: {
|
||||
'^.+\\.(ts|tsx|js|jsx|mjs)$': [
|
||||
'^.+\\.(ts|tsx)$': [
|
||||
'ts-jest',
|
||||
{
|
||||
diagnostics: false,
|
||||
useESM: true,
|
||||
tsconfig: {
|
||||
module: 'ESNext',
|
||||
target: 'ES2022'
|
||||
}
|
||||
useESM: true
|
||||
}
|
||||
]
|
||||
},
|
||||
moduleNameMapper: {
|
||||
'^(\\.{1,2}/.*)\\.js$': '$1'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
28396
out/cli.cjs
28396
out/cli.cjs
File diff suppressed because one or more lines are too long
37875
out/github-action.cjs
37875
out/github-action.cjs
File diff suppressed because one or more lines are too long
4867
package-lock.json
generated
4867
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
38
package.json
38
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "opencommit",
|
||||
"version": "3.2.8",
|
||||
"version": "3.1.2",
|
||||
"description": "Auto-generate impressive commits in 1 second. Killing lame commits with AI 🤯🔫",
|
||||
"keywords": [
|
||||
"git",
|
||||
@@ -17,11 +17,11 @@
|
||||
],
|
||||
"main": "cli.js",
|
||||
"bin": {
|
||||
"opencommit": "out/cli.cjs",
|
||||
"oco": "out/cli.cjs"
|
||||
"opencommit": "./out/cli.cjs",
|
||||
"oco": "./out/cli.cjs"
|
||||
},
|
||||
"repository": {
|
||||
"url": "git+https://github.com/di-sukharev/opencommit.git"
|
||||
"url": "https://github.com/di-sukharev/opencommit"
|
||||
},
|
||||
"type": "module",
|
||||
"author": "https://github.com/di-sukharev",
|
||||
@@ -44,11 +44,10 @@
|
||||
"ollama:start": "OCO_AI_PROVIDER='ollama' node ./out/cli.cjs",
|
||||
"dev": "ts-node ./src/cli.ts",
|
||||
"dev:gemini": "OCO_AI_PROVIDER='gemini' ts-node ./src/cli.ts",
|
||||
"build": "npx rimraf out && node esbuild.config.js",
|
||||
"build": "rimraf out && node esbuild.config.js",
|
||||
"build:push": "npm run build && git add . && git commit -m 'build' && git push",
|
||||
"deploy": "npm publish --tag latest",
|
||||
"deploy:build": "npm run build:push && git push --tags && npm run deploy",
|
||||
"deploy:patch": "npm version patch && npm run deploy:build",
|
||||
"deploy": "npm run build:push && git push --tags && npm publish --tag latest",
|
||||
"deploy:patch": "npm version patch && npm run deploy",
|
||||
"lint": "eslint src --ext ts && tsc --noEmit",
|
||||
"format": "prettier --write src",
|
||||
"test": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest ) test/unit",
|
||||
@@ -58,8 +57,7 @@
|
||||
"test:unit:docker": "npm run test:docker-build && DOCKER_CONTENT_TRUST=0 docker run --rm oco-test npm run test:unit",
|
||||
"test:e2e": "npm run test:e2e:setup && jest test/e2e",
|
||||
"test:e2e:setup": "sh test/e2e/setup.sh",
|
||||
"test:e2e:docker": "npm run test:docker-build && DOCKER_CONTENT_TRUST=0 docker run --rm oco-test npm run test:e2e",
|
||||
"mlx:start": "OCO_AI_PROVIDER='mlx' node ./out/cli.cjs"
|
||||
"test:e2e:docker": "npm run test:docker-build && DOCKER_CONTENT_TRUST=0 docker run --rm oco-test npm run test:e2e"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/types": "^17.4.4",
|
||||
@@ -67,15 +65,14 @@
|
||||
"@types/inquirer": "^9.0.3",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/node": "^16.18.14",
|
||||
"@typescript-eslint/eslint-plugin": "^8.29.0",
|
||||
"@typescript-eslint/parser": "^8.29.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.45.0",
|
||||
"@typescript-eslint/parser": "^5.45.0",
|
||||
"cli-testing-library": "^2.0.2",
|
||||
"dotenv": "^16.0.3",
|
||||
"esbuild": "^0.25.5",
|
||||
"eslint": "^9.24.0",
|
||||
"esbuild": "^0.15.18",
|
||||
"eslint": "^8.28.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^2.8.4",
|
||||
"rimraf": "^6.0.1",
|
||||
"ts-jest": "^29.1.2",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^4.9.3"
|
||||
@@ -83,13 +80,12 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.0",
|
||||
"@actions/exec": "^1.1.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@actions/github": "^5.1.1",
|
||||
"@anthropic-ai/sdk": "^0.19.2",
|
||||
"@azure/openai": "^1.0.0-beta.12",
|
||||
"@clack/prompts": "^0.6.1",
|
||||
"@dqbd/tiktoken": "^1.0.2",
|
||||
"@google/generative-ai": "^0.11.4",
|
||||
"@mistralai/mistralai": "^1.3.5",
|
||||
"@octokit/webhooks-schemas": "^6.11.0",
|
||||
"@octokit/webhooks-types": "^6.11.0",
|
||||
"axios": "^1.3.4",
|
||||
@@ -100,12 +96,6 @@
|
||||
"ignore": "^5.2.4",
|
||||
"ini": "^3.0.1",
|
||||
"inquirer": "^9.1.4",
|
||||
"openai": "^4.57.0",
|
||||
"punycode": "^2.3.1",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"overrides": {
|
||||
"ajv": "^8.17.1",
|
||||
"whatwg-url": "^14.0.0"
|
||||
"openai": "^4.57.0"
|
||||
}
|
||||
}
|
||||
|
||||
14
src/cli.ts
14
src/cli.ts
@@ -19,17 +19,7 @@ cli(
|
||||
name: 'opencommit',
|
||||
commands: [configCommand, hookCommand, commitlintConfigCommand],
|
||||
flags: {
|
||||
fgm: {
|
||||
type: Boolean,
|
||||
description: 'Use full GitMoji specification',
|
||||
default: false
|
||||
},
|
||||
context: {
|
||||
type: String,
|
||||
alias: 'c',
|
||||
description: 'Additional user input context for the commit message',
|
||||
default: ''
|
||||
},
|
||||
fgm: Boolean,
|
||||
yes: {
|
||||
type: Boolean,
|
||||
alias: 'y',
|
||||
@@ -47,7 +37,7 @@ cli(
|
||||
if (await isHookCalled()) {
|
||||
prepareCommitMessageHook();
|
||||
} else {
|
||||
commit(extraArgs, flags.context, false, flags.fgm, flags.yes);
|
||||
commit(extraArgs, false, flags.fgm, flags.yes);
|
||||
}
|
||||
},
|
||||
extraArgs
|
||||
|
||||
@@ -39,7 +39,6 @@ const checkMessageTemplate = (extraArgs: string[]): string | false => {
|
||||
interface GenerateCommitMessageFromGitDiffParams {
|
||||
diff: string;
|
||||
extraArgs: string[];
|
||||
context?: string;
|
||||
fullGitMojiSpec?: boolean;
|
||||
skipCommitConfirmation?: boolean;
|
||||
}
|
||||
@@ -47,7 +46,6 @@ interface GenerateCommitMessageFromGitDiffParams {
|
||||
const generateCommitMessageFromGitDiff = async ({
|
||||
diff,
|
||||
extraArgs,
|
||||
context = '',
|
||||
fullGitMojiSpec = false,
|
||||
skipCommitConfirmation = false
|
||||
}: GenerateCommitMessageFromGitDiffParams): Promise<void> => {
|
||||
@@ -58,8 +56,7 @@ const generateCommitMessageFromGitDiff = async ({
|
||||
try {
|
||||
let commitMessage = await generateCommitMessageByDiff(
|
||||
diff,
|
||||
fullGitMojiSpec,
|
||||
context
|
||||
fullGitMojiSpec
|
||||
);
|
||||
|
||||
const messageTemplate = checkMessageTemplate(extraArgs);
|
||||
@@ -149,32 +146,26 @@ ${chalk.grey('——————————————————')}`
|
||||
process.exit(0);
|
||||
}
|
||||
} else {
|
||||
const skipOption = `don't push`;
|
||||
const selectedRemote = (await select({
|
||||
message: 'Choose a remote to push to',
|
||||
options: [...remotes, skipOption].map((remote) => ({
|
||||
value: remote,
|
||||
label: remote
|
||||
}))
|
||||
options: remotes.map((remote) => ({ value: remote, label: remote }))
|
||||
})) as string;
|
||||
|
||||
if (isCancel(selectedRemote)) process.exit(1);
|
||||
|
||||
if (selectedRemote !== skipOption) {
|
||||
const pushSpinner = spinner();
|
||||
const pushSpinner = spinner();
|
||||
|
||||
pushSpinner.start(`Running 'git push ${selectedRemote}'`);
|
||||
pushSpinner.start(`Running 'git push ${selectedRemote}'`);
|
||||
|
||||
const { stdout } = await execa('git', ['push', selectedRemote]);
|
||||
const { stdout } = await execa('git', ['push', selectedRemote]);
|
||||
|
||||
if (stdout) outro(stdout);
|
||||
if (stdout) outro(stdout);
|
||||
|
||||
pushSpinner.stop(
|
||||
`${chalk.green(
|
||||
'✔'
|
||||
)} successfully pushed all commits to ${selectedRemote}`
|
||||
);
|
||||
}
|
||||
pushSpinner.stop(
|
||||
`${chalk.green(
|
||||
'✔'
|
||||
)} successfully pushed all commits to ${selectedRemote}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const regenerateMessage = await confirm({
|
||||
@@ -192,11 +183,7 @@ ${chalk.grey('——————————————————')}`
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
commitGenerationSpinner.stop(
|
||||
`${chalk.red('✖')} Failed to generate the commit message`
|
||||
);
|
||||
|
||||
console.log(error);
|
||||
commitGenerationSpinner.stop('📝 Commit message generated');
|
||||
|
||||
const err = error as Error;
|
||||
outro(`${chalk.red('✖')} ${err?.message || err}`);
|
||||
@@ -206,7 +193,6 @@ ${chalk.grey('——————————————————')}`
|
||||
|
||||
export async function commit(
|
||||
extraArgs: string[] = [],
|
||||
context: string = '',
|
||||
isStageAllFlag: Boolean = false,
|
||||
fullGitMojiSpec: boolean = false,
|
||||
skipCommitConfirmation: boolean = false
|
||||
@@ -239,9 +225,8 @@ export async function commit(
|
||||
|
||||
stagedFilesSpinner.start('Counting staged files');
|
||||
|
||||
if (stagedFiles.length === 0) {
|
||||
if (!stagedFiles.length) {
|
||||
stagedFilesSpinner.stop('No files are staged');
|
||||
|
||||
const isStageAllAndCommitConfirmedByUser = await confirm({
|
||||
message: 'Do you want to stage all files and generate commit message?'
|
||||
});
|
||||
@@ -249,8 +234,8 @@ export async function commit(
|
||||
if (isCancel(isStageAllAndCommitConfirmedByUser)) process.exit(1);
|
||||
|
||||
if (isStageAllAndCommitConfirmedByUser) {
|
||||
await commit(extraArgs, context, true, fullGitMojiSpec);
|
||||
process.exit(0);
|
||||
await commit(extraArgs, true, fullGitMojiSpec);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (stagedFiles.length === 0 && changedFiles.length > 0) {
|
||||
@@ -262,13 +247,13 @@ export async function commit(
|
||||
}))
|
||||
})) as string[];
|
||||
|
||||
if (isCancel(files)) process.exit(0);
|
||||
if (isCancel(files)) process.exit(1);
|
||||
|
||||
await gitAdd({ files });
|
||||
}
|
||||
|
||||
await commit(extraArgs, context, false, fullGitMojiSpec);
|
||||
process.exit(0);
|
||||
await commit(extraArgs, false, fullGitMojiSpec);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
stagedFilesSpinner.stop(
|
||||
@@ -281,7 +266,6 @@ export async function commit(
|
||||
generateCommitMessageFromGitDiff({
|
||||
diff: await getDiff({ files: stagedFiles }),
|
||||
extraArgs,
|
||||
context,
|
||||
fullGitMojiSpec,
|
||||
skipCommitConfirmation
|
||||
})
|
||||
|
||||
@@ -25,15 +25,12 @@ export enum CONFIG_KEYS {
|
||||
OCO_ONE_LINE_COMMIT = 'OCO_ONE_LINE_COMMIT',
|
||||
OCO_TEST_MOCK_TYPE = 'OCO_TEST_MOCK_TYPE',
|
||||
OCO_API_URL = 'OCO_API_URL',
|
||||
OCO_API_CUSTOM_HEADERS = 'OCO_API_CUSTOM_HEADERS',
|
||||
OCO_OMIT_SCOPE = 'OCO_OMIT_SCOPE',
|
||||
OCO_GITPUSH = 'OCO_GITPUSH' // todo: deprecate
|
||||
}
|
||||
|
||||
export enum CONFIG_MODES {
|
||||
get = 'get',
|
||||
set = 'set',
|
||||
describe = 'describe'
|
||||
set = 'set'
|
||||
}
|
||||
|
||||
export const MODEL_LIST = {
|
||||
@@ -79,86 +76,25 @@ export const MODEL_LIST = {
|
||||
'gemini-1.0-pro',
|
||||
'gemini-pro-vision',
|
||||
'text-embedding-004'
|
||||
],
|
||||
|
||||
groq: [
|
||||
'llama3-70b-8192', // Meta Llama 3 70B (default one, no daily token limit and 14 400 reqs/day)
|
||||
'llama3-8b-8192', // Meta Llama 3 8B
|
||||
'llama-guard-3-8b', // Llama Guard 3 8B
|
||||
'llama-3.1-8b-instant', // Llama 3.1 8B (Preview)
|
||||
'llama-3.1-70b-versatile', // Llama 3.1 70B (Preview)
|
||||
'gemma-7b-it', // Gemma 7B
|
||||
'gemma2-9b-it' // Gemma 2 9B
|
||||
],
|
||||
|
||||
mistral: [
|
||||
'ministral-3b-2410',
|
||||
'ministral-3b-latest',
|
||||
'ministral-8b-2410',
|
||||
'ministral-8b-latest',
|
||||
'open-mistral-7b',
|
||||
'mistral-tiny',
|
||||
'mistral-tiny-2312',
|
||||
'open-mistral-nemo',
|
||||
'open-mistral-nemo-2407',
|
||||
'mistral-tiny-2407',
|
||||
'mistral-tiny-latest',
|
||||
'open-mixtral-8x7b',
|
||||
'mistral-small',
|
||||
'mistral-small-2312',
|
||||
'open-mixtral-8x22b',
|
||||
'open-mixtral-8x22b-2404',
|
||||
'mistral-small-2402',
|
||||
'mistral-small-2409',
|
||||
'mistral-small-latest',
|
||||
'mistral-medium-2312',
|
||||
'mistral-medium',
|
||||
'mistral-medium-latest',
|
||||
'mistral-large-2402',
|
||||
'mistral-large-2407',
|
||||
'mistral-large-2411',
|
||||
'mistral-large-latest',
|
||||
'pixtral-large-2411',
|
||||
'pixtral-large-latest',
|
||||
'codestral-2405',
|
||||
'codestral-latest',
|
||||
'codestral-mamba-2407',
|
||||
'open-codestral-mamba',
|
||||
'codestral-mamba-latest',
|
||||
'pixtral-12b-2409',
|
||||
'pixtral-12b',
|
||||
'pixtral-12b-latest',
|
||||
'mistral-embed',
|
||||
'mistral-moderation-2411',
|
||||
'mistral-moderation-latest'
|
||||
],
|
||||
deepseek: ['deepseek-chat', 'deepseek-reasoner']
|
||||
]
|
||||
};
|
||||
|
||||
const getDefaultModel = (provider: string | undefined): string => {
|
||||
switch (provider) {
|
||||
case 'ollama':
|
||||
return '';
|
||||
case 'mlx':
|
||||
return '';
|
||||
case 'anthropic':
|
||||
return MODEL_LIST.anthropic[0];
|
||||
case 'gemini':
|
||||
return MODEL_LIST.gemini[0];
|
||||
case 'groq':
|
||||
return MODEL_LIST.groq[0];
|
||||
case 'mistral':
|
||||
return MODEL_LIST.mistral[0];
|
||||
case 'deepseek':
|
||||
return MODEL_LIST.deepseek[0];
|
||||
default:
|
||||
return MODEL_LIST.openai[0];
|
||||
}
|
||||
};
|
||||
|
||||
export enum DEFAULT_TOKEN_LIMITS {
|
||||
DEFAULT_MAX_TOKENS_INPUT = 4096,
|
||||
DEFAULT_MAX_TOKENS_OUTPUT = 500
|
||||
DEFAULT_MAX_TOKENS_INPUT = 40960,
|
||||
DEFAULT_MAX_TOKENS_OUTPUT = 4096
|
||||
}
|
||||
|
||||
const validateConfig = (
|
||||
@@ -190,7 +126,7 @@ export const configValidators = {
|
||||
validateConfig(
|
||||
'OCO_API_KEY',
|
||||
value,
|
||||
'You need to provide the OCO_API_KEY when OCO_AI_PROVIDER set to "openai" (default) or "ollama" or "mlx" or "azure" or "gemini" or "flowise" or "anthropic" or "deepseek". Run `oco config set OCO_API_KEY=your_key OCO_AI_PROVIDER=openai`'
|
||||
'You need to provide the OCO_API_KEY when OCO_AI_PROVIDER set to "openai" (default) or "ollama" or "azure" or "gemini" or "flowise" or "anthropic". Run `oco config set OCO_API_KEY=your_key OCO_AI_PROVIDER=openai`'
|
||||
);
|
||||
|
||||
return value;
|
||||
@@ -206,22 +142,6 @@ export const configValidators = {
|
||||
return value;
|
||||
},
|
||||
|
||||
[CONFIG_KEYS.OCO_API_CUSTOM_HEADERS](value) {
|
||||
try {
|
||||
// Custom headers must be a valid JSON string
|
||||
if (typeof value === 'string') {
|
||||
JSON.parse(value);
|
||||
}
|
||||
return value;
|
||||
} catch (error) {
|
||||
validateConfig(
|
||||
CONFIG_KEYS.OCO_API_CUSTOM_HEADERS,
|
||||
false,
|
||||
'Must be a valid JSON string of headers'
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
[CONFIG_KEYS.OCO_TOKENS_MAX_INPUT](value: any) {
|
||||
value = parseInt(value);
|
||||
validateConfig(
|
||||
@@ -254,16 +174,6 @@ export const configValidators = {
|
||||
return value;
|
||||
},
|
||||
|
||||
[CONFIG_KEYS.OCO_OMIT_SCOPE](value: any) {
|
||||
validateConfig(
|
||||
CONFIG_KEYS.OCO_OMIT_SCOPE,
|
||||
typeof value === 'boolean',
|
||||
'Must be boolean: true or false'
|
||||
);
|
||||
|
||||
return value;
|
||||
},
|
||||
|
||||
[CONFIG_KEYS.OCO_LANGUAGE](value: any) {
|
||||
const supportedLanguages = Object.keys(i18n);
|
||||
|
||||
@@ -331,18 +241,10 @@ export const configValidators = {
|
||||
|
||||
validateConfig(
|
||||
CONFIG_KEYS.OCO_AI_PROVIDER,
|
||||
[
|
||||
'openai',
|
||||
'mistral',
|
||||
'anthropic',
|
||||
'gemini',
|
||||
'azure',
|
||||
'test',
|
||||
'flowise',
|
||||
'groq',
|
||||
'deepseek'
|
||||
].includes(value) || value.startsWith('ollama'),
|
||||
`${value} is not supported yet, use 'ollama', 'mlx', 'anthropic', 'azure', 'gemini', 'flowise', 'mistral', 'deepseek' or 'openai' (default)`
|
||||
['openai', 'anthropic', 'gemini', 'azure', 'test', 'flowise'].includes(
|
||||
value
|
||||
) || value.startsWith('ollama'),
|
||||
`${value} is not supported yet, use 'ollama', 'anthropic', 'azure', 'gemini', 'flowise' or 'openai' (default)`
|
||||
);
|
||||
|
||||
return value;
|
||||
@@ -386,11 +288,7 @@ export enum OCO_AI_PROVIDER_ENUM {
|
||||
GEMINI = 'gemini',
|
||||
AZURE = 'azure',
|
||||
TEST = 'test',
|
||||
FLOWISE = 'flowise',
|
||||
GROQ = 'groq',
|
||||
MISTRAL = 'mistral',
|
||||
MLX = 'mlx',
|
||||
DEEPSEEK = 'deepseek'
|
||||
FLOWISE = 'flowise'
|
||||
}
|
||||
|
||||
export type ConfigType = {
|
||||
@@ -398,7 +296,6 @@ export type ConfigType = {
|
||||
[CONFIG_KEYS.OCO_TOKENS_MAX_INPUT]: number;
|
||||
[CONFIG_KEYS.OCO_TOKENS_MAX_OUTPUT]: number;
|
||||
[CONFIG_KEYS.OCO_API_URL]?: string;
|
||||
[CONFIG_KEYS.OCO_API_CUSTOM_HEADERS]?: string;
|
||||
[CONFIG_KEYS.OCO_DESCRIPTION]: boolean;
|
||||
[CONFIG_KEYS.OCO_EMOJI]: boolean;
|
||||
[CONFIG_KEYS.OCO_WHY]: boolean;
|
||||
@@ -409,7 +306,6 @@ export type ConfigType = {
|
||||
[CONFIG_KEYS.OCO_AI_PROVIDER]: OCO_AI_PROVIDER_ENUM;
|
||||
[CONFIG_KEYS.OCO_GITPUSH]: boolean;
|
||||
[CONFIG_KEYS.OCO_ONE_LINE_COMMIT]: boolean;
|
||||
[CONFIG_KEYS.OCO_OMIT_SCOPE]: boolean;
|
||||
[CONFIG_KEYS.OCO_TEST_MOCK_TYPE]: string;
|
||||
};
|
||||
|
||||
@@ -456,8 +352,8 @@ export const DEFAULT_CONFIG = {
|
||||
OCO_AI_PROVIDER: OCO_AI_PROVIDER_ENUM.OPENAI,
|
||||
OCO_ONE_LINE_COMMIT: false,
|
||||
OCO_TEST_MOCK_TYPE: 'commit-message',
|
||||
OCO_FLOWISE_ENDPOINT: ':',
|
||||
OCO_WHY: false,
|
||||
OCO_OMIT_SCOPE: false,
|
||||
OCO_GITPUSH: true // todo: deprecate
|
||||
};
|
||||
|
||||
@@ -481,7 +377,6 @@ const getEnvConfig = (envPath: string) => {
|
||||
OCO_MODEL: process.env.OCO_MODEL,
|
||||
OCO_API_URL: process.env.OCO_API_URL,
|
||||
OCO_API_KEY: process.env.OCO_API_KEY,
|
||||
OCO_API_CUSTOM_HEADERS: process.env.OCO_API_CUSTOM_HEADERS,
|
||||
OCO_AI_PROVIDER: process.env.OCO_AI_PROVIDER as OCO_AI_PROVIDER_ENUM,
|
||||
|
||||
OCO_TOKENS_MAX_INPUT: parseConfigVarValue(process.env.OCO_TOKENS_MAX_INPUT),
|
||||
@@ -497,7 +392,6 @@ const getEnvConfig = (envPath: string) => {
|
||||
OCO_PROMPT_MODULE: process.env.OCO_PROMPT_MODULE as OCO_PROMPT_MODULE_ENUM,
|
||||
OCO_ONE_LINE_COMMIT: parseConfigVarValue(process.env.OCO_ONE_LINE_COMMIT),
|
||||
OCO_TEST_MOCK_TYPE: process.env.OCO_TEST_MOCK_TYPE,
|
||||
OCO_OMIT_SCOPE: parseConfigVarValue(process.env.OCO_OMIT_SCOPE),
|
||||
|
||||
OCO_GITPUSH: parseConfigVarValue(process.env.OCO_GITPUSH) // todo: deprecate
|
||||
};
|
||||
@@ -550,25 +444,6 @@ interface GetConfigOptions {
|
||||
setDefaultValues?: boolean;
|
||||
}
|
||||
|
||||
const cleanUndefinedValues = (config: ConfigType) => {
|
||||
return Object.fromEntries(
|
||||
Object.entries(config).map(([_, v]) => {
|
||||
try {
|
||||
if (typeof v === 'string') {
|
||||
if (v === 'undefined') return [_, undefined];
|
||||
if (v === 'null') return [_, null];
|
||||
|
||||
const parsedValue = JSON.parse(v);
|
||||
return [_, parsedValue];
|
||||
}
|
||||
return [_, v];
|
||||
} catch (error) {
|
||||
return [_, v];
|
||||
}
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
export const getConfig = ({
|
||||
envPath = defaultEnvPath,
|
||||
globalPath = defaultConfigPath
|
||||
@@ -578,9 +453,7 @@ export const getConfig = ({
|
||||
|
||||
const config = mergeConfigs(envConfig, globalConfig);
|
||||
|
||||
const cleanConfig = cleanUndefinedValues(config);
|
||||
|
||||
return cleanConfig as ConfigType;
|
||||
return config;
|
||||
};
|
||||
|
||||
export const setConfig = (
|
||||
@@ -623,208 +496,28 @@ export const setConfig = (
|
||||
outro(`${chalk.green('✔')} config successfully set`);
|
||||
};
|
||||
|
||||
// --- HELP MESSAGE GENERATION ---
|
||||
function getConfigKeyDetails(key) {
|
||||
switch (key) {
|
||||
case CONFIG_KEYS.OCO_MODEL:
|
||||
return {
|
||||
description: 'The AI model to use for generating commit messages',
|
||||
values: MODEL_LIST
|
||||
};
|
||||
case CONFIG_KEYS.OCO_AI_PROVIDER:
|
||||
return {
|
||||
description: 'The AI provider to use',
|
||||
values: Object.values(OCO_AI_PROVIDER_ENUM)
|
||||
};
|
||||
case CONFIG_KEYS.OCO_PROMPT_MODULE:
|
||||
return {
|
||||
description: 'The prompt module to use for commit message generation',
|
||||
values: Object.values(OCO_PROMPT_MODULE_ENUM)
|
||||
};
|
||||
case CONFIG_KEYS.OCO_LANGUAGE:
|
||||
return {
|
||||
description: 'The locale to use for commit messages',
|
||||
values: Object.keys(i18n)
|
||||
};
|
||||
case CONFIG_KEYS.OCO_TEST_MOCK_TYPE:
|
||||
return {
|
||||
description: 'The type of test mock to use',
|
||||
values: ['commit-message', 'prompt-module-commitlint-config']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_ONE_LINE_COMMIT:
|
||||
return {
|
||||
description: 'One line commit message',
|
||||
values: ['true', 'false']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_DESCRIPTION:
|
||||
return {
|
||||
description: 'Postface a message with ~3 sentences description of the changes',
|
||||
values: ['true', 'false']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_EMOJI:
|
||||
return {
|
||||
description: 'Preface a message with GitMoji',
|
||||
values: ['true', 'false']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_WHY:
|
||||
return {
|
||||
description: 'Output a short description of why the changes were done after the commit message (default: false)',
|
||||
values: ['true', 'false']
|
||||
}
|
||||
case CONFIG_KEYS.OCO_OMIT_SCOPE:
|
||||
return {
|
||||
description: 'Do not include a scope in the commit message',
|
||||
values: ['true', 'false']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_GITPUSH:
|
||||
return {
|
||||
description: 'Push to git after commit (deprecated). If false, oco will exit after committing',
|
||||
values: ['true', 'false']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_TOKENS_MAX_INPUT:
|
||||
return {
|
||||
description: 'Max model token limit',
|
||||
values: ['Any positive integer']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_TOKENS_MAX_OUTPUT:
|
||||
return {
|
||||
description: 'Max response tokens',
|
||||
values: ['Any positive integer']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_API_KEY:
|
||||
return {
|
||||
description: 'API key for the selected provider',
|
||||
values: ['String (required for most providers)']
|
||||
};
|
||||
case CONFIG_KEYS.OCO_API_URL:
|
||||
return {
|
||||
description: 'Custom API URL - may be used to set proxy path to OpenAI API',
|
||||
values: ["URL string (must start with 'http://' or 'https://')"]
|
||||
};
|
||||
case CONFIG_KEYS.OCO_MESSAGE_TEMPLATE_PLACEHOLDER:
|
||||
return {
|
||||
description: 'Message template placeholder',
|
||||
values: ["String (must start with $)"]
|
||||
};
|
||||
default:
|
||||
return {
|
||||
description: 'String value',
|
||||
values: ['Any string']
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function printConfigKeyHelp(param) {
|
||||
if (!Object.values(CONFIG_KEYS).includes(param)) {
|
||||
console.log(chalk.red(`Unknown config parameter: ${param}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const details = getConfigKeyDetails(param as CONFIG_KEYS);
|
||||
|
||||
let desc = details.description;
|
||||
let defaultValue = undefined;
|
||||
if (param in DEFAULT_CONFIG) {
|
||||
defaultValue = DEFAULT_CONFIG[param];
|
||||
}
|
||||
|
||||
|
||||
console.log(chalk.bold(`\n${param}:`));
|
||||
console.log(chalk.gray(` Description: ${desc}`));
|
||||
if (defaultValue !== undefined) {
|
||||
// Print booleans and numbers as-is, strings without quotes
|
||||
if (typeof defaultValue === 'string') {
|
||||
console.log(chalk.gray(` Default: ${defaultValue}`));
|
||||
} else {
|
||||
console.log(chalk.gray(` Default: ${defaultValue}`));
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(details.values)) {
|
||||
console.log(chalk.gray(' Accepted values:'));
|
||||
details.values.forEach(value => {
|
||||
console.log(chalk.gray(` - ${value}`));
|
||||
});
|
||||
} else {
|
||||
console.log(chalk.gray(' Accepted values by provider:'));
|
||||
Object.entries(details.values).forEach(([provider, values]) => {
|
||||
console.log(chalk.gray(` ${provider}:`));
|
||||
(values as string[]).forEach(value => {
|
||||
console.log(chalk.gray(` - ${value}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function printAllConfigHelp() {
|
||||
console.log(chalk.bold('Available config parameters:'));
|
||||
for (const key of Object.values(CONFIG_KEYS).sort()) {
|
||||
const details = getConfigKeyDetails(key);
|
||||
// Try to get the default value from DEFAULT_CONFIG
|
||||
let defaultValue = undefined;
|
||||
if (key in DEFAULT_CONFIG) {
|
||||
defaultValue = DEFAULT_CONFIG[key];
|
||||
}
|
||||
|
||||
console.log(chalk.bold(`\n${key}:`));
|
||||
console.log(chalk.gray(` Description: ${details.description}`));
|
||||
if (defaultValue !== undefined) {
|
||||
if (typeof defaultValue === 'string') {
|
||||
console.log(chalk.gray(` Default: ${defaultValue}`));
|
||||
} else {
|
||||
console.log(chalk.gray(` Default: ${defaultValue}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(chalk.yellow('\nUse "oco config describe [PARAMETER]" to see accepted values and more details for a specific config parameter.'));
|
||||
}
|
||||
|
||||
export const configCommand = command(
|
||||
{
|
||||
name: COMMANDS.config,
|
||||
parameters: ['<mode>', '[key=values...]'],
|
||||
help: {
|
||||
description: 'Configure opencommit settings',
|
||||
examples: [
|
||||
'Describe all config parameters: oco config describe',
|
||||
'Describe a specific parameter: oco config describe OCO_MODEL',
|
||||
'Get a config value: oco config get OCO_MODEL',
|
||||
'Set a config value: oco config set OCO_MODEL=gpt-4'
|
||||
]
|
||||
}
|
||||
parameters: ['<mode>', '<key=values...>']
|
||||
},
|
||||
async (argv) => {
|
||||
try {
|
||||
const { mode, keyValues } = argv._;
|
||||
intro(`COMMAND: config ${mode} ${keyValues}`);
|
||||
|
||||
if (mode === CONFIG_MODES.describe) {
|
||||
if (!keyValues || keyValues.length === 0) {
|
||||
printAllConfigHelp();
|
||||
} else {
|
||||
for (const key of keyValues) {
|
||||
printConfigKeyHelp(key);
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
} else if (mode === CONFIG_MODES.get) {
|
||||
if (!keyValues || keyValues.length === 0) {
|
||||
throw new Error('No config keys specified for get mode');
|
||||
}
|
||||
if (mode === CONFIG_MODES.get) {
|
||||
const config = getConfig() || {};
|
||||
for (const key of keyValues) {
|
||||
outro(`${key}=${config[key as keyof typeof config]}`);
|
||||
}
|
||||
} else if (mode === CONFIG_MODES.set) {
|
||||
if (!keyValues || keyValues.length === 0) {
|
||||
throw new Error('No config keys specified for set mode');
|
||||
}
|
||||
await setConfig(
|
||||
keyValues.map((keyValue) => keyValue.split('=') as [string, string])
|
||||
);
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unsupported mode: ${mode}. Valid modes are: "set", "get", and "describe"`
|
||||
`Unsupported mode: ${mode}. Valid modes are: "set" and "get"`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { OpenAIClient as AzureOpenAIClient } from '@azure/openai';
|
||||
import { GoogleGenerativeAI as GeminiClient } from '@google/generative-ai';
|
||||
import { AxiosInstance as RawAxiosClient } from 'axios';
|
||||
import { OpenAI as OpenAIClient } from 'openai';
|
||||
import { Mistral as MistralClient } from '@mistralai/mistralai';
|
||||
|
||||
export interface AiEngineConfig {
|
||||
apiKey: string;
|
||||
@@ -11,7 +10,6 @@ export interface AiEngineConfig {
|
||||
maxTokensOutput: number;
|
||||
maxTokensInput: number;
|
||||
baseURL?: string;
|
||||
customHeaders?: Record<string, string>;
|
||||
}
|
||||
|
||||
type Client =
|
||||
@@ -19,8 +17,7 @@ type Client =
|
||||
| AzureOpenAIClient
|
||||
| AnthropicClient
|
||||
| RawAxiosClient
|
||||
| GeminiClient
|
||||
| MistralClient;
|
||||
| GeminiClient;
|
||||
|
||||
export interface AiEngine {
|
||||
config: AiEngineConfig;
|
||||
|
||||
@@ -8,7 +8,6 @@ import axios from 'axios';
|
||||
import chalk from 'chalk';
|
||||
import { OpenAI } from 'openai';
|
||||
import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { tokenCount } from '../utils/tokenCount';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
@@ -55,8 +54,8 @@ export class AnthropicEngine implements AiEngine {
|
||||
const data = await this.client.messages.create(params);
|
||||
|
||||
const message = data?.content[0].text;
|
||||
let content = message;
|
||||
return removeContentTags(content, 'think');
|
||||
|
||||
return message;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
outro(`${chalk.red('✖')} ${err?.message || err}`);
|
||||
|
||||
@@ -7,7 +7,6 @@ import axios from 'axios';
|
||||
import chalk from 'chalk';
|
||||
import { OpenAI } from 'openai';
|
||||
import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { tokenCount } from '../utils/tokenCount';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
@@ -53,9 +52,7 @@ export class AzureEngine implements AiEngine {
|
||||
if (message?.content === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let content = message?.content;
|
||||
return removeContentTags(content, 'think');
|
||||
return message?.content;
|
||||
} catch (error) {
|
||||
outro(`${chalk.red('✖')} ${this.config.model}`);
|
||||
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { tokenCount } from '../utils/tokenCount';
|
||||
import { OpenAiEngine, OpenAiConfig } from './openAi';
|
||||
|
||||
export interface DeepseekConfig extends OpenAiConfig {}
|
||||
|
||||
export class DeepseekEngine extends OpenAiEngine {
|
||||
constructor(config: DeepseekConfig) {
|
||||
// Call OpenAIEngine constructor with forced Deepseek baseURL
|
||||
super({
|
||||
...config,
|
||||
baseURL: 'https://api.deepseek.com/v1'
|
||||
});
|
||||
}
|
||||
|
||||
// Identical method from OpenAiEngine, re-implemented here
|
||||
public generateCommitMessage = async (
|
||||
messages: Array<OpenAI.Chat.Completions.ChatCompletionMessageParam>
|
||||
): Promise<string | null> => {
|
||||
const params = {
|
||||
model: this.config.model,
|
||||
messages,
|
||||
temperature: 0,
|
||||
top_p: 0.1,
|
||||
max_tokens: this.config.maxTokensOutput
|
||||
};
|
||||
|
||||
try {
|
||||
const REQUEST_TOKENS = messages
|
||||
.map((msg) => tokenCount(msg.content as string) + 4)
|
||||
.reduce((a, b) => a + b, 0);
|
||||
|
||||
if (
|
||||
REQUEST_TOKENS >
|
||||
this.config.maxTokensInput - this.config.maxTokensOutput
|
||||
)
|
||||
throw new Error(GenerateCommitMessageErrorEnum.tooMuchTokens);
|
||||
|
||||
const completion = await this.client.chat.completions.create(params);
|
||||
|
||||
const message = completion.choices[0].message;
|
||||
let content = message?.content;
|
||||
return removeContentTags(content, 'think');
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
if (
|
||||
axios.isAxiosError<{ error?: { message: string } }>(error) &&
|
||||
error.response?.status === 401
|
||||
) {
|
||||
const openAiError = error.response.data.error;
|
||||
|
||||
if (openAiError) throw new Error(openAiError.message);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
interface FlowiseAiConfig extends AiEngineConfig {}
|
||||
@@ -37,8 +36,7 @@ export class FlowiseEngine implements AiEngine {
|
||||
try {
|
||||
const response = await this.client.post('', payload);
|
||||
const message = response.data;
|
||||
let content = message?.text;
|
||||
return removeContentTags(content, 'think');
|
||||
return message?.text;
|
||||
} catch (err: any) {
|
||||
const message = err.response?.data?.error ?? err.message;
|
||||
throw new Error('local model issues. details: ' + message);
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from '@google/generative-ai';
|
||||
import axios from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
interface GeminiConfig extends AiEngineConfig {}
|
||||
@@ -72,8 +71,7 @@ export class GeminiEngine implements AiEngine {
|
||||
}
|
||||
});
|
||||
|
||||
const content = result.response.text();
|
||||
return removeContentTags(content, 'think');
|
||||
return result.response.text();
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
if (
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { OpenAiConfig, OpenAiEngine } from './openAi';
|
||||
|
||||
interface GroqConfig extends OpenAiConfig {}
|
||||
|
||||
export class GroqEngine extends OpenAiEngine {
|
||||
constructor(config: GroqConfig) {
|
||||
config.baseURL = 'https://api.groq.com/openai/v1';
|
||||
super(config);
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { tokenCount } from '../utils/tokenCount';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
// Using any for Mistral types to avoid type declaration issues
|
||||
export interface MistralAiConfig extends AiEngineConfig {}
|
||||
export type MistralCompletionMessageParam = Array<any>;
|
||||
|
||||
// Import Mistral dynamically to avoid TS errors
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const Mistral = require('@mistralai/mistralai').Mistral;
|
||||
|
||||
export class MistralAiEngine implements AiEngine {
|
||||
config: MistralAiConfig;
|
||||
client: any; // Using any type for Mistral client to avoid TS errors
|
||||
|
||||
constructor(config: MistralAiConfig) {
|
||||
this.config = config;
|
||||
|
||||
if (!config.baseURL) {
|
||||
this.client = new Mistral({ apiKey: config.apiKey });
|
||||
} else {
|
||||
this.client = new Mistral({ apiKey: config.apiKey, serverURL: config.baseURL });
|
||||
}
|
||||
}
|
||||
|
||||
public generateCommitMessage = async (
|
||||
messages: Array<OpenAI.Chat.Completions.ChatCompletionMessageParam>
|
||||
): Promise<string | null> => {
|
||||
const params = {
|
||||
model: this.config.model,
|
||||
messages: messages as MistralCompletionMessageParam,
|
||||
topP: 0.1,
|
||||
maxTokens: this.config.maxTokensOutput
|
||||
};
|
||||
|
||||
try {
|
||||
const REQUEST_TOKENS = messages
|
||||
.map((msg) => tokenCount(msg.content as string) + 4)
|
||||
.reduce((a, b) => a + b, 0);
|
||||
|
||||
if (
|
||||
REQUEST_TOKENS >
|
||||
this.config.maxTokensInput - this.config.maxTokensOutput
|
||||
)
|
||||
throw new Error(GenerateCommitMessageErrorEnum.tooMuchTokens);
|
||||
|
||||
const completion = await this.client.chat.complete(params);
|
||||
|
||||
if (!completion.choices)
|
||||
throw Error('No completion choice available.')
|
||||
|
||||
const message = completion.choices[0].message;
|
||||
|
||||
if (!message || !message.content)
|
||||
throw Error('No completion choice available.')
|
||||
|
||||
let content = message.content as string;
|
||||
return removeContentTags(content, 'think');
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
if (
|
||||
axios.isAxiosError<{ error?: { message: string } }>(error) &&
|
||||
error.response?.status === 401
|
||||
) {
|
||||
const mistralError = error.response.data.error;
|
||||
|
||||
if (mistralError) throw new Error(mistralError.message);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
interface MLXConfig extends AiEngineConfig {}
|
||||
|
||||
export class MLXEngine implements AiEngine {
|
||||
config: MLXConfig;
|
||||
client: AxiosInstance;
|
||||
|
||||
constructor(config) {
|
||||
this.config = config;
|
||||
this.client = axios.create({
|
||||
url: config.baseURL
|
||||
? `${config.baseURL}/${config.apiKey}`
|
||||
: 'http://localhost:8080/v1/chat/completions',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
async generateCommitMessage(
|
||||
messages: Array<OpenAI.Chat.Completions.ChatCompletionMessageParam>):
|
||||
Promise<string | undefined> {
|
||||
const params = {
|
||||
messages,
|
||||
temperature: 0,
|
||||
top_p: 0.1,
|
||||
repetition_penalty: 1.5,
|
||||
stream: false
|
||||
};
|
||||
try {
|
||||
const response = await this.client.post(
|
||||
this.client.getUri(this.config),
|
||||
params
|
||||
);
|
||||
|
||||
const choices = response.data.choices;
|
||||
const message = choices[0].message;
|
||||
let content = message?.content;
|
||||
return removeContentTags(content, 'think');
|
||||
} catch (err: any) {
|
||||
const message = err.response?.data?.error ?? err.message;
|
||||
throw new Error(`MLX provider error: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
interface OllamaConfig extends AiEngineConfig {}
|
||||
@@ -11,18 +10,11 @@ export class OllamaEngine implements AiEngine {
|
||||
|
||||
constructor(config) {
|
||||
this.config = config;
|
||||
|
||||
// Combine base headers with custom headers
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...config.customHeaders
|
||||
};
|
||||
|
||||
this.client = axios.create({
|
||||
url: config.baseURL
|
||||
? `${config.baseURL}/${config.apiKey}`
|
||||
: 'http://localhost:11434/api/chat',
|
||||
headers
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -41,9 +33,9 @@ export class OllamaEngine implements AiEngine {
|
||||
params
|
||||
);
|
||||
|
||||
const { message } = response.data;
|
||||
let content = message?.content;
|
||||
return removeContentTags(content, 'think');
|
||||
const message = response.data.message;
|
||||
|
||||
return message?.content;
|
||||
} catch (err: any) {
|
||||
const message = err.response?.data?.error ?? err.message;
|
||||
throw new Error(`Ollama provider error: ${message}`);
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import axios from 'axios';
|
||||
import { OpenAI } from 'openai';
|
||||
import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
|
||||
import { parseCustomHeaders } from '../utils/engine';
|
||||
import { removeContentTags } from '../utils/removeContentTags';
|
||||
import { tokenCount } from '../utils/tokenCount';
|
||||
import { AiEngine, AiEngineConfig } from './Engine';
|
||||
|
||||
export interface OpenAiConfig extends AiEngineConfig {}
|
||||
interface OpenAiConfig extends AiEngineConfig {}
|
||||
|
||||
export class OpenAiEngine implements AiEngine {
|
||||
config: OpenAiConfig;
|
||||
@@ -14,23 +12,7 @@ export class OpenAiEngine implements AiEngine {
|
||||
|
||||
constructor(config: OpenAiConfig) {
|
||||
this.config = config;
|
||||
|
||||
const clientOptions: OpenAI.ClientOptions = {
|
||||
apiKey: config.apiKey
|
||||
};
|
||||
|
||||
if (config.baseURL) {
|
||||
clientOptions.baseURL = config.baseURL;
|
||||
}
|
||||
|
||||
if (config.customHeaders) {
|
||||
const headers = parseCustomHeaders(config.customHeaders);
|
||||
if (Object.keys(headers).length > 0) {
|
||||
clientOptions.defaultHeaders = headers;
|
||||
}
|
||||
}
|
||||
|
||||
this.client = new OpenAI(clientOptions);
|
||||
this.client = new OpenAI({ apiKey: config.apiKey });
|
||||
}
|
||||
|
||||
public generateCommitMessage = async (
|
||||
@@ -54,12 +36,12 @@ export class OpenAiEngine implements AiEngine {
|
||||
this.config.maxTokensInput - this.config.maxTokensOutput
|
||||
)
|
||||
throw new Error(GenerateCommitMessageErrorEnum.tooMuchTokens);
|
||||
|
||||
|
||||
const completion = await this.client.chat.completions.create(params);
|
||||
|
||||
const message = completion.choices[0].message;
|
||||
let content = message?.content;
|
||||
return removeContentTags(content, 'think');
|
||||
|
||||
return message?.content;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
if (
|
||||
|
||||
@@ -11,10 +11,9 @@ const MAX_TOKENS_OUTPUT = config.OCO_TOKENS_MAX_OUTPUT;
|
||||
|
||||
const generateCommitMessageChatCompletionPrompt = async (
|
||||
diff: string,
|
||||
fullGitMojiSpec: boolean,
|
||||
context: string
|
||||
fullGitMojiSpec: boolean
|
||||
): Promise<Array<OpenAI.Chat.Completions.ChatCompletionMessageParam>> => {
|
||||
const INIT_MESSAGES_PROMPT = await getMainCommitPrompt(fullGitMojiSpec, context);
|
||||
const INIT_MESSAGES_PROMPT = await getMainCommitPrompt(fullGitMojiSpec);
|
||||
|
||||
const chatContextAsCompletionRequest = [...INIT_MESSAGES_PROMPT];
|
||||
|
||||
@@ -37,14 +36,10 @@ const ADJUSTMENT_FACTOR = 20;
|
||||
|
||||
export const generateCommitMessageByDiff = async (
|
||||
diff: string,
|
||||
fullGitMojiSpec: boolean = false,
|
||||
context: string = ""
|
||||
fullGitMojiSpec: boolean = false
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const INIT_MESSAGES_PROMPT = await getMainCommitPrompt(
|
||||
fullGitMojiSpec,
|
||||
context
|
||||
);
|
||||
const INIT_MESSAGES_PROMPT = await getMainCommitPrompt(fullGitMojiSpec);
|
||||
|
||||
const INIT_MESSAGES_PROMPT_LENGTH = INIT_MESSAGES_PROMPT.map(
|
||||
(msg) => tokenCount(msg.content as string) + 4
|
||||
@@ -74,8 +69,7 @@ export const generateCommitMessageByDiff = async (
|
||||
|
||||
const messages = await generateCommitMessageChatCompletionPrompt(
|
||||
diff,
|
||||
fullGitMojiSpec,
|
||||
context,
|
||||
fullGitMojiSpec
|
||||
);
|
||||
|
||||
const engine = getEngine();
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "česky",
|
||||
"commitFix": "fix(server.ts): zlepšení velikosti proměnné port na velká písmena PORT",
|
||||
"commitFeat": "feat(server.ts): přidání podpory pro proměnnou prostředí process.env.PORT",
|
||||
"commitDescription": "Proměnná port se nyní jmenuje PORT, což odpovídá konvenci pojmenování, protože PORT je konstanta. Podpora proměnné prostředí process.env.PORT umožňuje snadnější správu nastavení při spuštění.",
|
||||
"commitFixOmitScope": "fix: zlepšení velikosti proměnné port na velká písmena PORT",
|
||||
"commitFeatOmitScope": "feat: přidání podpory pro proměnnou prostředí process.env.PORT"
|
||||
"commitDescription": "Proměnná port se nyní jmenuje PORT, což odpovídá konvenci pojmenování, protože PORT je konstanta. Podpora proměnné prostředí process.env.PORT umožňuje snadnější správu nastavení při spuštění."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "Deutsch",
|
||||
"commitFix": "fix(server.ts): Ändere die Groß- und Kleinschreibung der Port-Variable von Kleinbuchstaben auf Großbuchstaben PORT.",
|
||||
"commitFeat": "Funktion(server.ts): Unterstützung für die Umgebungsvariable process.env.PORT hinzufügen",
|
||||
"commitDescription": "Die Port-Variable heißt jetzt PORT, was die Konsistenz mit den Namenskonventionen verbessert, da PORT eine Konstante ist. Die Unterstützung für eine Umgebungsvariable ermöglicht es der Anwendung, flexibler zu sein, da sie jetzt auf jedem verfügbaren Port laufen kann, der über die Umgebungsvariable process.env.PORT angegeben wird.",
|
||||
"commitFixOmitScope": "fix: Ändere die Groß- und Kleinschreibung der Port-Variable von Kleinbuchstaben auf Großbuchstaben PORT.",
|
||||
"commitFeatOmitScope": "Funktion: Unterstützung für die Umgebungsvariable process.env.PORT hinzufügen"
|
||||
"commitDescription": "Die Port-Variable heißt jetzt PORT, was die Konsistenz mit den Namenskonventionen verbessert, da PORT eine Konstante ist. Die Unterstützung für eine Umgebungsvariable ermöglicht es der Anwendung, flexibler zu sein, da sie jetzt auf jedem verfügbaren Port laufen kann, der über die Umgebungsvariable process.env.PORT angegeben wird."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "english",
|
||||
"commitFix": "fix(server.ts): change port variable case from lowercase port to uppercase PORT to improve semantics",
|
||||
"commitFeat": "feat(server.ts): add support for process.env.PORT environment variable to be able to run app on a configurable port",
|
||||
"commitDescription": "The port variable is now named PORT, which improves consistency with the naming conventions as PORT is a constant. Support for an environment variable allows the application to be more flexible as it can now run on any available port specified via the process.env.PORT environment variable.",
|
||||
"commitFixOmitScope": "fix: change port variable case from lowercase port to uppercase PORT to improve semantics",
|
||||
"commitFeatOmitScope": "feat: add support for process.env.PORT environment variable to be able to run app on a configurable port"
|
||||
"commitDescription": "The port variable is now named PORT, which improves consistency with the naming conventions as PORT is a constant. Support for an environment variable allows the application to be more flexible as it can now run on any available port specified via the process.env.PORT environment variable."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "spanish",
|
||||
"commitFix": "fix(server.ts): cambiar la variable port de minúsculas a mayúsculas PORT",
|
||||
"commitFeat": "feat(server.ts): añadir soporte para la variable de entorno process.env.PORT",
|
||||
"commitDescription": "La variable port ahora se llama PORT, lo que mejora la coherencia con las convenciones de nomenclatura, ya que PORT es una constante. El soporte para una variable de entorno permite que la aplicación sea más flexible, ya que ahora puede ejecutarse en cualquier puerto disponible especificado a través de la variable de entorno process.env.PORT.",
|
||||
"commitFixOmitScope": "fix: cambiar la variable port de minúsculas a mayúsculas PORT",
|
||||
"commitFeatOmitScope": "feat: añadir soporte para la variable de entorno process.env.PORT"
|
||||
"commitDescription": "La variable port ahora se llama PORT, lo que mejora la coherencia con las convenciones de nomenclatura, ya que PORT es una constante. El soporte para una variable de entorno permite que la aplicación sea más flexible, ya que ahora puede ejecutarse en cualquier puerto disponible especificado a través de la variable de entorno process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "française",
|
||||
"commitFix": "corriger(server.ts) : changer la casse de la variable de port de minuscules à majuscules (PORT)",
|
||||
"commitFeat": "fonctionnalité(server.ts) : ajouter la prise en charge de la variable d'environnement process.env.PORT",
|
||||
"commitDescription": "La variable de port est maintenant nommée PORT, ce qui améliore la cohérence avec les conventions de nommage car PORT est une constante. La prise en charge d'une variable d'environnement permet à l'application d'être plus flexible car elle peut maintenant s'exécuter sur n'importe quel port disponible spécifié via la variable d'environnement process.env.PORT.",
|
||||
"commitFixOmitScope": "corriger : changer la casse de la variable de port de minuscules à majuscules (PORT)",
|
||||
"commitFeatOmitScope": "fonctionnalité : ajouter la prise en charge de la variable d'environnement process.env.PORT"
|
||||
"commitDescription": "La variable de port est maintenant nommée PORT, ce qui améliore la cohérence avec les conventions de nommage car PORT est une constante. La prise en charge d'une variable d'environnement permet à l'application d'être plus flexible car elle peut maintenant s'exécuter sur n'importe quel port disponible spécifié via la variable d'environnement process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "bahasa",
|
||||
"commitFix": "fix(server.ts): mengubah huruf port variable dari huruf kecil ke huruf besar PORT",
|
||||
"commitFeat": "feat(server.ts): menambahkan support di process.env.PORT environment variabel",
|
||||
"commitDescription": "Port variabel bernama PORT, yang membantu konsistensi dengan memberi nama yaitu PORT yang konstan. Bantuan environment variabel membantu aplikasi lebih fleksibel, dan dapat di jalankan di port manapun yang tertulis pada process.env.PORT",
|
||||
"commitFixOmitScope": "fix: mengubah huruf port variable dari huruf kecil ke huruf besar PORT",
|
||||
"commitFeatOmitScope": "feat: menambahkan support di process.env.PORT environment variabel"
|
||||
"commitDescription": "Port variabel bernama PORT, yang membantu konsistensi dengan memberi nama yaitu PORT yang konstan. Bantuan environment variabel membantu aplikasi lebih fleksibel, dan dapat di jalankan di port manapun yang tertulis pada process.env.PORT"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "italiano",
|
||||
"commitFix": "fix(server.ts): cambia la grafia della variabile della porta dal minuscolo port al maiuscolo PORT",
|
||||
"commitFeat": "feat(server.ts): aggiunge il supporto per la variabile di ambiente process.env.PORT",
|
||||
"commitDescription": "La variabile port è ora chiamata PORT, migliorando la coerenza con le convenzioni di denominazione in quanto PORT è una costante. Il supporto per una variabile di ambiente consente all'applicazione di essere più flessibile poiché ora può essere eseguita su qualsiasi porta disponibile specificata tramite la variabile di ambiente process.env.PORT.",
|
||||
"commitFixOmitScope": "fix: cambia la grafia della variabile della porta dal minuscolo port al maiuscolo PORT",
|
||||
"commitFeatOmitScope": "feat: aggiunge il supporto per la variabile di ambiente process.env.PORT"
|
||||
"commitDescription": "La variabile port è ora chiamata PORT, migliorando la coerenza con le convenzioni di denominazione in quanto PORT è una costante. Il supporto per una variabile di ambiente consente all'applicazione di essere più flessibile poiché ora può essere eseguita su qualsiasi porta disponibile specificata tramite la variabile di ambiente process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "日本語",
|
||||
"commitFix": "修正(server.ts): ポート変数を小文字のportから大文字のPORTに変更",
|
||||
"commitFeat": "新機能(server.ts): 環境変数process.env.PORTのサポートを追加",
|
||||
"commitDescription": "ポート変数は現在PORTという名前になり、定数であるPORTを使うことで命名規則に一貫性が生まれました。環境変数をサポートすることで、環境変数process.env.PORTで指定された任意の利用可能なポートで実行できるようになり、アプリケーションはより柔軟になりました。",
|
||||
"commitFixOmitScope": "修正: ポート変数を小文字のportから大文字のPORTに変更",
|
||||
"commitFeatOmitScope": "新機能: 環境変数process.env.PORTのサポートを追加"
|
||||
"commitDescription": "ポート変数は現在PORTという名前になり、定数であるPORTを使うことで命名規則に一貫性が生まれました。環境変数をサポートすることで、環境変数process.env.PORTで指定された任意の利用可能なポートで実行できるようになり、アプリケーションはより柔軟になりました。"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "한국어",
|
||||
"commitFix": "fix(server.ts): 포트 변수를 소문자 port에서 대문자 PORT로 변경",
|
||||
"commitFeat": "피트(server.ts): process.env.PORT 환경 변수 지원 추가",
|
||||
"commitDescription": "포트 변수는 이제 PORT로 이름이 지정되어 상수인 PORT와 일관성 있는 이름 규칙을 따릅니다. 환경 변수 지원을 통해 애플리케이션은 이제 process.env.PORT 환경 변수로 지정된 사용 가능한 모든 포트에서 실행할 수 있으므로 더 유연해졌습니다.",
|
||||
"commitFixOmitScope": "fix: 포트 변수를 소문자 port에서 대문자 PORT로 변경",
|
||||
"commitFeatOmitScope": "피트: process.env.PORT 환경 변수 지원 추가"
|
||||
"commitDescription": "포트 변수는 이제 PORT로 이름이 지정되어 상수인 PORT와 일관성 있는 이름 규칙을 따릅니다. 환경 변수 지원을 통해 애플리케이션은 이제 process.env.PORT 환경 변수로 지정된 사용 가능한 모든 포트에서 실행할 수 있으므로 더 유연해졌습니다."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "Nederlands",
|
||||
"commitFix": "fix(server.ts): verander poortvariabele van kleine letters poort naar hoofdletters PORT",
|
||||
"commitFeat": "feat(server.ts): voeg ondersteuning toe voor process.env.PORT omgevingsvariabele",
|
||||
"commitDescription": "De poortvariabele heet nu PORT, wat de consistentie met de naamgevingsconventies verbetert omdat PORT een constante is. Ondersteuning voor een omgevingsvariabele maakt de applicatie flexibeler, omdat deze nu kan draaien op elke beschikbare poort die is gespecificeerd via de process.env.PORT omgevingsvariabele.",
|
||||
"commitFixOmitScope": "fix: verander poortvariabele van kleine letters poort naar hoofdletters PORT",
|
||||
"commitFeatOmitScope": "feat: voeg ondersteuning toe voor process.env.PORT omgevingsvariabele"
|
||||
"commitDescription": "De poortvariabele heet nu PORT, wat de consistentie met de naamgevingsconventies verbetert omdat PORT een constante is. Ondersteuning voor een omgevingsvariabele maakt de applicatie flexibeler, omdat deze nu kan draaien op elke beschikbare poort die is gespecificeerd via de process.env.PORT omgevingsvariabele."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "polski",
|
||||
"commitFix": "fix(server.ts): poprawa wielkości zmiennej port na pisane z dużymi literami PORT",
|
||||
"commitFeat": "feat(server.ts): dodanie obsługi zmiennej środowiskowej process.env.PORT",
|
||||
"commitDescription": "Zmienna port jest teraz nazwana PORT, co jest zgodne z konwencją nazewniczą ponieważ PORT jest stałą. Obsługa zmiennej środowiskowej process.env.PORT pozwala łatwiej zarządzać ustawieniami przy starcie.",
|
||||
"commitFixOmitScope": "fix: poprawa wielkości zmiennej port na pisane z dużymi literami PORT",
|
||||
"commitFeatOmitScope": "feat: dodanie obsługi zmiennej środowiskowej process.env.PORT"
|
||||
"commitDescription": "Zmienna port jest teraz nazwana PORT, co jest zgodne z konwencją nazewniczą ponieważ PORT jest stałą. Obsługa zmiennej środowiskowej process.env.PORT pozwala łatwiej zarządzać ustawieniami przy starcie."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "português",
|
||||
"commitFix": "fix(server.ts): altera o caso da variável de porta de port minúscula para PORT maiúscula",
|
||||
"commitFeat": "feat(server.ts): adiciona suporte para a variável de ambiente process.env.PORT",
|
||||
"commitDescription": "A variável de porta agora é denominada PORT, o que melhora a consistência com as convenções de nomenclatura, pois PORT é uma constante. O suporte para uma variável de ambiente permite que o aplicativo seja mais flexível, pois agora pode ser executado em qualquer porta disponível especificada por meio da variável de ambiente process.env.PORT.",
|
||||
"commitFixOmitScope": "fix: altera o caso da variável de porta de port minúscula para PORT maiúscula",
|
||||
"commitFeatOmitScope": "feat: adiciona suporte para a variável de ambiente process.env.PORT"
|
||||
"commitDescription": "A variável de porta agora é denominada PORT, o que melhora a consistência com as convenções de nomenclatura, pois PORT é uma constante. O suporte para uma variável de ambiente permite que o aplicativo seja mais flexível, pois agora pode ser executado em qualquer porta disponível especificada por meio da variável de ambiente process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "русский",
|
||||
"commitFix": "fix(server.ts): изменение регистра переменной порта с нижнего регистра port на верхний регистр PORT",
|
||||
"commitFeat": "feat(server.ts): добавлена поддержка переменной окружения process.env.PORT",
|
||||
"commitDescription": "Переменная port теперь называется PORT, что улучшает согласованность с соглашениями об именовании констант. Поддержка переменной окружения позволяет приложению быть более гибким, запускаясь на любом доступном порту, указанном с помощью переменной окружения process.env.PORT.",
|
||||
"commitFixOmitScope": "fix: изменение регистра переменной порта с нижнего регистра port на верхний регистр PORT",
|
||||
"commitFeatOmitScope": "feat: добавлена поддержка переменной окружения process.env.PORT"
|
||||
"commitDescription": "Переменная port теперь называется PORT, что улучшает согласованность с соглашениями об именовании констант. Поддержка переменной окружения позволяет приложению быть более гибким, запускаясь на любом доступном порту, указанном с помощью переменной окружения process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "svenska",
|
||||
"commitFix": "fixa(server.ts): ändra variabelnamnet för port från små bokstäver till stora bokstäver PORT",
|
||||
"commitFeat": "nyhet(server.ts): lägg till stöd för process.env.PORT miljövariabel",
|
||||
"commitDescription": "Variabeln som innehåller portnumret heter nu PORT vilket förbättrar konsekvensen med namngivningskonventionerna eftersom PORT är en konstant. Stöd för en miljövariabel gör att applikationen kan vara mer flexibel då den nu kan köras på vilken port som helst som specificeras via miljövariabeln process.env.PORT.",
|
||||
"commitFixOmitScope": "fixa: ändra variabelnamnet för port från små bokstäver till stora bokstäver PORT",
|
||||
"commitFeatOmitScope": "nyhet: lägg till stöd för process.env.PORT miljövariabel"
|
||||
"commitDescription": "Variabeln som innehåller portnumret heter nu PORT vilket förbättrar konsekvensen med namngivningskonventionerna eftersom PORT är en konstant. Stöd för en miljövariabel gör att applikationen kan vara mer flexibel då den nu kan köras på vilken port som helst som specificeras via miljövariabeln process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "ไทย",
|
||||
"commitFix": "fix(server.ts): เปลี่ยนตัวพิมพ์ของตัวแปร จากตัวพิมพ์เล็ก port เป็นตัวพิมพ์ใหญ่ PORT",
|
||||
"commitFeat": "feat(server.ts): เพิ่มการรองรับสำหรับตัวแปรสภาพแวดล้อม process.env.PORT",
|
||||
"commitDescription": "ตอนนี้ตัวแปรพอร์ตมีชื่อว่า PORT, ซึ่งปรับปรุงความสอดคล้องกับหลักการตั้งชื่อเนื่องจาก PORT เป็นค่าคงที่. การสนับสนุนสำหรับตัวแปรสภาพแวดล้อม ช่วยให้แอปพลิเคชันมีความยืดหยุ่นมากขึ้นเนื่องจาก สามารถทำงานบนพอร์ตใด ๆ ตามที่กำหนด ซึ่งระบุผ่านตัวแปรสภาพแวดล้อม process.env.PORT",
|
||||
"commitFixOmitScope": "fix: เปลี่ยนตัวพิมพ์ของตัวแปร จากตัวพิมพ์เล็ก port เป็นตัวพิมพ์ใหญ่ PORT",
|
||||
"commitFeatOmitScope": "feat: เพิ่มการรองรับสำหรับตัวแปรสภาพแวดล้อม process.env.PORT"
|
||||
"commitDescription": "ตอนนี้ตัวแปรพอร์ตมีชื่อว่า PORT, ซึ่งปรับปรุงความสอดคล้องกับหลักการตั้งชื่อเนื่องจาก PORT เป็นค่าคงที่. การสนับสนุนสำหรับตัวแปรสภาพแวดล้อม ช่วยให้แอปพลิเคชันมีความยืดหยุ่นมากขึ้นเนื่องจาก สามารถทำงานบนพอร์ตใด ๆ ตามที่กำหนด ซึ่งระบุผ่านตัวแปรสภาพแวดล้อม process.env.PORT"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "Turkish",
|
||||
"commitFix": "fix(server.ts): port değişkeni küçük harfli porttan büyük harfli PORT'a değiştirildi",
|
||||
"commitFeat": "feat(server.ts): process.env.PORT ortam değişkeni için destek eklendi.",
|
||||
"commitDescription": "Bağlantı noktası değişkeni artık PORT olarak adlandırıldı ve PORT bir sabit değişken olduğu için bu adlandırma tutarlılığı artırır. Ortam değişkeni desteği, artık process.env.PORT ortam değişkeni aracılığıyla belirtilen herhangi bir kullanılabilir bağlantı noktasında çalışabileceğinden uygulamanın daha esnek olmasını sağlar.",
|
||||
"commitFixOmitScope": "fix: port değişkeni küçük harfli porttan büyük harfli PORT'a değiştirildi",
|
||||
"commitFeatOmitScope": "feat: process.env.PORT ortam değişkeni için destek eklendi."
|
||||
"commitDescription": "Bağlantı noktası değişkeni artık PORT olarak adlandırıldı ve PORT bir sabit değişken olduğu için bu adlandırma tutarlılığı artırır. Ortam değişkeni desteği, artık process.env.PORT ortam değişkeni aracılığıyla belirtilen herhangi bir kullanılabilir bağlantı noktasında çalışabileceğinden uygulamanın daha esnek olmasını sağlar."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "vietnamese",
|
||||
"commitFix": "fix(server.ts): thay đổi chữ viết thường của biến port thành chữ viết hoa PORT",
|
||||
"commitFeat": "feat(server.ts): thêm hỗ trợ cho biến môi trường process.env.PORT",
|
||||
"commitDescription": "Biến port đã được đổi tên thành PORT, giúp cải thiện tính nhất quán trong việc đặt tên theo quy ước vì PORT là một hằng số. Hỗ trợ cho biến môi trường cho phép ứng dụng linh hoạt hơn khi có thể chạy trên bất kỳ cổng nào được chỉ định thông qua biến môi trường process.env.PORT.",
|
||||
"commitFixOmitScope": "fix: thay đổi chữ viết thường của biến port thành chữ viết hoa PORT",
|
||||
"commitFeatOmitScope": "feat: thêm hỗ trợ cho biến môi trường process.env.PORT"
|
||||
"commitDescription": "Biến port đã được đổi tên thành PORT, giúp cải thiện tính nhất quán trong việc đặt tên theo quy ước vì PORT là một hằng số. Hỗ trợ cho biến môi trường cho phép ứng dụng linh hoạt hơn khi có thể chạy trên bất kỳ cổng nào được chỉ định thông qua biến môi trường process.env.PORT."
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "简体中文",
|
||||
"commitFix": "fix(server.ts):将端口变量从小写port改为大写PORT",
|
||||
"commitFeat": "feat(server.ts):添加对process.env.PORT环境变量的支持",
|
||||
"commitDescription": "现在端口变量被命名为PORT,这提高了命名约定的一致性,因为PORT是一个常量。环境变量的支持使应用程序更加灵活,因为它现在可以通过process.env.PORT环境变量在任何可用端口上运行。",
|
||||
"commitFixOmitScope": "fix:将端口变量从小写port改为大写PORT",
|
||||
"commitFeatOmitScope": "feat:添加对process.env.PORT环境变量的支持"
|
||||
"commitDescription": "现在端口变量被命名为PORT,这提高了命名约定的一致性,因为PORT是一个常量。环境变量的支持使应用程序更加灵活,因为它现在可以通过process.env.PORT环境变量在任何可用端口上运行。"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
"localLanguage": "繁體中文",
|
||||
"commitFix": "修正(server.ts):將端口變數從小寫端口改為大寫PORT",
|
||||
"commitFeat": "功能(server.ts):新增對process.env.PORT環境變數的支援",
|
||||
"commitDescription": "現在port變數已更名為PORT,以符合命名慣例,因為PORT是一個常量。支援環境變數可以使應用程序更靈活,因為它現在可以通過process.env.PORT環境變數運行在任何可用端口上。",
|
||||
"commitFixOmitScope": "修正:將端口變數從小寫端口改為大寫PORT",
|
||||
"commitFeatOmitScope": "功能:新增對process.env.PORT環境變數的支援"
|
||||
"commitDescription": "現在port變數已更名為PORT,以符合命名慣例,因為PORT是一個常量。支援環境變數可以使應用程序更靈活,因為它現在可以通過process.env.PORT環境變數運行在任何可用端口上。"
|
||||
}
|
||||
|
||||
@@ -10,12 +10,10 @@ export default function () {
|
||||
const entriesToSet: [key: string, value: string | boolean | number][] = [];
|
||||
for (const entry of Object.entries(DEFAULT_CONFIG)) {
|
||||
const [key, _value] = entry;
|
||||
if (config[key] === 'undefined' || config[key] === undefined)
|
||||
entriesToSet.push(entry);
|
||||
if (config[key] === 'undefined') entriesToSet.push(entry);
|
||||
}
|
||||
|
||||
if (entriesToSet.length > 0) setConfig(entriesToSet);
|
||||
console.log(entriesToSet);
|
||||
};
|
||||
|
||||
setDefaultConfigValues(getGlobalConfig());
|
||||
|
||||
@@ -53,7 +53,6 @@ export const runMigrations = async () => {
|
||||
migration.name
|
||||
}: ${error}`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
isMigrated = true;
|
||||
|
||||
@@ -53,7 +53,7 @@ export const configureCommitlintIntegration = async (force = false) => {
|
||||
|
||||
spin.start('Generating consistency with given @commitlint rules');
|
||||
|
||||
const prompts = inferPromptsFromCommitlintConfig(commitLintConfig as any);
|
||||
const prompts = inferPromptsFromCommitlintConfig(commitLintConfig);
|
||||
|
||||
const consistencyPrompts =
|
||||
commitlintPrompts.GEN_COMMITLINT_CONSISTENCY_PROMPT(prompts);
|
||||
|
||||
@@ -56,28 +56,30 @@ const llmReadableRules: {
|
||||
blankline: (key, applicable) =>
|
||||
`There should ${applicable} be a blank line at the beginning of the ${key}.`,
|
||||
caseRule: (key, applicable, value: string | Array<string>) =>
|
||||
`The ${key} should ${applicable} be in ${Array.isArray(value)
|
||||
? `one of the following case:
|
||||
`The ${key} should ${applicable} be in ${
|
||||
Array.isArray(value)
|
||||
? `one of the following case:
|
||||
- ${value.join('\n - ')}.`
|
||||
: `${value} case.`
|
||||
: `${value} case.`
|
||||
}`,
|
||||
emptyRule: (key, applicable) => `The ${key} should ${applicable} be empty.`,
|
||||
enumRule: (key, applicable, value: string | Array<string>) =>
|
||||
`The ${key} should ${applicable} be one of the following values:
|
||||
`The ${key} should ${applicable} be one of the following values:
|
||||
- ${Array.isArray(value) ? value.join('\n - ') : value}.`,
|
||||
enumTypeRule: (key, applicable, value: string | Array<string>, prompt) =>
|
||||
`The ${key} should ${applicable} be one of the following values:
|
||||
- ${Array.isArray(value)
|
||||
`The ${key} should ${applicable} be one of the following values:
|
||||
- ${
|
||||
Array.isArray(value)
|
||||
? value
|
||||
.map((v) => {
|
||||
const description = getTypeRuleExtraDescription(v, prompt);
|
||||
if (description) {
|
||||
return `${v} (${description})`;
|
||||
} else return v;
|
||||
})
|
||||
.join('\n - ')
|
||||
.map((v) => {
|
||||
const description = getTypeRuleExtraDescription(v, prompt);
|
||||
if (description) {
|
||||
return `${v} (${description})`;
|
||||
} else return v;
|
||||
})
|
||||
.join('\n - ')
|
||||
: value
|
||||
}.`,
|
||||
}.`,
|
||||
fullStopRule: (key, applicable, value: string) =>
|
||||
`The ${key} should ${applicable} end with '${value}'.`,
|
||||
maxLengthRule: (key, applicable, value: string) =>
|
||||
@@ -202,11 +204,7 @@ export const inferPromptsFromCommitlintConfig = (
|
||||
* ubiquitous language from @commitlint.
|
||||
* While gpt-4 does this on it self, gpt-3.5 can't map this on his own atm.
|
||||
*/
|
||||
const STRUCTURE_OF_COMMIT = config.OCO_OMIT_SCOPE
|
||||
? `
|
||||
- Header of commit is composed of type and subject: <type-of-commit>: <subject-of-commit>
|
||||
- Description of commit is composed of body and footer (optional): <body-of-commit>\n<footer(s)-of-commit>`
|
||||
: `
|
||||
const STRUCTURE_OF_COMMIT = `
|
||||
- Header of commit is composed of type, scope, subject: <type-of-commit>(<scope-of-commit>): <subject-of-commit>
|
||||
- Description of commit is composed of body and footer (optional): <body-of-commit>\n<footer(s)-of-commit>`;
|
||||
|
||||
@@ -214,16 +212,16 @@ const STRUCTURE_OF_COMMIT = config.OCO_OMIT_SCOPE
|
||||
const GEN_COMMITLINT_CONSISTENCY_PROMPT = (
|
||||
prompts: string[]
|
||||
): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => [
|
||||
{
|
||||
role: 'system',
|
||||
content: `${IDENTITY} Your mission is to create clean and comprehensive commit messages for two different changes in a single codebase and output them in the provided JSON format: one for a bug fix and another for a new feature.
|
||||
{
|
||||
role: 'system',
|
||||
content: `${IDENTITY} Your mission is to create clean and comprehensive commit messages for two different changes in a single codebase and output them in the provided JSON format: one for a bug fix and another for a new feature.
|
||||
|
||||
Here are the specific requirements and conventions that should be strictly followed:
|
||||
|
||||
Commit Message Conventions:
|
||||
- The commit message consists of three parts: Header, Body, and Footer.
|
||||
- Header:
|
||||
- Format: ${config.OCO_OMIT_SCOPE ? '`<type>: <subject>`' : '`<type>(<scope>): <subject>`'}
|
||||
- Header:
|
||||
- Format: \`<type>(<scope>): <subject>\`
|
||||
- ${prompts.join('\n- ')}
|
||||
|
||||
JSON Output Format:
|
||||
@@ -231,24 +229,22 @@ JSON Output Format:
|
||||
\`\`\`json
|
||||
{
|
||||
"localLanguage": "${translation.localLanguage}",
|
||||
"commitFix": "<Header of commit for bug fix with scope>",
|
||||
"commitFeat": "<Header of commit for feature with scope>",
|
||||
"commitFixOmitScope": "<Header of commit for bug fix without scope>",
|
||||
"commitFeatOmitScope": "<Header of commit for feature without scope>",
|
||||
"commitFix": "<Header of commit for bug fix>",
|
||||
"commitFeat": "<Header of commit for feature>",
|
||||
"commitDescription": "<Description of commit for both the bug fix and the feature>"
|
||||
}
|
||||
\`\`\`
|
||||
- The "commitDescription" should not include the commit message's header, only the description.
|
||||
- The "commitDescription" should not include the commit message’s header, only the description.
|
||||
- Description should not be more than 74 characters.
|
||||
|
||||
Additional Details:
|
||||
- Changing the variable 'port' to uppercase 'PORT' is considered a bug fix.
|
||||
- Allowing the server to listen on a port specified through the environment variable is considered a new feature.
|
||||
- Changing the variable 'port' to uppercase 'PORT' is considered a bug fix.
|
||||
- Allowing the server to listen on a port specified through the environment variable is considered a new feature.
|
||||
|
||||
Example Git Diff is to follow:`
|
||||
},
|
||||
INIT_DIFF_PROMPT
|
||||
];
|
||||
},
|
||||
INIT_DIFF_PROMPT
|
||||
];
|
||||
|
||||
/**
|
||||
* Prompt to have LLM generate a message using @commitlint rules.
|
||||
@@ -262,25 +258,26 @@ const INIT_MAIN_PROMPT = (
|
||||
prompts: string[]
|
||||
): OpenAI.Chat.Completions.ChatCompletionMessageParam => ({
|
||||
role: 'system',
|
||||
content: `${IDENTITY} Your mission is to create clean and comprehensive commit messages in the given @commitlint convention and explain WHAT were the changes ${config.OCO_WHY ? '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."
|
||||
}
|
||||
content: `${IDENTITY} Your mission is to create clean and comprehensive commit messages in the given @commitlint convention and explain WHAT were the changes ${
|
||||
config.OCO_WHY ? '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."
|
||||
}
|
||||
Use the present tense. Use ${language} to answer.
|
||||
${config.OCO_ONE_LINE_COMMIT
|
||||
? 'Craft a concise commit message that encapsulates all changes made, with an emphasis on the primary updates. If the modifications share a common theme or scope, mention it succinctly; otherwise, leave the scope out to maintain focus. The goal is to provide a clear and unified overview of the changes in a one single message, without diverging into a list of commit per file change.'
|
||||
: ''
|
||||
}
|
||||
${config.OCO_OMIT_SCOPE
|
||||
? 'Do not include a scope in the commit message format. Use the format: <type>: <subject>'
|
||||
: ''
|
||||
}
|
||||
${
|
||||
config.OCO_ONE_LINE_COMMIT
|
||||
? 'Craft a concise commit message that encapsulates all changes made, with an emphasis on the primary updates. If the modifications share a common theme or scope, mention it succinctly; otherwise, leave the scope out to maintain focus. The goal is to provide a clear and unified overview of the changes in a one single message, without diverging into a list of commit per file change.'
|
||||
: ''
|
||||
}
|
||||
|
||||
You will strictly follow the following conventions to generate the content of the commit message:
|
||||
- ${prompts.join('\n- ')}
|
||||
|
||||
|
||||
@@ -4,8 +4,7 @@ import path from 'path';
|
||||
const findModulePath = (moduleName: string) => {
|
||||
const searchPaths = [
|
||||
path.join('node_modules', moduleName),
|
||||
path.join('node_modules', '.pnpm'),
|
||||
path.resolve(__dirname, '../..')
|
||||
path.join('node_modules', '.pnpm')
|
||||
];
|
||||
|
||||
for (const basePath of searchPaths) {
|
||||
@@ -60,7 +59,7 @@ export const getCommitLintPWDConfig =
|
||||
* ES Module (commitlint@v19.x.x. <= )
|
||||
* Directory import is not supported in ES Module resolution, so import the file directly
|
||||
*/
|
||||
modulePath = findModulePath('@commitlint/load/lib/load.js');
|
||||
modulePath = await findModulePath('@commitlint/load/lib/load.js');
|
||||
load = (await import(modulePath)).default;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -108,32 +108,12 @@ const getDescriptionInstruction = () =>
|
||||
|
||||
const getOneLineCommitInstruction = () =>
|
||||
config.OCO_ONE_LINE_COMMIT
|
||||
? 'Craft a concise, single sentence, commit message that encapsulates all changes made, with an emphasis on the primary updates. If the modifications share a common theme or scope, mention it succinctly; otherwise, leave the scope out to maintain focus. The goal is to provide a clear and unified overview of the changes in one single message.'
|
||||
? 'Craft a concise commit message that encapsulates all changes made, with an emphasis on the primary updates. If the modifications share a common theme or scope, mention it succinctly; otherwise, leave the scope out to maintain focus. The goal is to provide a clear and unified overview of the changes in a one single message, without diverging into a list of commit per file change.'
|
||||
: '';
|
||||
|
||||
const getScopeInstruction = () =>
|
||||
config.OCO_OMIT_SCOPE
|
||||
? 'Do not include a scope in the commit message format. Use the format: <type>: <subject>'
|
||||
: '';
|
||||
|
||||
/**
|
||||
* Get the context of the user input
|
||||
* @param extraArgs - The arguments passed to the command line
|
||||
* @example
|
||||
* $ oco -- This is a context used to generate the commit message
|
||||
* @returns - The context of the user input
|
||||
*/
|
||||
const userInputCodeContext = (context: string) => {
|
||||
if (context !== '' && context !== ' ') {
|
||||
return `Additional context provided by the user: <context>${context}</context>\nConsider this context when generating the commit message, incorporating relevant information when appropriate.`;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const INIT_MAIN_PROMPT = (
|
||||
language: string,
|
||||
fullGitMojiSpec: boolean,
|
||||
context: string
|
||||
fullGitMojiSpec: boolean
|
||||
): OpenAI.Chat.Completions.ChatCompletionMessageParam => ({
|
||||
role: 'system',
|
||||
content: (() => {
|
||||
@@ -146,18 +126,16 @@ const INIT_MAIN_PROMPT = (
|
||||
const conventionGuidelines = getCommitConvention(fullGitMojiSpec);
|
||||
const descriptionGuideline = getDescriptionInstruction();
|
||||
const oneLineCommitGuideline = getOneLineCommitInstruction();
|
||||
const scopeInstruction = getScopeInstruction();
|
||||
const generalGuidelines = `Use the present tense. Lines must not be longer than 74 characters. Use ${language} for the commit message.`;
|
||||
const userInputContext = userInputCodeContext(context);
|
||||
|
||||
return `${missionStatement}\n${diffInstruction}\n${conventionGuidelines}\n${descriptionGuideline}\n${oneLineCommitGuideline}\n${scopeInstruction}\n${generalGuidelines}\n${userInputContext}`;
|
||||
return `${missionStatement}\n${diffInstruction}\n${conventionGuidelines}\n${descriptionGuideline}\n${oneLineCommitGuideline}\n${generalGuidelines}`;
|
||||
})()
|
||||
});
|
||||
|
||||
export const INIT_DIFF_PROMPT: OpenAI.Chat.Completions.ChatCompletionMessageParam =
|
||||
{
|
||||
role: 'user',
|
||||
content: `diff --git a/src/server.ts b/src/server.ts
|
||||
{
|
||||
role: 'user',
|
||||
content: `diff --git a/src/server.ts b/src/server.ts
|
||||
index ad4db42..f3b18a9 100644
|
||||
--- a/src/server.ts
|
||||
+++ b/src/server.ts
|
||||
@@ -181,54 +159,33 @@ export const INIT_DIFF_PROMPT: OpenAI.Chat.Completions.ChatCompletionMessagePara
|
||||
+app.listen(process.env.PORT || PORT, () => {
|
||||
+ console.log(\`Server listening on port \${PORT}\`);
|
||||
});`
|
||||
};
|
||||
};
|
||||
|
||||
const COMMIT_TYPES = {
|
||||
fix: '🐛',
|
||||
feat: '✨'
|
||||
} as const;
|
||||
|
||||
const generateCommitString = (
|
||||
type: keyof typeof COMMIT_TYPES,
|
||||
message: string
|
||||
): string => {
|
||||
const cleanMessage = removeConventionalCommitWord(message);
|
||||
return config.OCO_EMOJI
|
||||
? `${COMMIT_TYPES[type]} ${cleanMessage}`
|
||||
: message;
|
||||
};
|
||||
|
||||
const getConsistencyContent = (translation: ConsistencyPrompt) => {
|
||||
const fixMessage = config.OCO_OMIT_SCOPE && translation.commitFixOmitScope
|
||||
? translation.commitFixOmitScope
|
||||
const getContent = (translation: ConsistencyPrompt) => {
|
||||
const fix = config.OCO_EMOJI
|
||||
? `🐛 ${removeConventionalCommitWord(translation.commitFix)}`
|
||||
: translation.commitFix;
|
||||
|
||||
const featMessage = config.OCO_OMIT_SCOPE && translation.commitFeatOmitScope
|
||||
? translation.commitFeatOmitScope
|
||||
const feat = config.OCO_EMOJI
|
||||
? `✨ ${removeConventionalCommitWord(translation.commitFeat)}`
|
||||
: translation.commitFeat;
|
||||
|
||||
const fix = generateCommitString('fix', fixMessage);
|
||||
const feat = config.OCO_ONE_LINE_COMMIT
|
||||
? ''
|
||||
: generateCommitString('feat', featMessage);
|
||||
|
||||
const description = config.OCO_DESCRIPTION
|
||||
? translation.commitDescription
|
||||
: '';
|
||||
|
||||
return [fix, feat, description].filter(Boolean).join('\n');
|
||||
return `${fix}\n${feat}\n${description}`;
|
||||
};
|
||||
|
||||
const INIT_CONSISTENCY_PROMPT = (
|
||||
translation: ConsistencyPrompt
|
||||
): OpenAI.Chat.Completions.ChatCompletionMessageParam => ({
|
||||
role: 'assistant',
|
||||
content: getConsistencyContent(translation)
|
||||
content: getContent(translation)
|
||||
});
|
||||
|
||||
export const getMainCommitPrompt = async (
|
||||
fullGitMojiSpec: boolean,
|
||||
context: string
|
||||
fullGitMojiSpec: boolean
|
||||
): Promise<Array<OpenAI.Chat.Completions.ChatCompletionMessageParam>> => {
|
||||
switch (config.OCO_PROMPT_MODULE) {
|
||||
case '@commitlint':
|
||||
@@ -250,14 +207,14 @@ export const getMainCommitPrompt = async (
|
||||
INIT_DIFF_PROMPT,
|
||||
INIT_CONSISTENCY_PROMPT(
|
||||
commitLintConfig.consistency[
|
||||
translation.localLanguage
|
||||
translation.localLanguage
|
||||
] as ConsistencyPrompt
|
||||
)
|
||||
];
|
||||
|
||||
default:
|
||||
return [
|
||||
INIT_MAIN_PROMPT(translation.localLanguage, fullGitMojiSpec, context),
|
||||
INIT_MAIN_PROMPT(translation.localLanguage, fullGitMojiSpec),
|
||||
INIT_DIFF_PROMPT,
|
||||
INIT_CONSISTENCY_PROMPT(translation)
|
||||
];
|
||||
|
||||
@@ -6,45 +6,18 @@ import { FlowiseEngine } from '../engine/flowise';
|
||||
import { GeminiEngine } from '../engine/gemini';
|
||||
import { OllamaEngine } from '../engine/ollama';
|
||||
import { OpenAiEngine } from '../engine/openAi';
|
||||
import { MistralAiEngine } from '../engine/mistral';
|
||||
import { TestAi, TestMockType } from '../engine/testAi';
|
||||
import { GroqEngine } from '../engine/groq';
|
||||
import { MLXEngine } from '../engine/mlx';
|
||||
import { DeepseekEngine } from '../engine/deepseek';
|
||||
|
||||
export function parseCustomHeaders(headers: any): Record<string, string> {
|
||||
let parsedHeaders = {};
|
||||
|
||||
if (!headers) {
|
||||
return parsedHeaders;
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof headers === 'object' && !Array.isArray(headers)) {
|
||||
parsedHeaders = headers;
|
||||
} else {
|
||||
parsedHeaders = JSON.parse(headers);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Invalid OCO_API_CUSTOM_HEADERS format, ignoring custom headers');
|
||||
}
|
||||
|
||||
return parsedHeaders;
|
||||
}
|
||||
|
||||
export function getEngine(): AiEngine {
|
||||
const config = getConfig();
|
||||
const provider = config.OCO_AI_PROVIDER;
|
||||
|
||||
const customHeaders = parseCustomHeaders(config.OCO_API_CUSTOM_HEADERS);
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
model: config.OCO_MODEL!,
|
||||
maxTokensOutput: config.OCO_TOKENS_MAX_OUTPUT!,
|
||||
maxTokensInput: config.OCO_TOKENS_MAX_INPUT!,
|
||||
baseURL: config.OCO_API_URL!,
|
||||
apiKey: config.OCO_API_KEY!,
|
||||
customHeaders
|
||||
apiKey: config.OCO_API_KEY!
|
||||
};
|
||||
|
||||
switch (provider) {
|
||||
@@ -66,18 +39,6 @@ export function getEngine(): AiEngine {
|
||||
case OCO_AI_PROVIDER_ENUM.FLOWISE:
|
||||
return new FlowiseEngine(DEFAULT_CONFIG);
|
||||
|
||||
case OCO_AI_PROVIDER_ENUM.GROQ:
|
||||
return new GroqEngine(DEFAULT_CONFIG);
|
||||
|
||||
case OCO_AI_PROVIDER_ENUM.MISTRAL:
|
||||
return new MistralAiEngine(DEFAULT_CONFIG);
|
||||
|
||||
case OCO_AI_PROVIDER_ENUM.MLX:
|
||||
return new MLXEngine(DEFAULT_CONFIG);
|
||||
|
||||
case OCO_AI_PROVIDER_ENUM.DEEPSEEK:
|
||||
return new DeepseekEngine(DEFAULT_CONFIG);
|
||||
|
||||
default:
|
||||
return new OpenAiEngine(DEFAULT_CONFIG);
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ export const gitAdd = async ({ files }: { files: string[] }) => {
|
||||
|
||||
await execa('git', ['add', ...files]);
|
||||
|
||||
gitAddSpinner.stop(`Staged ${files.length} files`);
|
||||
gitAddSpinner.stop('Done');
|
||||
};
|
||||
|
||||
export const getDiff = async ({ files }: { files: string[] }) => {
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* Removes content wrapped in specified tags from a string
|
||||
* @param content The content string to process
|
||||
* @param tag The tag name without angle brackets (e.g., 'think' for '<think></think>')
|
||||
* @returns The content with the specified tags and their contents removed, and trimmed
|
||||
*/
|
||||
export function removeContentTags<T extends string | null | undefined>(content: T, tag: string): T {
|
||||
if (!content || typeof content !== 'string') {
|
||||
return content;
|
||||
}
|
||||
|
||||
// Dynamic implementation for other cases
|
||||
const openTag = `<${tag}>`;
|
||||
const closeTag = `</${tag}>`;
|
||||
|
||||
// Parse the content and remove tags
|
||||
let result = '';
|
||||
let skipUntil: number | null = null;
|
||||
let depth = 0;
|
||||
|
||||
for (let i = 0; i < content.length; i++) {
|
||||
// Check for opening tag
|
||||
if (content.substring(i, i + openTag.length) === openTag) {
|
||||
depth++;
|
||||
if (depth === 1) {
|
||||
skipUntil = content.indexOf(closeTag, i + openTag.length);
|
||||
i = i + openTag.length - 1; // Skip the opening tag
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Check for closing tag
|
||||
else if (content.substring(i, i + closeTag.length) === closeTag && depth > 0) {
|
||||
depth--;
|
||||
if (depth === 0) {
|
||||
i = i + closeTag.length - 1; // Skip the closing tag
|
||||
skipUntil = null;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Only add character if not inside a tag
|
||||
if (skipUntil === null) {
|
||||
result += content[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize multiple spaces/tabs into a single space (preserves newlines), then trim.
|
||||
result = result.replace(/[ \t]+/g, ' ').trim();
|
||||
|
||||
return result as unknown as T;
|
||||
}
|
||||
@@ -125,7 +125,7 @@ describe('cli flow to push git branch', () => {
|
||||
await render('git', ['add index.ts'], { cwd: gitDir });
|
||||
|
||||
const { queryByText, findByText, userEvent } = await render(
|
||||
`OCO_AI_PROVIDER='test' OCO_GITPUSH='true' node`,
|
||||
`OCO_AI_PROVIDER='test' node`,
|
||||
[resolve('./out/cli.cjs')],
|
||||
{ cwd: gitDir }
|
||||
);
|
||||
@@ -158,7 +158,7 @@ describe('cli flow to push git branch', () => {
|
||||
await render('git', ['add index.ts'], { cwd: gitDir });
|
||||
|
||||
const { findByText, userEvent } = await render(
|
||||
`OCO_AI_PROVIDER='test' OCO_GITPUSH='true' node`,
|
||||
`OCO_AI_PROVIDER='test' node`,
|
||||
[resolve('./out/cli.cjs')],
|
||||
{ cwd: gitDir }
|
||||
);
|
||||
@@ -186,7 +186,7 @@ describe('cli flow to push git branch', () => {
|
||||
await render('git', ['add index.ts'], { cwd: gitDir });
|
||||
|
||||
const { findByText, userEvent } = await render(
|
||||
`OCO_AI_PROVIDER='test' OCO_GITPUSH='true' node`,
|
||||
`OCO_AI_PROVIDER='test' node`,
|
||||
[resolve('./out/cli.cjs')],
|
||||
{ cwd: gitDir }
|
||||
);
|
||||
|
||||
@@ -9,7 +9,7 @@ it('cli flow to generate commit message for 1 new file (staged)', async () => {
|
||||
await render('echo' ,[`'console.log("Hello World");' > index.ts`], { cwd: gitDir });
|
||||
await render('git' ,['add index.ts'], { cwd: gitDir });
|
||||
|
||||
const { queryByText, findByText, userEvent } = await render(`OCO_AI_PROVIDER='test' OCO_GITPUSH='true' node`, [resolve('./out/cli.cjs')], { cwd: gitDir });
|
||||
const { queryByText, findByText, userEvent } = await render(`OCO_AI_PROVIDER='test' node`, [resolve('./out/cli.cjs')], { cwd: gitDir });
|
||||
expect(await queryByText('No files are staged')).not.toBeInTheConsole();
|
||||
expect(await queryByText('Do you want to stage all files and generate commit message?')).not.toBeInTheConsole();
|
||||
|
||||
@@ -34,7 +34,7 @@ it('cli flow to generate commit message for 1 changed file (not staged)', async
|
||||
|
||||
await render('echo' ,[`'console.log("Good night World");' >> index.ts`], { cwd: gitDir });
|
||||
|
||||
const { findByText, userEvent } = await render(`OCO_AI_PROVIDER='test' OCO_GITPUSH='true' node`, [resolve('./out/cli.cjs')], { cwd: gitDir });
|
||||
const { findByText, userEvent } = await render(`OCO_AI_PROVIDER='test' node`, [resolve('./out/cli.cjs')], { cwd: gitDir });
|
||||
|
||||
expect(await findByText('No files are staged')).toBeInTheConsole();
|
||||
expect(await findByText('Do you want to stage all files and generate commit message?')).toBeInTheConsole();
|
||||
|
||||
@@ -5,8 +5,8 @@ import { prepareEnvironment, wait } from '../utils';
|
||||
import path from 'path';
|
||||
|
||||
function getAbsolutePath(relativePath: string) {
|
||||
// Use process.cwd() which should be the project root during test execution
|
||||
return path.resolve(process.cwd(), 'test/e2e/prompt-module', relativePath);
|
||||
const scriptDir = path.dirname(__filename);
|
||||
return path.resolve(scriptDir, relativePath);
|
||||
}
|
||||
async function setupCommitlint(dir: string, ver: 9 | 18 | 19) {
|
||||
let packagePath, packageJsonPath, configPath;
|
||||
@@ -47,7 +47,7 @@ describe('cli flow to run "oco commitlint force"', () => {
|
||||
`
|
||||
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
|
||||
OCO_PROMPT_MODULE='@commitlint' \
|
||||
OCO_AI_PROVIDER='test' OCO_GITPUSH='true' \
|
||||
OCO_AI_PROVIDER='test' \
|
||||
node ${resolve('./out/cli.cjs')} commitlint force \
|
||||
`,
|
||||
[],
|
||||
@@ -83,7 +83,7 @@ describe('cli flow to run "oco commitlint force"', () => {
|
||||
`
|
||||
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
|
||||
OCO_PROMPT_MODULE='@commitlint' \
|
||||
OCO_AI_PROVIDER='test' OCO_GITPUSH='true' \
|
||||
OCO_AI_PROVIDER='test' \
|
||||
node ${resolve('./out/cli.cjs')} commitlint force \
|
||||
`,
|
||||
[],
|
||||
@@ -119,7 +119,7 @@ describe('cli flow to run "oco commitlint force"', () => {
|
||||
`
|
||||
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
|
||||
OCO_PROMPT_MODULE='@commitlint' \
|
||||
OCO_AI_PROVIDER='test' OCO_GITPUSH='true' \
|
||||
OCO_AI_PROVIDER='test' \
|
||||
node ${resolve('./out/cli.cjs')} commitlint force \
|
||||
`,
|
||||
[],
|
||||
@@ -160,7 +160,7 @@ describe('cli flow to generate commit message using @commitlint prompt-module',
|
||||
`
|
||||
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
|
||||
OCO_PROMPT_MODULE='@commitlint' \
|
||||
OCO_AI_PROVIDER='test' OCO_GITPUSH='true' \
|
||||
OCO_AI_PROVIDER='test' \
|
||||
node ${resolve('./out/cli.cjs')} commitlint force \
|
||||
`,
|
||||
[],
|
||||
@@ -175,7 +175,7 @@ describe('cli flow to generate commit message using @commitlint prompt-module',
|
||||
`
|
||||
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
|
||||
OCO_PROMPT_MODULE='@commitlint' \
|
||||
OCO_AI_PROVIDER='test' OCO_GITPUSH='true' \
|
||||
OCO_AI_PROVIDER='test' \
|
||||
node ${resolve('./out/cli.cjs')} commitlint get \
|
||||
`,
|
||||
[],
|
||||
@@ -193,7 +193,7 @@ describe('cli flow to generate commit message using @commitlint prompt-module',
|
||||
`
|
||||
OCO_TEST_MOCK_TYPE='commit-message' \
|
||||
OCO_PROMPT_MODULE='@commitlint' \
|
||||
OCO_AI_PROVIDER='test' OCO_GITPUSH='true' \
|
||||
OCO_AI_PROVIDER='test' \
|
||||
node ${resolve('./out/cli.cjs')} \
|
||||
`,
|
||||
[],
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import 'cli-testing-library/extend-expect'
|
||||
import { configure } from 'cli-testing-library'
|
||||
import { jest } from '@jest/globals';
|
||||
import 'cli-testing-library/extend-expect';
|
||||
import { configure } from 'cli-testing-library';
|
||||
|
||||
// Make Jest available globally
|
||||
global.jest = jest;
|
||||
|
||||
/**
|
||||
* Adjusted the wait time for waitFor/findByText to 2000ms, because the default 1000ms makes the test results flaky
|
||||
*/
|
||||
configure({ asyncUtilTimeout: 2000 });
|
||||
configure({ asyncUtilTimeout: 2000 })
|
||||
|
||||
@@ -106,8 +106,7 @@ describe('config', () => {
|
||||
|
||||
envConfigFile = await generateConfig('.env', {
|
||||
OCO_TOKENS_MAX_INPUT: '8192',
|
||||
OCO_ONE_LINE_COMMIT: 'false',
|
||||
OCO_OMIT_SCOPE: 'true'
|
||||
OCO_ONE_LINE_COMMIT: 'false'
|
||||
});
|
||||
|
||||
const config = getConfig({
|
||||
@@ -120,31 +119,6 @@ describe('config', () => {
|
||||
expect(config.OCO_TOKENS_MAX_OUTPUT).toEqual(500);
|
||||
expect(config.OCO_GITPUSH).toEqual(true);
|
||||
expect(config.OCO_ONE_LINE_COMMIT).toEqual(false);
|
||||
expect(config.OCO_OMIT_SCOPE).toEqual(true);
|
||||
});
|
||||
|
||||
it('should handle custom HTTP headers correctly', async () => {
|
||||
globalConfigFile = await generateConfig('.opencommit', {
|
||||
OCO_API_CUSTOM_HEADERS: '{"X-Global-Header": "global-value"}'
|
||||
});
|
||||
|
||||
envConfigFile = await generateConfig('.env', {
|
||||
OCO_API_CUSTOM_HEADERS: '{"Authorization": "Bearer token123", "X-Custom-Header": "test-value"}'
|
||||
});
|
||||
|
||||
const config = getConfig({
|
||||
globalPath: globalConfigFile.filePath,
|
||||
envPath: envConfigFile.filePath
|
||||
});
|
||||
|
||||
expect(config).not.toEqual(null);
|
||||
expect(config.OCO_API_CUSTOM_HEADERS).toEqual({"Authorization": "Bearer token123", "X-Custom-Header": "test-value"});
|
||||
|
||||
// No need to parse JSON again since it's already an object
|
||||
const parsedHeaders = config.OCO_API_CUSTOM_HEADERS;
|
||||
expect(parsedHeaders).toHaveProperty('Authorization', 'Bearer token123');
|
||||
expect(parsedHeaders).toHaveProperty('X-Custom-Header', 'test-value');
|
||||
expect(parsedHeaders).not.toHaveProperty('X-Global-Header');
|
||||
});
|
||||
|
||||
it('should handle empty local config correctly', async () => {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import { removeContentTags } from '../../src/utils/removeContentTags';
|
||||
|
||||
describe('removeContentTags', () => {
|
||||
it('should remove content wrapped in specified tags', () => {
|
||||
const content = 'This is <think>something to hide</think> visible content';
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe('This is visible content');
|
||||
});
|
||||
|
||||
it('should handle multiple tag occurrences', () => {
|
||||
const content = '<think>hidden</think> visible <think>also hidden</think> text';
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe('visible text');
|
||||
});
|
||||
|
||||
it('should handle multiline content within tags', () => {
|
||||
const content = 'Start <think>hidden\nover multiple\nlines</think> End';
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe('Start End');
|
||||
});
|
||||
|
||||
it('should return content as is when tag is not found', () => {
|
||||
const content = 'Content without any tags';
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe('Content without any tags');
|
||||
});
|
||||
|
||||
it('should work with different tag names', () => {
|
||||
const content = 'This is <custom>something to hide</custom> visible content';
|
||||
const result = removeContentTags(content, 'custom');
|
||||
expect(result).toBe('This is visible content');
|
||||
});
|
||||
|
||||
it('should handle null content', () => {
|
||||
const content = null;
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
||||
it('should handle undefined content', () => {
|
||||
const content = undefined;
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe(undefined);
|
||||
});
|
||||
|
||||
it('should trim the result', () => {
|
||||
const content = ' <think>hidden</think> visible ';
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe('visible');
|
||||
});
|
||||
|
||||
it('should handle nested tags correctly', () => {
|
||||
const content = 'Outside <think>Inside <think>Nested</think></think> End';
|
||||
const result = removeContentTags(content, 'think');
|
||||
expect(result).toBe('Outside End');
|
||||
});
|
||||
});
|
||||
@@ -3,10 +3,10 @@
|
||||
"target": "ES2020",
|
||||
"lib": ["ES6", "ES2020"],
|
||||
|
||||
"module": "NodeNext",
|
||||
"module": "CommonJS",
|
||||
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "NodeNext",
|
||||
"moduleResolution": "Node",
|
||||
|
||||
"allowJs": true,
|
||||
|
||||
|
||||
Reference in New Issue
Block a user