-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
179 lines (152 loc) · 5.04 KB
/
index.ts
File metadata and controls
179 lines (152 loc) · 5.04 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
import { join } from "node:path";
import {
createContributionCommit,
fetchAllGitLabCommits,
initGitHubRepo,
pushToGitHub,
} from "./services";
import type { SyncConfig, SyncedCommitsRecord } from "./types";
import {
isCommitSynced,
loadSyncedCommits,
log,
markCommitSynced,
ProgressBar,
saveSyncedCommits,
} from "./utils";
/**
* Validates the configuration object
*/
function validateConfig(config: unknown): SyncConfig {
if (!config || typeof config !== "object") {
throw new Error("Config must be an object");
}
const c = config as Record<string, unknown>;
// Validate gitlab section
if (!c.gitlab || typeof c.gitlab !== "object") {
throw new Error("Missing 'gitlab' section in config");
}
const gitlab = c.gitlab as Record<string, unknown>;
if (typeof gitlab.url !== "string" || !gitlab.url) {
throw new Error("Missing 'gitlab.url' in config");
}
if (typeof gitlab.token !== "string" || !gitlab.token) {
throw new Error("Missing 'gitlab.token' in config");
}
if (typeof gitlab.authorEmail !== "string" || !gitlab.authorEmail) {
throw new Error("Missing 'gitlab.authorEmail' in config");
}
// Validate other required fields
if (typeof c.githubRepoPath !== "string" || !c.githubRepoPath) {
throw new Error("Missing 'githubRepoPath' in config");
}
if (typeof c.githubAuthorName !== "string" || !c.githubAuthorName) {
throw new Error("Missing 'githubAuthorName' in config");
}
if (typeof c.githubAuthorEmail !== "string" || !c.githubAuthorEmail) {
throw new Error("Missing 'githubAuthorEmail' in config");
}
return config as SyncConfig;
}
/**
* Loads configuration from config.json
*/
async function loadConfig(): Promise<SyncConfig> {
const configPath = join(process.cwd(), "config.json");
const configFile = Bun.file(configPath);
if (!(await configFile.exists())) {
throw new Error(
"config.json not found. Please create it based on config.example.json",
);
}
const content = await configFile.text();
try {
const parsed = JSON.parse(content);
return validateConfig(parsed);
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(`Invalid JSON in config.json: ${error.message}`);
}
throw error;
}
}
/**
* Main sync function
*/
async function sync(): Promise<void> {
console.log(`\n${"═".repeat(60)}`);
console.log(" GitLab → GitHub Contributions Sync");
console.log(`${"═".repeat(60)}\n`);
// Load configuration
const config = await loadConfig();
// Handle insecure TLS for self-hosted GitLab
if (config.gitlab.insecure) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
log.warn("TLS certificate verification disabled");
}
log.info(`GitLab: ${config.gitlab.url}`);
log.info(`Author: ${config.gitlab.authorEmail}`);
// Initialize GitHub repo if needed
await initGitHubRepo(config.githubRepoPath);
// Load synced commits record
const syncedFile = config.syncedCommitsFile ?? ".synced-commits.json";
const syncedRecord: SyncedCommitsRecord = await loadSyncedCommits(syncedFile);
const syncedCount = Object.keys(syncedRecord.commits).length;
log.info(`Found ${syncedCount} previously synced commits\n`);
// Fetch all commits from GitLab API
const allCommits = await fetchAllGitLabCommits(config.gitlab);
log.success(`Total: ${allCommits.length} commits found`);
// Filter out already synced commits
const newCommits = allCommits.filter(
(commit) => !isCommitSynced(syncedRecord, commit.hash),
);
log.info(`${newCommits.length} new commits to sync`);
if (newCommits.length === 0) {
log.success("Everything is up to date!");
return;
}
// Sort commits by date (oldest first)
newCommits.sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
);
// Create contribution commits with incremental save
console.log("\nSyncing commits:\n");
let successCount = 0;
const saveInterval = 50;
const progress = new ProgressBar(newCommits.length);
for (let i = 0; i < newCommits.length; i++) {
const commit = newCommits[i];
try {
await createContributionCommit(
config.githubRepoPath,
commit,
config.githubAuthorName,
config.githubAuthorEmail,
);
markCommitSynced(syncedRecord, commit.hash);
successCount++;
progress.update(successCount, commit.date.substring(0, 10));
// Incremental save to prevent data loss on crash
if (successCount % saveInterval === 0) {
await saveSyncedCommits(syncedFile, syncedRecord);
}
} catch (error) {
log.error(`\nFailed to sync commit ${commit.hash}: ${error}`);
}
}
// Final save
await saveSyncedCommits(syncedFile, syncedRecord);
progress.complete();
console.log(`${"─".repeat(60)}`);
// Push to GitHub
console.log("\nPushing to GitHub...");
await pushToGitHub(config.githubRepoPath);
console.log(`\n${"═".repeat(60)}`);
log.success("Sync complete!");
console.log(`${"═".repeat(60)}\n`);
}
// Run the sync
sync().catch((error) => {
log.error(`Sync failed: ${error}`);
process.exit(1);
});