plugin-git-manager 1.2.13 → 1.2.15

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.
Files changed (61) hide show
  1. package/dist/client/156.c27c2392746e7866.js +10 -0
  2. package/dist/client/434.1d19d4d6acc114f1.js +10 -0
  3. package/dist/client/900.ee2fa037aff389e2.js +10 -0
  4. package/dist/client/index.js +1 -1
  5. package/dist/client-v2/356.11ed4f8d56a6c08a.js +10 -0
  6. package/dist/client-v2/434.f8836ea116648de1.js +10 -0
  7. package/dist/client-v2/900.bef1c41d267e50c5.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +8 -7
  10. package/dist/locale/en-US.json +73 -2
  11. package/dist/locale/vi-VN.json +72 -1
  12. package/dist/locale/zh-CN.json +49 -0
  13. package/dist/server/actions/git-actions.js +32 -16
  14. package/dist/server/actions/gitlab-api.js +46 -20
  15. package/dist/server/actions/review.js +13 -10
  16. package/dist/server/actions/subtree.js +430 -0
  17. package/dist/server/collections/gitAccounts.js +86 -0
  18. package/dist/server/collections/gitRepositories.js +11 -10
  19. package/dist/server/collections/gitSubtreeConfigs.js +67 -0
  20. package/dist/server/collections/gitSubtreeRuns.js +60 -0
  21. package/dist/server/migrations/20260712000000-add-git-accounts.js +186 -0
  22. package/dist/server/plugin.js +76 -12
  23. package/dist/server/poller.js +12 -24
  24. package/dist/server/utils/get-repo-account.js +49 -0
  25. package/package.json +1 -1
  26. package/src/client/components/CommitHistory.tsx +21 -5
  27. package/src/client/components/GitAccounts.tsx +179 -0
  28. package/src/client/components/GitManagerSettings.tsx +10 -6
  29. package/src/client/components/GitOperations.tsx +27 -18
  30. package/src/client/components/LLMModelSelect.tsx +2 -2
  31. package/src/client/components/MarkdownView.tsx +1 -4
  32. package/src/client/components/MergeRequests.tsx +238 -129
  33. package/src/client/components/PollingStatus.tsx +10 -5
  34. package/src/client/components/RepositoryConfig.tsx +32 -14
  35. package/src/client/components/RepositoryPermissions.tsx +1 -8
  36. package/src/client/index.tsx +11 -0
  37. package/src/client-v2/components/SubtreeSplits.tsx +503 -0
  38. package/src/client-v2/locale.ts +8 -0
  39. package/src/client-v2/plugin.tsx +12 -5
  40. package/src/locale/en-US.json +73 -2
  41. package/src/locale/vi-VN.json +72 -1
  42. package/src/locale/zh-CN.json +49 -0
  43. package/src/server/__tests__/smoke.test.ts +1 -1
  44. package/src/server/__tests__/subtree.test.ts +73 -0
  45. package/src/server/actions/git-actions.ts +41 -20
  46. package/src/server/actions/gitlab-api.ts +59 -28
  47. package/src/server/actions/review.ts +13 -10
  48. package/src/server/actions/role-permissions.ts +2 -1
  49. package/src/server/actions/subtree.ts +460 -0
  50. package/src/server/collections/gitAccounts.ts +56 -0
  51. package/src/server/collections/gitRepositories.ts +11 -10
  52. package/src/server/collections/gitSubtreeConfigs.ts +37 -0
  53. package/src/server/collections/gitSubtreeRuns.ts +30 -0
  54. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -0
  55. package/src/server/plugin.ts +79 -5
  56. package/src/server/poller.ts +31 -32
  57. package/src/server/utils/get-repo-account.ts +23 -0
  58. package/dist/client/434.f82454801cf84906.js +0 -10
  59. package/dist/client/900.ec1fa7f16eb8cce6.js +0 -10
  60. package/dist/client-v2/434.c2f944f911a56da0.js +0 -10
  61. package/dist/client-v2/900.7a5e80bf21feda66.js +0 -10
