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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
|
import { and, eq } from "drizzle-orm";
import { mkdir, rm } from "fs/promises";
import { join } from "path";
import { db } from "../db";
import { repositories } from "../db/schema";
import { config } from "../lib/config";
export async function countRepoCommits(destPath: string): Promise<number> {
try {
const proc = Bun.spawn(
["git", "-C", destPath, "rev-list", "--all", "--count"],
{
stdout: "pipe",
stderr: "pipe",
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
}
);
const out = await new Response(proc.stdout).text();
const code = await proc.exited;
if (code !== 0) return 0;
const n = parseInt(out.trim(), 10);
return Number.isFinite(n) && n > 0 ? n : 0;
} catch {
return 0;
}
}
export interface ParsedGithubUrl {
owner: string;
repo: string;
}
export function parseGithubUrl(raw: string): ParsedGithubUrl | null {
const input = (raw || "").trim();
if (!input) return null;
const ssh = input.match(/^git@github\.com:([^/]+)\/([^/\s]+?)(?:\.git)?\/?$/i);
if (ssh) return { owner: ssh[1], repo: stripDotGit(ssh[2]) };
const http = input.match(
/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s?#]+?)(?:\.git)?\/?(?:[?#].*)?$/i
);
if (http) return { owner: http[1], repo: stripDotGit(http[2]) };
const short = input.match(/^([^/\s]+)\/([^/\s]+?)(?:\.git)?$/);
if (short) return { owner: short[1], repo: stripDotGit(short[2]) };
return null;
}
function stripDotGit(name: string): string {
return name.replace(/\.git$/i, "");
}
export function sanitizeRepoName(name: string): string {
const cleaned = name.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "");
return cleaned || "imported-repo";
}
export function buildCloneUrl(cloneUrl: string, token: string | null): string {
if (!token) return cloneUrl;
return cloneUrl.replace("https://github.com/", `https://${token}@github.com/`);
}
export function scrubSecrets(input: string, token: string | null): string {
if (!input) return input;
let out = input;
if (token) out = out.split(token).join("***");
out = out.replace(
/https:\/\/[^@\s]+@github\.com/gi,
"https://***@github.com"
);
return out;
}
export interface ImportOneRepoInput {
cloneUrl: string;
targetName: string;
ownerId: string;
ownerUsername: string;
token?: string | null;
description?: string | null;
isPrivate?: boolean;
defaultBranch?: string;
}
export type ImportOneRepoStatus = "success" | "skipped-exists" | "failed";
export interface ImportOneRepoResult {
status: ImportOneRepoStatus;
name: string;
notes: string;
}
export async function importOneRepo(
input: ImportOneRepoInput
): Promise<ImportOneRepoResult> {
const {
cloneUrl,
targetName,
ownerId,
ownerUsername,
token = null,
description = null,
isPrivate = false,
defaultBranch = "main",
} = input;
const safeName = sanitizeRepoName(targetName);
try {
const [existing] = await db
.select()
.from(repositories)
.where(
and(eq(repositories.ownerId, ownerId), eq(repositories.name, safeName))
)
.limit(1);
if (existing) {
const existingCommits = await countRepoCommits(existing.diskPath);
if (existingCommits === 0) {
return {
status: "failed",
name: safeName,
notes:
"A repo by this name already exists but is EMPTY — a previous import left an empty shell. Delete it and re-import to populate it.",
};
}
return {
status: "skipped-exists",
name: safeName,
notes: `Already exists in your namespace (${existingCommits} commits)`,
};
}
const destPath = join(config.gitReposPath, ownerUsername, `${safeName}.git`);
await mkdir(join(config.gitReposPath, ownerUsername), { recursive: true });
const authedCloneUrl = buildCloneUrl(cloneUrl, token);
const proc = Bun.spawn(
["git", "clone", "--bare", "--mirror", authedCloneUrl, destPath],
{
stdout: "pipe",
stderr: "pipe",
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
}
);
const stderr = await new Response(proc.stderr).text();
const exitCode = await proc.exited;
if (exitCode !== 0) {
return {
status: "failed",
name: safeName,
notes: `git clone failed: ${scrubSecrets(stderr, token).slice(0, 200)}`,
};
}
const commitCount = await countRepoCommits(destPath);
if (commitCount === 0) {
await rm(destPath, { recursive: true, force: true }).catch(() => {});
return {
status: "failed",
name: safeName,
notes:
"Clone produced an EMPTY repository — nothing was imported. The source may be empty, or private and the token lacks access. No repo was created; fix access and retry.",
};
}
await db.insert(repositories).values({
name: safeName,
ownerId,
description,
isPrivate,
defaultBranch: defaultBranch || "main",
diskPath: destPath,
starCount: 0,
});
return {
status: "success",
name: safeName,
notes: `Cloned + indexed (${commitCount} commits)`,
};
} catch (err) {
return {
status: "failed",
name: safeName,
notes: scrubSecrets(String(err), token).slice(0, 200),
};
}
}
|