-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmanaged-repos.ts
More file actions
192 lines (172 loc) · 5.69 KB
/
Copy pathmanaged-repos.ts
File metadata and controls
192 lines (172 loc) · 5.69 KB
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
import { existsSync } from 'node:fs';
import { mkdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import simpleGit from 'simple-git';
import type { Repository, ManagedMode } from '../models/workspace-config.js';
import { getHomeDir } from '../constants.js';
import { createGitEnv } from './git.js';
const CLONE_TIMEOUT_MS = 120_000; // 2 minutes for full clone
export interface ManagedRepoResult {
path: string;
repo: string;
action: 'cloned' | 'pulled' | 'skipped';
error?: string;
}
/**
* Expand ~ to home directory in a path.
*/
export function expandHome(p: string): string {
if (p.startsWith('~/') || p === '~') {
return p.replace('~', getHomeDir());
}
return p;
}
/**
* Should this repository be cloned if missing?
*/
export function shouldClone(managed: ManagedMode | undefined): boolean {
if (managed === undefined || managed === false) return false;
return true; // true, 'clone', 'sync' all clone if missing
}
/**
* Should this repository be pulled on sync?
*/
export function shouldPull(managed: ManagedMode | undefined): boolean {
if (managed === true || managed === 'sync') return true;
return false;
}
/**
* Validate that a repo identifier looks safe (no shell/git argument injection).
* Allows alphanumeric, hyphens, underscores, dots, and forward slashes.
*/
export function isValidRepo(repo: string): boolean {
return /^[\w.\-/]+$/.test(repo);
}
/**
* Build a clone URL from source platform and owner/repo.
*/
export function buildCloneUrl(source: string, repo: string): string {
if (!isValidRepo(repo)) {
throw new Error(`Invalid repo identifier: ${repo}`);
}
switch (source) {
case 'github':
return `https://github.com/${repo}.git`;
case 'gitlab':
return `https://gitlab.com/${repo}.git`;
case 'bitbucket':
return `https://bitbucket.org/${repo}.git`;
case 'azure-devops': {
// repo format: org/project/repo
const parts = repo.split('/');
if (parts.length === 3) {
return `https://dev.azure.com/${parts[0]}/${parts[1]}/_git/${parts[2]}`;
}
return `https://dev.azure.com/${repo}`;
}
default:
return `https://${source}/${repo}.git`;
}
}
/**
* Clone a repository to the specified path.
*/
async function cloneRepo(url: string, dest: string, branch?: string): Promise<void> {
await mkdir(dirname(dest), { recursive: true });
const git = simpleGit({ timeout: { block: CLONE_TIMEOUT_MS } }).env(createGitEnv());
const cloneOptions = branch ? ['--branch', branch] : [];
await git.clone(url, dest, cloneOptions);
}
/**
* Pull latest changes in an existing repository.
* Returns a skip reason if pull is unsafe, or undefined on success.
*/
async function pullRepo(repoPath: string, branch?: string): Promise<string | undefined> {
const git = simpleGit(repoPath, { timeout: { block: CLONE_TIMEOUT_MS } }).env(createGitEnv());
// Check for uncommitted changes
const status = await git.status();
if (!status.isClean()) {
return 'uncommitted changes';
}
// If branch is specified, check we're on it
if (branch) {
const currentBranch = status.current;
if (currentBranch !== branch) {
return `on branch '${currentBranch}', expected '${branch}'`;
}
}
await git.pull();
return undefined;
}
/**
* Process all managed repositories: clone missing ones and pull updates.
* Runs before plugin sync so newly cloned repos are available for skill discovery.
*/
export async function processManagedRepos(
repositories: Repository[],
workspacePath: string,
options: { offline?: boolean; skipManaged?: boolean; dryRun?: boolean } = {},
): Promise<ManagedRepoResult[]> {
if (options.skipManaged || options.offline || options.dryRun) return [];
const managed = repositories.filter((r) => r.managed);
if (managed.length === 0) return [];
const results: ManagedRepoResult[] = [];
for (const repo of managed) {
if (!repo.source || !repo.repo) {
results.push({
path: repo.path,
repo: repo.repo ?? repo.path,
action: 'skipped',
error: 'managed requires both source and repo fields',
});
continue;
}
const expandedPath = expandHome(repo.path);
const absolutePath = resolve(workspacePath, expandedPath);
if (!existsSync(absolutePath)) {
// Clone
if (!shouldClone(repo.managed)) {
results.push({ path: repo.path, repo: repo.repo, action: 'skipped' });
continue;
}
try {
const url = buildCloneUrl(repo.source, repo.repo);
await cloneRepo(url, absolutePath, repo.branch);
results.push({ path: repo.path, repo: repo.repo, action: 'cloned' });
} catch (error) {
results.push({
path: repo.path,
repo: repo.repo,
action: 'skipped',
error: `clone failed: ${error instanceof Error ? error.message : String(error)}`,
});
}
} else if (shouldPull(repo.managed)) {
// Pull
try {
const skipReason = await pullRepo(absolutePath, repo.branch);
if (skipReason) {
results.push({
path: repo.path,
repo: repo.repo,
action: 'skipped',
error: `pull skipped: ${skipReason}`,
});
} else {
results.push({ path: repo.path, repo: repo.repo, action: 'pulled' });
}
} catch (error) {
results.push({
path: repo.path,
repo: repo.repo,
action: 'skipped',
error: `pull failed: ${error instanceof Error ? error.message : String(error)}`,
});
}
} else {
// managed: 'clone' and path exists — nothing to do
results.push({ path: repo.path, repo: repo.repo, action: 'skipped' });
}
}
return results;
}