@@ -1,5 +1,7 @@
1
1
  {
2
2
  "Git Manager": "Quản lý Git",
3
+ "Git Accounts": "Tài khoản Git",
4
+ "Git Account": "Tài khoản Git",
3
5
  "Repositories": "Kho mã nguồn",
4
6
  "File Explorer": "Trình duyệt tệp",
5
7
  "History": "Lịch sử",
@@ -215,5 +217,74 @@
215
217
  "MR": "MR",
216
218
  "COMMIT": "Commit",
217
219
  "BRANCH": "Nhánh",
218
- "FOLDER": "Thư mục"
220
+ "FOLDER": "Thư mục",
221
+ "Add Account": "Thêm tài khoản",
222
+ "Edit Account": "Sửa tài khoản",
223
+ "Account Name": "Tên tài khoản",
224
+ "Account updated": "Đã cập nhật tài khoản",
225
+ "Account added": "Đã thêm tài khoản",
226
+ "Delete this account?": "Xóa tài khoản này?",
227
+ "Provider": "Nhà cung cấp",
228
+ "Base URL": "URL gốc",
229
+ "Leave empty for gitlab.com or github.com": "Để trống nếu dùng gitlab.com hoặc github.com",
230
+ "Leave empty to keep current": "Để trống để giữ hiện tại",
231
+ "Please select a Git account": "Vui lòng chọn tài khoản Git",
232
+ "Select the GitLab or GitHub account to use for this repository": "Chọn tài khoản GitLab hoặc GitHub để dùng cho kho này",
233
+ "Select an account": "Chọn một tài khoản",
234
+ "No accounts configured. Add one in the Git Accounts tab.": "Chưa có tài khoản nào. Hãy thêm trong tab Tài khoản Git.",
235
+ "None": "Không có",
236
+ "e.g. Company GitLab": "ví dụ: GitLab Công ty",
237
+ "Cannot delete this Git account because {{count}} repositories are using it": "Không thể xóa tài khoản Git này vì có {{count}} kho mã nguồn đang sử dụng",
238
+ "Subtree Splits": "Tách Git subtree",
239
+ "Add subtree configuration": "Thêm cấu hình subtree",
240
+ "Edit subtree configuration": "Sửa cấu hình subtree",
241
+ "Subtree configuration created": "Đã tạo cấu hình subtree",
242
+ "Subtree configuration updated": "Đã cập nhật cấu hình subtree",
243
+ "Delete this subtree configuration?": "Xóa cấu hình subtree này?",
244
+ "Source": "Nguồn",
245
+ "Source branch": "Nhánh nguồn",
246
+ "Source folder": "Thư mục nguồn",
247
+ "Target branch": "Nhánh đích",
248
+ "Remote name": "Tên remote",
249
+ "Default policy": "Chính sách mặc định",
250
+ "Push after run": "Push sau khi chạy",
251
+ "Last status": "Trạng thái gần nhất",
252
+ "Actions": "Thao tác",
253
+ "Run": "Chạy",
254
+ "Run subtree split": "Chạy tách subtree",
255
+ "Preview": "Xem trước",
256
+ "Fast-forward only": "Chỉ fast-forward",
257
+ "Replace target": "Thay thế nhánh đích",
258
+ "Merge histories": "Merge lịch sử",
259
+ "Replace target may discard target-only commits": "Thay thế nhánh đích có thể loại bỏ các commit chỉ có trên nhánh đích",
260
+ "Type the target branch name to confirm": "Nhập tên nhánh đích để xác nhận",
261
+ "Push target branch after success": "Push nhánh đích sau khi thành công",
262
+ "Target branch does not exist": "Nhánh đích chưa tồn tại",
263
+ "Subtree split completed": "Tách subtree thành công",
264
+ "Subtree relationship: target-missing": "Nhánh đích chưa tồn tại",
265
+ "Subtree relationship: already-up-to-date": "Nhánh đích đã được cập nhật",
266
+ "Subtree relationship: fast-forward": "Có thể fast-forward nhánh đích",
267
+ "Subtree relationship: diverged": "Nhánh đích đã phân kỳ",
268
+ "Source folder must be a non-empty relative path": "Thư mục nguồn phải là đường dẫn tương đối và không được để trống",
269
+ "Source folder contains an invalid path segment": "Thư mục nguồn chứa thành phần đường dẫn không hợp lệ",
270
+ "Invalid Git remote name": "Tên Git remote không hợp lệ",
271
+ "Invalid subtree update policy": "Chính sách cập nhật subtree không hợp lệ",
272
+ "Source branch and target branch must be different": "Nhánh nguồn và nhánh đích phải khác nhau",
273
+ "Repository working tree must be clean before running a subtree split": "Working tree phải sạch trước khi chạy tách subtree",
274
+ "Source branch was not found on the configured remote": "Không tìm thấy nhánh nguồn trên remote đã cấu hình",
275
+ "Source folder was not found in the selected source branch": "Không tìm thấy thư mục nguồn trong nhánh đã chọn",
276
+ "Selected source path is not a folder": "Đường dẫn nguồn đã chọn không phải thư mục",
277
+ "Git subtree split did not return a valid commit": "Git subtree split không trả về commit hợp lệ",
278
+ "Target branch cannot be fast-forwarded to the new subtree commit": "Không thể fast-forward nhánh đích đến subtree commit mới",
279
+ "Replace policy requires the preview target SHA": "Chính sách thay thế yêu cầu SHA của nhánh đích từ bước xem trước",
280
+ "Target branch changed after preview; run preview again": "Nhánh đích đã thay đổi sau bước xem trước; hãy xem trước lại",
281
+ "Replace policy requires the destructive subtree permission": "Chính sách thay thế yêu cầu quyền subtree có khả năng ghi đè",
282
+ "Run history": "Lịch sử chạy",
283
+ "Started at": "Bắt đầu lúc",
284
+ "Policy": "Chính sách",
285
+ "Split SHA": "SHA subtree",
286
+ "Target before": "Nhánh đích trước đó",
287
+ "Target after": "Nhánh đích sau đó"
288
+ ,"Execution mode": "Chế độ thực thi"
289
+ ,"App process": "App process"
219
290
  }
