Compare commits

...

61 Commits

Author SHA1 Message Date
di-sukharev
eb3be62a4f 3.0.20 2024-08-19 12:34:35 +03:00
di-sukharev
58ad1880ef Merge remote-tracking branch 'origin/dev' into marcelwiegand-master 2024-08-19 12:29:55 +03:00
marcelwiegand
5ee17235cb 🐛(anthropic.ts): fix incorrect usage of 'typeof' operator for MODEL variable 2024-08-19 11:13:37 +02:00
marcelwiegand
f9c7316eb3 🐛(openAi.ts): fix incorrect usage of 'typeof' operator for MODEL variable 2024-08-19 11:13:09 +02:00
di-sukharev
dfe2730a45 build 2024-08-19 10:42:36 +03:00
GPT10
a979ba091a 3.0.19 (#384)
* fix(config.ts): move 'gpt-4o-mini' in MODEL_LIST
* docs(config.ts): update API key validation message with detailed instructions
* refactor(config.ts): simplify model validation logic to check for string type instead of MODEL_LIST

* 3.0.19
2024-08-19 10:41:26 +03:00
di-sukharev
6bbe07a9a1 build 2024-08-19 10:28:45 +03:00
di-sukharev
0156bb9dc9 3.0.19 2024-08-19 10:26:46 +03:00
di-sukharev
e27bbd0ac1 fix(config.ts): move 'gpt-4o-mini' in MODEL_LIST
docs(config.ts): update API key validation message with detailed instructions
refactor(config.ts): simplify model validation logic to check for string type instead of MODEL_LIST
2024-08-19 10:25:24 +03:00
GPT10
f3371ac1e3 3.0.18 (#382)
* 📝 (README.md): add support for custom AI models and update documentation to reflect new environment variable OCO_ AI_PROVIDER (#351)

* feat/add gemini (#349)

* fix: prompt-module/@commitlint (#336)

* docs: spelling fix (#325)

---------

Co-authored-by: tumf <y.takahara@gmail.com>
Co-authored-by: Drew Payment <drew.payment@gmail.com>
Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Kellan Stevens <kellan@kellanstevens.com>
Co-authored-by: JMN09 <jmn09@mail.aub.edu>
Co-authored-by: JMN09 <157629053+JMN09@users.noreply.github.com>
2024-08-18 14:55:33 +03:00
di-sukharev
9cc9f9d757 build 2024-08-18 14:47:25 +03:00
di-sukharev
c8d5c53db1 3.0.18 2024-08-18 14:47:23 +03:00
di-sukharev
fc4326233d Merge remote-tracking branch 'origin/master' into dev 2024-08-18 14:23:26 +03:00
XIAOTIAN LIU
07f7a05c4b support read OCO_OLLAMA_API_URL from env to OllamaAiEngine and fix bug in getting ollma model name when slash exists (#375) 2024-08-18 14:22:30 +03:00
di-sukharev
9b2e41d255 fix(package.json): add override for whatwg-url to version 13.0.0 to fix punnycode warning 2024-08-18 14:21:27 +03:00
di-sukharev
6fad862aa5 Merge remote-tracking branch 'origin/master' into dev 2024-08-18 14:04:27 +03:00
XiaomaiTX
c425878f21 feat: allow any string as model (#367)
* refactor(anthropic.ts, openAi.ts): remove model validation against predefined list to allow any string as model, simplifying configuration and improving flexibility
2024-08-18 13:47:18 +03:00
di-sukharev
1fb592afb2 Merge branch 'murex-feature/Flowise' into dev 2024-08-18 13:42:19 +03:00
di-sukharev
684f3dadfc build 2024-08-18 13:41:58 +03:00
di-sukharev
76e6070012 Merge branch 'feature/Flowise' of github.com:murex/opencommit into murex-feature/Flowise 2024-08-18 13:41:38 +03:00
di-sukharev
cb72837866 build 2024-08-18 13:36:02 +03:00
di-sukharev
2432ef9de3 Merge remote-tracking branch 'origin/master' into dev 2024-08-18 13:35:38 +03:00
JMN09
026fd1822a Merge branch 'dev' into feature/Flowise
# Conflicts:
#	out/cli.cjs
#	out/github-action.cjs
#	src/commands/config.ts
#	src/utils/engine.ts
2024-08-14 15:30:12 +03:00
JMN09
b42a52ef24 Merge branch 'master' of https://github.com/murex/opencommit into feature/Flowise 2024-08-13 16:26:25 +03:00
XYCode Kerman
10b031ab36 fix(i18n): zh_CN is wrong (#379) 2024-08-13 10:59:48 +03:00
Isaque Borges
d63b825ae5 fix(config.ts): invalid default config (#371)
* 📝 (README.md): add support for custom AI models and update documentation to reflect new environment variable OCO_ AI_PROVIDER (#351)

* Feat/add gemini (#349)

* 🐛Fix: prompt-module/@commitlint (#336)

* fix(commitlint/utils.ts): correct variable used in search for JSON block end tag

* ♻️ (commitlint/config.ts & pwd-commitlint.ts): Refactor commitlint config loading to support both CJS and ESM modules

💡 (pwd-commitlint.ts): Add detailed comments and error handling for better clarity and robustness in commitlint module loading process

*  (package.json): Add setup script for e2e tests to install dependencies for commitlint configurations
🔧 (setup.sh): Add shell script to set up commitlint configurations for e2e tests

*  (config.ts): Add support for OCO_TEST_MOCK_TYPE configuration key to define test mock type for testing purposes
📝 (config.ts): Update documentation for OCO_TEST_MOCK_TYPE configuration key in configValidators and getConfig functions
📝 (testAi.ts): Add TEST_MOCK_TYPES constant array to define supported test mock types
📝 (testAi.ts): Update generateCommitMessage function to use OCO_TEST_MOCK_TYPE from config for different test mock types
📝 (commitlint.test.ts): Add e2e test for running "oco commitlint force" with different @commitlint versions using CJS and ESM
📝 (utils.ts): Add wait function to introduce delay in milliseconds for testing purposes

*  (commitlint.test.ts): refactor setupCommitlint function to accept a version parameter for better code organization and readability
📝 (commitlint.test.ts): add test case for commitlint@9 using CJS to ensure proper functionality and compatibility
📝 (commitlint.test.ts): add test case for commitlint@18 using CJS to ensure proper functionality and compatibility
📝 (commitlint.test.ts): add test case for commitlint@19 using ESM to ensure proper functionality and compatibility

* 🔧 (commitlint.test.ts): remove unnecessary commands to create and add index.ts file before running tests

* refactor(test/e2e/prompt-module/commitlint.test.ts): remove unused import configure
style(test/e2e/prompt-module/commitlint.test.ts): add missing semicolon for consistency
test(test/e2e/prompt-module/commitlint.test.ts): add e2e tests for @commitlint prompt-module integration

*  (e2e tests): add package.json copying to setupCommitlint for version accuracy
♻️ (commitlint config): refactor commitlint.config.js to use ES module syntax
 (package.json): specify "type": "module" to support ES module syntax

* docs: spelling fix (#325)

* 3.0.17

* ♻️ (config.ts): refactor OCO_AZURE_ENDPOINT default value from empty string to undefined resolving #352 - creates invalid config file

---------

Co-authored-by: tumf <y.takahara@gmail.com>
Co-authored-by: Drew Payment <drew.payment@gmail.com>
Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Kellan Stevens <kellan@kellanstevens.com>
Co-authored-by: di-sukharev <dim.sukharev@gmail.com>
2024-08-13 10:25:26 +03:00
JMN09
b66da48106 build 2024-08-02 17:52:16 +03:00
JMN09
6f24afc600 feature(commands/configs.ts, engine/flowise.ts, utils/engine.ts): Incorporated flowise in configuration variables, added it as an AiEngine, and added it as a return value for getEngine() 2024-08-02 17:50:34 +03:00
di-sukharev
a80dcb03c4 build 2024-07-20 11:05:26 +03:00
GPT10
bebbed856f v 3.0.17 (#366) 2024-07-20 11:03:05 +03:00
di-sukharev
2d5882c257 Merge remote-tracking branch 'origin/master' into dev 2024-07-20 11:00:56 +03:00
Ying-Shan Lin
37fb140563 Update Claude Models (#362) 2024-07-20 11:00:10 +03:00
di-sukharev
aebe7e200f 3.0.17 2024-07-20 10:59:52 +03:00
di-sukharev
6f1e4bcec6 Merge remote-tracking branch 'origin/master' into dev 2024-07-20 10:58:16 +03:00
XiaomaiTX
2059549dce feat: Add all of OpenAI GPT models (#365) 2024-07-20 10:48:00 +03:00
Kellan Stevens
8361dc6838 docs: spelling fix (#325) 2024-07-04 11:08:44 +03:00
Takanori Matsumoto
73ccae9de3 🐛Fix: prompt-module/@commitlint (#336)
* fix(commitlint/utils.ts): correct variable used in search for JSON block end tag

* ♻️ (commitlint/config.ts & pwd-commitlint.ts): Refactor commitlint config loading to support both CJS and ESM modules

💡 (pwd-commitlint.ts): Add detailed comments and error handling for better clarity and robustness in commitlint module loading process

*  (package.json): Add setup script for e2e tests to install dependencies for commitlint configurations
🔧 (setup.sh): Add shell script to set up commitlint configurations for e2e tests

*  (config.ts): Add support for OCO_TEST_MOCK_TYPE configuration key to define test mock type for testing purposes
📝 (config.ts): Update documentation for OCO_TEST_MOCK_TYPE configuration key in configValidators and getConfig functions
📝 (testAi.ts): Add TEST_MOCK_TYPES constant array to define supported test mock types
📝 (testAi.ts): Update generateCommitMessage function to use OCO_TEST_MOCK_TYPE from config for different test mock types
📝 (commitlint.test.ts): Add e2e test for running "oco commitlint force" with different @commitlint versions using CJS and ESM
📝 (utils.ts): Add wait function to introduce delay in milliseconds for testing purposes

*  (commitlint.test.ts): refactor setupCommitlint function to accept a version parameter for better code organization and readability
📝 (commitlint.test.ts): add test case for commitlint@9 using CJS to ensure proper functionality and compatibility
📝 (commitlint.test.ts): add test case for commitlint@18 using CJS to ensure proper functionality and compatibility
📝 (commitlint.test.ts): add test case for commitlint@19 using ESM to ensure proper functionality and compatibility

* 🔧 (commitlint.test.ts): remove unnecessary commands to create and add index.ts file before running tests

* refactor(test/e2e/prompt-module/commitlint.test.ts): remove unused import configure
style(test/e2e/prompt-module/commitlint.test.ts): add missing semicolon for consistency
test(test/e2e/prompt-module/commitlint.test.ts): add e2e tests for @commitlint prompt-module integration

*  (e2e tests): add package.json copying to setupCommitlint for version accuracy
♻️ (commitlint config): refactor commitlint.config.js to use ES module syntax
 (package.json): specify "type": "module" to support ES module syntax
2024-07-04 11:08:08 +03:00
Drew Payment
c58e0c62a4 Feat/add gemini (#349) 2024-07-04 11:03:54 +03:00
tumf
a4b4e65011 📝 (README.md): add support for custom AI models and update documentation to reflect new environment variable OCO_ AI_PROVIDER (#351) 2024-07-04 11:03:17 +03:00
senovr
18f52772b3 Make endpoint url for Ollama configurable (#355) 2024-07-02 20:59:55 +03:00
di-sukharev
fef25a2d06 build 2024-05-25 19:23:06 +03:00
di-sukharev
bf578da16a 3.0.16 2024-05-25 19:23:04 +03:00
di-sukharev
41330d5517 Merge branch 'master' of github.com:di-sukharev/opencommit 2024-05-25 19:22:06 +03:00
GPT10
a703fde7b2 release candidate (#348)
* test:  add the first E2E test and configuration to CI (#316)

* add tests

* Add push config (#220)

* feat: add instructions and support for configuring gpt-4-turbo (#320)

* 3.0.12

* build

* feat: add 'gpt-4-turbo' to supported models in README and config validation

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

*  fix the broken E2E tests due to the addition of OCO_GITPUSH (#321)

* test(oneFile.test.ts): update test expectations to match new push prompt text

* build

* Feat: Add Claude 3 support (#318)

* 3.0.12

* build

* feat: anthropic claude 3 support

* fix: add system prompt

* fix: type check

* fix: package version

* fix: update anthropic for dependency bug fix

* feat: update build files

* feat: update version number

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

* 🐛bug fix: enable to use the new format of OpenAI's project API Key (#328)

* fix(config.ts): remove validation for OCO_OPENAI_API_KEY length to accommodate variable key lengths

* build

* ♻️ refactor(config.ts): Addition of UnitTest environment and unittest for commands/config.ts#getConfig (#330)

* feat(jest.config.ts): update jest preset for TS ESM support and ignore patterns
feat(package.json): add test:unit script with NODE_OPTIONS for ESM
refactor(src/commands/config.ts): improve dotenv usage with dynamic paths
feat(src/commands/config.ts): allow custom config and env paths in getConfig
refactor(src/commands/config.ts): streamline environment variable access

feat(test/unit): add unit tests for config handling and utility functions

- Implement unit tests for `getConfig` function to ensure correct behavior
  in various scenarios including default values, global config, and local
  env file precedence.
- Add utility function `prepareFile` for creating temporary files during
  tests, facilitating testing of file-based configurations.

* feat(e2e.yml): add unit-test job to GitHub Actions for running unit tests on pull requests

* ci(test.yml): add GitHub Actions workflow for unit and e2e tests on pull requests

* refactor(config.ts): streamline environment variable access using process.env directly
test(config.test.ts): add setup and teardown for environment variables in tests to ensure test isolation

* feat(package.json): add `test:all` script to run all tests in Docker
refactor(package.json): consolidate Docker build steps into `test:docker-build` script for DRY principle
fix(package.json): ensure `test:unit:docker` and `test:e2e:docker` scripts use the same Docker image and remove container after run
chore(test/Dockerfile): remove default CMD to allow dynamic test script execution in Docker

* refactor(config.test.ts): anonymize API keys in tests for better security practices

* feat(config.test.ts): add tests for OCO_ANTHROPIC_API_KEY configuration

* refactor(config.ts): streamline path imports and remove unused DotenvParseOutput

- Simplify path module imports by removing default import and using named imports for `pathJoin` and `pathResolve`.
- Remove unused `DotenvParseOutput` import to clean up the code.

* refactor(config.test.ts): simplify API key mock values for clarity in tests

* test(config.test.ts): remove tests for default config values and redundant cases

- Removed tests that checked for default config values when no config or env files are present, as these scenarios are now handled differently.
- Eliminated tests for empty global config and local env files to streamline testing focus on actual config loading logic.
- Removed test for prioritizing local env over global config due to changes in config loading strategy, simplifying the configuration management.

* new version

* improve OCO_AI_PROVIDER=ollama[/model name] (#327)

* 🐛 (config.ts, engine/ollama.ts, utils/engine.ts): improve Ollama AI configuration and usage
 (config.ts): add support for multiple Ollama models and allow users to specify the model in their config
 (engine/ollama.ts, utils/engine.ts): refactor code to use the specified Ollama model instead of hardcoding it

* add build results

* add support for Azure OpenAI API - continue MR 167 (#324)

*  feat(api.ts): add support for Azure OpenAI API

The Azure OpenAI API is now supported in addition to the OpenAI API. The API type can be specified in the configuration file using the OPENAI_API_TYPE key. If the key is not specified, the default value is 'openai'. The AzureOpenAIApi class is added to the utils folder to handle the Azure OpenAI API calls. The createChatCompletion method is implemented in the AzureOpenAIApi class to handle the chat completion requests. The method is called in the generateCommitMessage method in the OpenAi class if the apiType is set to 'azure'.

* 🐛 fix(AzureOpenAI.ts): fix import path for AxiosRequestConfig to avoid conflicts with openai's axios dependency

In AzureOpenAI.ts, the import path for AxiosRequestConfig was changed to avoid conflicts with openai's axios dependency, which was causing lint errors.

* 🔧 fix(AzureOpenAI.ts): import RequiredError to fix error handling and remove commented out debug code

The RequiredError class was not being imported from the openai/dist/base module, causing errors to be thrown incorrectly. This has been fixed by importing the RequiredError class. Debug code has been removed and comments have been updated to reflect the changes made.

* 🔇 chore(AzureOpenAI.ts): remove console.log statement and translate Japanese comment

The commented console.log statement was removed to improve code cleanliness.

* 🔥 refactoring(api.ts, AzureOpenAI.ts): Leverage openai npm package
🐛 fix(config.ts): API Key string validation

*  (README.md): update opencommit command to set OCO_AI_PROVIDER instead of OPENAI_API_TYPE to improve consistency and clarity in configuration
♻️ (config.ts): update OCO_AI_PROVIDER enum in configValidators to include 'azure' and remove unnecessary conditionals to improve maintainability and extensibility
⬆️ (config.ts): add OCO_AZURE_API_VERSION to ConfigType and getConfig() to support new azure api version configuration
♻️ (engine/ollama.ts): add space between temperature and top_p properties to improve readability
♻️ (engine/openAi.ts): refactor OpenAi class to improve readability and maintainability by extracting configuration logic into separate switch statement
🔧 (generateCommitMessageFromGitDiff.ts): refactor MAX_TOKENS_INPUT and MAX_TOKENS_OUTPUT lines to improve readability
🔧 (generateCommitMessageFromGitDiff.ts): refactor generateCommitMessageByDiff and getMessagesPromisesByChangesInFile functions to use destructuring and improve readability
♻️ (generateCommitMessageFromGitDiff.ts): refactor getCommitMsgsPromisesFromFileDiffs function to use destructuring and improve readability
📝 (modules/commitlint/config.ts): add missing types to function parameters and improve readability by removing unnecessary comments and whitespace
📝 (modules/commitlint/utils.ts): fix indentation and add missing types to function parameters
📝 (prompts.ts): update INIT_MAIN_PROMPT description to include clarification on the use of present tense and line length
📝 (version.ts): fix import statements and add missing types to function parameters

*  (package.json): add @azure/openai dependency to support integration with Azure AI services
🔧 (config.ts): change CONFIG_KEYS.OCO_AZURE_API_VERSION to CONFIG_KEYS.OCO_AZURE_ENDPOINT to improve semantics and allow configuration of Azure endpoint URL
♻️ (config.ts): refactor configValidators to use OCO_AZURE_ENDPOINT instead of OCO_AZURE_API_VERSION and update validation message for OCO_AZURE_ENDPOINT
 (config.ts): add OCO_AZURE_ENDPOINT to getConfig function to retrieve Azure endpoint configuration from environment variables
 (azure.ts): introduce a new file azure.ts to implement Azure AI engine
 (azure.ts): implement generateCommitMessage function in Azure AI engine
 (prompts.ts): add a new line to INIT_MAIN_PROMPT to mention that changes within a single file should be described with a single commit message
♻️ (engine.ts): refactor getEngine function to add support for 'azure' as the AI provider and return the azure engine

* 📝 (prompts.ts): remove unnecessary information about crafting a concise commit message with a one single message for OCO_ONE_LINE_COMMIT configuration

* 3.0.14 (#333)

* test:  add the first E2E test and configuration to CI (#316)

* add tests

* Add push config (#220)

* feat: add instructions and support for configuring gpt-4-turbo (#320)

* 3.0.12

* build

* feat: add 'gpt-4-turbo' to supported models in README and config validation

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

*  fix the broken E2E tests due to the addition of OCO_GITPUSH (#321)

* test(oneFile.test.ts): update test expectations to match new push prompt text

* build

* Feat: Add Claude 3 support (#318)

* 3.0.12

* build

* feat: anthropic claude 3 support

* fix: add system prompt

* fix: type check

* fix: package version

* fix: update anthropic for dependency bug fix

* feat: update build files

* feat: update version number

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

* 🐛bug fix: enable to use the new format of OpenAI's project API Key (#328)

* fix(config.ts): remove validation for OCO_OPENAI_API_KEY length to accommodate variable key lengths

* build

* ♻️ refactor(config.ts): Addition of UnitTest environment and unittest for commands/config.ts#getConfig (#330)

* feat(jest.config.ts): update jest preset for TS ESM support and ignore patterns
feat(package.json): add test:unit script with NODE_OPTIONS for ESM
refactor(src/commands/config.ts): improve dotenv usage with dynamic paths
feat(src/commands/config.ts): allow custom config and env paths in getConfig
refactor(src/commands/config.ts): streamline environment variable access

feat(test/unit): add unit tests for config handling and utility functions

- Implement unit tests for `getConfig` function to ensure correct behavior
  in various scenarios including default values, global config, and local
  env file precedence.
- Add utility function `prepareFile` for creating temporary files during
  tests, facilitating testing of file-based configurations.

* feat(e2e.yml): add unit-test job to GitHub Actions for running unit tests on pull requests

* ci(test.yml): add GitHub Actions workflow for unit and e2e tests on pull requests

* refactor(config.ts): streamline environment variable access using process.env directly
test(config.test.ts): add setup and teardown for environment variables in tests to ensure test isolation

* feat(package.json): add `test:all` script to run all tests in Docker
refactor(package.json): consolidate Docker build steps into `test:docker-build` script for DRY principle
fix(package.json): ensure `test:unit:docker` and `test:e2e:docker` scripts use the same Docker image and remove container after run
chore(test/Dockerfile): remove default CMD to allow dynamic test script execution in Docker

* refactor(config.test.ts): anonymize API keys in tests for better security practices

* feat(config.test.ts): add tests for OCO_ANTHROPIC_API_KEY configuration

* refactor(config.ts): streamline path imports and remove unused DotenvParseOutput

- Simplify path module imports by removing default import and using named imports for `pathJoin` and `pathResolve`.
- Remove unused `DotenvParseOutput` import to clean up the code.

* refactor(config.test.ts): simplify API key mock values for clarity in tests

* test(config.test.ts): remove tests for default config values and redundant cases

- Removed tests that checked for default config values when no config or env files are present, as these scenarios are now handled differently.
- Eliminated tests for empty global config and local env files to streamline testing focus on actual config loading logic.
- Removed test for prioritizing local env over global config due to changes in config loading strategy, simplifying the configuration management.

* new version

---------

Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Moret84 <aurelienrivet@hotmail.fr>
Co-authored-by: yowatari <4982161+YOwatari@users.noreply.github.com>
Co-authored-by: metavind <94786679+metavind@users.noreply.github.com>

* 3.0.15

* build

* 🐛 (prepare-commit-msg-hook.ts): improve error message to cover missing OCO_ANTHROPIC_API_KEY and OCO_AZURE_API_KEY in addition to OCO_OPENAI_API_KEY

* 🐛 (azure.ts): fix check for OCO_AI_PROVIDER to properly assign provider variable
🐛 (azure.ts): initialize OpenAIClient only if provider is 'azure'
🔧 (Dockerfile): rearrange instructions to optimize caching by copying package.json and package-lock.json first before running npm ci and copying the rest of the files
🔧 (e2e/noChanges.test.ts): remove unnecessary line break
🔧 (e2e/oneFile.test.ts): remove unnecessary line break

---------

Co-authored-by: Takuya Ono <takuya-o@users.osdn.me>
Co-authored-by: GPT10 <57486732+di-sukharev@users.noreply.github.com>
Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Moret84 <aurelienrivet@hotmail.fr>
Co-authored-by: yowatari <4982161+YOwatari@users.noreply.github.com>
Co-authored-by: metavind <94786679+metavind@users.noreply.github.com>
Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

* feat(cli.ts, commit.ts): add `--yes` flag to skip commit confirmation prompt (#341)

docs(README.md): document the `--yes` flag usage in README for user guidance

---------

Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Moret84 <aurelienrivet@hotmail.fr>
Co-authored-by: yowatari <4982161+YOwatari@users.noreply.github.com>
Co-authored-by: metavind <94786679+metavind@users.noreply.github.com>
Co-authored-by: tumf <y.takahara@gmail.com>
Co-authored-by: Jakub Rosa <jakub.rosa.95@gmail.com>
Co-authored-by: Takuya Ono <takuya-o@users.osdn.me>
Co-authored-by: Ignacio Lago <ignacio@ignaciolago.com>
2024-05-25 19:21:50 +03:00
di-sukharev
c5ee5cd8df Merge remote-tracking branch 'origin/dev' 2024-05-25 19:14:41 +03:00
Ignacio Lago
312540456a feat(cli.ts, commit.ts): add --yes flag to skip commit confirmation prompt (#341)
docs(README.md): document the `--yes` flag usage in README for user guidance
2024-05-23 10:56:35 +03:00
yowatari
7ddbaf477a feat: add instructions and support for configuring gpt-4o (#340)
* feat(config.ts): add 'gpt-4o' to supported model list for enhanced model options
docs(config.ts): update error message to include 'gpt-4o' in the list of supported models

* docs(README.md): update OCO_MODEL options to include 'gpt-4o' model
2024-05-14 14:16:21 +03:00
Kai Xu
9a0f412fff fix(config.ts): add optional config parameter to [CONFIG_KEYS.OCO_ MODEL] validator to allow for dynamic model selection based on configuration (#337)
feat(engine/ollama.ts): integrate with config command to load OCO_MODEL from configuration and use it as the default AI engine model
2024-05-12 15:56:04 +03:00
Kotaro Nishigori
7cd3ef09cb Update README.md (#335) 2024-05-09 11:23:54 +03:00
Jakub Rosa
f814c6b89d add support for Azure OpenAI API - continue MR 167 (#324)
*  feat(api.ts): add support for Azure OpenAI API

The Azure OpenAI API is now supported in addition to the OpenAI API. The API type can be specified in the configuration file using the OPENAI_API_TYPE key. If the key is not specified, the default value is 'openai'. The AzureOpenAIApi class is added to the utils folder to handle the Azure OpenAI API calls. The createChatCompletion method is implemented in the AzureOpenAIApi class to handle the chat completion requests. The method is called in the generateCommitMessage method in the OpenAi class if the apiType is set to 'azure'.

* 🐛 fix(AzureOpenAI.ts): fix import path for AxiosRequestConfig to avoid conflicts with openai's axios dependency

In AzureOpenAI.ts, the import path for AxiosRequestConfig was changed to avoid conflicts with openai's axios dependency, which was causing lint errors.

* 🔧 fix(AzureOpenAI.ts): import RequiredError to fix error handling and remove commented out debug code

The RequiredError class was not being imported from the openai/dist/base module, causing errors to be thrown incorrectly. This has been fixed by importing the RequiredError class. Debug code has been removed and comments have been updated to reflect the changes made.

* 🔇 chore(AzureOpenAI.ts): remove console.log statement and translate Japanese comment

The commented console.log statement was removed to improve code cleanliness.

* 🔥 refactoring(api.ts, AzureOpenAI.ts): Leverage openai npm package
🐛 fix(config.ts): API Key string validation

*  (README.md): update opencommit command to set OCO_AI_PROVIDER instead of OPENAI_API_TYPE to improve consistency and clarity in configuration
♻️ (config.ts): update OCO_AI_PROVIDER enum in configValidators to include 'azure' and remove unnecessary conditionals to improve maintainability and extensibility
⬆️ (config.ts): add OCO_AZURE_API_VERSION to ConfigType and getConfig() to support new azure api version configuration
♻️ (engine/ollama.ts): add space between temperature and top_p properties to improve readability
♻️ (engine/openAi.ts): refactor OpenAi class to improve readability and maintainability by extracting configuration logic into separate switch statement
🔧 (generateCommitMessageFromGitDiff.ts): refactor MAX_TOKENS_INPUT and MAX_TOKENS_OUTPUT lines to improve readability
🔧 (generateCommitMessageFromGitDiff.ts): refactor generateCommitMessageByDiff and getMessagesPromisesByChangesInFile functions to use destructuring and improve readability
♻️ (generateCommitMessageFromGitDiff.ts): refactor getCommitMsgsPromisesFromFileDiffs function to use destructuring and improve readability
📝 (modules/commitlint/config.ts): add missing types to function parameters and improve readability by removing unnecessary comments and whitespace
📝 (modules/commitlint/utils.ts): fix indentation and add missing types to function parameters
📝 (prompts.ts): update INIT_MAIN_PROMPT description to include clarification on the use of present tense and line length
📝 (version.ts): fix import statements and add missing types to function parameters

*  (package.json): add @azure/openai dependency to support integration with Azure AI services
🔧 (config.ts): change CONFIG_KEYS.OCO_AZURE_API_VERSION to CONFIG_KEYS.OCO_AZURE_ENDPOINT to improve semantics and allow configuration of Azure endpoint URL
♻️ (config.ts): refactor configValidators to use OCO_AZURE_ENDPOINT instead of OCO_AZURE_API_VERSION and update validation message for OCO_AZURE_ENDPOINT
 (config.ts): add OCO_AZURE_ENDPOINT to getConfig function to retrieve Azure endpoint configuration from environment variables
 (azure.ts): introduce a new file azure.ts to implement Azure AI engine
 (azure.ts): implement generateCommitMessage function in Azure AI engine
 (prompts.ts): add a new line to INIT_MAIN_PROMPT to mention that changes within a single file should be described with a single commit message
♻️ (engine.ts): refactor getEngine function to add support for 'azure' as the AI provider and return the azure engine

* 📝 (prompts.ts): remove unnecessary information about crafting a concise commit message with a one single message for OCO_ONE_LINE_COMMIT configuration

* 3.0.14 (#333)

* test:  add the first E2E test and configuration to CI (#316)

* add tests

* Add push config (#220)

* feat: add instructions and support for configuring gpt-4-turbo (#320)

* 3.0.12

* build

* feat: add 'gpt-4-turbo' to supported models in README and config validation

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

*  fix the broken E2E tests due to the addition of OCO_GITPUSH (#321)

* test(oneFile.test.ts): update test expectations to match new push prompt text

* build

* Feat: Add Claude 3 support (#318)

* 3.0.12

* build

* feat: anthropic claude 3 support

* fix: add system prompt

* fix: type check

* fix: package version

* fix: update anthropic for dependency bug fix

* feat: update build files

* feat: update version number

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>

* 🐛bug fix: enable to use the new format of OpenAI's project API Key (#328)

* fix(config.ts): remove validation for OCO_OPENAI_API_KEY length to accommodate variable key lengths

* build

* ♻️ refactor(config.ts): Addition of UnitTest environment and unittest for commands/config.ts#getConfig (#330)

* feat(jest.config.ts): update jest preset for TS ESM support and ignore patterns
feat(package.json): add test:unit script with NODE_OPTIONS for ESM
refactor(src/commands/config.ts): improve dotenv usage with dynamic paths
feat(src/commands/config.ts): allow custom config and env paths in getConfig
refactor(src/commands/config.ts): streamline environment variable access

feat(test/unit): add unit tests for config handling and utility functions

- Implement unit tests for `getConfig` function to ensure correct behavior
  in various scenarios including default values, global config, and local
  env file precedence.
- Add utility function `prepareFile` for creating temporary files during
  tests, facilitating testing of file-based configurations.

* feat(e2e.yml): add unit-test job to GitHub Actions for running unit tests on pull requests

* ci(test.yml): add GitHub Actions workflow for unit and e2e tests on pull requests

* refactor(config.ts): streamline environment variable access using process.env directly
test(config.test.ts): add setup and teardown for environment variables in tests to ensure test isolation

* feat(package.json): add `test:all` script to run all tests in Docker
refactor(package.json): consolidate Docker build steps into `test:docker-build` script for DRY principle
fix(package.json): ensure `test:unit:docker` and `test:e2e:docker` scripts use the same Docker image and remove container after run
chore(test/Dockerfile): remove default CMD to allow dynamic test script execution in Docker

* refactor(config.test.ts): anonymize API keys in tests for better security practices

* feat(config.test.ts): add tests for OCO_ANTHROPIC_API_KEY configuration

* refactor(config.ts): streamline path imports and remove unused DotenvParseOutput

- Simplify path module imports by removing default import and using named imports for `pathJoin` and `pathResolve`.
- Remove unused `DotenvParseOutput` import to clean up the code.

* refactor(config.test.ts): simplify API key mock values for clarity in tests

* test(config.test.ts): remove tests for default config values and redundant cases

- Removed tests that checked for default config values when no config or env files are present, as these scenarios are now handled differently.
- Eliminated tests for empty global config and local env files to streamline testing focus on actual config loading logic.
- Removed test for prioritizing local env over global config due to changes in config loading strategy, simplifying the configuration management.

* new version

---------

Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Moret84 <aurelienrivet@hotmail.fr>
Co-authored-by: yowatari <4982161+YOwatari@users.noreply.github.com>
Co-authored-by: metavind <94786679+metavind@users.noreply.github.com>

* 3.0.15

* build

* 🐛 (prepare-commit-msg-hook.ts): improve error message to cover missing OCO_ANTHROPIC_API_KEY and OCO_AZURE_API_KEY in addition to OCO_OPENAI_API_KEY

* 🐛 (azure.ts): fix check for OCO_AI_PROVIDER to properly assign provider variable
🐛 (azure.ts): initialize OpenAIClient only if provider is 'azure'
🔧 (Dockerfile): rearrange instructions to optimize caching by copying package.json and package-lock.json first before running npm ci and copying the rest of the files
🔧 (e2e/noChanges.test.ts): remove unnecessary line break
🔧 (e2e/oneFile.test.ts): remove unnecessary line break

---------

Co-authored-by: Takuya Ono <takuya-o@users.osdn.me>
Co-authored-by: GPT10 <57486732+di-sukharev@users.noreply.github.com>
Co-authored-by: Takanori Matsumoto <matscube@gmail.com>
Co-authored-by: Moret84 <aurelienrivet@hotmail.fr>
Co-authored-by: yowatari <4982161+YOwatari@users.noreply.github.com>
Co-authored-by: metavind <94786679+metavind@users.noreply.github.com>
Co-authored-by: di-sukharev <dim.sukharev@gmail.com>
2024-05-09 11:23:00 +03:00
tumf
74024a4997 improve OCO_AI_PROVIDER=ollama[/model name] (#327)
* 🐛 (config.ts, engine/ollama.ts, utils/engine.ts): improve Ollama AI configuration and usage
 (config.ts): add support for multiple Ollama models and allow users to specify the model in their config
 (engine/ollama.ts, utils/engine.ts): refactor code to use the specified Ollama model instead of hardcoding it

* add build results
2024-05-07 10:51:24 +03:00
di-sukharev
cb7f5dd44d build 2024-05-05 19:12:25 +03:00
di-sukharev
058bad95cd new version 2024-05-05 19:04:19 +03:00
di-sukharev
7469633e3d Merge remote-tracking branch 'origin/master' into dev 2024-05-05 19:03:02 +03:00
Takanori Matsumoto
278e4cb4c2 ♻️ refactor(config.ts): Addition of UnitTest environment and unittest for commands/config.ts#getConfig (#330)
* feat(jest.config.ts): update jest preset for TS ESM support and ignore patterns
feat(package.json): add test:unit script with NODE_OPTIONS for ESM
refactor(src/commands/config.ts): improve dotenv usage with dynamic paths
feat(src/commands/config.ts): allow custom config and env paths in getConfig
refactor(src/commands/config.ts): streamline environment variable access

feat(test/unit): add unit tests for config handling and utility functions

- Implement unit tests for `getConfig` function to ensure correct behavior
  in various scenarios including default values, global config, and local
  env file precedence.
- Add utility function `prepareFile` for creating temporary files during
  tests, facilitating testing of file-based configurations.

* feat(e2e.yml): add unit-test job to GitHub Actions for running unit tests on pull requests

* ci(test.yml): add GitHub Actions workflow for unit and e2e tests on pull requests

* refactor(config.ts): streamline environment variable access using process.env directly
test(config.test.ts): add setup and teardown for environment variables in tests to ensure test isolation

* feat(package.json): add `test:all` script to run all tests in Docker
refactor(package.json): consolidate Docker build steps into `test:docker-build` script for DRY principle
fix(package.json): ensure `test:unit:docker` and `test:e2e:docker` scripts use the same Docker image and remove container after run
chore(test/Dockerfile): remove default CMD to allow dynamic test script execution in Docker

* refactor(config.test.ts): anonymize API keys in tests for better security practices

* feat(config.test.ts): add tests for OCO_ANTHROPIC_API_KEY configuration

* refactor(config.ts): streamline path imports and remove unused DotenvParseOutput

- Simplify path module imports by removing default import and using named imports for `pathJoin` and `pathResolve`.
- Remove unused `DotenvParseOutput` import to clean up the code.

* refactor(config.test.ts): simplify API key mock values for clarity in tests

* test(config.test.ts): remove tests for default config values and redundant cases

- Removed tests that checked for default config values when no config or env files are present, as these scenarios are now handled differently.
- Eliminated tests for empty global config and local env files to streamline testing focus on actual config loading logic.
- Removed test for prioritizing local env over global config due to changes in config loading strategy, simplifying the configuration management.
2024-05-05 18:46:15 +03:00
Takanori Matsumoto
e19305dee2 🐛bug fix: enable to use the new format of OpenAI's project API Key (#328)
* fix(config.ts): remove validation for OCO_OPENAI_API_KEY length to accommodate variable key lengths

* build
2024-05-02 12:07:21 +03:00
metavind
673eee209d Feat: Add Claude 3 support (#318)
* 3.0.12

* build

* feat: anthropic claude 3 support

* fix: add system prompt

* fix: type check

* fix: package version

* fix: update anthropic for dependency bug fix

* feat: update build files

* feat: update version number

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>
2024-04-14 13:20:12 +08:00
Takanori Matsumoto
91399a0c68 fix the broken E2E tests due to the addition of OCO_GITPUSH (#321)
* test(oneFile.test.ts): update test expectations to match new push prompt text

* build
2024-04-13 20:42:32 +08:00
yowatari
a4480893cb feat: add instructions and support for configuring gpt-4-turbo (#320)
* 3.0.12

* build

* feat: add 'gpt-4-turbo' to supported models in README and config validation

---------

Co-authored-by: di-sukharev <dim.sukharev@gmail.com>
2024-04-12 11:55:41 +08:00
Moret84
c410486e30 Add push config (#220) 2024-03-29 10:57:20 +08:00
Takanori Matsumoto
5cda8b1b03 test: add the first E2E test and configuration to CI (#316)
* add tests
2024-03-25 12:01:05 +08:00
44 changed files with 21906 additions and 3650 deletions

View File

@@ -58,7 +58,7 @@ git add <files...>
oco
```
Link to the GitMoji specification: https://gitmoji.dev/
### Running locally with Ollama
You can also run it with local model through ollama:
@@ -71,12 +71,29 @@ git add <files...>
OCO_AI_PROVIDER='ollama' opencommit
```
If you want to use a model other than mistral, you can do so by setting the `OCO_AI_PROVIDER` environment variable as follows:
```sh
OCO_AI_PROVIDER='ollama/llama3:8b' opencommit
```
if you have ollama that is set up in docker/ on another machine with GPUs (not locally), you can change the default endpoint url.
You can do so by setting the `OCO_OLLAMA_API_URL` environment variable as follows:
```sh
OCO_OLLAMA_API_URL='http://192.168.1.10:11434/api/chat' opencommit
```
where 192.168.1.10 is example of endpoint URL, where you have ollama set up.
### Flags
There are multiple optional flags that can be used with the `oco` command:
#### Use Full GitMoji Specification
Link to the GitMoji specification: https://gitmoji.dev/
This flag can only be used if the `OCO_EMOJI` configuration item is set to `true`. This flag allows users to use all emojis in the GitMoji specification, By default, the GitMoji full specification is set to `false`, which only includes 10 emojis (🐛✨📝🚀✅♻️⬆️🔧🌐💡).
This is due to limit the number of tokens sent in each request. However, if you would like to use the full GitMoji specification, you can use the `--fgm` flag.
@@ -84,6 +101,14 @@ This is due to limit the number of tokens sent in each request. However, if you
oco --fgm
```
#### Skip Commit Confirmation
This flag allows users to automatically commit the changes without having to manually confirm the commit message. This is useful for users who want to streamline the commit process and avoid additional steps. To use this flag, you can run the following command:
```
oco --yes
```
## Configuration
### Local per repo configuration
@@ -97,11 +122,12 @@ OCO_TOKENS_MAX_OUTPUT=<max response tokens (default: 500)>
OCO_OPENAI_BASE_PATH=<may be used to set proxy path to OpenAI api>
OCO_DESCRIPTION=<postface a message with ~3 sentences description of the changes>
OCO_EMOJI=<boolean, add GitMoji>
OCO_MODEL=<either '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'>
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'>
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>
OCO_ONE_LINE_COMMIT=<one line commit message, default: false>
OCO_AI_PROVIDER=<anthropic, azure, ollama or ollama/model default ollama model: mistral>
```
### Global config for all repos
@@ -111,7 +137,7 @@ Local config still has more priority than Global config, but you may set `OCO_MO
Simply set any of the variables above like this:
```sh
oco config set OCO_MODEL=gpt-4
oco config set OCO_MODEL=gpt-4o
```
Configure [GitMoji](https://gitmoji.dev/) to preface a message.
@@ -128,7 +154,7 @@ oco config set OCO_EMOJI=false
### Switch to GPT-4 or other models
By default, OpenCommit uses `gpt-3.5-turbo` model.
By default, OpenCommit uses `gpt-4o` model.
You may switch to GPT-4 which performs better, but costs ~x15 times more 🤠
@@ -139,16 +165,22 @@ oco config set OCO_MODEL=gpt-4
or for as a cheaper option:
```sh
oco config set OCO_MODEL=gpt-3.5-turbo
oco config set OCO_MODEL=gpt-4o-mini
```
or for GPT-4 Turbo (Preview) which is more capable, has knowledge of world events up to April 2023, a 128k context window and 2-3x cheaper vs GPT-4:
### Switch to Azure OpenAI
By default OpenCommit uses [OpenAI](https://openai.com).
You could switch to [Azure OpenAI Service](https://learn.microsoft.com/azure/cognitive-services/openai/)🚀
```sh
oco config set OCO_MODEL=gpt-4-0125-preview
opencommit config set OCO_AI_PROVIDER=azure
```
Make sure that you spell it `gpt-4` (lowercase) and that you have API access to the 4th model. Even if you have ChatGPT+, that doesn't necessarily mean that you have API access to GPT-4.
Of course need to set 'OPENAI_API_KEY'. And also need to set the
'OPENAI_BASE_PATH' for the endpoint and set the deployment name to
'model'.
### Locale configuration
@@ -174,7 +206,7 @@ All available languages are currently listed in the [i18n](https://github.com/di
Pushing to git is on by default but if you would like to turn it off just use:
```sh
oc config set OCO_GITPUSH=false
oco config set OCO_GITPUSH=false
```
### Switch to `@commitlint`
@@ -191,7 +223,7 @@ Replace `<module>` with either `conventional-commit` or `@commitlint`.
#### Example:
To switch to using th` '@commitlint` prompt module, run:
To switch to using the `'@commitlint` prompt module, run:
```sh
oco config set OCO_PROMPT_MODULE=@commitlint
@@ -359,7 +391,7 @@ jobs:
OCO_OPENAI_BASE_PATH: ''
OCO_DESCRIPTION: false
OCO_EMOJI: false
OCO_MODEL: gpt-3.5-turbo
OCO_MODEL: gpt-4o
OCO_LANGUAGE: en
OCO_PROMPT_MODULE: conventional-commit
```

0
example.txt Normal file
View File

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

170
package-lock.json generated
View File

@@ -1,20 +1,22 @@
{
"name": "opencommit",
"version": "3.0.15",
"version": "3.0.20",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opencommit",
"version": "3.0.15",
"version": "3.0.20",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/exec": "^1.1.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",
"@octokit/webhooks-schemas": "^6.11.0",
"@octokit/webhooks-types": "^6.11.0",
"ai": "^2.2.14",
@@ -137,6 +139,126 @@
"undici-types": "~5.26.4"
}
},
"node_modules/@azure-rest/core-client": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz",
"integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.3.0",
"@azure/core-rest-pipeline": "^1.5.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/abort-controller": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz",
"integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-auth": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.7.2.tgz",
"integrity": "sha512-Igm/S3fDYmnMq1uKS38Ae1/m37B3zigdlZw+kocwEhh5GjyKjPrXKO2J6rzpC1wAxrNil/jX9BJRqBshyjnF3g==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-util": "^1.1.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-rest-pipeline": {
"version": "1.15.2",
"resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.15.2.tgz",
"integrity": "sha512-BmWfpjc/QXc2ipHOh6LbUzp3ONCaa6xzIssTU0DwH9bbYNXJlGUL6tujx5TrbVd/QQknmS+vlQJGrCq2oL1gZA==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.4.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.3.0",
"@azure/logger": "^1.0.0",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-sse": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.2.tgz",
"integrity": "sha512-yf+pFIu8yCzXu9RbH2+8kp9vITIKJLHgkLgFNA6hxiDHK3fxeP596cHUj4c8Cm8JlooaUnYdHmF84KCZt3jbmw==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-tracing": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.1.2.tgz",
"integrity": "sha512-dawW9ifvWAWmUm9/h+/UQ2jrdvjCJ7VJEuCJ6XVNudzcOwm53BFZH4Q845vjfgoUAM8ZxokvVNxNxAITc502YA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-util": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.9.0.tgz",
"integrity": "sha512-AfalUQ1ZppaKuxPPMsFEUdX6GZPB3d9paR9d/TTL7Ow2De8cJaC7ibi7kWVlFAVPCYo31OcnGymc0R89DX8Oaw==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/logger": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.2.tgz",
"integrity": "sha512-l170uE7bsKpIU6B/giRc9i4NI0Mj+tANMMMxf7Zi/5cKzEqPayP7+X1WPrG7e+91JgY8N+7K7nF2WOi7iVhXvg==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/openai": {
"version": "1.0.0-beta.12",
"resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.12.tgz",
"integrity": "sha512-qKblxr6oVa8GsyNzY+/Ub9VmEsPYKhBrUrPaNEQiM+qrxnBPVm9kaeqGFFb/U78Q2zOabmhF9ctYt3xBW0nWnQ==",
"dependencies": {
"@azure-rest/core-client": "^1.1.7",
"@azure/core-auth": "^1.4.0",
"@azure/core-rest-pipeline": "^1.13.0",
"@azure/core-sse": "^2.0.0",
"@azure/core-util": "^1.4.0",
"@azure/logger": "^1.0.3",
"tslib": "^2.4.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@babel/code-frame": {
"version": "7.24.2",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.2.tgz",
@@ -930,6 +1052,14 @@
"node": ">=14"
}
},
"node_modules/@google/generative-ai": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.11.4.tgz",
"integrity": "sha512-hlw+E9Prv9aUIQISRnLSXi4rukFqKe5WhxPvzBccTvIvXjw2BHMFOJWSC/Gq7WE0W+L/qRHGmYxopmx9qjrB9w==",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@humanwhocodes/config-array": {
"version": "0.11.14",
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz",
@@ -2349,6 +2479,17 @@
"node": ">=0.4.0"
}
},
"node_modules/agent-base": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
"integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==",
"dependencies": {
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/agentkeepalive": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz",
@@ -3285,7 +3426,6 @@
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"dev": true,
"dependencies": {
"ms": "2.1.2"
},
@@ -4742,6 +4882,30 @@
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true
},
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
"dependencies": {
"agent-base": "^7.1.0",
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.4.tgz",
"integrity": "sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==",
"dependencies": {
"agent-base": "^7.0.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/human-signals": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-4.3.1.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "opencommit",
"version": "3.0.15",
"version": "3.0.20",
"description": "Auto-generate impressive commits in 1 second. Killing lame commits with AI 🤯🔫",
"keywords": [
"git",
@@ -43,16 +43,20 @@
"start": "node ./out/cli.cjs",
"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": "rimraf out && node esbuild.config.js",
"build:push": "npm run build && git add . && git commit -m 'build' && git push",
"deploy": "npm version patch && npm run build:push && git push --tags && npm publish --tag latest",
"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",
"test:all": "npm run test:unit:docker && npm run test:e2e:docker",
"test:docker-build": "docker build -t oco-test -f test/Dockerfile .",
"test:unit": "NODE_OPTIONS=--experimental-vm-modules jest test/unit",
"test:unit:docker": "npm run test:docker-build && DOCKER_CONTENT_TRUST=0 docker run --rm oco-test npm run test:unit",
"test:e2e": "jest test/e2e",
"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"
},
"devDependencies": {
@@ -77,9 +81,11 @@
"@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1",
"@actions/github": "^5.1.1",
"@azure/openai": "^1.0.0-beta.12",
"@anthropic-ai/sdk": "^0.19.2",
"@clack/prompts": "^0.6.1",
"@dqbd/tiktoken": "^1.0.2",
"@google/generative-ai": "^0.11.4",
"@octokit/webhooks-schemas": "^6.11.0",
"@octokit/webhooks-types": "^6.11.0",
"ai": "^2.2.14",
@@ -92,5 +98,8 @@
"ini": "^3.0.1",
"inquirer": "^9.1.4",
"openai": "^3.2.1"
},
"overrides": {
"whatwg-url": "13.0.0"
}
}

View File

@@ -18,7 +18,13 @@ cli(
name: 'opencommit',
commands: [configCommand, hookCommand, commitlintConfigCommand],
flags: {
fgm: Boolean
fgm: Boolean,
yes: {
type: Boolean,
alias: 'y',
description: 'Skip commit confirmation prompt',
default: false
}
},
ignoreArgv: (type) => type === 'unknown-flag' || type === 'argument',
help: { description: packageJSON.description }
@@ -29,7 +35,7 @@ cli(
if (await isHookCalled()) {
prepareCommitMessageHook();
} else {
commit(extraArgs, false, flags.fgm);
commit(extraArgs, false, flags.fgm, flags.yes);
}
},
extraArgs

View File

@@ -41,7 +41,8 @@ const checkMessageTemplate = (extraArgs: string[]): string | false => {
const generateCommitMessageFromGitDiff = async (
diff: string,
extraArgs: string[],
fullGitMojiSpec: boolean
fullGitMojiSpec: boolean,
skipCommitConfirmation: boolean
): Promise<void> => {
await assertGitRepo();
const commitSpinner = spinner();
@@ -76,7 +77,7 @@ ${commitMessage}
${chalk.grey('——————————————————')}`
);
const isCommitConfirmedByUser = await confirm({
const isCommitConfirmedByUser = skipCommitConfirmation || await confirm({
message: 'Confirm the commit message?'
});
@@ -154,6 +155,18 @@ ${chalk.grey('——————————————————')}`
} else outro(`${chalk.gray('✖')} process cancelled`);
}
}
if (!isCommitConfirmedByUser && !isCancel(isCommitConfirmedByUser)) {
const regenerateMessage = await confirm({
message: 'Do you want to regenerate the message ?'
});
if (regenerateMessage && !isCancel(isCommitConfirmedByUser)) {
await generateCommitMessageFromGitDiff(
diff,
extraArgs,
fullGitMojiSpec
)
}
}
} catch (error) {
commitSpinner.stop('📝 Commit message generated');
@@ -166,7 +179,8 @@ ${chalk.grey('——————————————————')}`
export async function commit(
extraArgs: string[] = [],
isStageAllFlag: Boolean = false,
fullGitMojiSpec: boolean = false
fullGitMojiSpec: boolean = false,
skipCommitConfirmation: boolean = false
) {
if (isStageAllFlag) {
const changedFiles = await getChangedFiles();
@@ -238,7 +252,8 @@ export async function commit(
generateCommitMessageFromGitDiff(
await getDiff({ files: stagedFiles }),
extraArgs,
fullGitMojiSpec
fullGitMojiSpec,
skipCommitConfirmation
)
);

View File

@@ -10,10 +10,14 @@ import { intro, outro } from '@clack/prompts';
import { COMMANDS } from '../CommandsEnum';
import { getI18nLocal } from '../i18n';
import { TEST_MOCK_TYPES } from '../engine/testAi';
export enum CONFIG_KEYS {
OCO_OPENAI_API_KEY = 'OCO_OPENAI_API_KEY',
OCO_ANTHROPIC_API_KEY = 'OCO_ANTHROPIC_API_KEY',
OCO_AZURE_API_KEY = 'OCO_AZURE_API_KEY',
OCO_GEMINI_API_KEY = 'OCO_GEMINI_API_KEY',
OCO_GEMINI_BASE_PATH = 'OCO_GEMINI_BASE_PATH',
OCO_TOKENS_MAX_INPUT = 'OCO_TOKENS_MAX_INPUT',
OCO_TOKENS_MAX_OUTPUT = 'OCO_TOKENS_MAX_OUTPUT',
OCO_OPENAI_BASE_PATH = 'OCO_OPENAI_BASE_PATH',
@@ -25,7 +29,13 @@ export enum CONFIG_KEYS {
OCO_PROMPT_MODULE = 'OCO_PROMPT_MODULE',
OCO_AI_PROVIDER = 'OCO_AI_PROVIDER',
OCO_GITPUSH = 'OCO_GITPUSH',
OCO_ONE_LINE_COMMIT = 'OCO_ONE_LINE_COMMIT'
OCO_ONE_LINE_COMMIT = 'OCO_ONE_LINE_COMMIT',
OCO_AZURE_ENDPOINT = 'OCO_AZURE_ENDPOINT',
OCO_TEST_MOCK_TYPE = 'OCO_TEST_MOCK_TYPE',
OCO_API_URL = 'OCO_API_URL',
OCO_OLLAMA_API_URL = 'OCO_OLLAMA_API_URL',
OCO_FLOWISE_ENDPOINT = 'OCO_FLOWISE_ENDPOINT',
OCO_FLOWISE_API_KEY = 'OCO_FLOWISE_API_KEY'
}
export enum CONFIG_MODES {
@@ -34,18 +44,50 @@ export enum CONFIG_MODES {
}
export const MODEL_LIST = {
openai: ['gpt-3.5-turbo',
'gpt-3.5-turbo-0125',
'gpt-4',
'gpt-4-turbo',
'gpt-4-1106-preview',
'gpt-4-turbo-preview',
'gpt-4-0125-preview'],
openai: [
'gpt-4o-mini',
'gpt-3.5-turbo',
'gpt-3.5-turbo-instruct',
'gpt-3.5-turbo-0613',
'gpt-3.5-turbo-0301',
'gpt-3.5-turbo-1106',
'gpt-3.5-turbo-0125',
'gpt-3.5-turbo-16k',
'gpt-3.5-turbo-16k-0613',
'gpt-3.5-turbo-16k-0301',
'gpt-4',
'gpt-4-0314',
'gpt-4-0613',
'gpt-4-1106-preview',
'gpt-4-0125-preview',
'gpt-4-turbo-preview',
'gpt-4-vision-preview',
'gpt-4-1106-vision-preview',
'gpt-4-turbo',
'gpt-4-turbo-2024-04-09',
'gpt-4-32k',
'gpt-4-32k-0314',
'gpt-4-32k-0613',
'gpt-4o',
'gpt-4o-2024-05-13',
'gpt-4o-mini-2024-07-18'
],
anthropic: ['claude-3-haiku-20240307',
'claude-3-sonnet-20240229',
'claude-3-opus-20240229']
}
anthropic: [
'claude-3-5-sonnet-20240620',
'claude-3-opus-20240229',
'claude-3-sonnet-20240229',
'claude-3-haiku-20240307'
],
gemini: [
'gemini-1.5-flash',
'gemini-1.5-pro',
'gemini-1.0-pro',
'gemini-pro-vision',
'text-embedding-004'
]
};
const getDefaultModel = (provider: string | undefined): string => {
switch (provider) {
@@ -53,6 +95,8 @@ const getDefaultModel = (provider: string | undefined): string => {
return '';
case 'anthropic':
return MODEL_LIST.anthropic[0];
case 'gemini':
return MODEL_LIST.gemini[0];
default:
return MODEL_LIST.openai[0];
}
@@ -79,16 +123,51 @@ const validateConfig = (
export const configValidators = {
[CONFIG_KEYS.OCO_OPENAI_API_KEY](value: any, config: any = {}) {
if (config.OCO_AI_PROVIDER == 'gemini') return value;
//need api key unless running locally with ollama
validateConfig(
'OpenAI API_KEY',
value || config.OCO_ANTHROPIC_API_KEY || config.OCO_AI_PROVIDER == 'ollama' || config.OCO_AI_PROVIDER == 'test',
'You need to provide an OpenAI/Anthropic API key'
value ||
config.OCO_ANTHROPIC_API_KEY ||
config.OCO_AI_PROVIDER.startsWith('ollama') ||
config.OCO_AZURE_API_KEY ||
config.OCO_AI_PROVIDER == 'test' ||
config.OCO_AI_PROVIDER == 'flowise',
'You need to provide an OpenAI/Anthropic/Azure or other provider API key via `oco config set OCO_OPENAI_API_KEY=your_key`, for help refer to docs https://github.com/di-sukharev/opencommit'
);
validateConfig(
CONFIG_KEYS.OCO_OPENAI_API_KEY,
value.startsWith('sk-'),
'Must start with "sk-"'
value.startsWith('sk-') || config.OCO_AI_PROVIDER != 'openai',
'Must start with "sk-" for openai provider'
);
return value;
},
[CONFIG_KEYS.OCO_AZURE_API_KEY](value: any, config: any = {}) {
validateConfig(
'ANTHROPIC_API_KEY',
value ||
config.OCO_OPENAI_API_KEY ||
config.OCO_AZURE_API_KEY ||
config.OCO_AI_PROVIDER == 'ollama' ||
config.OCO_AI_PROVIDER == 'test' ||
config.OCO_AI_PROVIDER == 'flowise',
'You need to provide an OpenAI/Anthropic/Azure API key'
);
return value;
},
[CONFIG_KEYS.OCO_GEMINI_API_KEY](value: any, config: any = {}) {
// only need to check for gemini api key if using gemini
if (config.OCO_AI_PROVIDER != 'gemini') return value;
validateConfig(
'Gemini API Key',
value || config.OCO_GEMINI_API_KEY || config.OCO_AI_PROVIDER == 'test',
'You need to provide an Gemini API key'
);
return value;
@@ -97,13 +176,27 @@ export const configValidators = {
[CONFIG_KEYS.OCO_ANTHROPIC_API_KEY](value: any, config: any = {}) {
validateConfig(
'ANTHROPIC_API_KEY',
value || config.OCO_OPENAI_API_KEY || config.OCO_AI_PROVIDER == 'ollama' || config.OCO_AI_PROVIDER == 'test',
value ||
config.OCO_OPENAI_API_KEY ||
config.OCO_AI_PROVIDER == 'ollama' ||
config.OCO_AI_PROVIDER == 'test' ||
config.OCO_AI_PROVIDER == 'flowise',
'You need to provide an OpenAI/Anthropic API key'
);
return value;
},
[CONFIG_KEYS.OCO_FLOWISE_API_KEY](value: any, config: any = {}) {
validateConfig(
CONFIG_KEYS.OCO_FLOWISE_API_KEY,
value || config.OCO_AI_PROVIDER != 'flowise',
'You need to provide a flowise API key'
);
return value;
},
[CONFIG_KEYS.OCO_DESCRIPTION](value: any) {
validateConfig(
CONFIG_KEYS.OCO_DESCRIPTION,
@@ -180,11 +273,15 @@ export const configValidators = {
return value;
},
[CONFIG_KEYS.OCO_MODEL](value: any) {
[CONFIG_KEYS.OCO_MODEL](value: any, config: any = {}) {
validateConfig(
CONFIG_KEYS.OCO_MODEL,
[...MODEL_LIST.openai, ...MODEL_LIST.anthropic].includes(value),
`${value} is not supported yet, use 'gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo' (default), 'gpt-3.5-turbo-0125', 'gpt-4-1106-preview', 'gpt-4-turbo-preview', 'gpt-4-0125-preview', 'claude-3-opus-20240229', 'claude-3-sonnet-20240229' or 'claude-3-haiku-20240307'`
typeof value === 'string',
`${value} is not supported yet, use:\n\n ${[
...MODEL_LIST.openai,
...MODEL_LIST.anthropic,
...MODEL_LIST.gemini
].join('\n')}`
);
return value;
},
@@ -223,10 +320,12 @@ export const configValidators = {
'',
'openai',
'anthropic',
'ollama',
'test'
].includes(value),
`${value} is not supported yet, use 'ollama' 'anthropic' or 'openai' (default)`
'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;
},
@@ -240,6 +339,47 @@ export const configValidators = {
return value;
},
[CONFIG_KEYS.OCO_AZURE_ENDPOINT](value: any) {
validateConfig(
CONFIG_KEYS.OCO_AZURE_ENDPOINT,
value.includes('openai.azure.com'),
'Must be in format "https://<resource name>.openai.azure.com/"'
);
return value;
},
[CONFIG_KEYS.OCO_FLOWISE_ENDPOINT](value: any) {
validateConfig(
CONFIG_KEYS.OCO_FLOWISE_ENDPOINT,
typeof value === 'string' && value.includes(':'),
'Value must be string and should include both I.P. and port number' // Considering the possibility of DNS lookup or feeding the I.P. explicitely, there is no pattern to verify, except a column for the port number
);
return value;
},
[CONFIG_KEYS.OCO_TEST_MOCK_TYPE](value: any) {
validateConfig(
CONFIG_KEYS.OCO_TEST_MOCK_TYPE,
TEST_MOCK_TYPES.includes(value),
`${value} is not supported yet, use ${TEST_MOCK_TYPES.map(
(t) => `'${t}'`
).join(', ')}`
);
return value;
},
[CONFIG_KEYS.OCO_OLLAMA_API_URL](value: any) {
// add simple api validator
validateConfig(
CONFIG_KEYS.OCO_API_URL,
typeof value === 'string' && value.startsWith('http'),
`${value} is not a valid URL`
);
return value;
}
};
export type ConfigType = {
@@ -248,18 +388,19 @@ export type ConfigType = {
const defaultConfigPath = pathJoin(homedir(), '.opencommit');
const defaultEnvPath = pathResolve(process.cwd(), '.env');
export const getConfig = ({
configPath = defaultConfigPath,
envPath = defaultEnvPath
}: {
configPath?: string
envPath?: string
configPath?: string;
envPath?: string;
} = {}): ConfigType | null => {
dotenv.config({ path: envPath });
const configFromEnv = {
OCO_OPENAI_API_KEY: process.env.OCO_OPENAI_API_KEY,
OCO_ANTHROPIC_API_KEY: process.env.OCO_ANTHROPIC_API_KEY,
OCO_AZURE_API_KEY: process.env.OCO_AZURE_API_KEY,
OCO_GEMINI_API_KEY: process.env.OCO_GEMINI_API_KEY,
OCO_TOKENS_MAX_INPUT: process.env.OCO_TOKENS_MAX_INPUT
? Number(process.env.OCO_TOKENS_MAX_INPUT)
: undefined,
@@ -267,18 +408,25 @@ export const getConfig = ({
? Number(process.env.OCO_TOKENS_MAX_OUTPUT)
: undefined,
OCO_OPENAI_BASE_PATH: process.env.OCO_OPENAI_BASE_PATH,
OCO_GEMINI_BASE_PATH: process.env.OCO_GEMINI_BASE_PATH,
OCO_DESCRIPTION: process.env.OCO_DESCRIPTION === 'true' ? true : false,
OCO_EMOJI: process.env.OCO_EMOJI === 'true' ? true : false,
OCO_MODEL: process.env.OCO_MODEL || getDefaultModel(process.env.OCO_AI_PROVIDER),
OCO_MODEL:
process.env.OCO_MODEL || getDefaultModel(process.env.OCO_AI_PROVIDER),
OCO_LANGUAGE: process.env.OCO_LANGUAGE || 'en',
OCO_MESSAGE_TEMPLATE_PLACEHOLDER:
process.env.OCO_MESSAGE_TEMPLATE_PLACEHOLDER || '$msg',
OCO_PROMPT_MODULE: process.env.OCO_PROMPT_MODULE || 'conventional-commit',
OCO_AI_PROVIDER: process.env.OCO_AI_PROVIDER || 'openai',
OCO_GITPUSH: process.env.OCO_GITPUSH === 'false' ? false : true,
OCO_ONE_LINE_COMMIT: process.env.OCO_ONE_LINE_COMMIT === 'true' ? true : false
OCO_ONE_LINE_COMMIT:
process.env.OCO_ONE_LINE_COMMIT === 'true' ? true : false,
OCO_AZURE_ENDPOINT: process.env.OCO_AZURE_ENDPOINT || undefined,
OCO_TEST_MOCK_TYPE: process.env.OCO_TEST_MOCK_TYPE || 'commit-message',
OCO_FLOWISE_ENDPOINT: process.env.OCO_FLOWISE_ENDPOINT || ':',
OCO_FLOWISE_API_KEY: process.env.OCO_FLOWISE_API_KEY || undefined,
OCO_OLLAMA_API_URL: process.env.OCO_OLLAMA_API_URL || undefined
};
const configExists = existsSync(configPath);
if (!configExists) return configFromEnv;
@@ -286,9 +434,7 @@ export const getConfig = ({
const config = iniParse(configFile);
for (const configKey of Object.keys(config)) {
if (
['null', 'undefined'].includes(config[configKey])
) {
if (['null', 'undefined'].includes(config[configKey])) {
config[configKey] = undefined;
continue;
}
@@ -301,10 +447,11 @@ export const getConfig = ({
config[configKey] = validValue;
} catch (error) {
outro(`Unknown '${configKey}' config option.`);
outro(`Unknown '${configKey}' config option or missing validator.`);
outro(
`Manually fix the '.env' file or global '~/.opencommit' config file.`
);
process.exit(1);
}
}
@@ -312,7 +459,10 @@ export const getConfig = ({
return config;
};
export const setConfig = (keyValues: [key: string, value: string][], configPath: string = defaultConfigPath) => {
export const setConfig = (
keyValues: [key: string, value: string][],
configPath: string = defaultConfigPath
) => {
const config = getConfig() || {};
for (const [configKey, configValue] of keyValues) {

View File

@@ -39,9 +39,9 @@ export const prepareCommitMessageHook = async (
const config = getConfig();
if (!config?.OCO_OPENAI_API_KEY) {
if (!config?.OCO_OPENAI_API_KEY && !config?.OCO_ANTHROPIC_API_KEY && !config?.OCO_AZURE_API_KEY) {
throw new Error(
'No OPEN_AI_API exists. Set your OPEN_AI_API=<key> in ~/.opencommit'
'No OPEN_AI_API or OCO_ANTHROPIC_API_KEY or OCO_AZURE_API_KEY exists. Set your key in ~/.opencommit'
);
}

View File

@@ -48,18 +48,16 @@ if (
const MODEL = config?.OCO_MODEL;
if (provider === 'anthropic' &&
!MODEL_LIST.anthropic.includes(MODEL) &&
command !== 'config' &&
mode !== CONFIG_MODES.set) {
outro(
`${chalk.red('✖')} Unsupported model ${MODEL} for Anthropic. Supported models are: ${MODEL_LIST.anthropic.join(
', '
)}`
);
process.exit(1);
typeof MODEL !== 'string' &&
command !== 'config' &&
mode !== CONFIG_MODES.set) {
outro(
`${chalk.red('✖')} Unsupported model ${MODEL}. The model can be any string, but the current configuration is not supported.`
);
process.exit(1);
}
class AnthropicAi implements AiEngine {
export class AnthropicAi implements AiEngine {
private anthropicAiApiConfiguration = {
apiKey: apiKey
};
@@ -120,5 +118,3 @@ class AnthropicAi implements AiEngine {
}
};
}
export const anthropicAi = new AnthropicAi();

109
src/engine/azure.ts Normal file
View File

@@ -0,0 +1,109 @@
import axios from 'axios';
import chalk from 'chalk';
import { execa } from 'execa';
import {
ChatCompletionRequestMessage,
} from 'openai';
import { OpenAIClient, AzureKeyCredential } from '@azure/openai';
import { intro, outro } from '@clack/prompts';
import {
CONFIG_MODES,
DEFAULT_TOKEN_LIMITS,
getConfig
} from '../commands/config';
import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
import { tokenCount } from '../utils/tokenCount';
import { AiEngine } from './Engine';
const config = getConfig();
const MAX_TOKENS_OUTPUT =
config?.OCO_TOKENS_MAX_OUTPUT ||
DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_OUTPUT;
const MAX_TOKENS_INPUT =
config?.OCO_TOKENS_MAX_INPUT || DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_INPUT;
let basePath = config?.OCO_OPENAI_BASE_PATH;
let apiKey = config?.OCO_AZURE_API_KEY;
let apiEndpoint = config?.OCO_AZURE_ENDPOINT;
const [command, mode] = process.argv.slice(2);
const provider = config?.OCO_AI_PROVIDER;
if (
provider === 'azure' &&
!apiKey &&
!apiEndpoint &&
command !== 'config' &&
mode !== CONFIG_MODES.set
) {
intro('opencommit');
outro(
'OCO_AZURE_API_KEY or OCO_AZURE_ENDPOINT are not set, please run `oco config set OCO_AZURE_API_KEY=<your token> . If you are using GPT, make sure you add payment details, so API works.`'
);
outro(
'For help look into README https://github.com/di-sukharev/opencommit#setup'
);
process.exit(1);
}
const MODEL = config?.OCO_MODEL || 'gpt-3.5-turbo';
export class Azure implements AiEngine {
private openAI!: OpenAIClient;
constructor() {
if (provider === 'azure') {
this.openAI = new OpenAIClient(apiEndpoint, new AzureKeyCredential(apiKey));
}
}
public generateCommitMessage = async (
messages: Array<ChatCompletionRequestMessage>
): Promise<string | undefined> => {
try {
const REQUEST_TOKENS = messages
.map((msg) => tokenCount(msg.content) + 4)
.reduce((a, b) => a + b, 0);
if (REQUEST_TOKENS > MAX_TOKENS_INPUT - MAX_TOKENS_OUTPUT) {
throw new Error(GenerateCommitMessageErrorEnum.tooMuchTokens);
}
const data = await this.openAI.getChatCompletions(MODEL, messages);
const message = data.choices[0].message;
if (message?.content === null) {
return undefined;
}
return message?.content;
} catch (error) {
outro(`${chalk.red('✖')} ${MODEL}`);
const err = error as Error;
outro(`${chalk.red('✖')} ${err?.message || err}`);
if (
axios.isAxiosError<{ error?: { message: string } }>(error) &&
error.response?.status === 401
) {
const openAiError = error.response.data.error;
if (openAiError?.message) outro(openAiError.message);
outro(
'For help look into README https://github.com/di-sukharev/opencommit#setup'
);
}
throw err;
}
};
}
export const azure = new Azure();

43
src/engine/flowise.ts Normal file
View File

@@ -0,0 +1,43 @@
import axios, { AxiosError } from 'axios';
import { ChatCompletionRequestMessage } from 'openai';
import { AiEngine } from './Engine';
import {
getConfig
} from '../commands/config';
const config = getConfig();
export class FlowiseAi implements AiEngine {
async generateCommitMessage(
messages: Array<ChatCompletionRequestMessage>
): Promise<string | undefined> {
const gitDiff = messages[ messages.length - 1 ]?.content?.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t');
const url = `http://${config?.OCO_FLOWISE_ENDPOINT}/api/v1/prediction/${config?.OCO_FLOWISE_API_KEY}`;
const payload = {
question : gitDiff,
overrideConfig : {
systemMessagePrompt: messages[0]?.content,
},
history : messages.slice( 1, -1 )
}
try {
const response = await axios.post(url, payload, {
headers: {
'Content-Type': 'application/json'
}
});
const message = response.data;
return message?.text;
} catch (err: any) {
const message = err.response?.data?.error ?? err.message;
throw new Error('local model issues. details: ' + message);
}
}
}

133
src/engine/gemini.ts Normal file
View File

@@ -0,0 +1,133 @@
import { ChatCompletionRequestMessage } from 'openai';
import { AiEngine } from './Engine';
import { Content, GenerativeModel, GoogleGenerativeAI, HarmBlockThreshold, HarmCategory, Part } from '@google/generative-ai';
import { CONFIG_MODES, ConfigType, DEFAULT_TOKEN_LIMITS, getConfig, MODEL_LIST } from '../commands/config';
import { intro, outro } from '@clack/prompts';
import chalk from 'chalk';
import axios from 'axios';
export class Gemini implements AiEngine {
private readonly config: ConfigType;
private readonly googleGenerativeAi: GoogleGenerativeAI;
private ai: GenerativeModel;
// vars
private maxTokens = {
input: DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_INPUT,
output: DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_OUTPUT
};
private basePath: string;
private apiKey: string;
private model: string;
constructor() {
this.config = getConfig() as ConfigType;
this.googleGenerativeAi = new GoogleGenerativeAI(this.config.OCO_GEMINI_API_KEY);
this.warmup();
}
async generateCommitMessage(messages: ChatCompletionRequestMessage[]): Promise<string | undefined> {
const systemInstruction = messages.filter(m => m.role === 'system')
.map(m => m.content)
.join('\n');
this.ai = this.googleGenerativeAi.getGenerativeModel({
model: this.model,
systemInstruction,
});
const contents = messages.filter(m => m.role !== 'system')
.map(m => ({ parts: [{ text: m.content } as Part], role: m.role == 'user' ? m.role : 'model', } as Content));
try {
const result = await this.ai.generateContent({
contents,
safetySettings: [
{
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
},
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE
},
],
generationConfig: {
maxOutputTokens: this.maxTokens.output,
temperature: 0,
topP: 0.1,
},
});
return result.response.text();
} catch (error) {
const err = error as Error;
outro(`${chalk.red('✖')} ${err?.message || err}`);
if (
axios.isAxiosError<{ error?: { message: string } }>(error) &&
error.response?.status === 401
) {
const geminiError = error.response.data.error;
if (geminiError?.message) outro(geminiError.message);
outro(
'For help look into README https://github.com/di-sukharev/opencommit#setup'
);
}
throw err;
}
}
private warmup(): void {
if (this.config.OCO_TOKENS_MAX_INPUT !== undefined) this.maxTokens.input = this.config.OCO_TOKENS_MAX_INPUT;
if (this.config.OCO_TOKENS_MAX_OUTPUT !== undefined) this.maxTokens.output = this.config.OCO_TOKENS_MAX_OUTPUT;
this.basePath = this.config.OCO_GEMINI_BASE_PATH;
this.apiKey = this.config.OCO_GEMINI_API_KEY;
const [command, mode] = process.argv.slice(2);
const provider = this.config.OCO_AI_PROVIDER;
if (provider === 'gemini' && !this.apiKey &&
command !== 'config' && mode !== 'set') {
intro('opencommit');
outro('OCO_GEMINI_API_KEY is not set, please run `oco config set OCO_GEMINI_API_KEY=<your token> . If you are using GPT, make sure you add payment details, so API works.');
outro(
'For help look into README https://github.com/di-sukharev/opencommit#setup'
);
process.exit(1);
}
this.model = this.config.OCO_MODEL || MODEL_LIST.gemini[0];
if (provider === 'gemini' &&
!MODEL_LIST.gemini.includes(this.model) &&
command !== 'config' &&
mode !== CONFIG_MODES.set) {
outro(
`${chalk.red('✖')} Unsupported model ${this.model} for Gemini. Supported models are: ${MODEL_LIST.gemini.join(
', '
)}`
);
process.exit(1);
}
}
}

View File

@@ -2,20 +2,36 @@ import axios, { AxiosError } from 'axios';
import { ChatCompletionRequestMessage } from 'openai';
import { AiEngine } from './Engine';
import {
getConfig
} from '../commands/config';
const config = getConfig();
export class OllamaAi implements AiEngine {
private model = "mistral"; // as default model of Ollama
private url = "http://localhost:11434/api/chat"; // default URL of Ollama API
setModel(model: string) {
this.model = model ?? config?.OCO_MODEL ?? 'mistral';
}
setUrl(url: string) {
this.url = url ?? config?.OCO_OLLAMA_API_URL ?? 'http://localhost:11434/api/chat';
}
async generateCommitMessage(
messages: Array<ChatCompletionRequestMessage>
): Promise<string | undefined> {
const model = 'mistral'; // todo: allow other models
const model = this.model;
//console.log(messages);
//process.exit()
const url = 'http://localhost:11434/api/chat';
const url = this.url;
const p = {
model,
messages,
options: {temperature: 0, top_p: 0.1},
options: { temperature: 0, top_p: 0.1 },
stream: false
};
try {
@@ -34,5 +50,3 @@ export class OllamaAi implements AiEngine {
}
}
}
export const ollamaAi = new OllamaAi();

View File

@@ -54,19 +54,17 @@ if (
const MODEL = config?.OCO_MODEL || 'gpt-3.5-turbo';
if (provider === 'openai' &&
!MODEL_LIST.openai.includes(MODEL) &&
typeof MODEL !== 'string' &&
command !== 'config' &&
mode !== CONFIG_MODES.set) {
outro(
`${chalk.red('✖')} Unsupported model ${MODEL} for OpenAI. Supported models are: ${MODEL_LIST.openai.join(
', '
)}`
`${chalk.red('✖')} Unsupported model ${MODEL}. The model can be any string, but the current configuration is not supported.`
);
process.exit(1);
}
class OpenAi implements AiEngine {
export class OpenAi implements AiEngine {
private openAiApiConfiguration = new OpenAiApiConfiguration({
apiKey: apiKey
});
@@ -91,7 +89,7 @@ class OpenAi implements AiEngine {
};
try {
const REQUEST_TOKENS = messages
.map((msg) => tokenCount(msg.content) + 4)
.map((msg) => tokenCount(msg.content as string) + 4)
.reduce((a, b) => a + b, 0);
if (REQUEST_TOKENS > MAX_TOKENS_INPUT - MAX_TOKENS_OUTPUT) {
@@ -124,6 +122,6 @@ class OpenAi implements AiEngine {
throw err;
}
};
}
export const api = new OpenAi();

View File

@@ -1,12 +1,31 @@
import { ChatCompletionRequestMessage } from 'openai';
import { AiEngine } from './Engine';
import { getConfig } from '../commands/config';
export const TEST_MOCK_TYPES = [
'commit-message',
'prompt-module-commitlint-config',
] as const
type TestMockType = typeof TEST_MOCK_TYPES[number];
export class TestAi implements AiEngine {
async generateCommitMessage(
messages: Array<ChatCompletionRequestMessage>
_messages: Array<ChatCompletionRequestMessage>
): Promise<string | undefined> {
return 'test commit message';
const config = getConfig();
switch (config?.OCO_TEST_MOCK_TYPE as TestMockType | undefined) {
case 'commit-message':
return 'fix(testAi.ts): test commit message';
case 'prompt-module-commitlint-config':
return `{\n` +
` "localLanguage": "english",\n` +
` "commitFix": "fix(server): Change 'port' variable to uppercase 'PORT'",\n` +
` "commitFeat": "feat(server): Allow server to listen on a port specified through environment variable",\n` +
` "commitDescription": "Change 'port' variable to uppercase 'PORT'. Allow server to listen on a port specified through environment variable."\n` +
`}`
default:
throw Error('unsupported test mock type')
}
}
}
export const testAi = new TestAi();

View File

@@ -10,8 +10,11 @@ import { tokenCount } from './utils/tokenCount';
import { getEngine } from './utils/engine';
const config = getConfig();
const MAX_TOKENS_INPUT = config?.OCO_TOKENS_MAX_INPUT || DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_INPUT;
const MAX_TOKENS_OUTPUT = config?.OCO_TOKENS_MAX_OUTPUT || DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_OUTPUT;
const MAX_TOKENS_INPUT =
config?.OCO_TOKENS_MAX_INPUT || DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_INPUT;
const MAX_TOKENS_OUTPUT =
config?.OCO_TOKENS_MAX_OUTPUT ||
DEFAULT_TOKEN_LIMITS.DEFAULT_MAX_TOKENS_OUTPUT;
const generateCommitMessageChatCompletionPrompt = async (
diff: string,
@@ -46,7 +49,7 @@ export const generateCommitMessageByDiff = async (
const INIT_MESSAGES_PROMPT = await getMainCommitPrompt(fullGitMojiSpec);
const INIT_MESSAGES_PROMPT_LENGTH = INIT_MESSAGES_PROMPT.map(
(msg) => tokenCount(msg.content) + 4
(msg) => tokenCount(msg.content as string) + 4
).reduce((a, b) => a + b, 0);
const MAX_REQUEST_TOKENS =
@@ -62,18 +65,21 @@ export const generateCommitMessageByDiff = async (
fullGitMojiSpec
);
const commitMessages = [];
const commitMessages = [] as string[];
for (const promise of commitMessagePromises) {
commitMessages.push(await promise);
commitMessages.push((await promise) as string);
await delay(2000);
}
return commitMessages.join('\n\n');
}
const messages = await generateCommitMessageChatCompletionPrompt(diff, fullGitMojiSpec);
const messages = await generateCommitMessageChatCompletionPrompt(
diff,
fullGitMojiSpec
);
const engine = getEngine()
const engine = getEngine();
const commitMessage = await engine.generateCommitMessage(messages);
if (!commitMessage)
@@ -100,7 +106,7 @@ function getMessagesPromisesByChangesInFile(
maxChangeLength
);
const lineDiffsWithHeader = [];
const lineDiffsWithHeader = [] as string[];
for (const change of mergedChanges) {
const totalChange = fileHeader + change;
if (tokenCount(totalChange) > maxChangeLength) {
@@ -112,7 +118,7 @@ function getMessagesPromisesByChangesInFile(
}
}
const engine = getEngine()
const engine = getEngine();
const commitMsgsFromFileLineDiffs = lineDiffsWithHeader.map(
async (lineDiff) => {
const messages = await generateCommitMessageChatCompletionPrompt(
@@ -129,7 +135,7 @@ function getMessagesPromisesByChangesInFile(
function splitDiff(diff: string, maxChangeLength: number) {
const lines = diff.split('\n');
const splitDiffs = [];
const splitDiffs = [] as string[];
let currentDiff = '';
if (maxChangeLength <= 0) {
@@ -175,7 +181,7 @@ export const getCommitMsgsPromisesFromFileDiffs = async (
// merge multiple files-diffs into 1 prompt to save tokens
const mergedFilesDiffs = mergeDiffs(diffByFiles, maxDiffLength);
const commitMessagePromises = [];
const commitMessagePromises = [] as Promise<string | undefined>[];
for (const fileDiff of mergedFilesDiffs) {
if (tokenCount(fileDiff) >= maxDiffLength) {
@@ -194,7 +200,7 @@ export const getCommitMsgsPromisesFromFileDiffs = async (
fullGitMojiSpec
);
const engine = getEngine()
const engine = getEngine();
commitMessagePromises.push(engine.generateCommitMessage(messages));
}
}

View File

@@ -1,6 +1,6 @@
{
"localLanguage": "简体中文",
"commitFix": "修复(server.ts)将端口变量从小写port改为大写PORT",
"commitFeat": "功能(server.ts)添加对process.env.PORT环境变量的支持",
"commitFix": "fix(server.ts)将端口变量从小写port改为大写PORT",
"commitFeat": "feat(server.ts)添加对process.env.PORT环境变量的支持",
"commitDescription": "现在端口变量被命名为PORT这提高了命名约定的一致性因为PORT是一个常量。环境变量的支持使应用程序更加灵活因为它现在可以通过process.env.PORT环境变量在任何可用端口上运行。"
}

View File

@@ -19,7 +19,16 @@ export const configureCommitlintIntegration = async (force = false) => {
const fileExists = await utils.commitlintLLMConfigExists();
let commitLintConfig = await getCommitLintPWDConfig();
const commitLintConfig = await getCommitLintPWDConfig();
if (commitLintConfig === null) {
throw new Error(
`Failed to load @commitlint config. Please check the following:
* @commitlint >= 9.0.0 is installed in the local directory.
* 'node_modules/@commitlint/load' package exists.
* A valid @commitlint configuration exists.
`,
);
}
// debug complete @commitlint configuration
// await fs.writeFile(
@@ -55,7 +64,7 @@ export const configureCommitlintIntegration = async (force = false) => {
// consistencyPrompts.map((p) => p.content)
// );
const engine = getEngine()
const engine = getEngine();
let consistency =
(await engine.generateCommitMessage(consistencyPrompts)) || '{}';
@@ -64,7 +73,7 @@ export const configureCommitlintIntegration = async (force = false) => {
// sometimes consistency is preceded by explanatory text like "Here is your JSON:"
consistency = utils.getJSONBlock(consistency);
// ... remaining might be extra set of "\n"
consistency = utils.removeDoubleNewlines(consistency);

View File

@@ -1,11 +1,25 @@
import fs from 'fs/promises';
import path from 'path';
const nodeModulesPath = path.join(
process.env.PWD || process.cwd(),
'node_modules',
'@commitlint',
'load'
);
const getCommitLintModuleType = async (): Promise<'cjs' | 'esm'> => {
const packageFile = 'node_modules/@commitlint/load/package.json';
const packageJsonPath = path.join(
process.env.PWD || process.cwd(),
packageFile,
);
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
if (!packageJson) {
throw new Error(`Failed to parse ${packageFile}`);
}
return packageJson.type === 'module' ? 'esm' : 'cjs';
};
/**
* QualifiedConfig from any version of @commitlint/types
* @see https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/types/src/load.ts
*/
type QualifiedConfigOnAnyVersion = { [key:string]: unknown };
/**
* This code is loading the configuration for the `@commitlint` package from the current working
@@ -13,8 +27,31 @@ const nodeModulesPath = path.join(
*
* @returns
*/
export const getCommitLintPWDConfig = async () => {
const load = require(nodeModulesPath).default;
export const getCommitLintPWDConfig = async (): Promise<QualifiedConfigOnAnyVersion | null> => {
let load, nodeModulesPath;
switch (await getCommitLintModuleType()) {
case 'cjs':
/**
* CommonJS (<= commitlint@v18.x.x.)
*/
nodeModulesPath = path.join(
process.env.PWD || process.cwd(),
'node_modules/@commitlint/load',
);
load = require(nodeModulesPath).default;
break;
case 'esm':
/**
* ES Module (commitlint@v19.x.x. <= )
* Directory import is not supported in ES Module resolution, so import the file directly
*/
nodeModulesPath = path.join(
process.env.PWD || process.cwd(),
'node_modules/@commitlint/load/lib/load.js',
);
load = (await import(nodeModulesPath)).default;
break;
}
if (load && typeof load === 'function') {
return await load();

View File

@@ -18,14 +18,14 @@ export const removeDoubleNewlines = (input: string): string => {
export const getJSONBlock = (input: string): string => {
const jsonIndex = input.search('```json');
if(jsonIndex > -1) {
if (jsonIndex > -1) {
input = input.slice(jsonIndex + 8);
const endJsonIndex = consistency.search('```');
const endJsonIndex = input.search('```');
input = input.slice(0, endJsonIndex);
}
return input;
};
export const commitlintLLMConfigExists = async (): Promise<boolean> => {
let exists;
try {
@@ -54,4 +54,4 @@ export const getCommitlintLLMConfig =
content.toString()
) as CommitlintLLMConfig;
return commitLintLLMConfig;
};
};

View File

@@ -118,7 +118,7 @@ const INIT_MAIN_PROMPT = (
${
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.'
: ""
: ''
}
Use the present tense. Lines must not be longer than 74 characters. Use ${language} for the commit message.`
});

View File

@@ -1,19 +1,37 @@
import { AiEngine } from '../engine/Engine';
import { api } from '../engine/openAi';
import { OpenAi } from '../engine/openAi';
import { Gemini } from '../engine/gemini';
import { getConfig } from '../commands/config';
import { ollamaAi } from '../engine/ollama';
import { anthropicAi } from '../engine/anthropic'
import { testAi } from '../engine/testAi';
import { OllamaAi } from '../engine/ollama';
import { AnthropicAi } from '../engine/anthropic'
import { TestAi } from '../engine/testAi';
import { Azure } from '../engine/azure';
import { FlowiseAi } from '../engine/flowise'
export function getEngine(): AiEngine {
const config = getConfig();
if (config?.OCO_AI_PROVIDER == 'ollama') {
const provider = config?.OCO_AI_PROVIDER;
if (provider?.startsWith('ollama')) {
const ollamaAi = new OllamaAi();
const model = provider.substring('ollama/'.length);
if (model) {
ollamaAi.setModel(model);
ollamaAi.setUrl(config?.OCO_OLLAMA_API_URL);
}
return ollamaAi;
} else if (config?.OCO_AI_PROVIDER == 'anthropic') {
return anthropicAi;
} else if (config?.OCO_AI_PROVIDER == 'test') {
return testAi;
} else if (provider == 'anthropic') {
return new AnthropicAi();
} else if (provider == 'test') {
return new TestAi();
} else if (provider == 'gemini') {
return new Gemini();
} else if (provider == 'azure') {
return new Azure();
} else if( provider == 'flowise'){
return new FlowiseAi();
}
//open ai gpt by default
return api;
return new OpenAi();
}

View File

@@ -1,5 +1,5 @@
import { outro } from "@clack/prompts";
import { execa } from "execa";
import { outro } from '@clack/prompts';
import { execa } from 'execa';
export const getOpenCommitLatestVersion = async (): Promise<
string | undefined
@@ -11,4 +11,4 @@ export const getOpenCommitLatestVersion = async (): Promise<
outro('Error while getting the latest version of opencommit');
return undefined;
}
};
};

View File

@@ -10,10 +10,13 @@ RUN apt-get install -y nodejs
RUN git config --global user.email "test@example.com"
RUN git config --global user.name "Test User"
COPY . /app
WORKDIR /app
COPY package.json /app/
COPY package-lock.json /app/
RUN ls -la
RUN npm install
RUN npm ci
COPY . /app
RUN ls -la
RUN npm run build

View File

@@ -5,7 +5,6 @@ import { prepareEnvironment } from './utils';
it('cli flow when there are no changes', async () => {
const { gitDir, cleanup } = await prepareEnvironment();
const { findByText } = await render(`OCO_AI_PROVIDER='test' node`, [resolve('./out/cli.cjs')], { cwd: gitDir });
expect(await findByText('No changes detected')).toBeInTheConsole();

View File

@@ -10,7 +10,6 @@ it('cli flow to generate commit message for 1 new file (staged)', async () => {
await render('git' ,['add index.ts'], { 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();

View File

@@ -0,0 +1,224 @@
import { resolve } from 'path';
import { render } from 'cli-testing-library';
import 'cli-testing-library/extend-expect';
import { prepareEnvironment, wait } from '../utils';
import path from 'path';
function getAbsolutePath(relativePath: string) {
const scriptDir = path.dirname(__filename);
return path.resolve(scriptDir, relativePath);
}
async function setupCommitlint(dir: string, ver: 9 | 18 | 19) {
let packagePath, packageJsonPath, configPath;
switch (ver) {
case 9:
packagePath = getAbsolutePath('./data/commitlint_9/node_modules');
packageJsonPath = getAbsolutePath('./data/commitlint_9/package.json');
configPath = getAbsolutePath('./data/commitlint_9/commitlint.config.js');
break;
case 18:
packagePath = getAbsolutePath('./data/commitlint_18/node_modules');
packageJsonPath = getAbsolutePath('./data/commitlint_18/package.json');
configPath = getAbsolutePath('./data/commitlint_18/commitlint.config.js');
break;
case 19:
packagePath = getAbsolutePath('./data/commitlint_19/node_modules');
packageJsonPath = getAbsolutePath('./data/commitlint_19/package.json');
configPath = getAbsolutePath('./data/commitlint_19/commitlint.config.js');
break;
}
await render('cp', ['-r', packagePath, '.'], { cwd: dir });
await render('cp', [packageJsonPath, '.'], { cwd: dir });
await render('cp', [configPath, '.'], { cwd: dir });
await wait(3000); // Avoid flakiness by waiting
}
describe('cli flow to run "oco commitlint force"', () => {
it('on commitlint@9 using CJS', async () => {
const { gitDir, cleanup } = await prepareEnvironment();
await setupCommitlint(gitDir, 9);
const npmList = await render('npm', ['list', '@commitlint/load'], {
cwd: gitDir
});
expect(await npmList.findByText('@commitlint/load@9')).toBeInTheConsole();
const { findByText } = await render(
`
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
OCO_PROMPT_MODULE='@commitlint' \
OCO_AI_PROVIDER='test' \
node ${resolve('./out/cli.cjs')} commitlint force \
`,
[],
{ cwd: gitDir }
);
expect(
await findByText('opencommit — configure @commitlint')
).toBeInTheConsole();
expect(
await findByText('Read @commitlint configuration')
).toBeInTheConsole();
expect(
await findByText('Generating consistency with given @commitlint rules')
).toBeInTheConsole();
expect(
await findByText('Done - please review contents of')
).toBeInTheConsole();
await cleanup();
});
it('on commitlint@18 using CJS', async () => {
const { gitDir, cleanup } = await prepareEnvironment();
await setupCommitlint(gitDir, 18);
const npmList = await render('npm', ['list', '@commitlint/load'], {
cwd: gitDir
});
expect(await npmList.findByText('@commitlint/load@18')).toBeInTheConsole();
const { findByText } = await render(
`
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
OCO_PROMPT_MODULE='@commitlint' \
OCO_AI_PROVIDER='test' \
node ${resolve('./out/cli.cjs')} commitlint force \
`,
[],
{ cwd: gitDir }
);
expect(
await findByText('opencommit — configure @commitlint')
).toBeInTheConsole();
expect(
await findByText('Read @commitlint configuration')
).toBeInTheConsole();
expect(
await findByText('Generating consistency with given @commitlint rules')
).toBeInTheConsole();
expect(
await findByText('Done - please review contents of')
).toBeInTheConsole();
await cleanup();
});
it('on commitlint@19 using ESM', async () => {
const { gitDir, cleanup } = await prepareEnvironment();
await setupCommitlint(gitDir, 19);
const npmList = await render('npm', ['list', '@commitlint/load'], {
cwd: gitDir
});
expect(await npmList.findByText('@commitlint/load@19')).toBeInTheConsole();
const { findByText } = await render(
`
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
OCO_PROMPT_MODULE='@commitlint' \
OCO_AI_PROVIDER='test' \
node ${resolve('./out/cli.cjs')} commitlint force \
`,
[],
{ cwd: gitDir }
);
expect(
await findByText('opencommit — configure @commitlint')
).toBeInTheConsole();
expect(
await findByText('Read @commitlint configuration')
).toBeInTheConsole();
expect(
await findByText('Generating consistency with given @commitlint rules')
).toBeInTheConsole();
expect(
await findByText('Done - please review contents of')
).toBeInTheConsole();
await cleanup();
});
});
describe('cli flow to generate commit message using @commitlint prompt-module', () => {
it('on commitlint@19 using ESM', async () => {
const { gitDir, cleanup } = await prepareEnvironment();
// Setup commitlint@19
await setupCommitlint(gitDir, 19);
const npmList = await render('npm', ['list', '@commitlint/load'], {
cwd: gitDir
});
expect(await npmList.findByText('@commitlint/load@19')).toBeInTheConsole();
// Run `oco commitlint force`
const commitlintForce = await render(
`
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
OCO_PROMPT_MODULE='@commitlint' \
OCO_AI_PROVIDER='test' \
node ${resolve('./out/cli.cjs')} commitlint force \
`,
[],
{ cwd: gitDir }
);
expect(
await commitlintForce.findByText('Done - please review contents of')
).toBeInTheConsole();
// Run `oco commitlint get`
const commitlintGet = await render(
`
OCO_TEST_MOCK_TYPE='prompt-module-commitlint-config' \
OCO_PROMPT_MODULE='@commitlint' \
OCO_AI_PROVIDER='test' \
node ${resolve('./out/cli.cjs')} commitlint get \
`,
[],
{ cwd: gitDir }
);
expect(
await commitlintGet.findByText('[object Object]')
).toBeInTheConsole();
// Run 'oco' using .opencommit-commitlint
await render('echo', [`'console.log("Hello World");' > index.ts`], {
cwd: gitDir
});
await render('git', ['add index.ts'], { cwd: gitDir });
const oco = await render(
`
OCO_TEST_MOCK_TYPE='commit-message' \
OCO_PROMPT_MODULE='@commitlint' \
OCO_AI_PROVIDER='test' \
node ${resolve('./out/cli.cjs')} \
`,
[],
{ cwd: gitDir }
);
expect(
await oco.findByText('Generating the commit message')
).toBeInTheConsole();
expect(
await oco.findByText('Confirm the commit message?')
).toBeInTheConsole();
oco.userEvent.keyboard('[Enter]');
expect(
await oco.findByText('Choose a remote to push to')
).toBeInTheConsole();
oco.userEvent.keyboard('[Enter]');
expect(
await oco.findByText('Successfully pushed all commits to origin')
).toBeInTheConsole();
await cleanup();
});
});

View File

@@ -0,0 +1,3 @@
module.exports = {
extends: ['@commitlint/config-conventional']
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
{
"name": "commitlint-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@commitlint/cli": "^18.0.0",
"@commitlint/config-conventional": "^18.0.0"
}
}

View File

@@ -0,0 +1,3 @@
export default {
extends: ['@commitlint/config-conventional']
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
{
"name": "commitlint-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@commitlint/cli": "^19.0.0",
"@commitlint/config-conventional": "^19.0.0"
}
}

View File

@@ -0,0 +1,3 @@
module.exports = {
extends: ['@commitlint/config-conventional']
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
{
"name": "commitlint-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@commitlint/cli": "^9.0.0",
"@commitlint/config-conventional": "^9.0.0"
}
}

11
test/e2e/setup.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/bin/sh
current_dir=$(pwd)
setup_dir="$(cd "$(dirname "$0")" && pwd)"
# Set up for prompt-module/commitlint
cd $setup_dir && cd prompt-module/data/commitlint_9 && npm ci
cd $setup_dir && cd prompt-module/data/commitlint_18 && npm ci
cd $setup_dir && cd prompt-module/data/commitlint_19 && npm ci
cd $current_dir

View File

@@ -29,3 +29,5 @@ export const prepareEnvironment = async (): Promise<{
cleanup,
}
}
export const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

View File

@@ -1,5 +1,8 @@
import 'cli-testing-library/extend-expect'
import { configure } from 'cli-testing-library'
import { jest } from '@jest/globals';
global.jest = jest;
/**
* Adjusted the wait time for waitFor/findByText to 2000ms, because the default 1000ms makes the test results flaky

View File

@@ -55,7 +55,7 @@ OCO_ONE_LINE_COMMIT="true"
expect(config!['OCO_LANGUAGE']).toEqual('de');
expect(config!['OCO_MESSAGE_TEMPLATE_PLACEHOLDER']).toEqual('$m');
expect(config!['OCO_PROMPT_MODULE']).toEqual('@commitlint');
expect(config!['OCO_AI_PROVIDER']).toEqual('ollama');
expect(() => ['ollama', 'gemini'].includes(config!['OCO_AI_PROVIDER'])).toBeTruthy();
expect(config!['OCO_GITPUSH']).toEqual(false);
expect(config!['OCO_ONE_LINE_COMMIT']).toEqual(true);
@@ -96,10 +96,10 @@ OCO_ONE_LINE_COMMIT="true"
expect(config!['OCO_LANGUAGE']).toEqual('de');
expect(config!['OCO_MESSAGE_TEMPLATE_PLACEHOLDER']).toEqual('$m');
expect(config!['OCO_PROMPT_MODULE']).toEqual('@commitlint');
expect(config!['OCO_AI_PROVIDER']).toEqual('ollama');
expect(() => ['ollama', 'gemini'].includes(config!['OCO_AI_PROVIDER'])).toBeTruthy();
expect(config!['OCO_GITPUSH']).toEqual(false);
expect(config!['OCO_ONE_LINE_COMMIT']).toEqual(true);
await envFile.cleanup();
});
});
});

105
test/unit/gemini.test.ts Normal file
View File

@@ -0,0 +1,105 @@
import { Gemini } from '../../src/engine/gemini';
import { ChatCompletionRequestMessage } from 'openai';
import { GenerativeModel, GoogleGenerativeAI } from '@google/generative-ai';
import { ConfigType, getConfig } from '../../src/commands/config';
describe('Gemini', () => {
let gemini: Gemini;
let mockConfig: ConfigType;
let mockGoogleGenerativeAi: GoogleGenerativeAI;
let mockGenerativeModel: GenerativeModel;
let mockExit: jest.SpyInstance<never, [code?: number | undefined], any>;
let mockWarmup: jest.SpyInstance<any, unknown[], any>;
const noop: (code?: number | undefined) => never = (code?: number | undefined) => {};
const mockGemini = () => {
gemini = new Gemini();
}
const oldEnv = process.env;
beforeEach(() => {
jest.resetModules();
process.env = { ...oldEnv };
jest.mock('@google/generative-ai');
jest.mock('../src/commands/config');
jest.mock('@clack/prompts', () => ({
intro: jest.fn(),
outro: jest.fn(),
}));
if (mockWarmup) mockWarmup.mockRestore();
mockExit = jest.spyOn(process, 'exit').mockImplementation();
mockConfig = getConfig() as ConfigType;
mockConfig.OCO_AI_PROVIDER = 'gemini';
mockConfig.OCO_GEMINI_API_KEY = 'mock-api-key';
mockConfig.OCO_MODEL = 'gemini-1.5-flash';
mockGoogleGenerativeAi = new GoogleGenerativeAI(mockConfig.OCO_GEMINI_API_KEY);
mockGenerativeModel = mockGoogleGenerativeAi.getGenerativeModel({ model: mockConfig.OCO_MODEL, });
});
afterEach(() => {
gemini = undefined as any;
})
afterAll(() => {
mockExit.mockRestore();
process.env = oldEnv;
});
it('should initialize with correct config', () => {
mockGemini();
// gemini = new Gemini();
expect(gemini).toBeDefined();
});
it('should warmup correctly', () => {
mockWarmup = jest.spyOn(Gemini.prototype as any, 'warmup').mockImplementation(noop);
mockGemini();
expect(gemini).toBeDefined();
});
it('should exit process if OCO_GEMINI_API_KEY is not set and command is not config', () => {
process.env.OCO_GEMINI_API_KEY = undefined;
process.env.OCO_AI_PROVIDER = 'gemini';
mockGemini();
expect(mockExit).toHaveBeenCalledWith(1);
});
it('should exit process if model is not supported and command is not config', () => {
process.env.OCO_GEMINI_API_KEY = undefined;
process.env.OCO_AI_PROVIDER = 'gemini';
mockGemini();
expect(mockExit).toHaveBeenCalledWith(1);
});
it('should generate commit message', async () => {
const mockGenerateContent = jest.fn().mockResolvedValue({ response: { text: () => 'generated content' } });
mockGenerativeModel.generateContent = mockGenerateContent;
mockWarmup = jest.spyOn(Gemini.prototype as any, 'warmup').mockImplementation(noop);
mockGemini();
const messages: ChatCompletionRequestMessage[] = [
{ role: 'system', content: 'system message' },
{ role: 'assistant', content: 'assistant message' },
];
jest.spyOn(gemini, 'generateCommitMessage').mockImplementation(async () => 'generated content');
const result = await gemini.generateCommitMessage(messages);
expect(result).toEqual('generated content');
expect(mockWarmup).toHaveBeenCalled();
});
});

View File

@@ -1,12 +1,12 @@
{
"compilerOptions": {
"target": "ESNext",
"lib": ["ES5", "ES6"],
"target": "ES2020",
"lib": ["ES6", "ES2020"],
"module": "ESNext",
// "rootDir": "./src",
"module": "CommonJS",
"resolveJsonModule": true,
"moduleResolution": "node",
"moduleResolution": "Node",
"allowJs": true,