-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-github-to-codeberg.ts
More file actions
272 lines (232 loc) · 8.46 KB
/
migrate-github-to-codeberg.ts
File metadata and controls
272 lines (232 loc) · 8.46 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
import { spawn } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
// Load environment variables
// NOTE: Bun automatically loads .env files, but we use dotenv for Node.js compatibility
let dotenv;
if (typeof Bun === 'undefined') {
dotenv = require('dotenv');
dotenv.config();
} else {
// Bun environment - .env is loaded automatically, but we can still use dotenv if needed
dotenv = require('dotenv');
dotenv.config();
}
// Interface for repository data
interface GitHubRepo {
name: string;
clone_url: string;
description?: string;
private: boolean;
}
class GitHubToCodebergMigrator {
private readonly githubToken: string;
private readonly codebergToken: string;
private readonly githubUsername: string;
private readonly codebergUsername: string;
constructor() {
this.githubToken = process.env.GITHUB_TOKEN || '';
this.codebergToken = process.env.CODEBERG_TOKEN || '';
this.githubUsername = process.env.GITHUB_USERNAME || '';
this.codebergUsername = process.env.CODEBERG_USERNAME || '';
// Validate required environment variables
if (!this.githubToken || !this.codebergToken || !this.githubUsername || !this.codebergUsername) {
console.error('Error: Missing required environment variables.');
console.log('Please set GITHUB_TOKEN, CODEBERG_TOKEN, GITHUB_USERNAME, and CODEBERG_USERNAME in your .env file.');
process.exit(1);
}
}
/**
* Fetches all repositories for the authenticated GitHub user
*/
async fetchGitHubRepos(): Promise<GitHubRepo[]> {
console.log('Fetching repositories from GitHub...');
const repos: GitHubRepo[] = [];
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': 'GitHub-to-Codeberg-Migrator'
}
}
);
if (!response.ok) {
throw new Error(`GitHub API request failed: ${response.status} ${response.statusText}`);
}
const pageRepos: GitHubRepo[] = await response.json();
if (pageRepos.length === 0) {
hasMorePages = false;
} else {
repos.push(...pageRepos);
page++;
}
}
} catch (error) {
console.error('Error fetching repositories:', error);
throw error;
}
console.log(`Found ${repos.length} repositories on GitHub`);
return repos;
}
/**
* Creates a new repository on Codeberg
*/
async createCodebergRepo(repo: GitHubRepo): 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(
'https://codeberg.org/api/v1/user/repos',
{
method: 'POST',
headers: {
'Authorization': `token ${this.codebergToken}`,
'Content-Type': 'application/json',
'User-Agent': 'GitHub-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 GitHub and pushes it to Codeberg
*/
async cloneAndPushRepo(githubRepo: GitHubRepo): Promise<boolean> {
const repoName = githubRepo.name;
console.log(`Migrating repository: ${repoName}`);
// 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 GitHub
console.log(`Cloning from GitHub: ${githubRepo.clone_url}`);
await this.executeCommand('git', [
'clone',
`https://${this.githubToken}@github.com/${this.githubUsername}/${repoName}.git`,
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 });
}
}
}
/**
* 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(): Promise<void> {
try {
console.log('Starting GitHub to Codeberg migration process...');
// Fetch repositories from GitHub
const repos = await this.fetchGitHubRepos();
// Filter out any repositories that shouldn't be migrated (e.g., forks)
const reposToMigrate = repos.filter(repo => !repo.fork);
console.log(`Found ${reposToMigrate.length} repositories to migrate (excluding forks)`);
let successCount = 0;
let errorCount = 0;
for (const repo of reposToMigrate) {
console.log(`\nProcessing: ${repo.name}`);
// Create repository 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);
if (migrationSuccess) {
successCount++;
} 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
if (typeof Bun !== 'undefined' ? import.meta.main : require.main === module) {
const migrator = new GitHubToCodebergMigrator();
migrator.migrate().catch(error => {
console.error('Migration process failed:', error);
process.exit(1);
});
}
export default GitHubToCodebergMigrator;