@@ -0,0 +1,49 @@
1
+ {
2
+ "Git Manager": "Git 管理器",
3
+ "Subtree Splits": "Subtree 拆分",
4
+ "Add subtree configuration": "添加 subtree 配置",
5
+ "Edit subtree configuration": "编辑 subtree 配置",
6
+ "Subtree configuration created": "已创建 subtree 配置",
7
+ "Subtree configuration updated": "已更新 subtree 配置",
8
+ "Delete this subtree configuration?": "删除此 subtree 配置?",
9
+ "Name": "名称",
10
+ "Repository": "仓库",
11
+ "Source": "源",
12
+ "Source branch": "源分支",
13
+ "Source folder": "源文件夹",
14
+ "Target branch": "目标分支",
15
+ "Remote name": "远程名称",
16
+ "Default policy": "默认策略",
17
+ "Push after run": "运行后推送",
18
+ "Enabled": "已启用",
19
+ "Last status": "最近状态",
20
+ "Actions": "操作",
21
+ "Run": "运行",
22
+ "Edit": "编辑",
23
+ "Delete": "删除",
24
+ "Deleted": "已删除",
25
+ "Run subtree split": "运行 subtree 拆分",
26
+ "Preview": "预览",
27
+ "Fast-forward only": "仅快进",
28
+ "Replace target": "替换目标分支",
29
+ "Merge histories": "合并历史",
30
+ "Replace target may discard target-only commits": "替换目标分支可能丢弃仅存在于目标分支的提交",
31
+ "Type the target branch name to confirm": "输入目标分支名称以确认",
32
+ "Push target branch after success": "成功后推送目标分支",
33
+ "Target branch does not exist": "目标分支不存在",
34
+ "Subtree split completed": "Subtree 拆分完成",
35
+ "Subtree relationship: target-missing": "目标分支不存在",
36
+ "Subtree relationship: already-up-to-date": "目标分支已是最新",
37
+ "Subtree relationship: fast-forward": "目标分支可以快进",
38
+ "Subtree relationship: diverged": "目标分支已分叉",
39
+ "Run history": "运行历史",
40
+ "Started at": "开始时间",
41
+ "Policy": "策略",
42
+ "Status": "状态",
43
+ "Split SHA": "拆分 SHA",
44
+ "Target before": "更新前目标",
45
+ "Target after": "更新后目标",
46
+ "Error": "错误"
47
+ ,"Execution mode": "执行模式"
48
+ ,"App process": "应用进程"
49
+ }
@@ -9,7 +9,7 @@ describe('Git Manager plugin smoke', () => {
9
9
 
10
10
  it('loads without starting the full app', async () => {
11
11
  app = await createMockServer({
12
- plugins: ["nocobase","git-manager"],
12
+ plugins: ['nocobase', 'git-manager'],
13
13
  });
14
14
 
15
15
  expect(app).toBeTruthy();
@@ -0,0 +1,73 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ SUBTREE_EXECUTION_MODE,
4
+ validateRemoteName,
5
+ validateRunAgainstPreview,
6
+ validateSubtreeConfigInput,
7
+ validateSubtreePolicy,
8
+ validateSubtreePrefix,
9
+ } from '../actions/subtree';
10
+
11
+ describe('Git subtree validation', () => {
12
+ it('accepts and normalizes one relative source folder', () => {
13
+ expect(validateSubtreePrefix('./apps/admin/')).toBe('apps/admin');
14
+ });
15
+
16
+ it.each(['../admin', 'apps/../admin', '/apps/admin', 'C:/apps/admin', ''])('rejects unsafe prefix %s', (prefix) => {
17
+ expect(() => validateSubtreePrefix(prefix)).toThrow();
18
+ });
19
+
20
+ it('requires different source and target branches', () => {
21
+ expect(() =>
22
+ validateSubtreeConfigInput({
23
+ sourceBranch: 'main',
24
+ targetBranch: 'main',
25
+ sourcePrefix: 'apps/admin',
26
+ remoteName: 'origin',
27
+ defaultPolicy: 'fastForward',
28
+ }),
29
+ ).toThrow('Source branch and target branch must be different');
30
+ });
31
+
32
+ it.each(['fastForward', 'replace', 'merge'])('accepts the %s policy', (policy) => {
33
+ expect(validateSubtreePolicy(policy)).toBe(policy);
34
+ });
35
+
36
+ it('rejects option injection in the remote name', () => {
37
+ expect(() => validateRemoteName('--upload-pack=evil')).toThrow('Invalid Git remote name');
38
+ });
39
+
40
+ it.each(['feature..bad', 'feature.lock', '.hidden', 'feature//bad'])('rejects invalid Git branch %s', (branch) => {
41
+ expect(() =>
42
+ validateSubtreeConfigInput({ sourceBranch: branch, targetBranch: 'deploy', sourcePrefix: 'apps/admin' }),
43
+ ).toThrow('Invalid branch name');
44
+ });
45
+ });
46
+
47
+ describe('Git subtree update policy', () => {
48
+ it('runs interactively on the app process instead of the review queue', () => {
49
+ expect(SUBTREE_EXECUTION_MODE).toBe('app');
50
+ });
51
+
52
+ it('blocks fast-forward when the target has diverged', () => {
53
+ expect(() => validateRunAgainstPreview('fastForward', { relationship: 'diverged', targetSha: 'old' })).toThrow(
54
+ 'Target branch cannot be fast-forwarded',
55
+ );
56
+ });
57
+
58
+ it('requires the exact preview SHA before replacing an existing target', () => {
59
+ expect(() => validateRunAgainstPreview('replace', { relationship: 'diverged', targetSha: 'old' })).toThrow(
60
+ 'requires the preview target SHA',
61
+ );
62
+ expect(() =>
63
+ validateRunAgainstPreview('replace', { relationship: 'diverged', targetSha: 'old' }, 'changed'),
64
+ ).toThrow('Target branch changed after preview');
65
+ expect(() =>
66
+ validateRunAgainstPreview('replace', { relationship: 'diverged', targetSha: 'old' }, 'old'),
67
+ ).not.toThrow();
68
+ });
69
+
70
+ it('allows merge for unrelated or diverged histories', () => {
71
+ expect(() => validateRunAgainstPreview('merge', { relationship: 'diverged', targetSha: 'old' })).not.toThrow();
72
+ });
73
+ });
@@ -4,6 +4,7 @@ import * as path from 'path';
4
4
  import * as fs from 'fs';
5
5
  import { spawnSync } from 'child_process';
6
6
  import { redactPat, redactError } from '../utils/redact';
7
+ import { getRepoAccount } from '../utils/get-repo-account';
7
8
 
8
9
  // Disallow leading `-` to prevent argument-injection (e.g. `--upload-pack=...`)
9
10
  // when refs are passed as positional args to git.
@@ -14,7 +15,7 @@ const repoLocks = new Map<string, Promise<any>>();
14
15
  const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || 'git';
15
16
  let gitAvailabilityChecked = false;
16
17
 
17
- function acquireLock(key: string): { promise: Promise<void>; release: () => void } {
18
+ export function acquireLock(key: string): { promise: Promise<void>; release: () => void } {
18
19
  const prev = repoLocks.get(key) || Promise.resolve();
19
20
  let release = () => {};
20
21
  const next = new Promise<void>((resolve) => {
@@ -32,8 +33,19 @@ function validateRef(ref: string): string {
32
33
  return ref;
33
34
  }
34
35
 
35
- function validateBranch(branch: string): string {
36
- if (!branch || !REF_PATTERN.test(branch)) {
36
+ export function validateBranch(branch: string): string {
37
+ const segments = branch.split('/');
38
+ if (
39
+ !branch ||
40
+ !REF_PATTERN.test(branch) ||
41
+ branch === '@' ||
42
+ branch.includes('..') ||
43
+ branch.includes('@{') ||
44
+ branch.includes('//') ||
45
+ branch.endsWith('/') ||
46
+ branch.endsWith('.') ||
47
+ segments.some((segment) => segment.startsWith('.') || segment.toLowerCase().endsWith('.lock'))
48
+ ) {
37
49
  throw new Error(`Invalid branch name: ${branch}`);
38
50
  }
39
51
  return branch;
@@ -51,14 +63,15 @@ function validateRepoUrl(repoUrl: string): void {
51
63
  }
52
64
  }
53
65
 
54
- async function withAuth(
66
+ export async function withAuth<T>(
55
67
  git: ReturnType<typeof simpleGit>,
56
68
  localPath: string,
57
69
  repoUrl: string,
58
70
  pat: string,
59
- fn: () => Promise<any>,
71
+ fn: () => Promise<T>,
60
72
  username?: string,
61
- ) {
73
+ remoteName = 'origin',
74
+ ): Promise<T> {
62
75
  // Lock by local working tree — that's what `git.remote('set-url', ...)`
63
76
  // mutates. Two repo records sharing a `repoUrl` but cloned to different
64
77
  // paths can run in parallel safely; conversely, two repos pointed at the
@@ -67,7 +80,7 @@ async function withAuth(
67
80
  const lock = acquireLock(lockKey);
68
81
  await lock.promise;
69
82
  const authUrl = getAuthUrl(repoUrl, pat, username);
70
- await git.remote(['set-url', 'origin', authUrl]);
83
+ await git.remote(['set-url', remoteName, authUrl]);
71
84
  try {
72
85
  return await fn();
73
86
  } catch (err) {
@@ -76,11 +89,11 @@ async function withAuth(
76
89
  } finally {
77
90
  // H-2 fix: guard PAT cleanup — if reset fails, the PAT-embedded URL persists on disk
78
91
  try {
79
- await git.remote(['set-url', 'origin', repoUrl]);
92
+ await git.remote(['set-url', remoteName, repoUrl]);
80
93
  } catch (cleanupErr) {
81
94
  // Critical: PAT may be persisted in .git/config — attempt one more cleanup
82
95
  try {
83
- await git.remote(['set-url', 'origin', repoUrl]);
96
+ await git.remote(['set-url', remoteName, repoUrl]);
84
97
  } catch {
85
98
  // Log but don't throw — the original operation already completed
86
99
  console.error(
@@ -120,7 +133,7 @@ function isMissingGitError(error: any) {
120
133
  return error?.code === 'ENOENT' || /spawn .*git.*ENOENT/i.test(message);
121
134
  }
122
135
 
123
- function createGit(baseDir?: string): SimpleGit {
136
+ export function createGit(baseDir?: string): SimpleGit {
124
137
  return simpleGit({ baseDir, binary: GIT_BINARY } as any);
125
138
  }
126
139
 
@@ -144,7 +157,7 @@ async function getRepo(ctx: Context) {
144
157
  }
145
158
 
146
159
  // Validate localPath to prevent path traversal
147
- function validateLocalPath(localPath: string): string {
160
+ export function validateLocalPath(localPath: string): string {
148
161
  const basePath = process.env.GIT_REPOS_BASE_PATH || path.join(process.cwd(), 'storage', 'git-repos');
149
162
  const resolved = path.resolve(basePath, localPath);
150
163
 
@@ -162,10 +175,12 @@ export async function clone(ctx: Context, next: () => Promise<void>) {
162
175
  const repo = await getRepo(ctx);
163
176
  const localPath = validateLocalPath(repo.get('localPath'));
164
177
  const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
165
- const pat = ((repo.get('pat') as string) || '').trim();
166
- const username = ((repo.get('username') as string) || '').trim();
167
178
  const defaultBranch = ((repo.get('defaultBranch') as string) || 'main').trim() || 'main';
168
179
 
180
+ const account = await getRepoAccount(ctx.db, repo);
181
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
182
+ const { pat, username } = account;
183
+
169
184
  validateRepoUrl(repoUrl);
170
185
  // Prevent argument-injection through `defaultBranch` (e.g. `--upload-pack=...`)
171
186
  validateBranch(defaultBranch);
@@ -207,9 +222,11 @@ export async function clone(ctx: Context, next: () => Promise<void>) {
207
222
  export async function pull(ctx: Context, next: () => Promise<void>) {
208
223
  const repo = await getRepo(ctx);
209
224
  const localPath = validateLocalPath(repo.get('localPath'));
210
- const pat = ((repo.get('pat') as string) || '').trim();
211
225
  const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
212
- const username = ((repo.get('username') as string) || '').trim();
226
+
227
+ const account = await getRepoAccount(ctx.db, repo);
228
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
229
+ const { pat, username } = account;
213
230
 
214
231
  const git = getGit(ctx, localPath);
215
232
  const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username);
@@ -221,9 +238,11 @@ export async function pull(ctx: Context, next: () => Promise<void>) {
221
238
  export async function push(ctx: Context, next: () => Promise<void>) {
222
239
  const repo = await getRepo(ctx);
223
240
  const localPath = validateLocalPath(repo.get('localPath'));
224
- const pat = ((repo.get('pat') as string) || '').trim();
225
241
  const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
226
- const username = ((repo.get('username') as string) || '').trim();
242
+
243
+ const account = await getRepoAccount(ctx.db, repo);
244
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
245
+ const { pat, username } = account;
227
246
 
228
247
  const git = getGit(ctx, localPath);
229
248
  const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username);
@@ -235,9 +254,11 @@ export async function push(ctx: Context, next: () => Promise<void>) {
235
254
  export async function fetch(ctx: Context, next: () => Promise<void>) {
236
255
  const repo = await getRepo(ctx);
237
256
  const localPath = validateLocalPath(repo.get('localPath'));
238
- const pat = ((repo.get('pat') as string) || '').trim();
239
257
  const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
240
- const username = ((repo.get('username') as string) || '').trim();
258
+
259
+ const account = await getRepoAccount(ctx.db, repo);
260
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
261
+ const { pat, username } = account;
241
262
 
242
263
  const git = getGit(ctx, localPath);
243
264
  const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username);
@@ -348,7 +369,7 @@ export async function fileTree(ctx: Context, next: () => Promise<void>) {
348
369
  path: fullPath,
349
370
  };
350
371
  })
351
- .filter(Boolean);
372
+ .filter((item): item is NonNullable<typeof item> => item !== null);
352
373
 
353
374
  // Sort: directories first, then files, both alphabetical
354
375
  items.sort((a, b) => {
@@ -1,5 +1,6 @@
1
1
  import { Context } from '@nocobase/actions';
2
2
  import { parseGitLabProject } from '../utils/gitlab-url';
3
+ import { getRepoAccount } from '../utils/get-repo-account';
3
4
 
4
5
  function getActionParams(ctx: Context) {
5
6
  return { ...ctx.action.params, ...ctx.action.params?.values, ...((ctx as any).request?.body || {}) };
@@ -18,7 +19,7 @@ async function gitlabFetch(apiBase: string, endpoint: string, pat: string, param
18
19
  const response = await fetch(url.toString(), {
19
20
  headers: {
20
21
  'PRIVATE-TOKEN': pat,
21
- 'Accept': 'application/json',
22
+ Accept: 'application/json',
22
23
  },
23
24
  });
24
25
 
@@ -39,16 +40,18 @@ async function getRepoApiContext(ctx: Context) {
39
40
  // Fix for POST requests where data might be in ctx.request.body
40
41
  const params = getActionParams(ctx);
41
42
  const { repositoryId } = params;
42
-
43
+
43
44
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
44
45
  filterByTk: repositoryId,
45
46
  });
46
47
  if (!repo) {
47
48
  ctx.throw(404, 'Repository not found');
48
49
  }
49
- const pat = (repo.get('pat') as string || '').trim();
50
- const repoUrl = (repo.get('repoUrl') as string || '').trim();
51
- const isGitHub = repoUrl.includes('github.com');
50
+
51
+ const account = await getRepoAccount(ctx.db, repo);
52
+ const pat = account?.pat || '';
53
+ const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
54
+ const isGitHub = account?.provider === 'github' || repoUrl.includes('github.com');
52
55
  const { apiBase, encodedProject, projectPath } = parseGitLabProject(repoUrl);
53
56
  return { repo, pat, apiBase, encodedProject, projectPath, isGitHub };
54
57
  }
@@ -64,7 +67,7 @@ async function githubFetch(endpoint: string, pat: string, params?: Record<string
64
67
  }
65
68
 
66
69
  const headers: any = {
67
- 'Accept': 'application/vnd.github.v3+json',
70
+ Accept: 'application/vnd.github.v3+json',
68
71
  };
69
72
  if (pat) {
70
73
  headers['Authorization'] = `Bearer ${pat}`;
@@ -80,7 +83,7 @@ async function githubFetch(endpoint: string, pat: string, params?: Record<string
80
83
  const linkHeader = response.headers.get('link');
81
84
  let totalPages = null;
82
85
  if (linkHeader) {
83
- const lastLink = linkHeader.split(',').find(s => s.includes('rel="last"'));
86
+ const lastLink = linkHeader.split(',').find((s) => s.includes('rel="last"'));
84
87
  if (lastLink) {
85
88
  const match = lastLink.match(/page=(\d+)/);
86
89
  if (match) totalPages = parseInt(match[1], 10);
@@ -95,14 +98,7 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
95
98
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
96
99
  // Merge params from query and body
97
100
  const params = getActionParams(ctx);
98
- const {
99
- state = 'opened',
100
- search,
101
- page = 1,
102
- perPage = 20,
103
- orderBy = 'updated_at',
104
- sort = 'desc',
105
- } = params;
101
+ const { state = 'opened', search, page = 1, perPage = 20, orderBy = 'updated_at', sort = 'desc' } = params;
106
102
 
107
103
  let result;
108
104
  let items;
@@ -138,12 +134,16 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
138
134
  iid: pr.number,
139
135
  title: pr.title,
140
136
  description: pr.body,
141
- state: pr.state === 'open' ? 'opened' : (pr.merged_at ? 'merged' : 'closed'),
137
+ state: pr.state === 'open' ? 'opened' : pr.merged_at ? 'merged' : 'closed',
142
138
  sourceBranch: pr.head?.ref,
143
139
  targetBranch: pr.base?.ref,
144
140
  author: pr.user ? { name: pr.user.login, username: pr.user.login, avatarUrl: pr.user.avatar_url } : null,
145
141
  assignees: (pr.assignees || []).map((a: any) => ({ name: a.login, username: a.login, avatarUrl: a.avatar_url })),
146
- reviewers: (pr.requested_reviewers || []).map((r: any) => ({ name: r.login, username: r.login, avatarUrl: r.avatar_url })),
142
+ reviewers: (pr.requested_reviewers || []).map((r: any) => ({
143
+ name: r.login,
144
+ username: r.login,
145
+ avatarUrl: r.avatar_url,
146
+ })),
147
147
  labels: (pr.labels || []).map((l: any) => l.name),
148
148
  draft: pr.draft || false,
149
149
  mergedBy: null, // Not returned by the PR list endpoint
@@ -178,9 +178,19 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
178
178
  state: mr.state,
179
179
  sourceBranch: mr.source_branch,
180
180
  targetBranch: mr.target_branch,
181
- author: mr.author ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url } : null,
182
- assignees: (mr.assignees || []).map((a: any) => ({ name: a.name, username: a.username, avatarUrl: a.avatar_url })),
183
- reviewers: (mr.reviewers || []).map((r: any) => ({ name: r.name, username: r.username, avatarUrl: r.avatar_url })),
181
+ author: mr.author
182
+ ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url }
183
+ : null,
184
+ assignees: (mr.assignees || []).map((a: any) => ({
185
+ name: a.name,
186
+ username: a.username,
187
+ avatarUrl: a.avatar_url,
188
+ })),
189
+ reviewers: (mr.reviewers || []).map((r: any) => ({
190
+ name: r.name,
191
+ username: r.username,
192
+ avatarUrl: r.avatar_url,
193
+ })),
184
194
  labels: mr.labels || [],
185
195
  draft: mr.draft || mr.work_in_progress || false,
186
196
  mergedBy: mr.merged_by ? { name: mr.merged_by.name, username: mr.merged_by.username } : null,
@@ -224,7 +234,7 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
224
234
  githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
225
235
  githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat).catch(() => ({ data: [] })),
226
236
  ]);
227
-
237
+
228
238
  const pr = prResult.data;
229
239
  const changes = (filesResult.data || []).map((c: any) => ({
230
240
  oldPath: c.previous_filename || c.filename,
@@ -240,12 +250,16 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
240
250
  iid: pr.number,
241
251
  title: pr.title,
242
252
  description: pr.body,
243
- state: pr.state === 'open' ? 'opened' : (pr.merged_at ? 'merged' : 'closed'),
253
+ state: pr.state === 'open' ? 'opened' : pr.merged_at ? 'merged' : 'closed',
244
254
  sourceBranch: pr.head?.ref,
245
255
  targetBranch: pr.base?.ref,
246
256
  author: pr.user ? { name: pr.user.login, username: pr.user.login, avatarUrl: pr.user.avatar_url } : null,
247
257
  assignees: (pr.assignees || []).map((a: any) => ({ name: a.login, username: a.login, avatarUrl: a.avatar_url })),
248
- reviewers: (pr.requested_reviewers || []).map((r: any) => ({ name: r.login, username: r.login, avatarUrl: r.avatar_url })),
258
+ reviewers: (pr.requested_reviewers || []).map((r: any) => ({
259
+ name: r.login,
260
+ username: r.login,
261
+ avatarUrl: r.avatar_url,
262
+ })),
249
263
  labels: (pr.labels || []).map((l: any) => l.name),
250
264
  draft: pr.draft || false,
251
265
  createdAt: pr.created_at,
@@ -275,7 +289,9 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
275
289
  if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
276
290
  const [mrResult, changesResult] = await Promise.all([
277
291
  gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
278
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat).catch(() => ({ data: {} })),
292
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat).catch(() => ({
293
+ data: {},
294
+ })),
279
295
  ]);
280
296
 
281
297
  const mr = mrResult.data;
@@ -296,9 +312,19 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
296
312
  state: mr.state,
297
313
  sourceBranch: mr.source_branch,
298
314
  targetBranch: mr.target_branch,
299
- author: mr.author ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url } : null,
300
- assignees: (mr.assignees || []).map((a: any) => ({ name: a.name, username: a.username, avatarUrl: a.avatar_url })),
301
- reviewers: (mr.reviewers || []).map((r: any) => ({ name: r.name, username: r.username, avatarUrl: r.avatar_url })),
315
+ author: mr.author
316
+ ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url }
317
+ : null,
318
+ assignees: (mr.assignees || []).map((a: any) => ({
319
+ name: a.name,
320
+ username: a.username,
321
+ avatarUrl: a.avatar_url,
322
+ })),
323
+ reviewers: (mr.reviewers || []).map((r: any) => ({
324
+ name: r.name,
325
+ username: r.username,
326
+ avatarUrl: r.avatar_url,
327
+ })),
302
328
  labels: mr.labels || [],
303
329
  draft: mr.draft || mr.work_in_progress || false,
304
330
  createdAt: mr.created_at,
@@ -333,7 +359,12 @@ export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>)
333
359
  }
334
360
 
335
361
  let notes = [];
336
- let pagination = { page: parseInt(String(page), 10), perPage: parseInt(String(perPage), 10), total: null, totalPages: null as any };
362
+ const pagination = {
363
+ page: parseInt(String(page), 10),
364
+ perPage: parseInt(String(perPage), 10),
365
+ total: null,
366
+ totalPages: null as any,
367
+ };
337
368
 
338
369
  if (isGitHub) {
339
370
  const result = await githubFetch(`/repos/${projectPath}/issues/${mrIid}/comments`, pat, {
@@ -2,6 +2,7 @@ import { Context } from '@nocobase/actions';
2
2
  import type { Application } from '@nocobase/server';
3
3
  import { parseGitLabProject } from '../utils/gitlab-url';
4
4
  import { redactPat } from '../utils/redact';
5
+ import { getRepoAccount } from '../utils/get-repo-account';
5
6
 
6
7
  export const WORKER_JOB_GIT_REVIEW_PROCESS = 'git-review:process';
7
8
  const REVIEW_QUEUE_CHANNEL = 'plugin-git-manager.review';
@@ -192,7 +193,7 @@ async function triggerReviewInternalLocked(app: Application, args: TriggerArgs):
192
193
  // works regardless of whether the trigger came from poller or manual UI.
193
194
  let headSha = args.headSha || null;
194
195
  if (args.targetType === 'mr' && !headSha && args.mrIid) {
195
- headSha = await fetchMrHeadSha(repo, args.mrIid).catch(() => null);
196
+ headSha = await fetchMrHeadSha(db, repo, args.mrIid).catch(() => null);
196
197
  }
197
198
 
198
199
  // Upsert review record (1 per MR/commit/branch target)
@@ -662,7 +663,7 @@ export async function reviewApprovePost(ctx: Context, next: () => Promise<void>)
662
663
  });
663
664
  if (!repo) ctx.throw(404, 'Repository not found');
664
665
 
665
- const noteId = await postNoteToGitLab(repo, Number(review.get('mrIid')), markdown);
666
+ const noteId = await postNoteToGitLab(ctx.db, repo, Number(review.get('mrIid')), markdown);
666
667
 
667
668
  const userId = (ctx as any).state?.currentUser?.id;
668
669
  await reviewsRepo.update({
@@ -880,7 +881,7 @@ async function runReview(app: Application, args: RunReviewArgs) {
880
881
  postStatus = 'skipped';
881
882
  } else if (postMode === 'auto' && args.targetType === 'mr' && args.mrIid) {
882
883
  try {
883
- postedNoteId = String(await postNoteToGitLab(args.repo, args.mrIid, content));
884
+ postedNoteId = String(await postNoteToGitLab(db, args.repo, args.mrIid, content));
884
885
  postStatus = 'posted';
885
886
  } catch (err: any) {
886
887
  autoPostError = redactPat(err?.message || String(err));
@@ -1102,11 +1103,12 @@ function extractLastAiMessageContent(result: any): string {
1102
1103
  return '';
1103
1104
  }
1104
1105
 
1105
- async function fetchMrHeadSha(repo: any, mrIid: number): Promise<string | null> {
1106
- const repoUrl = repo.get('repoUrl') as string;
1107
- const pat = repo.get('pat') as string;
1106
+ async function fetchMrHeadSha(db: any, repo: any, mrIid: number): Promise<string | null> {
1107
+ const account = await getRepoAccount(db, repo);
1108
+ const pat = account?.pat || '';
1108
1109
  if (!pat) return null;
1109
- const isGitHub = repoUrl.includes('github.com');
1110
+ const repoUrl = repo.get('repoUrl') as string;
1111
+ const isGitHub = account?.provider === 'github' || repoUrl.includes('github.com');
1110
1112
 
1111
1113
  try {
1112
1114
  if (isGitHub) {
@@ -1131,10 +1133,11 @@ async function fetchMrHeadSha(repo: any, mrIid: number): Promise<string | null>
1131
1133
  }
1132
1134
  }
1133
1135
 
1134
- async function postNoteToGitLab(repo: any, mrIid: number, body: string): Promise<number | string> {
1136
+ async function postNoteToGitLab(db: any, repo: any, mrIid: number, body: string): Promise<number | string> {
1137
+ const account = await getRepoAccount(db, repo);
1138
+ const pat = account?.pat || '';
1135
1139
  const repoUrl = repo.get('repoUrl') as string;
1136
- const pat = repo.get('pat') as string;
1137
- const isGitHub = repoUrl.includes('github.com');
1140
+ const isGitHub = account?.provider === 'github' || repoUrl.includes('github.com');
1138
1141
 
1139
1142
  if (isGitHub) {
1140
1143
  if (!pat) throw new Error('Repository has no PAT configured');
@@ -94,7 +94,8 @@ export async function updateRolePermissions(ctx: any, _next: () => Promise<void>
94
94
  if (action) {
95
95
  const actionData = action.toJSON ? action.toJSON() : action;
96
96
  const actionScope = actionData.scope;
97
- const actionScopeId = getRecordValue(actionScope, 'id') || actionData.scopeId || getRecordValue(action, 'scopeId');
97
+ const actionScopeId =
98
+ getRecordValue(actionScope, 'id') || actionData.scopeId || getRecordValue(action, 'scopeId');
98
99
  if (actionScopeId) {
99
100
  await ctx.db.getRepository('rolesResourcesScopes').update({
100
101
  filterByTk: actionScopeId,