-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathbot.ts
208 lines (175 loc) · 6 KB
/
bot.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { Context, Probot } from 'probot';
import { minimatch } from 'minimatch'
import { Chat } from './chat.js';
import log from 'loglevel';
const OPENAI_API_KEY = 'OPENAI_API_KEY';
const MAX_PATCH_COUNT = process.env.MAX_PATCH_LENGTH
? +process.env.MAX_PATCH_LENGTH
: Infinity;
export const robot = (app: Probot) => {
const loadChat = async (context: Context) => {
if (process.env.OPENAI_API_KEY) {
return new Chat(process.env.OPENAI_API_KEY);
}
const repo = context.repo();
try {
const { data } = (await context.octokit.request(
'GET /repos/{owner}/{repo}/actions/variables/{name}',
{
owner: repo.owner,
repo: repo.repo,
name: OPENAI_API_KEY,
}
)) as any;
if (!data?.value) {
return null;
}
return new Chat(data.value);
} catch {
await context.octokit.issues.createComment({
repo: repo.repo,
owner: repo.owner,
issue_number: context.pullRequest().pull_number,
body: `Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow [readme](https://github.com/anc95/ChatGPT-CodeReview) for more information`,
});
return null;
}
};
app.on(
['pull_request.opened', 'pull_request.synchronize'],
async (context) => {
const repo = context.repo();
const chat = await loadChat(context);
if (!chat) {
log.info('Chat initialized failed');
return 'no chat';
}
const pull_request = context.payload.pull_request;
log.debug('pull_request:', pull_request);
if (
pull_request.state === 'closed' ||
pull_request.locked
) {
log.info('invalid event payload');
return 'invalid event payload';
}
const target_label = process.env.TARGET_LABEL;
if (
target_label &&
(!pull_request.labels?.length ||
pull_request.labels.every((label) => label.name !== target_label))
) {
log.info('no target label attached');
return 'no target label attached';
}
const data = await context.octokit.repos.compareCommits({
owner: repo.owner,
repo: repo.repo,
base: context.payload.pull_request.base.sha,
head: context.payload.pull_request.head.sha,
});
let { files: changedFiles, commits } = data.data;
log.debug("compareCommits, base:", context.payload.pull_request.base.sha, "head:", context.payload.pull_request.head.sha)
log.debug("compareCommits.commits:", commits)
log.debug("compareCommits.files", changedFiles)
if (context.payload.action === 'synchronize' && commits.length >= 2) {
const {
data: { files },
} = await context.octokit.repos.compareCommits({
owner: repo.owner,
repo: repo.repo,
base: commits[commits.length - 2].sha,
head: commits[commits.length - 1].sha,
});
changedFiles = files
}
const ignoreList = (process.env.IGNORE || process.env.ignore || '')
.split('\n')
.filter((v) => v !== '');
const ignorePatterns = (process.env.IGNORE_PATTERNS || '').split(',').filter((v) => Boolean(v.trim()));
const includePatterns = (process.env.INCLUDE_PATTERNS || '').split(',').filter((v) => Boolean(v.trim()));
log.debug('ignoreList:', ignoreList);
log.debug('ignorePatterns:', ignorePatterns);
changedFiles = changedFiles?.filter(
(file) => {
const url = new URL(file.contents_url)
// if includePatterns is not empty, only include files that match the pattern
if (includePatterns.length) {
return matchPatterns(includePatterns, url.pathname)
}
if (ignoreList.includes(file.filename)) {
return false;
}
// if ignorePatterns is not empty, ignore files that match the pattern
if (ignorePatterns.length) {
return !matchPatterns(ignorePatterns, url.pathname)
}
return true
})
if (!changedFiles?.length) {
log.info('no change found');
return 'no change';
}
console.time('gpt cost');
const ress = [];
for (let i = 0; i < changedFiles.length; i++) {
const file = changedFiles[i];
const patch = file.patch || '';
if (file.status !== 'modified' && file.status !== 'added') {
continue;
}
if (!patch || patch.length > MAX_PATCH_COUNT) {
log.info(
`${file.filename} skipped caused by its diff is too large`
);
continue;
}
try {
const res = await chat?.codeReview(patch);
if (!!res) {
ress.push({
path: file.filename,
body: res,
position: patch.split('\n').length - 1,
})
}
} catch (e) {
log.info(`review ${file.filename} failed`, e);
}
}
try {
await context.octokit.pulls.createReview({
repo: repo.repo,
owner: repo.owner,
pull_number: context.pullRequest().pull_number,
body: "Code review by ChatGPT",
event: 'COMMENT',
commit_id: commits[commits.length - 1].sha,
comments: ress,
});
} catch (e) {
log.info(`Failed to create review`, e);
}
console.timeEnd('gpt cost');
log.info(
'successfully reviewed',
context.payload.pull_request.html_url
);
return 'success';
}
);
};
const matchPatterns = (patterns: string[], path: string) => {
return patterns.some((pattern) => {
try {
return minimatch(path, pattern.startsWith('/') ? "**" + pattern : pattern.startsWith("**") ? pattern : "**/" + pattern);
} catch {
// if the pattern is not a valid glob pattern, try to match it as a regular expression
try {
return new RegExp(pattern).test(path);
} catch (e) {
return false;
}
}
})
}