-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdetect-drift.js
More file actions
executable file
·289 lines (249 loc) · 9.99 KB
/
detect-drift.js
File metadata and controls
executable file
·289 lines (249 loc) · 9.99 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
#!/usr/bin/env node
/**
* Detect drift between REPOSITORIES.md and actual GitHub organization state
* Compares desired state (REPOSITORIES.md) with actual state (GitHub API)
*/
import { parseRepositoriesFile } from './parse-repositories.js';
import { fetchGitHubRepositories } from './fetch-github-state.js';
import { checkMultipleTransferPermissions } from './check-transfer-permissions.js';
/**
* Compare two arrays of topics
*/
function arraysEqual(a, b) {
if (!a && !b) return true;
if (!a || !b) return false;
if (a.length !== b.length) return false;
const sortedA = [...a].sort();
const sortedB = [...b].sort();
return sortedA.every((val, idx) => val === sortedB[idx]);
}
/**
* Detect differences between desired and actual repository states
* @param {Array} desiredRepos - Repositories defined in REPOSITORIES.md
* @param {Array} actualRepos - Repositories in GitHub organization
* @param {Map} transferPermissions - Optional map of origin repo to permission results
*/
function detectDrift(desiredRepos, actualRepos, transferPermissions = new Map()) {
const drift = {
missing: [], // In REPOSITORIES.md but not in GitHub
extra: [], // In GitHub but not in REPOSITORIES.md
descriptionDiff: [], // Description mismatch
topicsDiff: [], // Topics mismatch
pendingTransfer: [], // Repositories with origin field
transferPermissions, // Permission status for repositories with origin
};
// Create lookup maps
const desiredMap = new Map(desiredRepos.map(r => [r.name, r]));
const actualMap = new Map(actualRepos.map(r => [r.name, r]));
// Find missing and different repos
for (const desired of desiredRepos) {
const actual = actualMap.get(desired.name);
// Check for origin field (repository transfer - not yet implemented)
if (desired.origin) {
drift.pendingTransfer.push(desired);
continue; // Skip other checks for transfer repos
}
if (!actual) {
drift.missing.push(desired);
} else {
// Check description
if (desired.description !== actual.description) {
drift.descriptionDiff.push({
name: desired.name,
desired: desired.description,
actual: actual.description,
});
}
// Check topics
if (!arraysEqual(desired.topics, actual.topics)) {
drift.topicsDiff.push({
name: desired.name,
desired: desired.topics || [],
actual: actual.topics || [],
});
}
}
}
// Find extra repos
for (const actual of actualRepos) {
if (!desiredMap.has(actual.name)) {
drift.extra.push(actual);
}
}
return drift;
}
/**
* Format drift report as markdown
*/
function formatDriftReport(drift, desiredCount, actualCount) {
const lines = [];
lines.push('# 🔍 Repository Drift Report');
lines.push('');
lines.push(`**Summary**: ${desiredCount} repositories in REPOSITORIES.md, ${actualCount} repositories in GitHub organization`);
lines.push('');
const hasDrift = drift.missing.length > 0 ||
drift.extra.length > 0 ||
drift.descriptionDiff.length > 0 ||
drift.topicsDiff.length > 0 ||
drift.pendingTransfer.length > 0;
if (!hasDrift) {
lines.push('✅ **No drift detected** - REPOSITORIES.md matches GitHub organization state');
return lines.join('\n');
}
lines.push('⚠️ **Drift detected** - Differences found between REPOSITORIES.md and GitHub');
lines.push('');
// Pending transfers
if (drift.pendingTransfer.length > 0) {
lines.push(`## 🚧 Repository Transfer Pending (${drift.pendingTransfer.length})`);
lines.push('');
lines.push('⚠️ **TRANSFER FEATURE IN DEVELOPMENT** - These repositories have an `Origin` field for migration:');
lines.push('');
for (const repo of drift.pendingTransfer) {
const permission = drift.transferPermissions.get(repo.origin);
lines.push(`- **${repo.name}** ← \`${repo.origin}\``);
lines.push(` - Description: ${repo.description}`);
if (permission) {
if (permission.hasPermission) {
lines.push(` - ✅ **Permission Status**: ${permission.details}`);
lines.push(` - **Ready for transfer** (once transfer automation is complete)`);
} else {
lines.push(` - ❌ **Permission Status**: ${permission.details}`);
lines.push(` - **Action required**: Grant worlddriven admin access to \`${repo.origin}\``);
lines.push('');
lines.push(' **How to grant access:**');
lines.push(` 1. Go to https://github.com/${repo.origin}/settings/access`);
lines.push(' 2. Click "Add people" or "Add teams"');
lines.push(' 3. Search for "worlddriven" and select the organization');
lines.push(' 4. Set permission level to **Admin**');
lines.push(' 5. Send the invitation - worlddriven will auto-accept');
}
} else {
lines.push(` - ⚠️ **Permission Status**: Not checked`);
lines.push(` - Run drift detection to verify permissions`);
}
}
lines.push('');
lines.push('**Note**: Transfer automation is under development. See issue #9 for progress.');
lines.push('');
}
// Missing repositories
if (drift.missing.length > 0) {
lines.push(`## 📝 Missing in GitHub (${drift.missing.length})`);
lines.push('');
lines.push('These repositories are defined in REPOSITORIES.md but do not exist in GitHub:');
lines.push('');
for (const repo of drift.missing) {
lines.push(`- **${repo.name}**: ${repo.description}`);
}
lines.push('');
}
// Extra repositories
if (drift.extra.length > 0) {
lines.push(`## ➕ Not in REPOSITORIES.md (${drift.extra.length})`);
lines.push('');
lines.push('These repositories exist in GitHub but are not documented in REPOSITORIES.md:');
lines.push('');
for (const repo of drift.extra) {
lines.push(`- **${repo.name}**: ${repo.description || '(no description)'}`);
}
lines.push('');
}
// Description differences
if (drift.descriptionDiff.length > 0) {
lines.push(`## 📄 Description Mismatches (${drift.descriptionDiff.length})`);
lines.push('');
for (const diff of drift.descriptionDiff) {
lines.push(`### ${diff.name}`);
lines.push(`- **In REPOSITORIES.md**: ${diff.desired || '(empty)'}`);
lines.push(`- **In GitHub**: ${diff.actual || '(empty)'}`);
lines.push('');
}
}
// Topics differences
if (drift.topicsDiff.length > 0) {
lines.push(`## 🏷️ Topics Mismatches (${drift.topicsDiff.length})`);
lines.push('');
for (const diff of drift.topicsDiff) {
lines.push(`### ${diff.name}`);
lines.push(`- **In REPOSITORIES.md**: ${diff.desired.join(', ') || '(none)'}`);
lines.push(`- **In GitHub**: ${diff.actual.join(', ') || '(none)'}`);
lines.push('');
}
}
return lines.join('\n');
}
/**
* Main function
*/
async function main() {
const token = process.env.WORLDDRIVEN_GITHUB_TOKEN;
if (!token) {
console.error('❌ Error: WORLDDRIVEN_GITHUB_TOKEN environment variable is not set');
process.exit(1);
}
try {
console.error('📖 Parsing REPOSITORIES.md...');
const desiredRepos = await parseRepositoriesFile();
console.error('🌐 Fetching GitHub organization state...');
const actualRepos = await fetchGitHubRepositories(token);
// Check permissions for repositories with origin field
const reposWithOrigin = desiredRepos.filter(r => r.origin);
let transferPermissions = new Map();
if (reposWithOrigin.length > 0) {
console.error('🔐 Checking transfer permissions...');
const originRepos = reposWithOrigin.map(r => r.origin);
transferPermissions = await checkMultipleTransferPermissions(token, originRepos);
}
console.error('🔍 Detecting drift...\n');
const drift = detectDrift(desiredRepos, actualRepos, transferPermissions);
const report = formatDriftReport(drift, desiredRepos.length, actualRepos.length);
console.log(report);
// Check for pending transfers with missing permissions (blocks CI)
const blockedTransfers = drift.pendingTransfer.filter(
r => !drift.transferPermissions.get(r.origin)?.hasPermission
);
// Report drift status
const hasDrift = drift.missing.length > 0 ||
drift.extra.length > 0 ||
drift.descriptionDiff.length > 0 ||
drift.topicsDiff.length > 0 ||
drift.pendingTransfer.length > 0;
if (hasDrift) {
console.error('\n📋 Drift Summary:');
if (drift.missing.length > 0 || drift.extra.length > 0 ||
drift.descriptionDiff.length > 0 || drift.topicsDiff.length > 0) {
console.error(' ✅ Configuration drift will be fixed on merge');
}
if (drift.pendingTransfer.length > 0) {
const readyCount = drift.pendingTransfer.length - blockedTransfers.length;
if (readyCount > 0) {
console.error(` ✅ ${readyCount} repository transfer(s) ready (admin permission granted)`);
}
if (blockedTransfers.length > 0) {
console.error(` ❌ ${blockedTransfers.length} repository transfer(s) blocked (missing admin permission)`);
}
}
}
// Only fail CI if there are blocked transfers (missing permissions)
if (blockedTransfers.length > 0) {
console.error('\n❌ Error: Cannot proceed with repository transfer(s) - missing permissions');
console.error('');
for (const repo of blockedTransfers) {
console.error(` → ${repo.origin}: https://github.com/${repo.origin}/settings/access`);
}
console.error('');
console.error(' Grant worlddriven "Admin" access at the URLs above to unblock this PR.');
process.exit(1);
}
process.exit(0);
} catch (error) {
console.error(`❌ Error: ${error.message}`);
process.exit(1);
}
}
// Export for use as module
export { detectDrift, formatDriftReport };
// CLI usage
if (import.meta.url === `file://${process.argv[1]}`) {
main();
}