-
Notifications
You must be signed in to change notification settings - Fork 53
1196 lines (1041 loc) · 50.1 KB
/
Copy pathclean-up.yml
File metadata and controls
1196 lines (1041 loc) · 50.1 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
999
1000
name: 🧹 Cleanup CCache
on:
workflow_dispatch:
inputs:
cleanup_type:
type: choice
description: 'Cleanup target'
required: true
default: 'cache_only'
options:
- cache_only # Only clean caches
- runs_only # Only clean workflow runs
- full_cleanup # Both caches and runs
- analyze_only # Just analyze, don't delete
device_filter:
type: choice
description: 'Device cache to clean'
required: false
default: 'ALL'
options:
- ALL
# Kernel Versions
- android15-6.6
- android14-6.1
- android14-5.15
- android13-5.15
- android13-5.10
- android12-5.10
# OnePlus Phones
- OP15T
- OP15r
- OP15
- OP13
- OP13-CPH
- OP13-PJZ
- OP13r
- OP13S
- OP13T
- OP12
- OP12r
- OP11
- OP11r
- OP10pro
- OP10t
- OP10r
# OnePlus Nord Series
- OP-NORD-6
- OP-NORD-5
- OP-NORD-4
- OP-NORD-3
- OP-NORD-4-CE
- OP-NORD-CE-5
- OP-NORD-CE4-LITE
- OP-NORD-N30-SE
# OnePlus Ace Series
- OP-TURBO-6V
- OP-TURBO-6
- OP-ACE-6T
- OP-ACE-6
- OP-ACE-6-ULTRA
- OP-ACE-5-PRO
- OP-ACE-5
- OP-ACE-5-ULTRA
- OP-ACE-5-RACE
- OP-ACE-3-PRO
- OP-ACE-3V
- OP-ACE-3
- OP-ACE-2-PRO
- OP-ACE-2
- OP-ACE-2V
- OP-ACE-RACE
- OP-ACE
# OnePlus Tablets & Others
- OP-OPEN
- OP-PAD-4
- OP-PAD-3-PRO
- OP-PAD-3-SM8750
- OP-PAD-3-MT6897
- OP-PAD-2-PRO
- OP-PAD-2-SM8650
- OP-PAD-2-MT6991
- OP-PAD-PRO
- OP-PAD-MT6983
- OP-PAD-LITE
- OP-PAD-GO-2
- OP-PAD-GO
cache_pattern:
type: choice
description: 'Cache type to clean'
required: false
default: 'all_caches'
options:
- all_caches # All cache types
- ccache_only # Only ccache (kernel builds)
- ccache_stale # Only stale ccache (>14 days)
- apt_only # Only apt packages
- kernel_only # Only kernel-related caches
- old_only # Only caches older than 7 days
cache_age_days:
description: 'Delete caches older than N days'
required: false
default: '7'
keep_recent_runs:
description: 'Keep N most recent successful runs'
required: false
default: '3'
days_to_keep:
description: 'Keep runs from last N days'
required: false
default: '7'
dry_run:
description: 'Dry run (show what would be deleted)'
required: false
type: boolean
default: false
force_cleanup:
description: 'Force cleanup even if usage is low'
required: false
type: boolean
default: false
permissions:
actions: write
contents: read
jobs:
analyze:
runs-on: ubuntu-latest
outputs:
should_cleanup: ${{ steps.analysis.outputs.should_cleanup }}
total_cache_size: ${{ steps.analysis.outputs.total_size }}
cache_count: ${{ steps.analysis.outputs.cache_count }}
usage_percent: ${{ steps.analysis.outputs.usage_percent }}
ccache_count: ${{ steps.analysis.outputs.ccache_count }}
ccache_size: ${{ steps.analysis.outputs.ccache_size }}
steps:
- name: 📊 Analyze Repository Health
id: analysis
uses: actions/github-script@v7
with:
script: |
const { owner, repo } = context.repo;
const forceCleanup = '${{ inputs.force_cleanup }}' === 'true';
console.log('🔍 Analyzing repository cache health...\n');
let page = 1;
let totalCacheSize = 0;
let cacheCount = 0;
let oldestCache = null;
let newestCache = null;
const cachesByType = {
ccache: { size: 0, count: 0 },
apt: { size: 0, count: 0 },
kernel: { size: 0, count: 0 },
other: { size: 0, count: 0 }
};
const cachesByDevice = new Map();
const cacheAgeDistribution = {
fresh: 0, // < 7 days
recent: 0, // 7-14 days
old: 0, // 14-30 days
stale: 0 // > 30 days
};
// Collect all cache data
while (true) {
const res = await github.rest.actions.getActionsCacheList({
owner,
repo,
per_page: 100,
page: page
});
const caches = res.data.actions_caches;
if (!caches || caches.length === 0) break;
for (const cache of caches) {
totalCacheSize += cache.size_in_bytes;
cacheCount++;
const cacheDate = new Date(cache.created_at);
const ageDays = Math.floor((new Date() - cacheDate) / (1000 * 60 * 60 * 24));
// Age distribution
if (ageDays < 7) cacheAgeDistribution.fresh++;
else if (ageDays < 14) cacheAgeDistribution.recent++;
else if (ageDays < 30) cacheAgeDistribution.old++;
else cacheAgeDistribution.stale++;
if (!oldestCache || cacheDate < new Date(oldestCache.created_at)) {
oldestCache = cache;
}
if (!newestCache || cacheDate > new Date(newestCache.created_at)) {
newestCache = cache;
}
// Categorize by type
if (cache.key.startsWith('ccache-')) {
cachesByType.ccache.size += cache.size_in_bytes;
cachesByType.ccache.count++;
// Extract device name from ccache key
const match = cache.key.match(/ccache-([^-]+)-/);
if (match) {
const device = match[1];
if (!cachesByDevice.has(device)) {
cachesByDevice.set(device, {
size: 0,
count: 0,
lastAccessed: cache.last_accessed_at,
oldestCache: ageDays,
newestCache: ageDays
});
}
const deviceData = cachesByDevice.get(device);
deviceData.size += cache.size_in_bytes;
deviceData.count++;
deviceData.oldestCache = Math.max(deviceData.oldestCache, ageDays);
deviceData.newestCache = Math.min(deviceData.newestCache, ageDays);
if (new Date(cache.last_accessed_at) > new Date(deviceData.lastAccessed)) {
deviceData.lastAccessed = cache.last_accessed_at;
}
}
} else if (cache.key.includes('apt')) {
cachesByType.apt.size += cache.size_in_bytes;
cachesByType.apt.count++;
} else if (cache.key.includes('kernel') || cache.key.includes('android')) {
cachesByType.kernel.size += cache.size_in_bytes;
cachesByType.kernel.count++;
} else {
cachesByType.other.size += cache.size_in_bytes;
cachesByType.other.count++;
}
}
if (caches.length < 100) break;
page++;
}
// Calculate metrics
const totalGB = (totalCacheSize / 1024 / 1024 / 1024).toFixed(2);
const limit = 10; // 10 GB GitHub limit
const usagePercent = ((totalCacheSize / (limit * 1024 * 1024 * 1024)) * 100).toFixed(1);
// Determine if cleanup is needed
const shouldCleanup = forceCleanup || parseFloat(usagePercent) > 75;
// Health status
let healthEmoji = '🟢';
let healthStatus = 'Healthy';
if (usagePercent > 90) {
healthEmoji = '🔴';
healthStatus = 'Critical';
} else if (usagePercent > 75) {
healthEmoji = '🟡';
healthStatus = 'Warning';
}
// Output for next jobs
core.setOutput('should_cleanup', shouldCleanup.toString());
core.setOutput('total_size', totalCacheSize.toString());
core.setOutput('cache_count', cacheCount.toString());
core.setOutput('usage_percent', usagePercent);
core.setOutput('ccache_count', cachesByType.ccache.count.toString());
core.setOutput('ccache_size', cachesByType.ccache.size.toString());
// Generate detailed summary
let summary = core.summary
.addHeading(`${healthEmoji} Cache Health Analysis - ${healthStatus}`)
.addRaw(`\n### 📊 Overall Statistics\n\n`)
.addTable([
[{data: 'Metric', header: true}, {data: 'Value', header: true}],
['Total Caches', cacheCount.toString()],
['Total Size', `${totalGB} GB`],
['Limit', `${limit} GB`],
['Usage', `${usagePercent}%`],
['Available', `${(limit - parseFloat(totalGB)).toFixed(2)} GB`],
['Status', healthStatus]
]);
// Cache breakdown by type
summary.addRaw(`\n### 🗂️ Cache Breakdown by Type\n\n`)
.addTable([
[{data: 'Type', header: true}, {data: 'Count', header: true}, {data: 'Size (GB)', header: true}, {data: 'Percentage', header: true}],
['ccache (Kernel Builds)',
cachesByType.ccache.count.toString(),
(cachesByType.ccache.size / 1024 / 1024 / 1024).toFixed(2),
`${((cachesByType.ccache.size / totalCacheSize) * 100).toFixed(1)}%`
],
['Kernel-related',
cachesByType.kernel.count.toString(),
(cachesByType.kernel.size / 1024 / 1024 / 1024).toFixed(2),
`${((cachesByType.kernel.size / totalCacheSize) * 100).toFixed(1)}%`
],
['APT Packages',
cachesByType.apt.count.toString(),
(cachesByType.apt.size / 1024 / 1024 / 1024).toFixed(2),
`${((cachesByType.apt.size / totalCacheSize) * 100).toFixed(1)}%`
],
['Other',
cachesByType.other.count.toString(),
(cachesByType.other.size / 1024 / 1024 / 1024).toFixed(2),
`${((cachesByType.other.size / totalCacheSize) * 100).toFixed(1)}%`
]
]);
// ccache-specific statistics
if (cachesByType.ccache.count > 0) {
const avgCcacheSize = cachesByType.ccache.size / cachesByType.ccache.count;
const avgCcacheSizeMB = (avgCcacheSize / 1024 / 1024).toFixed(2);
const ccachePercent = ((cachesByType.ccache.size / totalCacheSize) * 100).toFixed(1);
summary.addRaw(`\n### ⚡ ccache Statistics\n\n`)
.addTable([
[{data: 'Metric', header: true}, {data: 'Value', header: true}],
['Total ccache Entries', cachesByType.ccache.count.toString()],
['Total ccache Size', `${(cachesByType.ccache.size / 1024 / 1024 / 1024).toFixed(2)} GB`],
['Average Cache Size', `${avgCcacheSizeMB} MB`],
['Percentage of Total', `${ccachePercent}%`],
['Unique Devices', cachesByDevice.size.toString()]
]);
// ccache recommendations
if (parseFloat(ccachePercent) > 80) {
summary.addRaw(`\n⚠️ **ccache dominates storage** (${ccachePercent}%)\n`)
.addRaw(`- Consider reducing \`CCACHE_MAXSIZE\` in build workflow\n`)
.addRaw(`- Clean stale device caches not actively built\n`)
.addRaw(`- Use \`clean_build\` option occasionally to verify builds\n`);
}
}
// Age distribution
summary.addRaw(`\n### 📅 Cache Age Distribution\n\n`)
.addTable([
[{data: 'Age Range', header: true}, {data: 'Count', header: true}, {data: 'Percentage', header: true}],
['Fresh (< 7 days)', cacheAgeDistribution.fresh.toString(), `${((cacheAgeDistribution.fresh / cacheCount) * 100).toFixed(1)}%`],
['Recent (7-14 days)', cacheAgeDistribution.recent.toString(), `${((cacheAgeDistribution.recent / cacheCount) * 100).toFixed(1)}%`],
['Old (14-30 days)', cacheAgeDistribution.old.toString(), `${((cacheAgeDistribution.old / cacheCount) * 100).toFixed(1)}%`],
['Stale (> 30 days)', cacheAgeDistribution.stale.toString(), `${((cacheAgeDistribution.stale / cacheCount) * 100).toFixed(1)}%`]
]);
// Top devices by cache size
if (cachesByDevice.size > 0) {
const topDevices = Array.from(cachesByDevice.entries())
.sort((a, b) => b[1].size - a[1].size)
.slice(0, 15);
summary.addRaw(`\n### 📱 Top 15 Devices by Cache Size\n\n`)
.addTable([
[{data: 'Device', header: true}, {data: 'Caches', header: true}, {data: 'Size (GB)', header: true}, {data: 'Age Range (days)', header: true}],
...topDevices.map(([device, data]) => [
device,
data.count.toString(),
(data.size / 1024 / 1024 / 1024).toFixed(2),
`${data.newestCache}-${data.oldestCache}`
])
]);
// Identify inactive devices
const now = new Date();
const inactiveThreshold = 30; // days
const inactiveDevices = Array.from(cachesByDevice.entries())
.filter(([_, data]) => {
const daysSinceAccess = Math.floor((now - new Date(data.lastAccessed)) / (1000 * 60 * 60 * 24));
return daysSinceAccess > inactiveThreshold;
})
.sort((a, b) => b[1].size - a[1].size);
if (inactiveDevices.length > 0) {
summary.addRaw(`\n### 🚫 Inactive Devices (Not accessed in ${inactiveThreshold}+ days)\n\n`)
.addTable([
[{data: 'Device', header: true}, {data: 'Size (GB)', header: true}, {data: 'Days Since Access', header: true}],
...inactiveDevices.slice(0, 10).map(([device, data]) => [
device,
(data.size / 1024 / 1024 / 1024).toFixed(2),
Math.floor((now - new Date(data.lastAccessed)) / (1000 * 60 * 60 * 24)).toString()
])
]);
const inactiveSizeGB = inactiveDevices.reduce((sum, [_, data]) => sum + data.size, 0) / 1024 / 1024 / 1024;
summary.addRaw(`\n💡 **Potential savings:** ${inactiveSizeGB.toFixed(2)} GB by cleaning inactive devices\n`);
}
}
// Age information
if (oldestCache && newestCache) {
const oldestDate = new Date(oldestCache.created_at);
const newestDate = new Date(newestCache.created_at);
const daysDiff = Math.floor((newestDate - oldestDate) / (1000 * 60 * 60 * 24));
summary.addRaw(`\n### 📅 Cache Age Information\n\n`)
.addTable([
[{data: 'Metric', header: true}, {data: 'Value', header: true}],
['Oldest Cache', oldestDate.toISOString().split('T')[0]],
['Newest Cache', newestDate.toISOString().split('T')[0]],
['Age Range', `${daysDiff} days`]
]);
}
// Recommendations
summary.addRaw(`\n### 💡 Recommendations\n\n`);
if (parseFloat(usagePercent) > 90) {
summary.addRaw(`- 🔴 **URGENT:** Cache usage is critical (${usagePercent}%)\n`)
.addRaw(`- Run cleanup immediately with \`device_filter: ALL\`\n`)
.addRaw(`- Consider cleaning old device caches\n`)
.addRaw(`- Review ccache size limits in build workflows\n`);
} else if (parseFloat(usagePercent) > 75) {
summary.addRaw(`- 🟡 **WARNING:** Cache usage is high (${usagePercent}%)\n`)
.addRaw(`- Schedule cleanup soon\n`)
.addRaw(`- Consider targeting specific devices\n`);
} else {
summary.addRaw(`- 🟢 Cache usage is healthy (${usagePercent}%)\n`)
.addRaw(`- Regular weekly cleanup recommended\n`)
.addRaw(`- No immediate action required\n`);
}
// Stale cache recommendations
if (cacheAgeDistribution.stale > 0) {
const staleSizeEstimate = (cacheAgeDistribution.stale / cacheCount) * totalCacheSize;
const staleSizeGB = (staleSizeEstimate / 1024 / 1024 / 1024).toFixed(2);
summary.addRaw(`\n- 📦 **${cacheAgeDistribution.stale} stale caches** (>30 days old)\n`)
.addRaw(`- Estimated size: ~${staleSizeGB} GB\n`)
.addRaw(`- Run with \`cache_pattern: ccache_stale\` to clean\n`);
}
if (shouldCleanup && !forceCleanup) {
summary.addRaw(`\n⚠️ **Automatic cleanup will proceed** (usage > 75%)\n`);
} else if (forceCleanup) {
summary.addRaw(`\n⚡ **Force cleanup enabled** - proceeding regardless of usage\n`);
}
summary.write();
console.log(`\n✅ Analysis complete:`);
console.log(` - Total: ${totalGB} GB (${usagePercent}%)`);
console.log(` - Caches: ${cacheCount}`);
console.log(` - ccache: ${cachesByType.ccache.count} (${(cachesByType.ccache.size / 1024 / 1024 / 1024).toFixed(2)} GB)`);
console.log(` - Devices: ${cachesByDevice.size}`);
console.log(` - Cleanup needed: ${shouldCleanup}`);
cleanup-caches:
runs-on: ubuntu-latest
needs: analyze
if: |
always() &&
(inputs.cleanup_type == 'cache_only' || inputs.cleanup_type == 'full_cleanup') &&
(inputs.cleanup_type != 'analyze_only')
steps:
- name: 🗑️ Smart Cache Cleanup
uses: actions/github-script@v7
with:
script: |
const { owner, repo } = context.repo;
const deviceFilter = '${{ inputs.device_filter }}';
const cachePattern = '${{ inputs.cache_pattern }}';
const dryRun = '${{ inputs.dry_run }}' === 'true';
const cacheAgeDays = parseInt('${{ inputs.cache_age_days }}');
const shouldCleanup = '${{ needs.analyze.outputs.should_cleanup }}' === 'true';
const forceCleanup = '${{ inputs.force_cleanup }}' === 'true';
console.log(`🎯 Configuration:`);
console.log(` - Device Filter: ${deviceFilter}`);
console.log(` - Cache Pattern: ${cachePattern}`);
console.log(` - Age Threshold: ${cacheAgeDays} days`);
console.log(` - Dry Run: ${dryRun}`);
console.log(` - Should Cleanup: ${shouldCleanup}`);
console.log(` - Force Cleanup: ${forceCleanup}\n`);
// Check if we should proceed
if (!shouldCleanup && !forceCleanup && !dryRun) {
console.log('ℹ️ Cache usage is healthy, skipping cleanup');
console.log('💡 Use force_cleanup=true to cleanup anyway');
core.summary
.addHeading('ℹ️ Cleanup Skipped')
.addRaw(`Cache usage is healthy (${${{ needs.analyze.outputs.usage_percent }}}%)\n\n`)
.addRaw('No cleanup needed at this time.\n')
.write();
return;
}
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - cacheAgeDays);
// For stale ccache pattern, use 14 days
const staleCutoffDate = new Date();
staleCutoffDate.setDate(staleCutoffDate.getDate() - 14);
let totalDeleted = 0;
let totalSize = 0;
let page = 1;
const deletedCaches = [];
const skippedCaches = [];
// Track statistics by category
const deletionStats = {
ccache: { count: 0, size: 0 },
apt: { count: 0, size: 0 },
kernel: { count: 0, size: 0 },
other: { count: 0, size: 0 }
};
// Helper function to check if cache should be deleted
function shouldDeleteCache(cache) {
const cacheKey = cache.key;
const cacheDate = new Date(cache.created_at);
const ageDays = Math.floor((new Date() - cacheDate) / (1000 * 60 * 60 * 24));
// Device filter logic
const deviceMatch =
deviceFilter === 'ALL' ||
cacheKey.includes(deviceFilter) ||
cacheKey.includes(`-${deviceFilter}-`) ||
cacheKey.startsWith(`${deviceFilter}-`);
if (!deviceMatch) {
return { delete: false, reason: 'device_filter' };
}
// Age filter for 'old_only' pattern
if (cachePattern === 'old_only' && cacheDate >= cutoffDate) {
return { delete: false, reason: 'too_new' };
}
// Cache pattern logic
let patternMatch = false;
let category = 'other';
switch (cachePattern) {
case 'ccache_only':
patternMatch = cacheKey.startsWith('ccache-');
category = 'ccache';
break;
case 'ccache_stale':
patternMatch = cacheKey.startsWith('ccache-') && cacheDate < staleCutoffDate;
category = 'ccache';
break;
case 'apt_only':
patternMatch = cacheKey.includes('apt-cache') || cacheKey.includes('apt-');
category = 'apt';
break;
case 'kernel_only':
patternMatch = cacheKey.includes('kernel-') ||
cacheKey.includes('android') ||
cacheKey.startsWith('ccache-');
if (cacheKey.startsWith('ccache-')) category = 'ccache';
else category = 'kernel';
break;
case 'old_only':
patternMatch = cacheDate < cutoffDate;
if (cacheKey.startsWith('ccache-')) category = 'ccache';
else if (cacheKey.includes('apt')) category = 'apt';
else if (cacheKey.includes('kernel')) category = 'kernel';
break;
case 'all_caches':
default:
patternMatch = true;
if (cacheKey.startsWith('ccache-')) category = 'ccache';
else if (cacheKey.includes('apt')) category = 'apt';
else if (cacheKey.includes('kernel')) category = 'kernel';
}
return {
delete: patternMatch,
reason: patternMatch ? 'match' : 'pattern_mismatch',
category: category
};
}
// Fetch and process caches
console.log('🔍 Scanning caches...\n');
while (true) {
const res = await github.rest.actions.getActionsCacheList({
owner,
repo,
per_page: 100,
page: page
});
const caches = res.data.actions_caches;
if (!caches || caches.length === 0) break;
for (const cache of caches) {
const decision = shouldDeleteCache(cache);
const sizeMB = (cache.size_in_bytes / 1024 / 1024).toFixed(2);
const agedays = Math.floor((new Date() - new Date(cache.created_at)) / (1000 * 60 * 60 * 24));
if (decision.delete) {
deletedCaches.push({
key: cache.key,
size: sizeMB,
sizeBytes: cache.size_in_bytes,
age: agedays,
created: cache.created_at,
id: cache.id,
category: decision.category
});
if (dryRun) {
console.log(`🔍 Would delete: ${cache.key}`);
console.log(` Size: ${sizeMB} MB | Age: ${agedays} days | Type: ${decision.category}`);
} else {
console.log(`🗑️ Deleting: ${cache.key}`);
console.log(` Size: ${sizeMB} MB | Age: ${agedays} days | Type: ${decision.category}`);
try {
// Use deleteActionsCacheByKey which is safer for caches created across different refs
await github.rest.actions.deleteActionsCacheByKey({
owner,
repo,
key: cache.key,
ref: cache.ref || 'refs/heads/main'
});
totalDeleted++;
totalSize += cache.size_in_bytes;
// Update category stats
deletionStats[decision.category].count++;
deletionStats[decision.category].size += cache.size_in_bytes;
} catch (error) {
console.log(` ⚠️ Failed: ${error.message}`);
skippedCaches.push({
key: cache.key,
reason: error.message
});
}
}
} else if (decision.reason !== 'device_filter') {
// Only log non-device-filter skips in verbose mode
// console.log(`⏭️ Skipping: ${cache.key} (${decision.reason})`);
}
}
if (caches.length < 100) break;
page++;
}
const sizeMB = (totalSize / 1024 / 1024).toFixed(2);
const sizeGB = (totalSize / 1024 / 1024 / 1024).toFixed(2);
console.log(`\n✅ ${dryRun ? 'Would delete' : 'Deleted'} ${totalDeleted} caches`);
console.log(`📊 Space ${dryRun ? 'would be' : ''} freed: ${sizeMB} MB (${sizeGB} GB)`);
// Generate detailed summary
let summary = core.summary
.addHeading(`🧹 Cache Cleanup ${dryRun ? 'Preview' : 'Summary'}`)
.addTable([
[{data: 'Metric', header: true}, {data: 'Value', header: true}],
['Caches ' + (dryRun ? 'to Delete' : 'Deleted'), totalDeleted.toString()],
['Space ' + (dryRun ? 'to Free' : 'Freed'), `${sizeMB} MB (${sizeGB} GB)`],
['Device Filter', deviceFilter],
['Cache Pattern', cachePattern],
['Age Threshold', `${cacheAgeDays} days`]
]);
// Deletion breakdown by type
if (totalDeleted > 0 || dryRun) {
summary.addHeading('📊 Deletion Breakdown by Type', 3)
.addTable([
[{data: 'Type', header: true}, {data: 'Count', header: true}, {data: 'Size (GB)', header: true}, {data: 'Percentage', header: true}],
['ccache',
deletionStats.ccache.count.toString(),
(deletionStats.ccache.size / 1024 / 1024 / 1024).toFixed(2),
totalSize > 0 ? `${((deletionStats.ccache.size / totalSize) * 100).toFixed(1)}%` : '0%'
],
['Kernel-related',
deletionStats.kernel.count.toString(),
(deletionStats.kernel.size / 1024 / 1024 / 1024).toFixed(2),
totalSize > 0 ? `${((deletionStats.kernel.size / totalSize) * 100).toFixed(1)}%` : '0%'
],
['APT Packages',
deletionStats.apt.count.toString(),
(deletionStats.apt.size / 1024 / 1024 / 1024).toFixed(2),
totalSize > 0 ? `${((deletionStats.apt.size / totalSize) * 100).toFixed(1)}%` : '0%'
],
['Other',
deletionStats.other.count.toString(),
(deletionStats.other.size / 1024 / 1024 / 1024).toFixed(2),
totalSize > 0 ? `${((deletionStats.other.size / totalSize) * 100).toFixed(1)}%` : '0%'
]
]);
}
// Add top 20 largest caches
if (deletedCaches.length > 0) {
const topCaches = deletedCaches
.sort((a, b) => parseFloat(b.size) - parseFloat(a.size))
.slice(0, 20);
summary.addHeading('📦 Top 20 Largest Caches ' + (dryRun ? 'to Delete' : 'Deleted'), 3)
.addTable([
[{data: 'Cache Key', header: true}, {data: 'Size (MB)', header: true}, {data: 'Age (days)', header: true}, {data: 'Type', header: true}],
...topCaches.map(c => [c.key, c.size, c.age.toString(), c.category])
]);
}
// Add oldest caches
if (deletedCaches.length > 0) {
const oldestCaches = deletedCaches
.sort((a, b) => b.age - a.age)
.slice(0, 10);
summary.addHeading('📅 Top 10 Oldest Caches ' + (dryRun ? 'to Delete' : 'Deleted'), 3)
.addTable([
[{data: 'Cache Key', header: true}, {data: 'Age (days)', header: true}, {data: 'Size (MB)', header: true}, {data: 'Type', header: true}],
...oldestCaches.map(c => [c.key, c.age.toString(), c.size, c.category])
]);
}
// Device breakdown for ccache deletions
if (deletionStats.ccache.count > 0) {
const deviceDeletions = new Map();
for (const cache of deletedCaches) {
if (cache.category === 'ccache') {
const match = cache.key.match(/ccache-([^-]+)-/);
if (match) {
const device = match[1];
if (!deviceDeletions.has(device)) {
deviceDeletions.set(device, { count: 0, size: 0 });
}
const data = deviceDeletions.get(device);
data.count++;
data.size += cache.sizeBytes;
}
}
}
if (deviceDeletions.size > 0) {
const topDevices = Array.from(deviceDeletions.entries())
.sort((a, b) => b[1].size - a[1].size)
.slice(0, 10);
summary.addHeading('📱 Top 10 Devices by Deleted ccache', 3)
.addTable([
[{data: 'Device', header: true}, {data: 'Caches', header: true}, {data: 'Size (GB)', header: true}],
...topDevices.map(([device, data]) => [
device,
data.count.toString(),
(data.size / 1024 / 1024 / 1024).toFixed(2)
])
]);
}
}
// Add failures if any
if (skippedCaches.length > 0) {
summary.addHeading('⚠️ Failed Deletions', 3)
.addTable([
[{data: 'Cache Key', header: true}, {data: 'Reason', header: true}],
...skippedCaches.map(c => [c.key, c.reason])
]);
}
summary.write();
cleanup-runs:
runs-on: ubuntu-latest
needs: analyze
if: |
always() &&
(inputs.cleanup_type == 'runs_only' || inputs.cleanup_type == 'full_cleanup') &&
(inputs.cleanup_type != 'analyze_only')
steps:
- name: 🗑️ Clean old workflow runs
uses: actions/github-script@v7
with:
script: |
const { owner, repo } = context.repo;
const keepRecent = parseInt('${{ inputs.keep_recent_runs }}');
const daysToKeep = parseInt('${{ inputs.days_to_keep }}');
const dryRun = '${{ inputs.dry_run }}' === 'true';
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
console.log(`📅 Configuration:`);
console.log(` - Keeping runs from: ${cutoffDate.toISOString()}`);
console.log(` - Keeping ${keepRecent} most recent successful runs per workflow`);
console.log(` - Dry Run: ${dryRun}\n`);
const workflows = await github.rest.actions.listRepoWorkflows({
owner,
repo
});
let totalDeleted = 0;
let totalFailed = 0;
const workflowStats = [];
for (const workflow of workflows.data.workflows) {
console.log(`\n📋 Processing: ${workflow.name}`);
let page = 1;
let successfulRuns = [];
let deletedInWorkflow = 0;
let failedInWorkflow = 0;
const runsByStatus = {
success: 0,
failure: 0,
cancelled: 0,
skipped: 0,
other: 0
};
while (true) {
const runs = await github.rest.actions.listWorkflowRuns({
owner,
repo,
workflow_id: workflow.id,
per_page: 100,
page: page
});
if (runs.data.workflow_runs.length === 0) break;
for (const run of runs.data.workflow_runs) {
const runDate = new Date(run.created_at);
const ageDays = Math.floor((new Date() - runDate) / (1000 * 60 * 60 * 24));
// Count by status
runsByStatus[run.conclusion || 'other']++;
// Track successful runs
if (run.conclusion === 'success') {
successfulRuns.push(run);
}
// Determine if should delete
const isOld = runDate < cutoffDate;
const isFailed = run.conclusion === 'failure';
const isCancelled = run.conclusion === 'cancelled';
const isSkipped = run.conclusion === 'skipped';
const tooManySuccessful = run.conclusion === 'success' &&
successfulRuns.length > keepRecent;
const shouldDelete =
(isFailed && isOld) ||
(isCancelled && isOld) ||
(isSkipped && isOld) ||
(tooManySuccessful && isOld);
if (shouldDelete) {
if (dryRun) {
console.log(`🔍 Would delete: #${run.run_number} (${run.conclusion}, ${ageDays}d old)`);
} else {
console.log(`🗑️ Deleting: #${run.run_number} (${run.conclusion}, ${ageDays}d old)`);
try {
await github.rest.actions.deleteWorkflowRun({
owner,
repo,
run_id: run.id
});
deletedInWorkflow++;
totalDeleted++;
} catch (error) {
console.log(` ⚠️ Failed: ${error.message}`);
failedInWorkflow++;
totalFailed++;
}
}
}
}
if (runs.data.workflow_runs.length < 100) break;
page++;
}
if (deletedInWorkflow > 0 || Object.values(runsByStatus).some(v => v > 0)) {
workflowStats.push({
name: workflow.name,
deleted: deletedInWorkflow,
failed: failedInWorkflow,
stats: runsByStatus
});
}
}
console.log(`\n✅ Total runs ${dryRun ? 'to delete' : 'deleted'}: ${totalDeleted}`);
if (totalFailed > 0) {
console.log(`⚠️ Failed deletions: ${totalFailed}`);
}
// Generate summary
let summary = core.summary
.addHeading(`🧹 Workflow Runs ${dryRun ? 'Preview' : 'Summary'}`)
.addTable([
[{data: 'Metric', header: true}, {data: 'Value', header: true}],
['Runs ' + (dryRun ? 'to Delete' : 'Deleted'), totalDeleted.toString()],
['Failed Deletions', totalFailed.toString()],
['Kept Recent Successful', keepRecent.toString()],
['Days Kept', daysToKeep.toString()]
]);
if (workflowStats.length > 0) {
summary.addHeading('📊 Per-Workflow Breakdown', 3)
.addTable([
[
{data: 'Workflow', header: true},
{data: 'Deleted', header: true},
{data: 'Success', header: true},
{data: 'Failure', header: true},
{data: 'Cancelled', header: true}
],
...workflowStats.map(w => [
w.name,
w.deleted.toString(),
w.stats.success.toString(),
w.stats.failure.toString(),
w.stats.cancelled.toString()
])
]);
}
summary.write();
final-report:
runs-on: ubuntu-latest
needs: [analyze, cleanup-caches, cleanup-runs]
if: always()
steps:
- name: 📊 Final Repository Health Report
uses: actions/github-script@v7
with:
script: |
const { owner, repo } = context.repo;
const dryRun = '${{ inputs.dry_run }}' === 'true';
console.log('📊 Generating final health report...\n');
// Get current cache usage (after cleanup)
let page = 1;
let totalCacheSize = 0;
let cachesByType = {
ccache: 0,
apt: 0,
kernel: 0,
other: 0
};
let cacheCount = 0;
const buildFrequency = new Map();
const recentCutoff = new Date();
recentCutoff.setDate(recentCutoff.getDate() - 30);
while (true) {
const res = await github.rest.actions.getActionsCacheList({
owner,
repo,
per_page: 100,
page: page
});
const caches = res.data.actions_caches;
if (!caches || caches.length === 0) break;
for (const cache of caches) {
totalCacheSize += cache.size_in_bytes;
cacheCount++;
if (cache.key.startsWith('ccache-')) {
cachesByType.ccache += cache.size_in_bytes;
// Track build frequency
const match = cache.key.match(/ccache-([^-]+)-/);
if (match && new Date(cache.last_accessed_at) > recentCutoff) {
const device = match[1];
buildFrequency.set(device, (buildFrequency.get(device) || 0) + 1);
}
} else if (cache.key.includes('apt')) {
cachesByType.apt += cache.size_in_bytes;
} else if (cache.key.includes('kernel') || cache.key.includes('android')) {
cachesByType.kernel += cache.size_in_bytes;
} else {
cachesByType.other += cache.size_in_bytes;
}
}
if (caches.length < 100) break;
page++;