@parvez3019/gemini-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,77 @@
1
+ # @hataiit9x/gemini-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
+ `@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
11
+ deployment and uses the Gemini AI API to obtain review results. Please note that when using it, ensure compliance with company regulations. 😉
12
+
13
+
14
+ ## Features
15
+
16
+ - 🛠️ Support configuration GitLab API address
17
+ - ⚙️ Support configuration Gemini API Key to implement load balancing of interface calls (multiple Keys are separated by commas)
18
+ - 📦 Support configuration Gemini custom model ID
19
+ - 📦 Support configuration GitLab Project ID
20
+ - 📦 Support configuration GitLab Merge Request ID
21
+ - 🚀 Support running in CI/CD
22
+ - 🚦 Automatically wait and try again when the rate limit is exceeded
23
+ - 💬 The review results are appended to the location of the corresponding code block in the form of comments
24
+
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm i @hataiit9x/gemini-review-code
30
+ `````
31
+
32
+ ## Use
33
+
34
+ ### Use via shell script
35
+
36
+ ```shell
37
+ Usage: gemini-review-code [options]
38
+ Options:
39
+ -g, --gitlab-api-url <string> GitLab API URL (default: " https://gitlab.com/api/v4")
40
+ -t, --gitlab-access-token <string> GitLab Access Token
41
+ -a, --api-key <string> Gemini API Key
42
+ -p, --project-id <number> GitLab Project ID
43
+ -m, --merge-request-id <string> GitLab Merge Request ID
44
+ -c, --custom-model <string> Custom Model ID, (default: "gemini-1.5-flash")
45
+ -h, --help display help for command
46
+ ```
47
+
48
+ Example:
49
+
50
+ ```sh
51
+ 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
52
+ ```
53
+
54
+ ### Use in CI
55
+
56
+ Set the `GITLAB_TOKEN` and `API_KEY` variables in GitLab CI/CD, `.gitlab-ci.yml` is as follows:
57
+
58
+ ```yml
59
+ stages:
60
+ - merge-request
61
+
62
+ Code Review:
63
+ stage: merge-request
64
+ image: node:16
65
+ script:
66
+ - npm i @hataiit9x/gemini-review-code -g
67
+ - gemini-review-code -t "$GITLAB_TOKEN" -a "$API_KEY" -c "$CUSTOM_MODELS" -p "$CI_MERGE_REQUEST_PROJECT_ID" -m "$CI_MERGE_REQUEST_IID"
68
+ only:
69
+ - merge_requests
70
+ when: on_success
71
+ ```
72
+
73
+ ## contribute
74
+ Welcome to contribute code, ask questions and suggestions! 👏
75
+
76
+ ## License
77
+ 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,90 @@
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(apiUrl, accessToken, customModel) {
38
+ this.apiUrl = apiUrl;
39
+ this.accessToken = accessToken;
40
+ this.customModel = customModel;
41
+ this.apiClient = axios_1.default.create({
42
+ baseURL: apiUrl,
43
+ });
44
+ }
45
+ reviewCodeChange(change) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ const apiKey = this.accessToken;
48
+ const geminiAPIURL = this.apiUrl;
49
+ const model = this.customModel || utils_1.geminiCompletionsConfig.model;
50
+ const url = `${geminiAPIURL}/v1beta/models/${model}:generateContent?key=${apiKey}`; // change to generateContent
51
+ const headers = {
52
+ 'Content-Type': 'application/json',
53
+ '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',
54
+ };
55
+ const body = {
56
+ contents: [
57
+ {
58
+ role: 'user',
59
+ parts: [
60
+ {
61
+ text: change
62
+ }
63
+ ]
64
+ }
65
+ ],
66
+ systemInstruction: {
67
+ parts: [
68
+ {
69
+ text: utils_1.geminiSystemContent
70
+ },
71
+ {
72
+ text: utils_1.geminiSuggestContent
73
+ }
74
+ ]
75
+ },
76
+ safetySettings: SAFETY_SETTINGS,
77
+ };
78
+ const response = yield this.apiClient.post(url, body, {
79
+ headers: headers,
80
+ });
81
+ if (response.status < 200 || response.status >= 300) {
82
+ throw new Error('Request failed');
83
+ }
84
+ const data = response.data;
85
+ return data.candidates[0].content.parts[0].text;
86
+ });
87
+ }
88
+ }
89
+ exports.Gemini = Gemini;
90
+ //# 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,Y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OAAO;aACnB,CAAC,CAAC;YAEH,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC;gBAClD,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;YACtC,CAAC;YACD,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;YAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACpD,CAAC;KAAA;CACJ;AApDD,wBAoDC"}
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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J,aAAa,EAAE,MAAM,IAClB,OAAO,KACV,QAAQ,EAAE,MAAM,CAAC,QAAQ,EACzB,QAAQ,EAAE,MAAM,CAAC,QAAQ,KACtB,MAAA,IAAI,CAAC,gBAAgB,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,69 @@
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
+ .parse(process.argv);
25
+ function run() {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ var _a, _b;
28
+ const { gitlabApiUrl, gitlabAccessToken, apiKey, projectId, mergeRequestId, customModel, } = program.opts();
29
+ const gitlab = new gitlab_1.GitLab({ gitlabApiUrl, gitlabAccessToken, projectId, mergeRequestId });
30
+ let aiClient;
31
+ aiClient = new gemini_1.Gemini('https://generativelanguage.googleapis.com', apiKey, customModel); // create a new instance of the Gemini class
32
+ yield gitlab.init().catch(() => {
33
+ console.log('gitlab init error');
34
+ });
35
+ const changes = yield gitlab.getMergeRequestChanges().catch(() => {
36
+ console.log('get merge request changes error');
37
+ });
38
+ for (const change of changes) {
39
+ 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('@@'))) {
40
+ continue;
41
+ }
42
+ const diffBlocks = (0, utils_1.getDiffBlocks)(change === null || change === void 0 ? void 0 : change.diff);
43
+ while (!!diffBlocks.length) {
44
+ const item = diffBlocks.shift();
45
+ const lineRegex = /@@\s-(\d+)(?:,(\d+))?\s\+(\d+)(?:,(\d+))?\s@@/;
46
+ const matches = lineRegex.exec(item);
47
+ if (matches) {
48
+ const lineObj = (0, utils_1.getLineObj)(matches, item);
49
+ 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)) {
50
+ try {
51
+ const suggestion = yield aiClient.reviewCodeChange(item);
52
+ yield gitlab.addReviewComment(lineObj, change, suggestion);
53
+ }
54
+ catch (e) {
55
+ if (((_b = e === null || e === void 0 ? void 0 : e.response) === null || _b === void 0 ? void 0 : _b.status) === 429) {
56
+ console.log('Too Many Requests, try again');
57
+ yield (0, utils_1.delay)(60 * 1000);
58
+ diffBlocks.push(item);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
65
+ console.log('done');
66
+ });
67
+ }
68
+ module.exports = run;
69
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,yCAAkC;AAClC,qCAAgC;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AAC;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,CAAC,CAAC,CAAC;AAC7D,CAAC,CAAA;AAFY,QAAA,KAAK,SAEjB;AAEM,MAAM,a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ACD,OAAO,OAAO,CAAC;AACnB,CAAC,CAAA;AAhBY,QAAA,UAAU,cAgBtB"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@parvez3019/gemini-review-code",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "bin": {
6
+ "gemini-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/parvez3019/gemini-review-code"
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.0.4"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "description": "![](preview.png)",
34
+ "bugs": {
35
+ "url": "https://github.com/parvez3019/gemini-review-code/issues"
36
+ },
37
+ "homepage": "https://github.com/parvez3019/gemini-review-code#readme",
38
+ "keywords": [
39
+ "AI",
40
+ "Gemini",
41
+ "Code",
42
+ "Reviewer",
43
+ "Gitlab CI",
44
+ "Gitlab"
45
+ ],
46
+ "author": "parvez.hassan"
47
+ }