@jmandawg/gemini-vertex-review-code 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Tai Ha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @jmandawg/gemini-vertex-review-code
2
+
3
+ [![npm version](https://badge.fury.io/js/%40hataiit9x%2Freview-code-ai.svg)](https://badge.fury.io/js/%40hataiit9x%2Freview-code-ai)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ ## Summary
7
+
8
+ ![](preview.png)
9
+
10
+ This is a fork of the excellent work by `@hataiit9x` which adds support for vertex AI.
11
+ For more details, visit the [@hataiit9x/gemini-review-code](https://github.com/hataiit9x/gemini-review-code).
12
+
13
+ `@hataiit9x/gemini-review-code` It is a small tool used for code review in GitLab Merge Requests. It supports calling the GitLab API for private
14
+ deployment and uses the Gemini AI API to obtain review results. Please note that when using it, ensure compliance with company regulations. 😉
15
+
16
+
17
+ ## Features
18
+
19
+ - 🛠️ Support configuration GitLab API address
20
+ - ⚙️ Support configuration Gemini API Key to implement load balancing of interface calls (multiple Keys are separated by commas)
21
+ - 📦 Support configuration Gemini custom model ID
22
+ - 📦 Support configuration GitLab Project ID
23
+ - 📦 Support configuration GitLab Merge Request ID
24
+ - 🚀 Support running in CI/CD
25
+ - 🚦 Automatically wait and try again when the rate limit is exceeded
26
+ - 💬 The review results are appended to the location of the corresponding code block in the form of comments
27
+
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ npm i @hataiit9x/gemini-review-code
33
+ `````
34
+
35
+ ## Use
36
+
37
+ ### Use via shell script
38
+
39
+ ```shell
40
+ Usage: gemini-review-code [options]
41
+ Options:
42
+ -g, --gitlab-api-url <string> GitLab API URL (default: " https://gitlab.com/api/v4")
43
+ -t, --gitlab-access-token <string> GitLab Access Token
44
+ -a, --api-key <string> Gemini API Key
45
+ -p, --project-id <number> GitLab Project ID
46
+ -m, --merge-request-id <string> GitLab Merge Request ID
47
+ -c, --custom-model <string> Custom Model ID, (default: "gemini-1.5-flash")
48
+ -h, --help display help for command
49
+ -l, --location <string> GCP location (vertex only) (default: "global")
50
+ -z, --google-project-id <string> Google Project ID (vertex only)
51
+ ```
52
+
53
+ Example:
54
+
55
+ ```sh
56
+ gemini-review-code -g https://gitlab.com/api/v4 -t glpat-xxxxxxx -a AIzaSyAYNxxxxxxx,AIzaSyAYNxxxxxxx -p 1 -c gpt-3.5-turbo 432288 -m 8
57
+ ```
58
+
59
+ ### Use in CI
60
+
61
+ Set the `GITLAB_TOKEN` and `API_KEY` variables in GitLab CI/CD, `.gitlab-ci.yml` is as follows:
62
+
63
+ ```yml
64
+ stages:
65
+ - merge-request
66
+
67
+ Code Review:
68
+ stage: merge-request
69
+ image: node:16
70
+ script:
71
+ - npm i @hataiit9x/gemini-review-code -g
72
+ - gemini-review-code -t "$GITLAB_TOKEN" -a "$API_KEY" -c "$CUSTOM_MODELS" -p "$CI_MERGE_REQUEST_PROJECT_ID" -m "$CI_MERGE_REQUEST_IID"
73
+ only:
74
+ - merge_requests
75
+ when: on_success
76
+ ```
77
+
78
+ ## contribute
79
+ Welcome to contribute code, ask questions and suggestions! 👏
80
+
81
+ ## License
82
+ This project is based on the MIT license. See the LICENSE file for details. 📜
package/bin/index.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ const run = require('../lib/index.js');
4
+
5
+ run().catch(error => {
6
+ console.error(error);
7
+ process.exit(1);
8
+ });
package/lib/gemini.js ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.Gemini = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const utils_1 = require("./utils");
18
+ const SAFETY_SETTINGS = [
19
+ {
20
+ category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
21
+ threshold: 'BLOCK_NONE',
22
+ },
23
+ {
24
+ category: 'HARM_CATEGORY_HATE_SPEECH',
25
+ threshold: 'BLOCK_NONE',
26
+ },
27
+ {
28
+ category: 'HARM_CATEGORY_HARASSMENT',
29
+ threshold: 'BLOCK_NONE',
30
+ },
31
+ {
32
+ category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
33
+ threshold: 'BLOCK_NONE',
34
+ },
35
+ ];
36
+ class Gemini {
37
+ constructor(accessToken, customModel, googleProjectId, location) {
38
+ this.accessToken = accessToken;
39
+ this.customModel = customModel;
40
+ this.googleProjectId = googleProjectId;
41
+ this.location = location;
42
+ this.apiUrl = this.googleProjectId ? 'https://aiplatform.googleapis.com' : 'https://generativelanguage.googleapis.com';
43
+ this.apiClient = axios_1.default.create({
44
+ baseURL: this.apiUrl
45
+ });
46
+ }
47
+ reviewCodeChange(change) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ const apiKey = this.accessToken;
50
+ const geminiAPIURL = this.apiUrl;
51
+ const model = this.customModel || utils_1.geminiCompletionsConfig.model;
52
+ var url = `${geminiAPIURL}/v1beta/models/${model}:generateContent?key=${apiKey}`; // change to generateContent
53
+ if (this.googleProjectId) {
54
+ url = `${geminiAPIURL}/v1/projects/${this.googleProjectId}/locations/${this.location}/publishers/google/models/${model}:generateContent`; // change to generateContent
55
+ }
56
+ const headers = Object.assign({ 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41' }, this.googleProjectId && { Authorization: `Bearer ${this.accessToken}` });
57
+ const body = {
58
+ contents: [
59
+ {
60
+ role: 'user',
61
+ parts: [
62
+ {
63
+ text: change
64
+ }
65
+ ]
66
+ }
67
+ ],
68
+ systemInstruction: {
69
+ parts: [
70
+ {
71
+ text: utils_1.geminiSystemContent
72
+ },
73
+ {
74
+ text: utils_1.geminiSuggestContent
75
+ }
76
+ ]
77
+ },
78
+ safetySettings: SAFETY_SETTINGS,
79
+ };
80
+ try {
81
+ const response = yield this.apiClient.post(url, body, {
82
+ headers: headers,
83
+ });
84
+ if (response.status < 200 || response.status >= 300) {
85
+ throw new Error('Request failed');
86
+ }
87
+ const data = response.data;
88
+ return data.candidates[0].content.parts[0].text;
89
+ }
90
+ catch (e) {
91
+ console.log(JSON.stringify(e));
92
+ throw e;
93
+ }
94
+ });
95
+ }
96
+ }
97
+ exports.Gemini = Gemini;
98
+ //# sourceMappingURL=gemini.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gemini.js","sourceRoot":"","sources":["../src/gemini.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,kDAA2C;AAC3C,mCAIiB;AACjB,MAAM,eAAe,GAAG;IACpB;QACI,QAAQ,EAAE,iCAAiC;QAC3C,SAAS,EAAE,YAAY;KAC1B;IACD;QACI,QAAQ,EAAE,2BAA2B;QACrC,SAAS,EAAE,YAAY;KAC1B;IACD;QACI,QAAQ,EAAE,0BAA0B;QACpC,SAAS,EAAE,YAAY;KAC1B;IACD;QACI,QAAQ,EAAE,iCAAiC;QAC3C,SAAS,EAAE,YAAY;KAC1B;CACJ,CAAA;AAED,MAAa,MAAM;IAKf,YAAoB,WAAmB,EAAU,WAAoB,EAAU,eAAwB,EAAU,QAAiB;QAA9G,gBAAW,GAAX,WAAW,CAAQ;QAAU,gBAAW,GAAX,WAAW,CAAS;QAAU,oBAAe,GAAf,eAAe,CAAS;QAAU,aAAQ,GAAR,QAAQ,CAAS;QAC9H,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC,2CAA2C,CAAC;QACvH,IAAI,CAAC,SAAS,GAAG,eAAK,CAAC,MAAM,CAAC;YAC1B,OAAO,EAAE,IAAI,CAAC,MAAM;SACvB,CAAC,CAAC;IACP,CAAC;IAEK,gBAAgB,CAAC,MAAc;;YACjC,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,CAAA;YAC/B,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAA;YAChC,MAAM,KAAK,GAAG,IAAI,CAA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,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;YAChD,CAAC;YAAC,OAAM,CAAC,EAAE,CAAC;gBACR,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC/B,MAAM,CAAC,CAAC;YACZ,CAAC;QACL,CAAC;KAAA;CACJ;AAlED,wBAkEC"}
package/lib/gitlab.js ADDED
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.GitLab = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const parseLastDiff = (gitDiff) => {
18
+ var _a;
19
+ const diffList = gitDiff.split('\n').reverse();
20
+ const lastLineFirstChar = (_a = diffList === null || diffList === void 0 ? void 0 : diffList[1]) === null || _a === void 0 ? void 0 : _a[0];
21
+ const lastDiff = diffList.find((item) => {
22
+ return /^@@ \-\d+,\d+ \+\d+,\d+ @@/g.test(item);
23
+ }) || '';
24
+ const [lastOldLineCount, lastNewLineCount] = lastDiff
25
+ .replace(/@@ \-(\d+),(\d+) \+(\d+),(\d+) @@.*/g, ($0, $1, $2, $3, $4) => {
26
+ return `${+$1 + +$2},${+$3 + +$4}`;
27
+ })
28
+ .split(',');
29
+ if (!/^\d+$/.test(lastOldLineCount) || !/^\d+$/.test(lastNewLineCount)) {
30
+ return {
31
+ old_line: -1,
32
+ new_line: -1,
33
+ };
34
+ }
35
+ const old_line = lastLineFirstChar === '+' ? -1 : (parseInt(lastOldLineCount) || 0) - 1;
36
+ const new_line = lastLineFirstChar === '-' ? -1 : (parseInt(lastNewLineCount) || 0) - 1;
37
+ return {
38
+ old_line,
39
+ new_line,
40
+ };
41
+ };
42
+ class GitLab {
43
+ constructor({ gitlabApiUrl, gitlabAccessToken, projectId, mergeRequestId }) {
44
+ this.projectId = projectId;
45
+ this.mrId = mergeRequestId;
46
+ this.diffRefs = {};
47
+ this.apiClient = axios_1.default.create({
48
+ baseURL: gitlabApiUrl,
49
+ headers: {
50
+ 'Private-Token': gitlabAccessToken,
51
+ },
52
+ });
53
+ }
54
+ init() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ yield this.getMergeRequestInfo();
57
+ });
58
+ }
59
+ getMergeRequestInfo() {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ const response = yield this.apiClient.get(`/projects/${this.projectId}/merge_requests/${this.mrId}`);
62
+ this.mergeRequestInfo = response === null || response === void 0 ? void 0 : response.data;
63
+ });
64
+ }
65
+ getMergeRequestChanges() {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ var _a;
68
+ const response = yield this.apiClient.get(`/projects/${this.projectId}/merge_requests/${this.mrId}/diffs`);
69
+ const changes = (_a = response.data) === null || _a === void 0 ? void 0 : _a.map((item) => {
70
+ const { old_line, new_line } = parseLastDiff(item.diff);
71
+ return Object.assign(Object.assign({}, item), { old_line, new_line });
72
+ });
73
+ return changes;
74
+ });
75
+ }
76
+ getFileContent(filePath) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ var _a;
79
+ const response = yield this.apiClient.get(`/projects/${this.projectId}/repository/files/${encodeURIComponent(filePath)}/raw?ref=${(_a = this.mergeRequestInfo) === null || _a === void 0 ? void 0 : _a.source_branch}`);
80
+ return (response === null || response === void 0 ? void 0 : response.data) || '';
81
+ });
82
+ }
83
+ addReviewComment(lineObj, change, suggestion) {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ var _a;
86
+ const response = yield this.apiClient.post(`/projects/${this.projectId}/merge_requests/${this.mrId}/discussions`, {
87
+ body: suggestion,
88
+ position: Object.assign(Object.assign(Object.assign({ position_type: 'text' }, lineObj), { new_path: change.new_path, old_path: change.old_path }), (_a = this.mergeRequestInfo) === null || _a === void 0 ? void 0 : _a.diff_refs),
89
+ });
90
+ return response.data;
91
+ });
92
+ }
93
+ }
94
+ exports.GitLab = GitLab;
95
+ //# sourceMappingURL=gitlab.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gitlab.js","sourceRoot":"","sources":["../src/gitlab.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,kDAA2C;AAmB3C,MAAM,aAAa,GAAG,CAAC,OAAe,EAAE,EAAE;;IACtC,MAAM,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC;IAC/C,MAAM,iBAAiB,GAAG,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAG,CAAC,CAAC,0CAAG,CAAC,CAAC,CAAC;IAC7C,MAAM,QAAQ,GACV,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,OAAO,6BAA6B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpD,CAAC,CAAC,IAAI,EAAE,CAAC;IAEb,MAAM,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,GAAG,QAAQ;SAChD,OAAO,CAAC,sCAAsC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;QACpE,OAAO,GAAG,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC;IACvC,CAAC,CAAC;SACD,KAAK,CAAC,GAAG,CAAC,CAAC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AgB,0CAAE,SAAS,CACtC;aACJ,CAAC,CAAC;YACH,OAAO,QAAQ,CAAC,IAAI,CAAC;QACzB,CAAC;KAAA;CACJ;AAvDD,wBAuDC"}
package/lib/index.js ADDED
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const commander_1 = require("commander");
13
+ const gitlab_1 = require("./gitlab");
14
+ const gemini_1 = require("./gemini");
15
+ const utils_1 = require("./utils");
16
+ const program = new commander_1.Command();
17
+ program
18
+ .option('-g, --gitlab-api-url <string>', 'GitLab API URL', ' https://gitlab.com/api/v4')
19
+ .option('-t, --gitlab-access-token <string>', 'GitLab Access Token')
20
+ .option('-a, --api-key <string>', 'Gemini API Key')
21
+ .option('-p, --project-id <number>', 'GitLab Project ID')
22
+ .option('-m, --merge-request-id <string>', 'GitLab Merge Request ID')
23
+ .option('-c, --custom-model <string>', 'Custom Model ID', 'gemini-1.5-flash')
24
+ .option('-l, --location <string>', 'GCP location', 'global')
25
+ .option('-z, --google-project-id <string>', 'Google Project ID')
26
+ .parse(process.argv);
27
+ function run() {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ var _a, _b;
30
+ const { gitlabApiUrl, gitlabAccessToken, apiKey, projectId, mergeRequestId, customModel, location, googleProjectId, } = program.opts();
31
+ const gitlab = new gitlab_1.GitLab({ gitlabApiUrl, gitlabAccessToken, projectId, mergeRequestId });
32
+ let aiClient;
33
+ aiClient = new gemini_1.Gemini(apiKey, customModel, googleProjectId, location); // create a new instance of the Gemini class
34
+ yield gitlab.init().catch(() => {
35
+ console.log('gitlab init error');
36
+ });
37
+ const changes = yield gitlab.getMergeRequestChanges().catch(() => {
38
+ console.log('get merge request changes error');
39
+ });
40
+ for (const change of changes) {
41
+ if (change.renamed_file || change.deleted_file || !((_a = change === null || change === void 0 ? void 0 : change.diff) === null || _a === void 0 ? void 0 : _a.startsWith('@@'))) {
42
+ continue;
43
+ }
44
+ const diffBlocks = (0, utils_1.getDiffBlocks)(change === null || change === void 0 ? void 0 : change.diff);
45
+ while (!!diffBlocks.length) {
46
+ const item = diffBlocks.shift();
47
+ const lineRegex = /@@\s-(\d+)(?:,(\d+))?\s\+(\d+)(?:,(\d+))?\s@@/;
48
+ const matches = lineRegex.exec(item);
49
+ if (matches) {
50
+ const lineObj = (0, utils_1.getLineObj)(matches, item);
51
+ if (((lineObj === null || lineObj === void 0 ? void 0 : lineObj.new_line) && (lineObj === null || lineObj === void 0 ? void 0 : lineObj.new_line) > 0) || (lineObj.old_line && lineObj.old_line > 0)) {
52
+ try {
53
+ const suggestion = yield aiClient.reviewCodeChange(item);
54
+ yield gitlab.addReviewComment(lineObj, change, suggestion);
55
+ }
56
+ catch (e) {
57
+ if (((_b = e === null || e === void 0 ? void 0 : e.response) === null || _b === void 0 ? void 0 : _b.status) === 429) {
58
+ console.log('Too Many Requests, try again');
59
+ yield (0, utils_1.delay)(60 * 1000);
60
+ diffBlocks.push(item);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ console.log('done');
68
+ });
69
+ }
70
+ module.exports = run;
71
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,yCAAkC;AAClC,qCAAgC;AAChC,qCAAgC;AAChC,mCAAyD;AAEzD,MAAM,OAAO,GAAG,IAAI,mBAA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BAA8B,CAAC,CAAC;gCAC5C,MAAM,IAAA,aAAK,EAAC,EAAE,GAAG,IAAI,CAAC,CAAC;gCACvB,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;4BAC1B,CAAC;wBACL,CAAC;oBACL,CAAC;gBACL,CAAC;YACL,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;CAAA;AAED,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC"}
package/lib/utils.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLineObj = exports.getDiffBlocks = exports.delay = exports.geminiCompletionsConfig = exports.geminiSuggestContent = exports.geminiSystemContent = void 0;
4
+ exports.geminiSystemContent = "You are a code reviewer,Your role is to identify bugs, performance issues, and areas for optimization in the submitted code. You are also responsible for providing constructive feedback and suggesting best practices to improve the overall quality of the code. ";
5
+ exports.geminiSuggestContent = "Next, I will send you each step of the merge request in standard git diff format, your task is:\n" +
6
+ " - Review the code changes (diffs) in the patch and provide feedback.\n" +
7
+ " - Examine it carefully to see if it really has bugs or needs room for optimization, highlight them. \n" +
8
+ " - Do not highlight minor issues and nitpicks.\n" +
9
+ " - Use bullet points if you have multiple comments.\n" +
10
+ " - You don't have to explain what the code does\n" +
11
+ " Here are the changes that were committed this time";
12
+ exports.geminiCompletionsConfig = {
13
+ temperature: 1,
14
+ topP: 0.95,
15
+ topK: 64,
16
+ maxOutputTokens: 8192,
17
+ responseMimeType: "text/plain",
18
+ model: "gemini-1.5-flash",
19
+ };
20
+ const delay = (time) => {
21
+ return new Promise(resolve => setTimeout(resolve, time));
22
+ };
23
+ exports.delay = delay;
24
+ const getDiffBlocks = (diff) => {
25
+ const regex = /(?=@@\s-\d+(?:,\d+)?\s\+\d+(?:,\d+)?\s@@)/g;
26
+ const diffBlocks = diff.split(regex);
27
+ return diffBlocks;
28
+ };
29
+ exports.getDiffBlocks = getDiffBlocks;
30
+ const getLineObj = (matches, item) => {
31
+ var _a, _b, _c;
32
+ const lineObj = {};
33
+ const lastLine = (_c = (_b = (_a = item.split(/\r?\n/)) === null || _a === void 0 ? void 0 : _a.reverse()) === null || _b === void 0 ? void 0 : _b[1]) === null || _c === void 0 ? void 0 : _c.trim();
34
+ const oldLineStart = +matches[1];
35
+ const oldLineEnd = +matches[2] || 0;
36
+ const newLineStart = +matches[3];
37
+ const newLineEnd = +matches[4] || 0;
38
+ if ((lastLine === null || lastLine === void 0 ? void 0 : lastLine[0]) === '+') {
39
+ lineObj.new_line = newLineStart + newLineEnd - 1;
40
+ }
41
+ else if ((lastLine === null || lastLine === void 0 ? void 0 : lastLine[0]) === '-') {
42
+ lineObj.old_line = oldLineStart + oldLineEnd - 1;
43
+ }
44
+ else {
45
+ lineObj.new_line = newLineStart + newLineEnd - 1;
46
+ lineObj.old_line = oldLineStart + oldLineEnd - 1;
47
+ }
48
+ return lineObj;
49
+ };
50
+ exports.getLineObj = getLineObj;
51
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AACa,QAAA,mBAAmB,GAAG,uQAAuQ,CAAA;AAE7R,QAAA,oBAAoB,GAAG,mGAAmG;IACnI,gGAAgG;IAChG,gIAAgI;IAChI,yEAAyE;IACzE,8EAA8E;IAC9E,0EAA0E;IAC1E,4EAA4E,CAAA;AAGnE,QAAA,uBAAuB,GAAG;IACnC,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,EAAE;IACR,eAAe,EAAE,IAAI;IACrB,gBAAgB,EAAE,YAAY;IAC9B,KAAK,EAAE,kBAAkB;CAC5B,CAAA;AAEM,MAAM,KAAK,GAAG,CAAC,IAAY,EAAE,EAAE;IAClC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI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D,OAAO,CAAC,QAAQ,GAAG,YAAY,GAAG,UAAU,GAAG,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,OAAO,CAAC;AACnB,CAAC,CAAA;AAhBY,QAAA,UAAU,cAgBtB"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@jmandawg/gemini-vertex-review-code",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "bin": {
6
+ "gemini-vertex-review-code": "bin/index.js"
7
+ },
8
+ "scripts": {
9
+ "start": "tsc --watch",
10
+ "build": "tsc"
11
+ },
12
+ "files": [
13
+ "lib",
14
+ "bin"
15
+ ],
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/jmandawg/gemini-vertex-review-code.git"
20
+ },
21
+ "dependencies": {
22
+ "@types/axios": "^0.14.0",
23
+ "@types/commander": "^2.12.2",
24
+ "@types/node": "^20.2.1",
25
+ "axios": "^1.4.0",
26
+ "commander": "^10.0.1",
27
+ "typescript": "^5.9.3"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "description": "![](preview.png)",
34
+ "bugs": {
35
+ "url": "https://github.com/jmandawg/gemini-vertex-review-code/issues"
36
+ },
37
+ "homepage": "https://github.com/jmandawg/gemini-vertex-review-code#readme",
38
+ "keywords": [
39
+ "AI",
40
+ "Gemini",
41
+ "Code",
42
+ "Reviewer",
43
+ "Gitlab CI",
44
+ "Gitlab"
45
+ ],
46
+ "author": "Tai.Ha"
47
+ }