plugin-git-manager 1.3.3 → 1.4.1
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/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
- package/dist/client/317.e7b1d59371812c30.js +10 -0
- package/dist/client/434.05d0ba2b821105dc.js +10 -0
- package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
- package/dist/client/454.625da741a7e1161f.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
- package/dist/client-v2/434.764113d20743a45b.js +10 -0
- package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
- package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +10 -9
- package/dist/locale/en-US.json +38 -1
- package/dist/locale/vi-VN.json +38 -1
- package/dist/locale/zh-CN.json +41 -1
- package/dist/node_modules/simple-git/package.json +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/actions/chat-context.js +282 -0
- package/dist/server/actions/git-actions.js +387 -80
- package/dist/server/actions/gitlab-api.js +101 -15
- package/dist/server/actions/subtree.js +20 -10
- package/dist/server/chat-context-admission.js +187 -0
- package/dist/server/plugin.js +142 -10
- package/dist/server/repository-access.js +2 -2
- package/dist/server/request-method-policy.js +4 -1
- package/dist/server/services/review-source.js +2 -1
- package/dist/server/utils/cluster-git.js +181 -0
- package/package.json +2 -2
- package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
- package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
- package/src/client/__tests__/ai-context.test.tsx +119 -0
- package/src/client/__tests__/workflowRoutes.test.ts +3 -1
- package/src/client/ai-context.tsx +3 -113
- package/src/client/components/CommitHistory.tsx +19 -7
- package/src/client/components/FileExplorer.tsx +80 -34
- package/src/client/components/GitManagerSettings.tsx +21 -5
- package/src/client/components/GitOperations.tsx +25 -4
- package/src/client/components/GitRuntimeBanner.tsx +97 -0
- package/src/client/components/RepositoryConfig.tsx +28 -6
- package/src/client/context/GitManagerContext.tsx +174 -15
- package/src/client/index.tsx +3 -5
- package/src/client/workflowRoutes.ts +11 -0
- package/src/client-v2/ai-context.tsx +135 -72
- package/src/client-v2/components/GitContextPicker.tsx +418 -0
- package/src/client-v2/git-context-api.ts +59 -0
- package/src/client-v2/plugin.tsx +2 -4
- package/src/locale/en-US.json +38 -1
- package/src/locale/vi-VN.json +38 -1
- package/src/locale/zh-CN.json +41 -1
- package/src/server/__tests__/chat-context-admission.test.ts +276 -0
- package/src/server/__tests__/chat-context-options.test.ts +144 -0
- package/src/server/__tests__/git-actions.test.ts +329 -4
- package/src/server/__tests__/git-chat-context.test.ts +138 -0
- package/src/server/__tests__/git-security.test.ts +52 -0
- package/src/server/__tests__/smoke.test.ts +232 -1
- package/src/server/actions/chat-context.ts +302 -0
- package/src/server/actions/git-actions.ts +428 -89
- package/src/server/actions/gitlab-api.ts +113 -14
- package/src/server/actions/subtree.ts +23 -6
- package/src/server/chat-context-admission.ts +182 -0
- package/src/server/plugin.ts +163 -3
- package/src/server/repository-access.ts +2 -2
- package/src/server/request-method-policy.ts +3 -0
- package/src/server/services/review-source.ts +3 -2
- package/src/server/utils/cluster-git.ts +209 -0
- package/dist/client/317.17ed0018e3e7db00.js +0 -10
- package/dist/client/434.b2eeaaef33aae6e0.js +0 -10
- package/dist/client/453.fc3042c9740d8fab.js +0 -10
- package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
- package/dist/client-v2/434.19c7579c06b9077c.js +0 -10
- package/dist/client-v2/453.5e507c94c59277b1.js +0 -10
|
@@ -1,9 +1,60 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { execFileSync } from 'child_process';
|
|
4
|
+
import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
|
|
5
|
+
import { tmpdir } from 'os';
|
|
6
|
+
import { join } from 'path';
|
|
1
7
|
import { Context } from '@nocobase/actions';
|
|
2
|
-
import { vi } from 'vitest';
|
|
8
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
9
|
+
import {
|
|
10
|
+
clone,
|
|
11
|
+
fileContent,
|
|
12
|
+
fileTree,
|
|
13
|
+
getRepo,
|
|
14
|
+
installGit,
|
|
15
|
+
resetGitBinaryCacheForTests,
|
|
16
|
+
runtimeStatus,
|
|
17
|
+
validateRepoRelativePath,
|
|
18
|
+
withAuth,
|
|
19
|
+
} from '../actions/git-actions';
|
|
20
|
+
import { mergeRequestDetail, mergeRequestNotes, readChatMergeRequest } from '../actions/gitlab-api';
|
|
21
|
+
import { subtreeOptions } from '../actions/subtree';
|
|
22
|
+
import { resolveReviewSource } from '../services/review-source';
|
|
23
|
+
import { resetClusterGitDispatchCooldownForTests } from '../utils/cluster-git';
|
|
24
|
+
|
|
25
|
+
const record = (values: Record<string, unknown>) => ({ get: (key: string) => values[key] });
|
|
26
|
+
|
|
27
|
+
function createThrower() {
|
|
28
|
+
return vi.fn((status: number, message: string): never => {
|
|
29
|
+
throw Object.assign(new Error(message), { status });
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('Git Manager git actions & security fixes', () => {
|
|
34
|
+
let fixture: string;
|
|
35
|
+
const originalBase = process.env.GIT_REPOS_BASE_PATH;
|
|
36
|
+
const originalGitBinary = process.env.GIT_BINARY_PATH;
|
|
37
|
+
|
|
38
|
+
beforeEach(() => {
|
|
39
|
+
fixture = mkdtempSync(join(tmpdir(), 'git-actions-test-'));
|
|
40
|
+
process.env.GIT_REPOS_BASE_PATH = fixture;
|
|
41
|
+
delete process.env.GIT_BINARY_PATH;
|
|
42
|
+
resetGitBinaryCacheForTests();
|
|
43
|
+
resetClusterGitDispatchCooldownForTests();
|
|
44
|
+
});
|
|
3
45
|
|
|
4
|
-
|
|
46
|
+
afterEach(() => {
|
|
47
|
+
vi.restoreAllMocks();
|
|
48
|
+
vi.unstubAllGlobals();
|
|
49
|
+
if (originalBase === undefined) delete process.env.GIT_REPOS_BASE_PATH;
|
|
50
|
+
else process.env.GIT_REPOS_BASE_PATH = originalBase;
|
|
51
|
+
if (originalGitBinary === undefined) delete process.env.GIT_BINARY_PATH;
|
|
52
|
+
else process.env.GIT_BINARY_PATH = originalGitBinary;
|
|
53
|
+
resetGitBinaryCacheForTests();
|
|
54
|
+
resetClusterGitDispatchCooldownForTests();
|
|
55
|
+
rmSync(fixture, { recursive: true, force: true });
|
|
56
|
+
});
|
|
5
57
|
|
|
6
|
-
describe('Git Manager git actions', () => {
|
|
7
58
|
it('uses the repository ID from the request body over the URL parameter', async () => {
|
|
8
59
|
const repository = { id: 20 };
|
|
9
60
|
const findOne = vi.fn().mockResolvedValue(repository);
|
|
@@ -13,7 +64,7 @@ describe('Git Manager git actions', () => {
|
|
|
13
64
|
db: {
|
|
14
65
|
getRepository: vi.fn().mockReturnValue({ findOne }),
|
|
15
66
|
},
|
|
16
|
-
throw:
|
|
67
|
+
throw: createThrower(),
|
|
17
68
|
};
|
|
18
69
|
|
|
19
70
|
const result = await getRepo(context as unknown as Context);
|
|
@@ -21,4 +72,278 @@ describe('Git Manager git actions', () => {
|
|
|
21
72
|
expect(findOne).toHaveBeenCalledWith({ filterByTk: 20 });
|
|
22
73
|
expect(result).toBe(repository);
|
|
23
74
|
});
|
|
75
|
+
|
|
76
|
+
it.each(['../../../other-org/secret-repo/pulls/1', '../variables', '0', '-4', '12/files', 'abc'])(
|
|
77
|
+
'blocks path traversal and non-integer mrIid (%s) before calling provider API',
|
|
78
|
+
async (badMrIid) => {
|
|
79
|
+
const fetchMock = vi.fn();
|
|
80
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
81
|
+
const repoRecord = record({ id: 1, gitAccountId: 1, repoUrl: 'https://github.com/org/allowed-repo.git' });
|
|
82
|
+
const accountRecord = record({ provider: 'github', baseUrl: null, pat: 'ghp_secret', username: 'bot' });
|
|
83
|
+
const db = {
|
|
84
|
+
getRepository: (name: string) => ({
|
|
85
|
+
findOne: async () => (name === 'gitAccounts' ? accountRecord : repoRecord),
|
|
86
|
+
}),
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const makeCtx = () =>
|
|
90
|
+
({
|
|
91
|
+
db,
|
|
92
|
+
action: { params: { repositoryId: 1, mrIid: badMrIid } },
|
|
93
|
+
throw: createThrower(),
|
|
94
|
+
}) as unknown as Context;
|
|
95
|
+
|
|
96
|
+
await expect(mergeRequestDetail(makeCtx(), async () => {})).rejects.toMatchObject({
|
|
97
|
+
status: 400,
|
|
98
|
+
message: 'Invalid merge request ID',
|
|
99
|
+
});
|
|
100
|
+
await expect(mergeRequestNotes(makeCtx(), async () => {})).rejects.toMatchObject({
|
|
101
|
+
status: 400,
|
|
102
|
+
message: 'Invalid merge request ID',
|
|
103
|
+
});
|
|
104
|
+
await expect(readChatMergeRequest(makeCtx(), badMrIid as unknown as number, 1)).rejects.toMatchObject({
|
|
105
|
+
status: 400,
|
|
106
|
+
message: 'Invalid merge request ID',
|
|
107
|
+
});
|
|
108
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
109
|
+
},
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
it('validates repository-relative paths by segment while allowing filenames containing double dots', () => {
|
|
113
|
+
expect(validateRepoRelativePath('docs/v1..v2-migration.md')).toBe('docs/v1..v2-migration.md');
|
|
114
|
+
expect(validateRepoRelativePath('/src/index.ts/')).toBe('src/index.ts');
|
|
115
|
+
for (const unsafe of ['../secret', 'src/../../etc/passwd', 'src/./file.ts', 'C:/windows/win.ini', 'bad\0file.ts']) {
|
|
116
|
+
expect(() => validateRepoRelativePath(unsafe)).toThrow('Invalid file path');
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('reads UTF-8 Vietnamese filenames without octal quoting in fileTree and fileContent', async () => {
|
|
121
|
+
const repoDir = join(fixture, 'utf8-repo');
|
|
122
|
+
mkdirSync(repoDir);
|
|
123
|
+
execFileSync('git', ['init', '-b', 'main', repoDir], { stdio: 'ignore' });
|
|
124
|
+
const utf8File = 'tài-liệu..v2.md';
|
|
125
|
+
writeFileSync(join(repoDir, utf8File), 'Xin chào NocoBase', 'utf8');
|
|
126
|
+
execFileSync('git', ['-C', repoDir, 'add', utf8File], { stdio: 'ignore' });
|
|
127
|
+
execFileSync(
|
|
128
|
+
'git',
|
|
129
|
+
['-C', repoDir, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-m', 'utf8'],
|
|
130
|
+
{ stdio: 'ignore' },
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
const repoRecord = record({ id: 1, localPath: 'utf8-repo', repoUrl: 'https://github.com/org/utf8.git' });
|
|
134
|
+
const db = {
|
|
135
|
+
getRepository: () => ({ findOne: async () => repoRecord }),
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const treeCtx = {
|
|
139
|
+
db,
|
|
140
|
+
action: { params: { repositoryId: 1, ref: 'HEAD' } },
|
|
141
|
+
body: undefined as unknown,
|
|
142
|
+
throw: createThrower(),
|
|
143
|
+
};
|
|
144
|
+
await fileTree(treeCtx as unknown as Context, async () => {});
|
|
145
|
+
const treeItems = (treeCtx.body as { data: Array<{ name: string; path: string }> }).data;
|
|
146
|
+
expect(treeItems).toEqual([expect.objectContaining({ name: utf8File, path: utf8File })]);
|
|
147
|
+
|
|
148
|
+
const contentCtx = {
|
|
149
|
+
db,
|
|
150
|
+
action: { params: { repositoryId: 1, ref: 'HEAD', filePath: utf8File } },
|
|
151
|
+
body: undefined as unknown,
|
|
152
|
+
throw: createThrower(),
|
|
153
|
+
};
|
|
154
|
+
await fileContent(contentCtx as unknown as Context, async () => {});
|
|
155
|
+
expect(contentCtx.body).toMatchObject({
|
|
156
|
+
success: true,
|
|
157
|
+
data: { content: 'Xin chào NocoBase', filePath: utf8File, ref: 'HEAD' },
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('uses distributed lockManager in withAuth and skips rewriting remote URL when unchanged', async () => {
|
|
162
|
+
const runExclusive = vi.fn(async (_key: string, fn: () => Promise<unknown>) => fn());
|
|
163
|
+
const git = {
|
|
164
|
+
env: vi.fn(),
|
|
165
|
+
raw: vi.fn().mockResolvedValue('https://github.com/org/repo.git\n'),
|
|
166
|
+
remote: vi.fn(),
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const result = await withAuth(
|
|
170
|
+
git as never,
|
|
171
|
+
join(fixture, 'locked-repo'),
|
|
172
|
+
'https://github.com/org/repo.git',
|
|
173
|
+
'ghp_token',
|
|
174
|
+
async () => 'ok',
|
|
175
|
+
'bot',
|
|
176
|
+
'origin',
|
|
177
|
+
{ runExclusive },
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
expect(result).toBe('ok');
|
|
181
|
+
expect(runExclusive).toHaveBeenCalledTimes(1);
|
|
182
|
+
expect(git.remote).not.toHaveBeenCalled();
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('reports accurate missing-directory and missing-git errors in subtree and review-source', async () => {
|
|
186
|
+
const repoRecord = record({
|
|
187
|
+
id: 1,
|
|
188
|
+
gitAccountId: 1,
|
|
189
|
+
localPath: 'not-cloned-yet',
|
|
190
|
+
repoUrl: 'https://github.com/org/repo.git',
|
|
191
|
+
defaultBranch: 'main',
|
|
192
|
+
});
|
|
193
|
+
const accountRecord = record({ provider: 'github', baseUrl: null, pat: 'ghp_token', username: 'bot' });
|
|
194
|
+
const db = {
|
|
195
|
+
getRepository: (name: string) => ({
|
|
196
|
+
findOne: async () => (name === 'gitAccounts' ? accountRecord : repoRecord),
|
|
197
|
+
}),
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
const subtreeCtx = {
|
|
201
|
+
db,
|
|
202
|
+
action: { params: { repositoryId: 1 } },
|
|
203
|
+
t: (msg: string) => msg,
|
|
204
|
+
throw: createThrower(),
|
|
205
|
+
};
|
|
206
|
+
await expect(subtreeOptions(subtreeCtx as unknown as Context, async () => {})).rejects.toMatchObject({
|
|
207
|
+
status: 400,
|
|
208
|
+
message: 'Repository directory does not exist. Please clone the repository first.',
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
vi.stubGlobal(
|
|
212
|
+
'fetch',
|
|
213
|
+
vi
|
|
214
|
+
.fn()
|
|
215
|
+
.mockResolvedValue(
|
|
216
|
+
new Response(JSON.stringify({ id: 99, html_url: 'https://github.com/org/repo' }), { status: 200 }),
|
|
217
|
+
),
|
|
218
|
+
);
|
|
219
|
+
await expect(
|
|
220
|
+
resolveReviewSource(db as never, repoRecord, { targetType: 'branch', branch: 'main' }),
|
|
221
|
+
).rejects.toMatchObject({
|
|
222
|
+
status: 400,
|
|
223
|
+
message: 'Repository directory does not exist. Please clone the repository first.',
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it('reconnects an existing matching git directory during clone instead of failing with directory exists', async () => {
|
|
228
|
+
const remoteBare = join(fixture, 'remote.git');
|
|
229
|
+
const existingClone = join(fixture, 'existing-clone');
|
|
230
|
+
mkdirSync(remoteBare);
|
|
231
|
+
mkdirSync(existingClone);
|
|
232
|
+
execFileSync('git', ['init', '--bare', remoteBare], { stdio: 'ignore' });
|
|
233
|
+
execFileSync('git', ['init', '-b', 'main', existingClone], { stdio: 'ignore' });
|
|
234
|
+
execFileSync('git', ['-C', existingClone, 'remote', 'add', 'origin', 'https://github.com/org/repo.git'], {
|
|
235
|
+
stdio: 'ignore',
|
|
236
|
+
});
|
|
237
|
+
execFileSync(
|
|
238
|
+
'git',
|
|
239
|
+
[
|
|
240
|
+
'-C',
|
|
241
|
+
existingClone,
|
|
242
|
+
'config',
|
|
243
|
+
`url.${remoteBare.replace(/\\/g, '/')}.insteadOf`,
|
|
244
|
+
'https://github.com/org/repo.git',
|
|
245
|
+
],
|
|
246
|
+
{ stdio: 'ignore' },
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
const update = vi.fn().mockResolvedValue(undefined);
|
|
250
|
+
const repoRecord = record({
|
|
251
|
+
id: 5,
|
|
252
|
+
gitAccountId: 1,
|
|
253
|
+
localPath: 'existing-clone',
|
|
254
|
+
repoUrl: 'https://github.com/org/repo.git',
|
|
255
|
+
defaultBranch: 'main',
|
|
256
|
+
});
|
|
257
|
+
const accountRecord = record({ provider: 'github', baseUrl: null, pat: 'ghp_token', username: 'bot' });
|
|
258
|
+
|
|
259
|
+
const ctx = {
|
|
260
|
+
db: {
|
|
261
|
+
getRepository: (name: string) => ({
|
|
262
|
+
findOne: async () => (name === 'gitAccounts' ? accountRecord : repoRecord),
|
|
263
|
+
update,
|
|
264
|
+
}),
|
|
265
|
+
},
|
|
266
|
+
action: { params: { repositoryId: 5 } },
|
|
267
|
+
body: undefined as unknown,
|
|
268
|
+
throw: createThrower(),
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
await clone(ctx as unknown as Context, async () => {});
|
|
272
|
+
expect(update).toHaveBeenCalledWith({ filterByTk: 5, values: { status: 'connected' } });
|
|
273
|
+
expect(ctx.body).toMatchObject({ success: true, message: 'Repository reconnected successfully' });
|
|
274
|
+
expect(existsSync(existingClone)).toBe(true);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it('auto-dispatches Cluster Manager git installation when git is missing and recovers dynamically once installed', async () => {
|
|
278
|
+
const missingBin = join(fixture, 'missing-git-bin');
|
|
279
|
+
process.env.GIT_BINARY_PATH = missingBin;
|
|
280
|
+
resetGitBinaryCacheForTests();
|
|
281
|
+
|
|
282
|
+
const publish = vi.fn().mockResolvedValue(undefined);
|
|
283
|
+
const updateConfig = vi.fn().mockResolvedValue(undefined);
|
|
284
|
+
const pkgConfig = record({
|
|
285
|
+
id: 1,
|
|
286
|
+
aptPackages: 'python3\ngit',
|
|
287
|
+
initStatus: 'succeeded',
|
|
288
|
+
lastInitAt: '2026-11-25T19:02:33.000Z',
|
|
289
|
+
initProgressPercent: 100,
|
|
290
|
+
aptMirrorUrl: '',
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
const app = {
|
|
294
|
+
pm: { get: (name: string) => (name === 'plugin-cluster-manager' ? {} : undefined) },
|
|
295
|
+
db: {
|
|
296
|
+
getCollection: (name: string) => (name === 'workerPackagesConfigs' ? {} : undefined),
|
|
297
|
+
getRepository: (name: string) =>
|
|
298
|
+
name === 'workerPackagesConfigs'
|
|
299
|
+
? { findOne: async () => pkgConfig, create: vi.fn(), update: updateConfig }
|
|
300
|
+
: undefined,
|
|
301
|
+
},
|
|
302
|
+
pubSubManager: { isConnected: async () => true, publish },
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const statusCtx = {
|
|
306
|
+
app,
|
|
307
|
+
body: undefined as unknown,
|
|
308
|
+
throw: createThrower(),
|
|
309
|
+
};
|
|
310
|
+
await runtimeStatus(statusCtx as unknown as Context, async () => {});
|
|
311
|
+
|
|
312
|
+
expect(publish).toHaveBeenCalledWith('cluster-manager.install-packages', {
|
|
313
|
+
targetRole: 'all',
|
|
314
|
+
packages: { apt: ['git'] },
|
|
315
|
+
registryConfig: { aptMirrorUrl: undefined },
|
|
316
|
+
});
|
|
317
|
+
expect(statusCtx.body).toMatchObject({
|
|
318
|
+
success: true,
|
|
319
|
+
data: {
|
|
320
|
+
gitAvailable: false,
|
|
321
|
+
clusterManager: { available: true, gitConfigured: true, status: 'running' },
|
|
322
|
+
},
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
// Simulate Cluster Manager finishing git installation on the running node without restarting the server
|
|
326
|
+
delete process.env.GIT_BINARY_PATH;
|
|
327
|
+
const recoveredCtx = {
|
|
328
|
+
app,
|
|
329
|
+
body: undefined as unknown,
|
|
330
|
+
throw: createThrower(),
|
|
331
|
+
};
|
|
332
|
+
await runtimeStatus(recoveredCtx as unknown as Context, async () => {});
|
|
333
|
+
expect(recoveredCtx.body).toMatchObject({
|
|
334
|
+
success: true,
|
|
335
|
+
data: { gitAvailable: true },
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
const installCtx = {
|
|
339
|
+
app,
|
|
340
|
+
body: undefined as unknown,
|
|
341
|
+
throw: createThrower(),
|
|
342
|
+
};
|
|
343
|
+
await installGit(installCtx as unknown as Context, async () => {});
|
|
344
|
+
expect(installCtx.body).toMatchObject({
|
|
345
|
+
success: true,
|
|
346
|
+
data: { alreadyInstalled: true },
|
|
347
|
+
});
|
|
348
|
+
});
|
|
24
349
|
});
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { execFileSync } from 'child_process';
|
|
4
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync, renameSync } from 'fs';
|
|
5
|
+
import { tmpdir } from 'os';
|
|
6
|
+
import { join } from 'path';
|
|
7
|
+
import type { Context } from '@nocobase/actions';
|
|
8
|
+
import { log, readChatCommit } from '../actions/git-actions';
|
|
9
|
+
|
|
10
|
+
describe('Git chat commit context', () => {
|
|
11
|
+
let fixture: string;
|
|
12
|
+
let repoPath: string;
|
|
13
|
+
const previousBasePath = process.env.GIT_REPOS_BASE_PATH;
|
|
14
|
+
|
|
15
|
+
const runGit = (args: string[]) => execFileSync('git', ['-C', repoPath, ...args], { encoding: 'utf8' }).trim();
|
|
16
|
+
|
|
17
|
+
const commit = (message: string) => {
|
|
18
|
+
runGit(['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'add', '-A']);
|
|
19
|
+
runGit(['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-m', message]);
|
|
20
|
+
return runGit(['rev-parse', 'HEAD']);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const createContext = (params: Record<string, unknown> = {}) => {
|
|
24
|
+
const repository = { get: (field: string) => (field === 'localPath' ? 'repository' : undefined) };
|
|
25
|
+
const context = {
|
|
26
|
+
action: { params: { repositoryId: 1, ...params } },
|
|
27
|
+
db: {
|
|
28
|
+
getRepository: vi.fn(() => ({ findOne: vi.fn().mockResolvedValue(repository) })),
|
|
29
|
+
},
|
|
30
|
+
throw: (status: number, message: string): never => {
|
|
31
|
+
throw Object.assign(new Error(message), { status });
|
|
32
|
+
},
|
|
33
|
+
body: undefined as unknown,
|
|
34
|
+
};
|
|
35
|
+
return context as unknown as Context & { body: unknown };
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
beforeEach(() => {
|
|
39
|
+
fixture = mkdtempSync(join(tmpdir(), 'git-chat-context-'));
|
|
40
|
+
repoPath = join(fixture, 'repository');
|
|
41
|
+
mkdirSync(repoPath);
|
|
42
|
+
process.env.GIT_REPOS_BASE_PATH = fixture;
|
|
43
|
+
execFileSync('git', ['init', '--initial-branch=main', repoPath], { stdio: 'ignore' });
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
afterEach(() => {
|
|
47
|
+
if (previousBasePath === undefined) delete process.env.GIT_REPOS_BASE_PATH;
|
|
48
|
+
else process.env.GIT_REPOS_BASE_PATH = previousBasePath;
|
|
49
|
+
if (fixture) rmSync(fixture, { recursive: true, force: true });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('reads a root commit and returns only the bounded changed file context', async () => {
|
|
53
|
+
writeFileSync(join(repoPath, 'root.txt'), 'root content\n');
|
|
54
|
+
const rootCommit = commit('Initial commit');
|
|
55
|
+
|
|
56
|
+
const result = await readChatCommit(createContext(), rootCommit, 50, 1024);
|
|
57
|
+
|
|
58
|
+
expect(result.commitSha).toBe(rootCommit);
|
|
59
|
+
expect(result.subject).toBe('Initial commit');
|
|
60
|
+
expect(result.files).toEqual([{ oldPath: 'root.txt', newPath: 'root.txt', status: 'A' }]);
|
|
61
|
+
expect(result.diff).toContain('+root content');
|
|
62
|
+
expect(result.truncated).toBe(false);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('reads history from the selected branch and applies the requested offset', async () => {
|
|
66
|
+
writeFileSync(join(repoPath, 'root.txt'), 'root\n');
|
|
67
|
+
commit('root');
|
|
68
|
+
writeFileSync(join(repoPath, 'main.txt'), 'main\n');
|
|
69
|
+
commit('main change');
|
|
70
|
+
runGit(['checkout', '-b', 'feature/chat-context']);
|
|
71
|
+
writeFileSync(join(repoPath, 'feature-one.txt'), 'first\n');
|
|
72
|
+
const firstFeatureCommit = commit('first feature change');
|
|
73
|
+
writeFileSync(join(repoPath, 'feature-two.txt'), 'second\n');
|
|
74
|
+
commit('second feature change');
|
|
75
|
+
|
|
76
|
+
const context = createContext({ branch: 'feature/chat-context', skip: 1, maxCount: 1 });
|
|
77
|
+
await log(context, vi.fn().mockResolvedValue(undefined));
|
|
78
|
+
|
|
79
|
+
const body = context.body as { data: { all: Array<{ hash: string }> } };
|
|
80
|
+
expect(body.data.all).toHaveLength(1);
|
|
81
|
+
expect(body.data.all[0].hash).toBe(firstFeatureCommit);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('compares merge commits with their first parent', async () => {
|
|
85
|
+
writeFileSync(join(repoPath, 'root.txt'), 'root\n');
|
|
86
|
+
commit('root');
|
|
87
|
+
runGit(['checkout', '-b', 'feature']);
|
|
88
|
+
writeFileSync(join(repoPath, 'feature.txt'), 'feature change\n');
|
|
89
|
+
commit('feature change');
|
|
90
|
+
runGit(['checkout', 'main']);
|
|
91
|
+
writeFileSync(join(repoPath, 'main-only.txt'), 'main change\n');
|
|
92
|
+
commit('main change');
|
|
93
|
+
runGit(['merge', '--no-ff', 'feature', '-m', 'merge feature']);
|
|
94
|
+
const mergeCommit = runGit(['rev-parse', 'HEAD']);
|
|
95
|
+
|
|
96
|
+
const result = await readChatCommit(createContext(), mergeCommit, 50, 2048);
|
|
97
|
+
|
|
98
|
+
expect(result.subject).toBe('merge feature');
|
|
99
|
+
expect(result.files.map((file) => file.newPath)).toEqual(['feature.txt']);
|
|
100
|
+
expect(result.diff).toContain('+feature change');
|
|
101
|
+
expect(result.diff).not.toContain('main-only.txt');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('lists binary changes without adding binary contents to the diff', async () => {
|
|
105
|
+
writeFileSync(join(repoPath, 'binary.bin'), Buffer.from([0, 1, 2, 255]));
|
|
106
|
+
const binaryCommit = commit('Add binary file');
|
|
107
|
+
|
|
108
|
+
const result = await readChatCommit(createContext(), binaryCommit, 50, 2048);
|
|
109
|
+
|
|
110
|
+
expect(result.files.map((file) => file.newPath)).toEqual(['binary.bin']);
|
|
111
|
+
expect(result.diff).not.toContain('GIT binary patch');
|
|
112
|
+
expect(result.limitations).toContain('Binary file contents are not included in the diff.');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('preserves both names for a detected rename', async () => {
|
|
116
|
+
writeFileSync(join(repoPath, 'before.txt'), 'same contents\n');
|
|
117
|
+
commit('Add file');
|
|
118
|
+
renameSync(join(repoPath, 'before.txt'), join(repoPath, 'after.txt'));
|
|
119
|
+
const renameCommit = commit('Rename file');
|
|
120
|
+
|
|
121
|
+
const result = await readChatCommit(createContext(), renameCommit, 50, 2048);
|
|
122
|
+
|
|
123
|
+
expect(result.files).toEqual([{ oldPath: 'before.txt', newPath: 'after.txt', status: 'R100' }]);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('truncates UTF-8 diffs at the byte limit without exceeding it', async () => {
|
|
127
|
+
writeFileSync(join(repoPath, 'unicode.txt'), `${'café 🙂\n'.repeat(80)}`);
|
|
128
|
+
const unicodeCommit = commit('Add unicode content');
|
|
129
|
+
const byteLimit = 280;
|
|
130
|
+
|
|
131
|
+
const result = await readChatCommit(createContext(), unicodeCommit, 50, byteLimit);
|
|
132
|
+
|
|
133
|
+
expect(Buffer.byteLength(result.diff, 'utf8')).toBeLessThanOrEqual(byteLimit);
|
|
134
|
+
expect(result.truncated).toBe(true);
|
|
135
|
+
expect(result.limitations).toContain('The diff was truncated to the configured limit.');
|
|
136
|
+
expect(result.diff).not.toMatch(/\uFFFD$/);
|
|
137
|
+
});
|
|
138
|
+
});
|
|
@@ -71,6 +71,58 @@ describe('Git credential destination', () => {
|
|
|
71
71
|
await mergeRequests({ db, action: { params: { repositoryId: 1 } } } as unknown as Context, async () => {});
|
|
72
72
|
expect(fetchMock).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ redirect: 'error' }));
|
|
73
73
|
});
|
|
74
|
+
|
|
75
|
+
it('preserves GitHub next-page state when a merged-state page filters to no results', async () => {
|
|
76
|
+
const fetchMock = vi.fn().mockResolvedValue(
|
|
77
|
+
new Response(JSON.stringify([{ number: 42, state: 'closed', merged_at: null }]), {
|
|
78
|
+
status: 200,
|
|
79
|
+
headers: {
|
|
80
|
+
link: '<https://api.github.com/repos/team/r/pulls?page=2>; rel="next", <https://api.github.com/repos/team/r/pulls?page=4>; rel="last"',
|
|
81
|
+
},
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
85
|
+
const { db } = database('https://github.com/team/r', null, 'github');
|
|
86
|
+
const context = {
|
|
87
|
+
db,
|
|
88
|
+
action: { params: { repositoryId: 1, state: 'merged', page: 1, perPage: 20 } },
|
|
89
|
+
body: undefined as unknown,
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
await mergeRequests(context as unknown as Context, async () => {});
|
|
93
|
+
|
|
94
|
+
expect(fetchMock.mock.calls[0][0]).toContain('state=closed');
|
|
95
|
+
expect(context.body).toMatchObject({
|
|
96
|
+
success: true,
|
|
97
|
+
data: [],
|
|
98
|
+
pagination: { page: 1, perPage: 20, total: null, totalPages: null, hasMore: true },
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('uses GitLab next-page headers to preserve hasMore', async () => {
|
|
103
|
+
const fetchMock = vi.fn().mockResolvedValue(
|
|
104
|
+
new Response(JSON.stringify([{ id: 42, iid: 7, title: 'MR', state: 'opened' }]), {
|
|
105
|
+
status: 200,
|
|
106
|
+
headers: { 'x-next-page': '2', 'x-total-pages': '5', 'x-total': '81' },
|
|
107
|
+
}),
|
|
108
|
+
);
|
|
109
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
110
|
+
const { db } = database();
|
|
111
|
+
const context = {
|
|
112
|
+
db,
|
|
113
|
+
action: { params: { repositoryId: 1, page: 1, perPage: 20 } },
|
|
114
|
+
body: undefined as unknown,
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
await mergeRequests(context as unknown as Context, async () => {});
|
|
118
|
+
|
|
119
|
+
expect(fetchMock.mock.calls[0][0]).toContain('page=1');
|
|
120
|
+
expect(context.body).toMatchObject({
|
|
121
|
+
success: true,
|
|
122
|
+
data: [{ id: 42, iid: 7, title: 'MR' }],
|
|
123
|
+
pagination: { page: 1, perPage: 20, total: 81, totalPages: 5, hasMore: true },
|
|
124
|
+
});
|
|
125
|
+
});
|
|
74
126
|
});
|
|
75
127
|
|
|
76
128
|
describe('Git filesystem and process credentials', () => {
|