-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate-projects.js
More file actions
998 lines (846 loc) · 32.5 KB
/
update-projects.js
File metadata and controls
998 lines (846 loc) · 32.5 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const crypto = require("crypto");
// ============================================================================
// CONFIGURATION & CONSTANTS
// ============================================================================
const CONFIG = {
OWNER: process.env.GITHUB_REPOSITORY_OWNER,
TOKEN: process.env.GITHUB_TOKEN,
MAX_RETRIES: 5,
INITIAL_RETRY_DELAY_MS: 1000,
MAX_RETRY_DELAY_MS: 30000,
API_TIMEOUT_MS: 30000,
GIT_TIMEOUT_MS: 10000,
MAX_CONCURRENT_FETCHES: 3,
README_PATH: "profile/README.md",
LOCK_FILE: ".github-update-lock",
STATE_FILE: ".github-update-state.json",
HEALTH_FILE: ".github-health.json",
PROJECTS_MARKER_START: "<!-- PROJECTS:START -->",
PROJECTS_MARKER_END: "<!-- PROJECTS:END -->",
SLACK_WEBHOOK_URL: process.env.SLACK_WEBHOOK_URL,
};
const SEVERITY = {
INFO: "INFO",
WARN: "WARN",
ERROR: "ERROR",
DEBUG: "DEBUG",
};
// Busy hours (UTC) - avoid peak times
const BUSY_HOURS = [9, 10, 11, 12, 17, 18, 19];
// ============================================================================
// LOGGING SYSTEM
// ============================================================================
class Logger {
constructor() {
this.logs = [];
this.startTime = Date.now();
}
log(level, message, metadata = {}) {
const timestamp = new Date().toISOString();
const elapsed = Date.now() - this.startTime;
const logEntry = {
timestamp,
level,
message,
elapsed,
metadata,
};
this.logs.push(logEntry);
const metaStr = Object.keys(metadata).length
? ` | ${JSON.stringify(metadata)}`
: "";
console.log(
`[${timestamp}] [${level}] [${elapsed}ms] ${message}${metaStr}`
);
}
info(message, metadata) {
this.log(SEVERITY.INFO, message, metadata);
}
warn(message, metadata) {
this.log(SEVERITY.WARN, message, metadata);
}
error(message, metadata) {
this.log(SEVERITY.ERROR, message, metadata);
}
debug(message, metadata) {
if (process.env.DEBUG === "true") {
this.log(SEVERITY.DEBUG, message, metadata);
}
}
getLogs() {
return this.logs;
}
saveLogs(filePath) {
try {
fs.writeFileSync(
filePath,
JSON.stringify(this.logs, null, 2),
"utf8"
);
this.info("Logs saved", { filePath });
} catch (err) {
this.error("Failed to save logs", { error: err.message });
}
}
}
const logger = new Logger();
// ============================================================================
// STATE MANAGEMENT
// ============================================================================
class StateManager {
constructor(stateFile) {
this.stateFile = stateFile;
this.state = this.load();
}
load() {
try {
if (fs.existsSync(this.stateFile)) {
const data = fs.readFileSync(this.stateFile, "utf8");
return JSON.parse(data);
}
} catch (err) {
logger.warn("Failed to load state", { error: err.message });
}
return this.createEmptyState();
}
createEmptyState() {
return {
lastSuccessfulRun: null,
lastAttemptedRun: null,
failureCount: 0,
successCount: 0,
lastContentHash: null,
lastRepositoryCount: 0,
version: 1,
};
}
save() {
try {
fs.writeFileSync(
this.stateFile,
JSON.stringify(this.state, null, 2),
"utf8"
);
logger.debug("State saved", { state: this.state });
} catch (err) {
logger.error("Failed to save state", { error: err.message });
throw err;
}
}
markAttempt() {
this.state.lastAttemptedRun = new Date().toISOString();
}
markSuccess(contentHash, repoCount) {
this.state.lastSuccessfulRun = new Date().toISOString();
this.state.failureCount = 0;
this.state.successCount++;
this.state.lastContentHash = contentHash;
this.state.lastRepositoryCount = repoCount;
this.save();
}
markFailure() {
this.state.failureCount++;
this.save();
}
shouldAbortOnConsecutiveFailures(maxConsecutiveFailures = 3) {
return this.state.failureCount >= maxConsecutiveFailures;
}
}
const stateManager = new StateManager(CONFIG.STATE_FILE);
// ============================================================================
// DISTRIBUTED LOCK MANAGEMENT
// ============================================================================
class DistributedLock {
constructor(lockFile, ttlSeconds = 300) {
this.lockFile = lockFile;
this.ttlSeconds = ttlSeconds;
}
tryAcquire() {
try {
if (fs.existsSync(this.lockFile)) {
const lockData = JSON.parse(
fs.readFileSync(this.lockFile, "utf8")
);
const ageSeconds =
(Date.now() - lockData.timestamp) / 1000;
if (ageSeconds < this.ttlSeconds) {
logger.warn("Another process holds the lock", {
ageSeconds,
lockPid: lockData.pid,
});
return false;
}
logger.warn("Lock expired, removing stale lock");
fs.unlinkSync(this.lockFile);
}
const lockData = {
timestamp: Date.now(),
pid: process.pid,
hostname: require("os").hostname(),
workflowRunId: process.env.GITHUB_RUN_ID || "local",
};
fs.writeFileSync(
this.lockFile,
JSON.stringify(lockData, null, 2),
"utf8"
);
logger.info("Lock acquired");
return true;
} catch (err) {
logger.error("Failed to acquire lock", { error: err.message });
return false;
}
}
release() {
try {
if (fs.existsSync(this.lockFile)) {
fs.unlinkSync(this.lockFile);
logger.info("Lock released");
}
} catch (err) {
logger.error("Failed to release lock", { error: err.message });
}
}
}
const lock = new DistributedLock(CONFIG.LOCK_FILE);
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
function calculateHash(content) {
return crypto.createHash("sha256").update(content).digest("hex");
}
function executeGit(command, timeoutMs = CONFIG.GIT_TIMEOUT_MS) {
try {
logger.debug("Executing git command", { command });
const output = execSync(command, {
encoding: "utf-8",
timeout: timeoutMs,
stdio: ["pipe", "pipe", "pipe"],
});
logger.debug("Git command succeeded", { command, outputLength: output.length });
return { success: true, output: output.trim() };
} catch (error) {
logger.debug("Git command failed", { command, error: error.message });
return {
success: false,
error: error.message,
status: error.status,
};
}
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function calculateBackoffDelay(attempt) {
const exponentialDelay = Math.min(
CONFIG.INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt - 1),
CONFIG.MAX_RETRY_DELAY_MS
);
const jitter = Math.random() * 0.1 * exponentialDelay;
return exponentialDelay + jitter;
}
function shouldDeferExecution() {
const hour = new Date().getHours();
if (BUSY_HOURS.includes(hour) && Math.random() < 0.3) {
logger.warn("Deferring execution due to busy hour", { hour });
return true;
}
return false;
}
// ============================================================================
// NOTIFICATION SYSTEM
// ============================================================================
class NotificationService {
static async sendSlackNotification(status, metrics) {
if (!CONFIG.SLACK_WEBHOOK_URL) {
logger.debug("Slack webhook not configured, skipping notification");
return;
}
try {
const color = status === "success" ? "#36a64f" : "#ff0000";
const emoji = status === "success" ? "✅" : "❌";
const payload = {
attachments: [
{
color,
title: `${emoji} Profile Update ${status.toUpperCase()}`,
text: `Repositories updated: ${metrics.repositoriesProcessed || 0}`,
fields: [
{
title: "Duration",
value: `${metrics.duration}ms`,
short: true,
},
{
title: "Run ID",
value: process.env.GITHUB_RUN_ID || "local",
short: true,
},
{
title: "Repositories Fetched",
value: `${metrics.repositoriesFetched || 0}`,
short: true,
},
{
title: "File Updated",
value: metrics.fileUpdated ? "Yes" : "No",
short: true,
},
],
ts: Math.floor(Date.now() / 1000),
},
],
};
await fetch(CONFIG.SLACK_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
logger.info("Slack notification sent", { status });
} catch (err) {
logger.warn("Failed to send Slack notification", {
error: err.message,
});
}
}
}
// ============================================================================
// VALIDATION LAYER
// ============================================================================
class Validator {
static validateConfig() {
if (!CONFIG.OWNER) {
throw new Error("GITHUB_REPOSITORY_OWNER environment variable not set");
}
if (!CONFIG.TOKEN) {
throw new Error("GITHUB_TOKEN environment variable not set");
}
logger.info("Configuration validated", { owner: CONFIG.OWNER });
}
static validateReadmeFile() {
if (!fs.existsSync(CONFIG.README_PATH)) {
throw new Error(`README file not found at ${CONFIG.README_PATH}`);
}
const content = fs.readFileSync(CONFIG.README_PATH, "utf8");
if (!content.includes(CONFIG.PROJECTS_MARKER_START)) {
throw new Error(
`README missing marker: ${CONFIG.PROJECTS_MARKER_START}`
);
}
if (!content.includes(CONFIG.PROJECTS_MARKER_END)) {
throw new Error(
`README missing marker: ${CONFIG.PROJECTS_MARKER_END}`
);
}
logger.info("README file validated");
return content;
}
static validateRepositories(repositories) {
if (!Array.isArray(repositories)) {
throw new Error("Repositories response is not an array");
}
if (repositories.length === 0) {
logger.warn("No repositories found");
}
logger.info("Repositories validated", { count: repositories.length });
return repositories;
}
static validateFinalContent(content) {
if (content.length === 0) {
throw new Error("Final README content is empty");
}
if (!content.includes(CONFIG.PROJECTS_MARKER_START)) {
throw new Error("Missing projects start marker in final content");
}
if (!content.includes(CONFIG.PROJECTS_MARKER_END)) {
throw new Error("Missing projects end marker in final content");
}
logger.info("Final content validation passed", {
contentLength: content.length,
});
}
}
// ============================================================================
// GITHUB API CLIENT WITH ADVANCED RETRY
// ============================================================================
class GitHubAPIClient {
constructor(token) {
this.token = token;
}
async checkRateLimit() {
try {
logger.info("Checking GitHub API rate limit");
const response = await fetch(
`https://api.github.com/rate_limit`,
{
headers: {
Authorization: `Bearer ${this.token}`,
Accept: "application/vnd.github+json",
},
}
);
const data = await response.json();
const remaining = data.resources.core.remaining;
const limit = data.resources.core.limit;
const resetTime = new Date(data.resources.core.reset * 1000);
logger.info("Rate limit status", {
remaining,
limit,
percentageUsed: Math.round((1 - remaining / limit) * 100),
resetTime: resetTime.toISOString(),
});
if (remaining < 10) {
throw new Error(
`Rate limit critical: ${remaining}/${limit} requests remaining. Reset at ${resetTime.toISOString()}`
);
}
return { remaining, limit, resetTime };
} catch (err) {
logger.error("Failed to check rate limit", { error: err.message });
throw err;
}
}
async fetchWithRetry(url, options = {}, attempt = 1) {
try {
logger.debug("API request", { url, attempt });
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
CONFIG.API_TIMEOUT_MS
);
const response = await fetch(url, {
...options,
signal: controller.signal,
headers: {
Authorization: `Bearer ${this.token}`,
Accept: "application/vnd.github+json",
"User-Agent": "GitHub-Actions-Profile-Updater/2.0",
...options.headers,
},
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const rateLimitRemaining = response.headers.get("x-ratelimit-remaining");
const rateLimitReset = response.headers.get("x-ratelimit-reset");
logger.warn("API request failed", {
url,
status: response.status,
rateLimitRemaining,
rateLimitReset,
error: errorData.message,
});
throw new HTTPError(
`API request failed: ${response.status}`,
response.status,
errorData
);
}
const rateLimitRemaining = response.headers.get("x-ratelimit-remaining");
logger.debug("API request succeeded", {
url,
rateLimitRemaining,
});
return await response.json();
} catch (error) {
if (attempt < CONFIG.MAX_RETRIES) {
const delay = calculateBackoffDelay(attempt);
logger.warn("Retrying API request", {
url,
attempt,
nextAttemptIn: `${delay.toFixed(0)}ms`,
error: error.message,
});
await sleep(delay);
return this.fetchWithRetry(url, options, attempt + 1);
}
throw error;
}
}
async getOwnerType() {
const data = await this.fetchWithRetry(
`https://api.github.com/users/${CONFIG.OWNER}`
);
return data.type === "Organization" ? "organization" : "user";
}
async getRepositories() {
const ownerType = await this.getOwnerType();
const endpoint =
ownerType === "organization"
? `https://api.github.com/orgs/${CONFIG.OWNER}/repos`
: `https://api.github.com/users/${CONFIG.OWNER}/repos`;
logger.info("Fetching repositories", {
ownerType,
endpoint,
});
const allRepos = [];
let page = 1;
let hasMore = true;
while (hasMore && page <= 100) {
const data = await this.fetchWithRetry(
`${endpoint}?per_page=100&sort=updated&page=${page}`
);
if (!Array.isArray(data)) {
break;
}
allRepos.push(...data);
hasMore = data.length === 100;
page++;
logger.debug("Fetched repositories page", {
page: page - 1,
itemsInPage: data.length,
});
}
logger.info("All repositories fetched", { total: allRepos.length });
return allRepos;
}
}
class HTTPError extends Error {
constructor(message, status, data) {
super(message);
this.name = "HTTPError";
this.status = status;
this.data = data;
}
}
// ============================================================================
// GIT OPERATIONS WITH SAFETY
// ============================================================================
class GitOperations {
static async ensureCleanState() {
logger.info("Ensuring clean git state");
if (fs.existsSync(".git/MERGE_HEAD")) {
logger.warn("Merge in progress, aborting");
executeGit("git merge --abort");
}
if (fs.existsSync(".git/REBASE_HEAD")) {
logger.warn("Rebase in progress, aborting");
executeGit("git rebase --abort");
}
const statusResult = executeGit("git status --porcelain");
if (statusResult.success && statusResult.output.length > 0) {
logger.warn("Uncommitted changes detected, stashing");
const stashResult = executeGit("git stash");
if (!stashResult.success) {
throw new Error(`Failed to stash changes: ${stashResult.error}`);
}
}
logger.info("Git state is clean");
}
static async prepareForUpdate() {
logger.info("Preparing git for update");
const fetchResult = executeGit(
"git fetch origin main --force --prune"
);
if (!fetchResult.success) {
throw new Error(`Failed to fetch: ${fetchResult.error}`);
}
const currentResult = executeGit("git rev-parse HEAD");
const currentCommit = currentResult.success ? currentResult.output : "unknown";
const remoteResult = executeGit("git rev-parse origin/main");
const remoteCommit = remoteResult.success ? remoteResult.output : "unknown";
logger.info("Git status", {
currentCommit: currentCommit.substring(0, 7),
remoteCommit: remoteCommit.substring(0, 7),
isBehind: currentCommit !== remoteCommit,
});
if (currentCommit !== remoteCommit) {
logger.warn("Local branch is behind remote, resetting");
const resetResult = executeGit("git reset --hard origin/main");
if (!resetResult.success) {
throw new Error(`Failed to reset: ${resetResult.error}`);
}
}
}
static async commitAndPush(message, filePath) {
logger.info("Committing changes", { message, filePath });
executeGit('git config user.name "github-actions[bot]"');
executeGit('git config user.email "github-actions[bot]@users.noreply.github.com"');
const addResult = executeGit(`git add "${filePath}"`);
if (!addResult.success) {
throw new Error(`Failed to stage file: ${addResult.error}`);
}
const diffResult = executeGit("git diff --cached --name-only");
if (!diffResult.success || diffResult.output.length === 0) {
logger.info("No changes to commit");
return false;
}
const commitResult = executeGit(
`git commit -m "${message}" --no-verify`
);
if (!commitResult.success) {
if (commitResult.error.includes("nothing to commit")) {
logger.info("Nothing to commit");
return false;
}
throw new Error(`Failed to commit: ${commitResult.error}`);
}
logger.info("Commit created successfully");
let pushAttempt = 0;
while (pushAttempt < CONFIG.MAX_RETRIES) {
pushAttempt++;
const pushResult = executeGit("git push origin main");
if (pushResult.success) {
logger.info("Push successful");
return true;
}
logger.warn("Push failed", {
attempt: pushAttempt,
error: pushResult.error,
});
if (
pushResult.error.includes("rejected") ||
pushResult.error.includes("no changes added")
) {
logger.info("Pulling latest changes and retrying");
const pullResult = executeGit("git pull --rebase origin main");
if (!pullResult.success) {
throw new Error(`Failed to pull: ${pullResult.error}`);
}
const readmeContent = fs.readFileSync(
CONFIG.README_PATH,
"utf8"
);
fs.writeFileSync(CONFIG.README_PATH, readmeContent);
executeGit(`git add "${filePath}"`);
const newCommitResult = executeGit(
`git commit -m "${message}" --no-verify || true`
);
if (pushAttempt < CONFIG.MAX_RETRIES) {
await sleep(calculateBackoffDelay(pushAttempt));
}
} else {
throw new Error(`Unrecoverable push error: ${pushResult.error}`);
}
}
throw new Error("Failed to push after all retries");
}
}
// ============================================================================
// HEALTH CHECK & MONITORING
// ============================================================================
class HealthMonitor {
static saveHealthStatus(status, metrics) {
try {
const health = {
status,
lastRun: new Date().toISOString(),
nextRun: new Date(Date.now() + 6 * 60 * 60 * 1000).toISOString(),
repositoryCount: metrics.repositoriesProcessed || 0,
duration: metrics.duration || 0,
successCount: stateManager.state.successCount,
failureCount: stateManager.state.failureCount,
uptime: stateManager.state.successCount > 0 ? "healthy" : "initializing",
};
fs.writeFileSync(
CONFIG.HEALTH_FILE,
JSON.stringify(health, null, 2),
"utf8"
);
logger.info("Health status saved", health);
} catch (err) {
logger.warn("Failed to save health status", { error: err.message });
}
}
}
// ============================================================================
// MAIN WORKFLOW
// ============================================================================
class ProfileUpdater {
constructor() {
this.client = new GitHubAPIClient(CONFIG.TOKEN);
this.repositories = [];
this.previousContent = null;
this.newContent = null;
this.metrics = {
startTime: Date.now(),
startTimeISO: new Date().toISOString(),
duration: 0,
repositoriesFetched: 0,
repositoriesProcessed: 0,
fileUpdated: false,
rateLimitRemaining: 0,
};
}
async run() {
stateManager.markAttempt();
try {
// Step 0: Check for busy hour deferral
if (shouldDeferExecution()) {
logger.info("⏸️ Deferring execution due to busy hour");
return;
}
// Step 1: Validation
logger.info("🚀 Starting profile update workflow v2.0");
Validator.validateConfig();
this.previousContent = Validator.validateReadmeFile();
// Step 2: Rate limit check
const rateLimit = await this.client.checkRateLimit();
this.metrics.rateLimitRemaining = rateLimit.remaining;
// Step 3: Consecutive failure check
if (stateManager.shouldAbortOnConsecutiveFailures(5)) {
throw new Error(
"Too many consecutive failures. Aborting to prevent cascade."
);
}
// Step 4: Distributed locking
if (!lock.tryAcquire()) {
logger.warn("Workflow already running. Exiting gracefully.");
return;
}
try {
// Step 5: Fetch repositories
this.repositories = await this.client.getRepositories();
Validator.validateRepositories(this.repositories);
this.metrics.repositoriesFetched = this.repositories.length;
// Step 6: Process repositories
const processedRepos = this.filterAndSortRepos(this.repositories);
this.metrics.repositoriesProcessed = processedRepos.length;
logger.info("Repositories processed", {
total: this.repositories.length,
filtered: processedRepos.length,
excluded: this.repositories.length - processedRepos.length,
});
// Step 7: Generate content
this.newContent = this.generateProjectsTable(processedRepos);
// Step 8: Update README (merge table into README)
this.updateReadmeContent();
// Step 9: Validate final content AFTER merging
Validator.validateFinalContent(this.newContent);
// Step 10: Check for actual changes
if (this.previousContent === this.newContent) {
logger.info("✅ No changes detected. Profile is up-to-date");
this.metrics.fileUpdated = false;
this.metrics.duration = Date.now() - this.metrics.startTime;
stateManager.markSuccess(
calculateHash(this.previousContent),
processedRepos.length
);
HealthMonitor.saveHealthStatus("success", this.metrics);
await NotificationService.sendSlackNotification("success", this.metrics);
return;
}
// Step 11: Git operations
await GitOperations.ensureCleanState();
await GitOperations.prepareForUpdate();
// Step 12: Commit and push with enhanced message
const commitMessage = this.generateCommitMessage(processedRepos);
const committed = await GitOperations.commitAndPush(
commitMessage,
CONFIG.README_PATH
);
this.metrics.duration = Date.now() - this.metrics.startTime;
if (committed) {
const newHash = calculateHash(this.newContent);
this.metrics.fileUpdated = true;
stateManager.markSuccess(newHash, processedRepos.length);
logger.info(
`✅ Successfully updated ${processedRepos.length} projects`,
this.metrics
);
HealthMonitor.saveHealthStatus("success", this.metrics);
await NotificationService.sendSlackNotification("success", this.metrics);
} else {
logger.info("✅ No changes to commit");
this.metrics.fileUpdated = false;
stateManager.markSuccess(
calculateHash(this.previousContent),
processedRepos.length
);
HealthMonitor.saveHealthStatus("success", this.metrics);
await NotificationService.sendSlackNotification("success", this.metrics);
}
} finally {
lock.release();
}
} catch (error) {
this.metrics.duration = Date.now() - this.metrics.startTime;
this.metrics.error = error.message;
stateManager.markFailure();
logger.error("❌ Workflow failed", {
error: error.message,
stack: error.stack,
metrics: this.metrics,
});
await GitOperations.ensureCleanState().catch(() => {});
logger.saveLogs(".github-update-logs.json");
HealthMonitor.saveHealthStatus("failed", this.metrics);
await NotificationService.sendSlackNotification("failure", this.metrics);
throw error;
}
}
filterAndSortRepos(repositories) {
return repositories
.filter(repo => !repo.fork)
.filter(repo => !repo.archived)
.filter(repo => repo.name !== ".github")
.sort((a, b) => a.name.localeCompare(b.name));
}
generateProjectsTable(repos) {
let table =
`| Repository | Description |\n| ---------- | ----------- |\n`;
if (repos.length === 0) {
table += `| Coming Soon | Initial infrastructure repositories in progress |\n`;
} else {
for (const repo of repos) {
const description = (repo.description ?? "No description")
.substring(0, 100)
.replace(/\|/g, "\\|")
.replace(/\n/g, " ")
.replace(/\[/g, "\\[")
.replace(/\]/g, "\\]");
table += `| [${repo.name}](${repo.html_url}) | ${description} |\n`;
}
}
return table;
}
generateCommitMessage(repos) {
const timestamp = new Date().toISOString();
const excluded = this.repositories.length - repos.length;
return (
`chore(profile): update projects table\n\n` +
`- Total repositories: ${repos.length}\n` +
`- Excluded (forks/archived): ${excluded}\n` +
`- Updated at: ${timestamp}\n` +
`- Duration: ${this.metrics.duration}ms\n\n` +
`[skip ci]`
);
}
updateReadmeContent() {
const regex = new RegExp(
`${CONFIG.PROJECTS_MARKER_START}[\\s\\S]*?${CONFIG.PROJECTS_MARKER_END}`,
"g"
);
this.newContent = this.previousContent.replace(
regex,
`${CONFIG.PROJECTS_MARKER_START}\n${this.newContent}\n${CONFIG.PROJECTS_MARKER_END}`
);
fs.writeFileSync(
CONFIG.README_PATH,
this.newContent,
"utf8"
);
logger.info("README content updated");
}
}
// ============================================================================
// EXECUTION
// ============================================================================
async function main() {
try {
const updater = new ProfileUpdater();
await updater.run();
logger.saveLogs(".github-update-logs.json");
process.exit(0);
} catch (error) {
logger.saveLogs(".github-update-logs.json");
process.exit(1);
}
}
main().catch(error => {
console.error("Fatal error:", error);
process.exit(1);
});