forked from mona-actions/gh-repo-stats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgh-repo-stats
executable file
·1652 lines (1492 loc) · 53.3 KB
/
gh-repo-stats
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
#!/usr/bin/env bash
# shellcheck disable=SC2004,SC2322,SC2323
################################################################################
################################################################################
####### Get repo statistics from Org(s) ########################################
################################################################################
################################################################################
# LEGEND:
# This script will use the github API to list all repos
# and sizes for an organization(s)
# It will return an output.csv or table with the following statistics:
#
# Organization Name
# Repository Name
# If empty
# Last push
# Last commit
# isFork
# isArchived
# Size(mb)
# Total record count
# Collaborator count
# Protected branches
# PR reviews
# Milestones
# Issues
# Pull requests
# PR review comments
# Commit comments
# Issue comments
# Issue events
# Releases
# Projects
# Migration URL
# Created
#
# This will work for users on GitHub.com that are trying to figure out
# how many repos they own, and how large they are.
#
# This can be used by services to help distinguish what repos
# could be an issue, as well as help prepare for a migration
#
# PREREQS:
# You need to have the following to run this script successfully:
# - GitHub Personal Access Token with a scope of "repos" and access to the organization(s) that will be analyzed
# - Either the name of the organization to be analyzed, or a list of organizations with
# the format provided by the Organization csv report found at [YOUR_GHE_DOMAIN]/stafftools/reports
# - jq installed on the machine running the query
#
# NOTES:
# - Repositories under 1 mb will be shown as 0mb
#
###########
# GLOBALS #
###########
SLEEP='300' # Number of seconds to sleep if out of API calls
SLEEP_RETRY_COUNT='15' # Number of times to try to sleep before giving up
SLEEP_COUNTER='0' # Counter of how many times we have gone to sleep
EXISTING_FILE='0' # Check if a file already exists
OUTPUT="${OUTPUT_PARAM:-CSV}" # Output type CSV or Table
REPO_LIST_ARRAY=() # Array of repo names to be analyzed
GITHUB_TOKEN_TYPE=${GITHUB_TOKEN_TYPE:-user} # Whether 'user' or 'app' PAT
VERSION="cloud"
VERSION_MAJOR="0"
VERSION_MINOR="0"
REPO_PAGE_SIZE=10
EXTRA_PAGE_SIZE=50
################################################################################
#### Function PrintUsage #######################################################
PrintUsage()
{
cat <<EOM
Usage: gh repo-stats [options]
Options:
-d, --debug : Enable Debug logging
-e, --extra-page-size : Set the pagination size for subsequent, paginated GraphQL queries; reduce if timeout occurs
Default: $EXTRA_PAGE_SIZE
-h, --help : Show script help
-H, --hostname : The GitHub hostname for the request
Default: github.com
-i, --input : Set path to a file with a list of organizations to scan, one per line, newline delimited
-o, --org : Name of the GitHub Organization to be analyzed
-O, --output : Format of output, can either be "CSV" or "Table"
Default: $OUTPUT
-p, --repo-page-size : Set the pagination size for the initial repository GraphQL query; reduce if timeout occurs
Default: $REPO_PAGE_SIZE
If a timeout occurs, reduce this value
-r, --analyze-repo-conflicts : Checks the Repo Name against repos in other organizations and generates a list
of potential naming conflicts if those orgs are to be merged during migration
-rl, --repo-list : Path to a file with a list of repositories to scan, one per line, newline delimited
-t, --token : Set Personal Access Token with repo scope
Default: token for hostname via gh auth token
-T, --analyze-team-conflicts : Gathers each org's teams and checks against other orgs to generate a list of
potential naming conflicts if those orgs are to be merged during migration
-y, --token-type : Type of Personal Access, can either be "user" or "app"
Default: $GITHUB_TOKEN_TYPE
Description:
Scans an organization or list of organizations for all repositories and gathers size statistics for each repository
Example:
gh repo-stats -o my-org-name
gh repo-stats -o my-org-name -H github.example.com
EOM
exit 0
}
####################################
# Read in the parameters if passed #
####################################
PARAMS=""
while (( "$#" )); do
case "$1" in
-h|--help)
PrintUsage;
;;
-H|--hostname)
export GH_HOST=$2
shift 2
;;
-d|--debug)
DEBUG=true
export GH_DEBUG=api
shift
;;
-t|--token)
export GH_TOKEN=$2
shift 2
;;
-y|--token-type)
GITHUB_TOKEN_TYPE=$2
shift 2
;;
-i|--input)
INPUT_FILE_NAME=$2
shift 2
;;
-r|--analyze-repo-conflicts)
ANALYZE_CONFLICTS=1
shift
;;
-T|--analyze-team-conflicts)
ANALYZE_TEAMS=1
shift
;;
-p|--repo-page-size)
REPO_PAGE_SIZE=$2
shift 2
;;
-e|--extra-page-size)
EXTRA_PAGE_SIZE=$2
shift 2
;;
-O|--output)
OUTPUT_PARAM=$2
shift 2
;;
-o|--org)
ORG_NAME=$2
shift 2
;;
-rl|--repo-list)
REPO_LIST_FILE=$2
shift 2
;;
--) # end argument parsing
shift
break
;;
-*) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
##################################################
# Set positional arguments in their proper place #
##################################################
eval set -- "$PARAMS"
################################################################################
############################ FUNCTIONS #########################################
################################################################################
################################################################################
################################################################################
#### Function DebugJQ ##########################################################
DebugJQ() {
# If Debug is on, print it out...
if [[ ${DEBUG} == true ]]; then
echo "$1" | jq '.'
fi
}
################################################################################
#### Function Debug ############################################################
Debug() {
# If Debug is on, print it out...
if [[ ${DEBUG} == true ]]; then
echo "$1"
fi
}
################################################################################
#### Function Header ###########################################################
Header() {
echo ""
echo "######################################################"
echo "######################################################"
echo "############# GitHub repo list and sizer #############"
echo "######################################################"
echo "######################################################"
echo ""
################################################################
# Validate we can hit the endpoint by getting the current user #
################################################################
if [[ ${GITHUB_TOKEN_TYPE} == "user" ]]; then
USER_DATA=$(gh api user)
ERROR_CODE=$?
#######################
# Validate the return #
#######################
if [ "${ERROR_CODE}" -ne 0 ]; then
echo "Error getting user"
echo "${USER_DATA}"
else
USER_LOGIN=$(echo "${USER_DATA}" | jq -r '.login')
# Check for success
if [[ -z ${USER_LOGIN} ]]; then
# Got bad return
echo "ERROR! Failed to validate GHE instance"
echo "Received error: ${USER_DATA}"
exit 1
else
Debug "Successfully validated access to GHE Instance..."
fi
fi
fi
#####################
# Check GHE version #
#####################
if [[ "$(isCloud)" -eq 0 ]]; then
META_DATA=$(gh api meta)
ERROR_CODE=$?
#######################
# Validate the return #
#######################
if [ "${ERROR_CODE}" -ne 0 ]; then
echo "Error getting GHE version"
echo "${META_DATA}"
else
VERSION=$(echo "${META_DATA}" | jq -r '.installed_version')
# Get major/minor versions
VERSION_MAJOR=$(echo "${VERSION}" | cut -d "." -f 1);
VERSION_MINOR=$(echo "${VERSION}" | cut -d "." -f 2);
# Validate supported versions
if [[ "$(isCompatibleGHESVersion)" -eq "0" ]]; then
echo "GitHub Enterprise Server v${VERSION} is not supported."
exit 1;
else
echo "GitHub Enterprise Server v${VERSION}"
fi
fi
fi
Debug "Version: ${VERSION}"
###########################
# Check org or input file #
###########################
if [[ -z ${ORG_NAME} ]] && [[ -z ${INPUT_FILE_NAME} ]]; then
###########################################
# Get the name of the GitHub Organization #
###########################################
echo ""
echo "------------------------------------------------------"
echo "Please enter name of the GitHub Organization you wish to"
echo "gather information from, followed by [ENTER]:"
########################
# Read input from user #
########################
read -r ORG_NAME
# Clean any whitespace that may be enetered
ORG_NAME_NO_WHITESPACE="$(echo -e "${ORG_NAME}" | tr -d '[:space:]')"
ORG_NAME="${ORG_NAME_NO_WHITESPACE}"
#########################
# Validate the Org Name #
#########################
if [ ${#ORG_NAME} -le 1 ]; then
echo "Error! You must give a valid Organization name!"
exit 1
fi
fi
###########################################
# Make lower case to prevent weird issues #
###########################################
ORG_NAME=$(echo "${ORG_NAME}" | tr '[:upper:]' '[:lower:]')
}
################################################################################
#### Function Footer ###########################################################
Footer() {
#######################################
# Basic footer information and totals #
#######################################
echo ""
echo "######################################################"
echo "The script has completed"
echo ""
if [[ ${OUTPUT} != "CSV" ]]; then
column -t -s',' "${OUTPUT_FILE_NAME}"
rm -f "${OUTPUT_FILE_NAME}"
else
echo "Results file:[${OUTPUT_FILE_NAME}]"
fi
echo "######################################################"
echo ""
}
################################################################################
#### Function GenerateFiles ####################################################
GenerateFiles() {
##########################
# Get current date stamp #
##########################
# Get datestring YYYYMMDDHHMM
DATE=$(date +%Y%m%d%H%M)
####################
# Create File Name #
####################
# Example: MyOrg-all_repos-201901041059.csv
OUTPUT_FILE_NAME="$ORG_NAME-all_repos-$DATE.csv"
######################################################
# Need to see if there is a file that already exists #
######################################################
EXISTING_FILE_CMD=$(find . -name "$ORG_NAME-all_repos-*" |grep . 2>&1)
#######################
# Load the error code #
#######################
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ "${ERROR_CODE}" -eq 0 ]; then
# There is already file
# Going to use and append
OUTPUT_FILE_NAME="${EXISTING_FILE_CMD:2}"
EXISTING_FILE=1
fi
if [[ ${ANALYZE_CONFLICTS} -eq 1 ]]; then
REPO_CONFLICTS_OUTPUT_FILE="$ORG_NAME-repo-conflicts-${DATE}.csv"
######################################################
# Need to see if there is a file that already exists #
######################################################
EXISTING_FILE_CMD=$(find . -name "$ORG_NAME-repo-conflicts-*" |grep . 2>&1)
#######################
# Load the error code #
#######################
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ "${ERROR_CODE}" -eq 0 ]; then
# There is already file
# Going to use and append
REPO_CONFLICTS_OUTPUT_FILE="${EXISTING_FILE_CMD:2}"
fi
if ! echo "conflict qty, repo name, org names" > "${REPO_CONFLICTS_OUTPUT_FILE}"
then
echo "Failed to generate result file: ${REPO_CONFLICTS_OUTPUT_FILE}!"
exit 1
fi
fi
if [[ ${ANALYZE_TEAMS} -eq 1 ]]; then
TEAM_CONFLICTS_OUTPUT_FILE="$ORG_NAME-team-conflicts-${DATE}.csv"
######################################################
# Need to see if there is a file that already exists #
######################################################
EXISTING_FILE_CMD=$(find . -name "$ORG_NAME-team-conflicts-*" |grep . 2>&1)
#######################
# Load the error code #
#######################
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ "${ERROR_CODE}" -eq 0 ]; then
# There is already file
# Going to use and append
TEAM_CONFLICTS_OUTPUT_FILE="${EXISTING_FILE_CMD:2}"
fi
if ! echo "conflict qty, team name, org names" > "${TEAM_CONFLICTS_OUTPUT_FILE}"
then
echo "Failed to generate result file: ${TEAM_CONFLICTS_OUTPUT_FILE}!"
exit 1
fi
fi
#########################################
# Only add header if were not appending #
#########################################
if [ "${EXISTING_FILE}" -ne 1 ]; then
#############################
# Create Header in the file #
#############################
echo "Creating file header..."
IS_EMPTY_HEADER="Is_Empty,";
if [[ "$(isCompatibleGHESVersion)" -eq "2" ]]; then
IS_EMPTY_HEADER="";
fi
echo "Org_Name,Repo_Name,${IS_EMPTY_HEADER}Last_Push,Last_Update,isFork,isArchived,Repo_Size(mb),Record_Count,Collaborator_Count,Protected_Branch_Count,PR_Review_Count,Milestone_Count,Issue_Count,PR_Count,PR_Review_Comment_Count,Commit_Comment_Count,Issue_Comment_Count,Issue_Event_Count,Release_Count,Project_Count,Branch_Count,Tag_Count,Discussion_Count,Has_Wiki,Full_URL,Migration_Issue,Created" >>"${OUTPUT_FILE_NAME}" 2>&1
#######################
# Load the error code #
#######################
# shellcheck disable=SC2320
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ ${ERROR_CODE} -ne 0 ]; then
echo "ERROR! Failed to write headers to file:[${OUTPUT_FILE_NAME}]!"
exit 1
fi
fi
}
################################################################################
#### Function CheckAdminRights #################################################
CheckAdminRights() {
if [[ ${GITHUB_TOKEN_TYPE} == "app" ]]; then
echo "Skip checking user PAT admin rights for GitHub App token"
return 0
fi
################
# Pull in vars #
################
ORG_NAME="$1"
##################
# Get membership #
##################
MEMBERSHIP_DATA=$(gh api "orgs/${ORG_NAME}/memberships/${USER_LOGIN}")
ERROR_CODE=$?
if [ "${ERROR_CODE}" -ne 0 ]; then
echo "Error getting Membership for Org: ${ORG_NAME}"
echo "${MEMBERSHIP_DATA}"
exit 1
else
MEMBERSHIP_STATUS=$(echo "${MEMBERSHIP_DATA}" | jq -r '.role')
MEMBERSHIP_STATUS="admin"
if [[ ${MEMBERSHIP_STATUS} = "admin" ]]; then
Debug "You are an owner. Getting Repo Stats"
else
echo "You are not an owner of org: ${ORG_NAME}"
echo "cannot grab all needed information without access!"
exit 1
fi
fi
}
################################################################################
#### Function isGHEC ###########################################################
isCloud() {
if [[ "$OSTYPE" == "msys" ]]; then
# If the operating system is Windows escape leading slash
ROOT_DATA=$(gh api //)
else
# If the operating system is Unix-like (e.g., Linux, macOS)
ROOT_DATA=$(gh api /)
fi
USER_URL=$(echo -n "${ROOT_DATA}" | jq -r '.current_user_url')
if [[ "${USER_URL}" != "https://api.github.com/user" ]]; then
echo 0;
else
echo 1;
fi
}
################################################################################
#### Function isIncompatibleGHESVersion ########################################
isCompatibleGHESVersion() {
if [[ "$(isCloud)" -eq 0 ]] && [[ "${VERSION_MAJOR}" -lt 3 ]]; then
if [[ "${VERSION_MAJOR}" -eq 2 ]] && [[ "${VERSION_MINOR}" -ge 20 ]]; then
if [[ "${VERSION_MINOR}" -gt 21 ]]; then
# GHES >= v2.22 (supported)
echo 1;
else
# GHES v2.20 & v2.21 (no isEmpty supported)
echo 2;
fi
else
# GHES < v2.20 (not supported)
echo 0;
fi
else
# GHEC or GHES >= v3 (supported)
echo 1;
fi
}
################################################################################
#### Function GetOrgsFromFile ##################################################
GetOrgsFromFile() {
# shellcheck disable=SC2034
# Unused variables left for readability
while IFS=, read -r login
do
ORG_NAME="${login}"
echo "Checking access to org: ${ORG_NAME}"
######################
# Check Admin Rights #
######################
CheckAdminRights "${ORG_NAME}"
#############################################
# Check the API limit remaining for GraphQL #
#############################################
CheckAPILimit
######################
# Get repos from Org #
######################
GetRepos
######################
# Get the teams info #
######################
if [[ ${ANALYZE_TEAMS} -eq 1 ]]; then
GetTeams
fi
done < "${INPUT_FILE_NAME}"
}
################################################################################
#### Function CheckAPILimit ####################################################
CheckAPILimit() {
##############################################################
# Check what is remaining, and if 0, we need to sleep it off #
##############################################################
API_REMAINING_REQUEST=$(gh api rate_limit)
API_REMAINING_MESSAGE=$(echo "${API_REMAINING_REQUEST}" | jq -r '.message' 2>&1)
if [[ "${API_REMAINING_MESSAGE}" != "Rate limiting is not enabled." ]]; then
GRAPHQL_REMAINING=$(echo "${API_REMAINING_REQUEST}" | jq -r '.resources.graphql.remaining' 2>&1);
CORE_REMAINING=$(echo "${API_REMAINING_REQUEST}" | jq -r '.resources.core.remaining' 2>&1);
else
GRAPHQL_REMAINING=9999999999
CORE_REMAINING=9999999999
fi
#######################
# Load the error code #
#######################
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ "${ERROR_CODE}" -ne 0 ]; then
echo "ERROR! Failed to get valid response back from GitHub API!"
echo "ERROR:[${GRAPHQL_REMAINING}]"
exit 1
fi
##########################################
# Check to see if we have API calls left #
##########################################
if [[ "${GRAPHQL_REMAINING}" -eq 0 ]]; then
# Increment the sleep counter
((SLEEP_COUNTER++))
# Warn the user
echo "WARN! We have run out of GrahpQL calls and need to sleep!"
echo "Sleeping for ${SLEEP} seconds before next check"
# Check if we have slept enough
if [ "${SLEEP_COUNTER}" -gt "${SLEEP_RETRY_COUNT}" ]; then
# We have been doing this too long
echo "ERROR! We have tried to wait for:[$SLEEP_RETRY_COUNT] attempts!"
echo "ERROR! We only sleep for:[${SLEEP_COUNTER}] attempts!"
echo "Bailing out!"
exit 1
else
# Get some sleep...
sleep "${SLEEP}"
fi
elif [[ "${GRAPHQL_REMAINING}" == 9999999999 ]]; then
echo "API rate limiting is not enabled."
else
printf "Rate limits remaining: %'d GraphQL points %'d REST calls\n" "${GRAPHQL_REMAINING}" "${CORE_REMAINING}"
fi
}
################################################################################
#### Function GetRepos #########################################################
GetRepos() {
# When the version is 2.21, we need to remove the isEmpty flag
IS_EMPTY_FLAG="isEmpty";
if [[ "$(isCompatibleGHESVersion)" -eq "2" ]]; then
IS_EMPTY_FLAG="";
fi
QUERY="query(\$login: String!, \$pageSize: Int!, \$endCursor: String) {
organization(login: \$login) {
repositories(first: \$pageSize, after: \$endCursor, orderBy: {field: NAME, direction: ASC}) {
totalDiskUsage
pageInfo {
endCursor
hasNextPage
}
nodes {
branches: refs(refPrefix:\"refs/heads/\") {
totalCount
}
branchProtectionRules {
totalCount
}
commitComments {
totalCount
}
collaborators {
totalCount
}
createdAt
diskUsage
discussions {
totalCount
}
hasWikiEnabled
${IS_EMPTY_FLAG}
isFork
isArchived
issues(first: \$pageSize) {
totalCount
pageInfo {
endCursor
hasNextPage
}
nodes {
timeline {
totalCount
}
comments {
totalCount
}
}
}
milestones {
totalCount
}
name
owner {
login
}
projects {
totalCount
}
pullRequests(first: \$pageSize) {
totalCount
pageInfo {
endCursor
hasNextPage
}
nodes {
comments {
totalCount
}
commits {
totalCount
}
number
reviews(first: \$pageSize) {
totalCount
pageInfo {
endCursor
hasNextPage
}
nodes {
comments {
totalCount
}
}
}
timeline {
totalCount
}
}
}
pushedAt
releases {
totalCount
}
tags: refs(refPrefix: \"refs/tags/\") {
totalCount
}
updatedAt
url
}
}
}
}"
Debug "Getting repos"
if [[ -n "$REPO_NEXT_PAGE" ]]; then
DATA_BLOCK=$(gh api graphql -f query="$QUERY" -F login="$ORG_NAME" -F pageSize="$REPO_PAGE_SIZE" -F endCursor="$REPO_NEXT_PAGE")
else
DATA_BLOCK=$(gh api graphql -f query="$QUERY" -F login="$ORG_NAME" -F pageSize="$REPO_PAGE_SIZE")
fi
ERROR_CODE=$?
if [ "${ERROR_CODE}" -ne 0 ]; then
# We are using to big of a page size, so we need to do smaller pagination
echo "Error getting Repos for Org: ${ORG_NAME}"
echo "--repo-page-size might need to be set to a lower value"
else
ERROR_MESSAGE=$(echo "${DATA_BLOCK}" | jq -r '.errors[]?')
if [[ -n "${ERROR_MESSAGE}" ]]; then
echo "ERROR --- Errors occurred while retrieving repos for org: ${ORG_NAME}"
echo "${ERROR_MESSAGE}" | jq '.'
echo "REPOS:"
echo "${DATA_BLOCK}" | jq '.data.organization.repositories.nodes[].name'
fi
##########################
# Get the Next Page Flag #
##########################
HAS_NEXT_PAGE=$(echo "${DATA_BLOCK}" | jq -r '.data.organization.repositories.pageInfo.hasNextPage')
##############################
# Get the Current End Cursor #
##############################
REPO_NEXT_PAGE=$(echo "${DATA_BLOCK}" | jq -r '.data.organization.repositories.pageInfo.endCursor')
#############################################
# Parse all the repo data out of data block #
#############################################
ParseRepos "${DATA_BLOCK}"
########################################
# See if we need to loop for more data #
########################################
if [ "${HAS_NEXT_PAGE}" == "false" ]; then
# We have all the data, we can move on
echo "Gathered all repositories for org: ${ORG_NAME}"
REPO_NEXT_PAGE=""
elif [ "${HAS_NEXT_PAGE}" == "true" ]; then
# We need to loop through GitHub to get all repos
Debug "More pages of repos, gathering next batch"
#############################################
# Check the API limit remaining for GraphQL #
#############################################
CheckAPILimit
#######################################
# Call GetRepos again with new cursor #
#######################################
GetRepos
else
# Failing to get this value means we didnt get a good response back from GitHub
# And it could be bad input from user, not enough access, or a bad token
# Fail out and have user validate the info
echo ""
echo "######################################################"
echo "ERROR! Failed response back from GitHub on org: ${ORG_NAME}!"
echo "Please validate your PAT, Organization, and access levels!"
echo "######################################################"
fi
fi
}
################################################################################
#### Function ParseRepos #######################################################
ParseRepos() {
##########################
# Pull in the data block #
##########################
PARSE_DATA=$1
REPOS=$(echo "${PARSE_DATA}" | jq -r '.data.organization.repositories.nodes')
for REPO_DATA in $(echo -n "${REPOS}" | jq -r '.[] | @base64'); do
_jq() {
echo -n "${REPO_DATA}" | base64 --decode | jq -r "${1}"
}
OWNER=$(_jq '.owner.login' | tr '[:upper:]' '[:lower:]')
REPO_NAME=$(_jq '.name' | tr '[:upper:]' '[:lower:]')
#########################################################
# Need to see if the user gave a repo list to filter on #
#########################################################
if [[ -n "${REPO_LIST_FILE}" ]]; then
# convert REPO_NAME to lowercase
CHECK_REPO_NAME=$(echo "${REPO_NAME}" | tr '[:upper:]' '[:lower:]')
# Check if the repo name is in the list
for REPO in "${REPO_LIST_ARRAY[@]}"; do
if [[ "${REPO}" == "${CHECK_REPO_NAME}" ]]; then
# Found a match, we can continue
ParseRepoData "${REPO_DATA}"
fi
done
else
#################################################################
# Need to check if this repo has already been parsed in the doc #
#################################################################
grep "${OWNER},${REPO_NAME}," "${OUTPUT_FILE_NAME}" >/dev/null 2>&1
#######################
# Load the error code #
#######################
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ ${ERROR_CODE} -eq 0 ]; then
# Found this in the csv already
echo "Repo:[${OWNER}/${REPO_NAME}] has previously been analyzed, moving on..."
elif [ ${ERROR_CODE} -ne 0 ] && [[ -z "${REPO_LIST_FILE}" ]]; then
echo "Analyzing Repo: ${REPO_NAME}"
ParseRepoData "${REPO_DATA}"
fi
fi
done
}
################################################################################
#### Function ParseRepoData ####################################################
ParseRepoData() {
# Pull in the repos data block
REPO_DATA=$1
# Convert the format to JSON
_jq() {
echo -n "${REPO_DATA}" | base64 --decode | jq -r "${1}"
}
OWNER=$(_jq '.owner.login' | tr '[:upper:]' '[:lower:]')
REPO_NAME=$(_jq '.name' | tr '[:upper:]' '[:lower:]')
REPO_SIZE_KB=$(_jq '.diskUsage')
REPO_SIZE=$(ConvertKBToMB "${REPO_SIZE_KB}")
# Look for isEmpty property only if it's supported
IS_EMPTY="";
if [[ "$(isCompatibleGHESVersion)" -eq "1" ]]; then
IS_EMPTY="$(_jq '.isEmpty'),"
fi
CREATED_AT=$(_jq '.createdAt')
PUSHED_AT=$(_jq '.pushedAt')
UPDATED_AT=$(_jq '.updatedAt')
HAS_WIKI=$(_jq '.hasWikiEnabled')
IS_FORK=$(_jq '.isFork')
IS_ARCHIVED=$(_jq '.isArchived')
URL=$(_jq '.url')
MILESTONE_CT=$(_jq '.milestones.totalCount')
COLLABORATOR_CT=$(_jq '.collaborators.totalCount')
PR_CT=$(_jq '.pullRequests.totalCount')
ISSUE_CT=$(_jq '.issues.totalCount')
RELEASE_CT=$(_jq '.releases.totalCount')
COMMIT_COMMENT_CT=$(_jq '.commitComments.totalCount')
PROJECT_CT=$(_jq '.projects.totalCount')
BRANCH_CT=$(_jq '.branches.totalCount')
TAG_CT=$(_jq '.tags.totalCount')
DISCUSSION_CT=$(_jq '.discussions.totalCount')
if [[ "${VERSION}" == "cloud" ]]; then
PROTECTED_BRANCH_CT=$(_jq '.branchProtectionRules.totalCount')
else
PROTECTED_BRANCH_CT=$(_jq '.protectedBranches.totalCount')
fi
ISSUE_EVENT_CT=0
ISSUE_COMMENT_CT=0
PR_REVIEW_CT=0
PR_REVIEW_COMMENT_CT=0
##################
# Analyze Issues #
##################
if [[ $ISSUE_CT -ne 0 ]]; then
AnalyzeIssues "${REPO_DATA}"
fi
#########################
# Analyze Pull Requests #
#########################
if [[ $PR_CT -ne 0 ]]; then
AnalyzePullRequests "${REPO_DATA}"
fi
###########################
# Build the output string #
###########################
RECORD_CT=$((COLLABORATOR_CT + PROTECTED_BRANCH_CT + PR_REVIEW_CT + MILESTONE_CT + ISSUE_CT + PR_CT + PR_REVIEW_COMMENT_CT + COMMIT_COMMENT_CT + ISSUE_COMMENT_CT + ISSUE_EVENT_CT + RELEASE_CT + PROJECT_CT))
####################################
# Get if this is a migration issue #
####################################
MIGRATION_ISSUE=$(MarkMigrationIssues "${REPO_SIZE}" "${RECORD_CT}")
if [ "${MIGRATION_ISSUE}" -eq 0 ]; then
MIGRATION_ISSUE="TRUE"
else
MIGRATION_ISSUE="FALSE"
fi
########################
# Write it to the file #
########################
echo "${ORG_NAME},${REPO_NAME},${IS_EMPTY}${PUSHED_AT},${UPDATED_AT},${IS_FORK},${IS_ARCHIVED},${REPO_SIZE},${RECORD_CT},${COLLABORATOR_CT},${PROTECTED_BRANCH_CT},${PR_REVIEW_CT},${MILESTONE_CT},${ISSUE_CT},${PR_CT},${PR_REVIEW_COMMENT_CT},${COMMIT_COMMENT_CT},${ISSUE_COMMENT_CT},${ISSUE_EVENT_CT},${RELEASE_CT},${PROJECT_CT},${BRANCH_CT},${TAG_CT},${DISCUSSION_CT},${HAS_WIKI},${URL},${MIGRATION_ISSUE},${CREATED_AT}" >>"${OUTPUT_FILE_NAME}"
#######################
# Load the error code #
#######################
# shellcheck disable=SC2320
ERROR_CODE=$?
##############################
# Check the shell for errors #
##############################
if [ "${ERROR_CODE}" -ne 0 ]; then
echo "ERROR! Failed to write output to file:[${OUTPUT_FILE_NAME}]"
exit 1
fi
##############################
# Check to anazyle conflicts #
##############################
if [[ ${ANALYZE_CONFLICTS} -eq 1 ]]; then
### Check the repository name against array of all previously-processed repositories
REPO_INDEX=-1
for ITEM in "${!REPO_LIST[@]}"; do
if [[ "${REPO_LIST[${ITEM}]}" = "${REPO_NAME}" ]]; then
REPO_INDEX=${i}
fi
done
### If this is the first instance of that repository name, add it to the list and add the group name to its array
if [[ ${REPO_INDEX} -eq -1 ]]; then
Debug "Repo: ${REPO_NAME} is unique. Adding to the list!"
REPO_LIST+=( "${REPO_NAME}" )
GROUP_LIST[(( ${#REPO_LIST[@]} - 1 ))]=${ORG_NAME}
NUMBER_OF_CONFLICTS[(( ${#REPO_LIST[@]} - 1 ))]=1
else
echo "Repo: ${REPO_NAME} already exists. Adding ${ORG_NAME} to the conflict list"
GROUP_LIST[${REPO_INDEX}]+=" ${ORG_NAME}"
(( NUMBER_OF_CONFLICTS[REPO_INDEX]++ ))
fi
fi
}
################################################################################
#### Function AnalyzeIssues ####################################################
AnalyzeIssues() {
THIS_REPO=$1
_pr_issue_jq() {
echo -n "${THIS_REPO}" | base64 --decode | jq -r "${1}"
}
ISSUES=$(_pr_issue_jq '.issues.nodes')
##########################
# Get the Next Page Flag #
##########################
HAS_NEXT_ISSUES_PAGE=$(_pr_issue_jq '.issues.pageInfo.hasNextPage')
##############################
# Get the Current End Cursor #
##############################
ISSUE_NEXT_PAGE=$(_pr_issue_jq '.issues.pageInfo.endCursor')
for ISSUE in $(echo -n "${ISSUES}" | jq -r '.[] | @base64'); do
_issue_jq() {
echo -n "${ISSUE}" | base64 --decode | jq -r "${1}"
}