-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-universal-to-codeberg.ts
More file actions
571 lines (498 loc) · 19.3 KB
/
migrate-universal-to-codeberg.ts
File metadata and controls
571 lines (498 loc) · 19.3 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import { spawn } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { createRequire } from 'module';
// Load environment variables at startup
function loadEnvironment() {
if (typeof Bun === 'undefined') {
// For Node.js
try {
const require = createRequire(import.meta.url);
require('dotenv').config();
} catch (error) {
console.warn('dotenv not available, relying on environment variables being set externally');
}
}
// For Bun, environment variables are loaded automatically
}
// Load environment before class instantiation
loadEnvironment();
// Interface for repository data
interface Repo {
name: string;
clone_url: string;
description?: string;
private: boolean;
fork?: boolean;
}
interface MigrationOptions {
source: 'github' | 'gitlab';
includeForks?: boolean;
deleteSource?: boolean;
}
class UniversalToCodebergMigrator {
private readonly githubToken: string;
private readonly gitlabToken: string;
private readonly codebergToken: string;
private readonly githubUsername: string;
private readonly gitlabUsername: string;
private readonly codebergUsername: string;
private readonly codebergBaseUrl: string;
constructor() {
this.githubToken = process.env.GITHUB_TOKEN || '';
this.gitlabToken = process.env.GITLAB_TOKEN || '';
this.codebergToken = process.env.CODEBERG_TOKEN || '';
this.githubUsername = process.env.GITHUB_USERNAME || '';
this.gitlabUsername = process.env.GITLAB_USERNAME || '';
this.codebergUsername = process.env.CODEBERG_USERNAME || '';
this.codebergBaseUrl = process.env.CODEBERG_BASE_URL || 'https://codeberg.org';
// Validate required environment variables based on source
this.validateEnvVariables();
}
private validateEnvVariables(): void {
if (!this.codebergToken || !this.codebergUsername) {
console.error('Error: Missing required Codeberg environment variables.');
console.log('Please set CODEBERG_TOKEN and CODEBERG_USERNAME in your .env file.');
process.exit(1);
}
}
/**
* Fetches all repositories for the authenticated GitHub user
*/
async fetchGitHubRepos(): Promise<Repo[]> {
console.log('Fetching repositories from GitHub...');
const repos: Repo[] = [];
let page = 1;
let hasMorePages = true;
try {
while (hasMorePages) {
const response = await fetch(
`https://api.github.com/user/repos?page=${page}&per_page=100`,
{
headers: {
'Authorization': `token ${this.githubToken}`,
'User-Agent': 'Universal-to-Codeberg-Migrator'
}
}
);
if (!response.ok) {
throw new Error(`GitHub API request failed: ${response.status} ${response.statusText}`);
}
const pageRepos: Repo[] = await response.json();
if (pageRepos.length === 0) {
hasMorePages = false;
} else {
// GitHub API includes a 'fork' property to identify forked repos
const normalizedRepos: Repo[] = pageRepos.map((repo: any) => ({
name: repo.name,
clone_url: repo.clone_url,
description: repo.description || '',
private: repo.private,
fork: repo.fork
}));
repos.push(...normalizedRepos);
page++;
}
}
} catch (error) {
console.error('Error fetching repositories from GitHub:', error);
throw error;
}
console.log(`Found ${repos.length} repositories on GitHub`);
return repos;
}
/**
* Fetches all projects for the authenticated GitLab user
*/
async fetchGitLabRepos(): Promise<Repo[]> {
console.log('Fetching repositories from GitLab...');
const repos: Repo[] = [];
let page = 1;
let hasMorePages = true;
try {
while (hasMorePages) {
const response = await fetch(
`https://gitlab.com/api/v4/projects?owned=true&page=${page}&per_page=100&membership=true`,
{
headers: {
'Authorization': `Bearer ${this.gitlabToken}`,
'User-Agent': 'Universal-to-Codeberg-Migrator'
}
}
);
if (!response.ok) {
throw new Error(`GitLab API request failed: ${response.status} ${response.statusText}`);
}
const pageRepos: Repo[] = await response.json();
if (pageRepos.length === 0) {
hasMorePages = false;
} else {
// GitLab API returns different field names
const normalizedRepos: Repo[] = pageRepos.map((project: any) => ({
name: project.name,
clone_url: project.http_url_to_repo,
description: project.description || '',
private: project.visibility === 'private',
fork: !!project.forked_from_project
}));
repos.push(...normalizedRepos);
page++;
}
}
} catch (error) {
console.error('Error fetching repositories from GitLab:', error);
throw error;
}
console.log(`Found ${repos.length} repositories on GitLab`);
return repos;
}
/**
* Creates a new repository on Codeberg
*/
async createCodebergRepo(repo: Repo): Promise<boolean> {
console.log(`Creating repository ${repo.name} on Codeberg...`);
const repoData = {
auto_init: false,
description: repo.description || '',
name: repo.name,
private: repo.private
};
try {
const response = await fetch(
`${this.codebergBaseUrl}/api/v1/user/repos`,
{
method: 'POST',
headers: {
'Authorization': `token ${this.codebergToken}`,
'Content-Type': 'application/json',
'User-Agent': 'Universal-to-Codeberg-Migrator'
},
body: JSON.stringify(repoData)
}
);
if (!response.ok) {
// Check if the repository already exists
if (response.status === 409) {
console.log(`Repository ${repo.name} already exists on Codeberg`);
return true;
} else {
throw new Error(`Codeberg API request failed: ${response.status} ${response.statusText}`);
}
}
console.log(`Repository ${repo.name} created successfully on Codeberg`);
return true;
} catch (error) {
console.error(`Error creating repository ${repo.name} on Codeberg:`, error);
return false;
}
}
/**
* Clones a repository from source and pushes it to Codeberg
*/
async cloneAndPushRepo(sourceRepo: Repo, source: 'github' | 'gitlab'): Promise<boolean> {
const repoName = sourceRepo.name;
// Check if repository already exists on Codeberg by making an API request
const repoExists = await this.checkCodebergRepoExists(repoName);
if (repoExists) {
console.log(`Repository ${repoName} already exists on Codeberg, skipping migration...`);
return true; // Count as successful since it already exists
}
console.log(`Migrating repository: ${repoName} (from ${source})`);
// Create a temporary directory for cloning
const tempDir = path.join(process.cwd(), 'temp-repos');
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
const repoDir = path.join(tempDir, repoName);
try {
// Remove directory if it exists (from a previous failed attempt)
if (fs.existsSync(repoDir)) {
fs.rmSync(repoDir, { recursive: true, force: true });
}
// Clone the repository from the source
if (source === 'github') {
console.log(`Cloning from GitHub: https://github.com/${this.githubUsername}/${repoName}.git`);
// For GitHub, we use the token in the URL format for authentication
const githubUrl = `https://${this.githubUsername}:${this.githubToken}@github.com/${this.githubUsername}/${repoName}.git`;
await this.executeCommand('git', [
'clone',
githubUrl,
repoDir
]);
} else { // gitlab
console.log(`Cloning from GitLab: https://gitlab.com/${this.gitlabUsername}/${repoName}.git`);
// For GitLab, we use the token in the URL
const gitlabUrl = `https://oauth2:${this.gitlabToken}@gitlab.com/${this.gitlabUsername}/${repoName}.git`;
await this.executeCommand('git', [
'clone',
gitlabUrl,
repoDir
]);
}
// Set Git user details for the migration
await this.executeCommand('git', ['-C', repoDir, 'config', 'user.name', this.codebergUsername]);
await this.executeCommand('git', ['-C', repoDir, 'config', 'user.email', `${this.codebergUsername}@codeberg.org`]);
// Add Codeberg as a remote
const codebergRemoteUrl = `https://${this.codebergToken}@codeberg.org/${this.codebergUsername}/${repoName}.git`;
await this.executeCommand('git', ['-C', repoDir, 'remote', 'add', 'codeberg', codebergRemoteUrl]);
// Push all branches and tags to Codeberg
console.log(`Pushing to Codeberg: https://codeberg.org/${this.codebergUsername}/${repoName}`);
await this.executeCommand('git', ['-C', repoDir, 'push', '--all', 'codeberg']);
await this.executeCommand('git', ['-C', repoDir, 'push', '--tags', 'codeberg']);
console.log(`Repository ${repoName} migrated successfully!`);
return true;
} catch (error) {
console.error(`Error migrating repository ${repoName}:`, error);
return false;
} finally {
// Clean up temporary directory
if (fs.existsSync(repoDir)) {
fs.rmSync(repoDir, { recursive: true, force: true });
}
}
}
/**
* Checks if a repository already exists on Codeberg
*/
private async checkCodebergRepoExists(repoName: string): Promise<boolean> {
try {
const response = await fetch(
`${this.codebergBaseUrl}/api/v1/repos/${this.codebergUsername}/${repoName}`,
{
headers: {
'Authorization': `token ${this.codebergToken}`,
'User-Agent': 'Universal-to-Codeberg-Migrator'
}
}
);
// If the repository exists, the API will return a 200 status
// If it doesn't exist, it will return a 404 status
return response.status === 200;
} catch (error) {
// If we can't check due to an error, we'll assume it doesn't exist
console.warn(`Could not check if repository ${repoName} exists on Codeberg:`, error);
return false;
}
}
/**
* Deletes a repository from the source platform (GitHub or GitLab)
*/
private async deleteSourceRepo(repoName: string, source: 'github' | 'gitlab'): Promise<boolean> {
try {
let response: Response;
if (source === 'github') {
if (!this.githubToken || !this.githubUsername) {
console.error('GitHub credentials not available for deletion');
return false;
}
// Check if the repository is a fork to handle appropriately
// First, get repository details to check if it's a fork
const repoDetailsResponse = await fetch(
`https://api.github.com/repos/${this.githubUsername}/${repoName}`,
{
headers: {
'Authorization': `token ${this.githubToken}`,
'User-Agent': 'Universal-to-Codeberg-Migrator'
}
}
);
let isFork = false;
if (repoDetailsResponse.ok) {
const repoDetails = await repoDetailsResponse.json();
isFork = repoDetails.fork === true;
}
console.log(`Repository ${repoName} is ${isFork ? 'a fork' : 'not a fork'}`);
// Attempt to delete the repository
response = await fetch(
`https://api.github.com/repos/${this.githubUsername}/${repoName}`,
{
method: 'DELETE',
headers: {
'Authorization': `token ${this.githubToken}`,
'User-Agent': 'Universal-to-Codeberg-Migrator'
}
}
);
} else { // gitlab
if (!this.gitlabToken || !this.gitlabUsername) {
console.error('GitLab credentials not available for deletion');
return false;
}
// URL encode the project name for GitLab API
const encodedProjectName = encodeURIComponent(`${this.gitlabUsername}/${repoName}`);
response = await fetch(
`https://gitlab.com/api/v4/projects/${encodedProjectName}`,
{
method: 'DELETE',
headers: {
'Authorization': `Bearer ${this.gitlabToken}`,
'User-Agent': 'Universal-to-Codeberg-Migrator'
}
}
);
}
if (response.status === 204) {
// GitHub returns 204 No Content on successful deletion
return true;
} else if (response.status === 202) {
// GitLab returns 202 Accepted on successful deletion
return true;
} else if (response.status === 404) {
console.warn(`Repository ${repoName} not found on ${source}, may have already been deleted`);
return true; // Consider this a success since it doesn't exist
} else if (response.status === 403) {
console.error(`Forbidden: Cannot delete repository ${repoName} on ${source}. This may be due to repository permissions or it being a fork.`);
return false;
} else {
console.error(`Deletion failed with status: ${response.status} ${response.statusText}`);
return false;
}
} catch (error) {
console.error(`Error deleting repository ${repoName} from ${source}:`, error);
return false;
}
}
/**
* Executes a shell command and returns a promise
*/
private executeCommand(command: string, args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { stdio: 'inherit' });
child.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Command '${command} ${args.join(' ')}' exited with code ${code}`));
}
});
child.on('error', (error) => {
reject(error);
});
});
}
/**
* Main migration process
*/
async migrate(options: MigrationOptions): Promise<void> {
try {
console.log(`Starting ${options.source} to Codeberg migration process...`);
let repos: Repo[] = [];
// Fetch repositories from source
if (options.source === 'github') {
if (!this.githubToken || !this.githubUsername) {
console.error('Error: Missing required GitHub environment variables.');
console.log('Please set GITHUB_TOKEN and GITHUB_USERNAME in your .env file.');
process.exit(1);
}
repos = await this.fetchGitHubRepos();
} else { // gitlab
if (!this.gitlabToken || !this.gitlabUsername) {
console.error('Error: Missing required GitLab environment variables.');
console.log('Please set GITLAB_TOKEN and GITLAB_USERNAME in your .env file.');
process.exit(1);
}
repos = await this.fetchGitLabRepos();
}
// Filter out forks if not including them
const reposToMigrate = options.includeForks ? repos : repos.filter(repo => !repo.fork);
console.log(`Found ${reposToMigrate.length} repositories to migrate (${options.includeForks ? '' : 'excluding'} forks)`);
let successCount = 0;
let errorCount = 0;
for (const repo of reposToMigrate) {
console.log(`\nProcessing: ${repo.name}`);
// Check if repository already exists on Codeberg
const repoAlreadyExists = await this.checkCodebergRepoExists(repo.name);
if (repoAlreadyExists) {
console.log(`Repository ${repo.name} already exists on Codeberg, skipping migration...`);
successCount++; // Count as successful since it already exists
continue;
}
// Repository doesn't exist, so create it on Codeberg
const repoCreated = await this.createCodebergRepo(repo);
if (!repoCreated) {
console.error(`Failed to create repository ${repo.name} on Codeberg`);
errorCount++;
continue;
}
// Clone and push repository
const migrationSuccess = await this.cloneAndPushRepo(repo, options.source);
if (migrationSuccess) {
successCount++;
// If delete-source option is enabled, delete the source repository after successful migration
if (options.deleteSource) {
console.log(`Attempting to delete source repository: ${repo.name} from ${options.source}...`);
const deletionSuccess = await this.deleteSourceRepo(repo.name, options.source);
if (deletionSuccess) {
console.log(`Source repository ${repo.name} deleted successfully from ${options.source}`);
} else {
console.error(`Failed to delete source repository ${repo.name} from ${options.source}`);
// Note: We don't count this as an error that affects the migration success
}
}
} else {
errorCount++;
}
}
console.log(`\nMigration completed!`);
console.log(`Successful migrations: ${successCount}`);
console.log(`Failed migrations: ${errorCount}`);
// Clean up temporary directory
const tempDir = path.join(process.cwd(), 'temp-repos');
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
}
}
}
// Run the migration if this script is executed directly
// Use proper ES module main detection
async function runMain() {
if (typeof Bun !== 'undefined' ? import.meta.main : process.argv[1] === import.meta.url) {
// Parse command line arguments
const args = process.argv.slice(2);
const options: MigrationOptions = {
source: 'github', // default
includeForks: false
};
// Parse source argument
if (args.includes('--source')) {
const sourceIndex = args.indexOf('--source');
if (sourceIndex !== -1 && args[sourceIndex + 1]) {
const source = args[sourceIndex + 1];
if (source === 'github' || source === 'gitlab') {
options.source = source;
} else {
console.error('Error: Source must be either "github" or "gitlab"');
process.exit(1);
}
}
}
// Parse include-forks argument
if (args.includes('--include-forks')) {
options.includeForks = true;
}
// Parse delete-source argument
if (args.includes('--delete-source')) {
console.log("WARNING: The --delete-source flag will delete repositories from the source platform after successful migration.");
console.log("This action is irreversible. Please ensure all data has been successfully migrated.");
console.log("You have 10 seconds to cancel this operation by pressing Ctrl+C.");
await new Promise(resolve => setTimeout(resolve, 10000)); // 10 second delay to allow cancellation
options.deleteSource = true;
console.log("Deletion after migration enabled.");
}
const migrator = new UniversalToCodebergMigrator();
try {
await migrator.migrate(options);
} catch (error) {
console.error('Migration process failed:', error);
process.exit(1);
}
}
}
// Execute the main function
runMain().catch(console.error);
export default UniversalToCodebergMigrator;
export type { MigrationOptions };