forked from Automattic/vip-go-ci
-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.php
1701 lines (1450 loc) · 31.4 KB
/
misc.php
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
<?php
/*
* Log information to the console.
* Include timestamp, and any debug-data
* our caller might pass us.
*/
function vipgoci_log(
$str,
$debug_data = array(),
$debug_level = 0,
$irc = false
) {
global $vipgoci_debug_level;
/*
* Determine if to log the message; if
* debug-level of the message is not high
* enough compared to the debug-level specified
* to be the threshold, do not print it, but
* otherwise, do print it,
*/
if ( $debug_level > $vipgoci_debug_level ) {
return;
}
echo '[ ' . date( 'c' ) . ' -- ' . (int) $debug_level . ' ] ' .
$str .
'; ' .
print_r(
json_encode(
$debug_data,
JSON_PRETTY_PRINT
),
true
) .
PHP_EOL;
/*
* Send to IRC API as well if asked
* to do so. Include debugging information as well.
*/
if ( true === $irc ) {
vipgoci_irc_api_alert_queue(
$str .
'; ' .
print_r(
json_encode(
$debug_data
),
true
)
);
}
}
/**
* Exit program, using vipgoci_log() to print a
* message before doing so.
*
* @codeCoverageIgnore
*/
function vipgoci_sysexit(
$str,
$debug_data = array(),
$exit_status = VIPGOCI_EXIT_USAGE_ERROR
) {
if ( $exit_status === VIPGOCI_EXIT_USAGE_ERROR ) {
$str = 'Usage: ' . $str;
}
vipgoci_log(
$str,
$debug_data,
0
);
exit( $exit_status );
}
/*
* Given a patch-file, the function will return an
* associative array, mapping the patch-file
* to the raw committed file.
*
* In the resulting array, the keys represent every
* line in the patch (except for the "@@" lines),
* while the values represent line-number in the
* raw committed line. Some keys might point
* to empty values, in which case there is no
* relation between the two.
*/
function vipgoci_patch_changed_lines(
$repo_owner,
$repo_name,
$github_token,
$pr_base_sha,
$commit_id,
$file_name
) {
/*
* Fetch patch for all files of the Pull-Request
*/
$patch_arr = vipgoci_github_diffs_fetch(
$repo_owner,
$repo_name,
$github_token,
$pr_base_sha,
$commit_id,
false,
false,
false
);
/*
* Get patch for the relevant file
* our caller is interested in
*/
$lines_arr = explode(
"\n",
$patch_arr[ $file_name ]
);
$lines_changed = array();
$i = 1;
foreach ( $lines_arr as $line ) {
preg_match_all(
"/^@@\s+[-\+]([0-9]+,[0-9]+)\s+[-\+]([0-9]+,[0-9]+)\s+@@/",
$line,
$matches
);
if ( ! empty( $matches[0] ) ) {
$start_end = explode(
',',
$matches[2][0]
);
$i = $start_end[0];
$lines_changed[] = null;
}
else if ( empty( $matches[0] ) ) {
if ( empty( $line[0] ) ) {
// Do nothing
}
else if (
( $line[0] == '-' ) ||
( $line[0] == '\\' )
) {
$lines_changed[] = null;
}
else if (
( $line[0] == '+' ) ||
( $line[0] == " " ) ||
( $line[0] == "\t" )
) {
$lines_changed[] = $i++;
}
}
}
/*
* In certain edge-cases, line 1 in the patch
* will refer to line 0 in the code, which
* is not what we want. In these cases, we
* simply hard-code line 1 in the patch to match
* with line 1 in the code.
*/
if (
( isset( $lines_changed[1] ) ) &&
(
( $lines_changed[1] === null ) ||
( $lines_changed[1] === 0 )
)
||
( ! isset( $lines_changed[1] ) )
) {
$lines_changed[1] = 1;
}
return $lines_changed;
}
/*
* Get a specific item from in-memory cache based on
* $cache_id_arr if $data is null, or if $data is not null,
* add a specific item to cache.
*
* The data is stored in an associative array, with
* key being an array (or anything else) -- $cache_id_arr --,
* and used to identify the data up on retrieval.
*
* If the data being cached is an object, we make a copy of it,
* and then store it. When the cached data is being retrieved,
* we return a copy of the cached data.
*/
function vipgoci_cache( $cache_id_arr, $data = null ) {
global $vipgoci_cache_buffer;
/*
* Special invocation: Allow for
* the cache to be cleared.
*/
if (
( is_string(
$cache_id_arr
) )
&&
(
VIPGOCI_CACHE_CLEAR ===
$cache_id_arr
)
) {
$vipgoci_cache_buffer = array();
return true;
}
$cache_id = json_encode(
$cache_id_arr
);
if ( null === $data ) {
if ( isset( $vipgoci_cache_buffer[ $cache_id ] ) ) {
$ret = $vipgoci_cache_buffer[ $cache_id ];
// If an object, copy and return the copy
if ( is_object( $ret ) ) {
$ret = clone $ret;
}
return $ret;
}
else {
return false;
}
}
// If an object, copy, save it, and return the copy
if ( is_object( $data ) ) {
$data = clone $data;
}
$vipgoci_cache_buffer[ $cache_id ] = $data;
return $data;
}
/**
* Support function for other functions
* that use the internal cache and need to indicate
* that information from the cache was used.
*
* @codeCoverageIgnore
*/
function vipgoci_cached_indication_str( $cache_used ) {
return $cache_used ? ' (cached)' : '';
}
/*
* Create a temporary file, and return the
* full-path to the file.
*/
function vipgoci_save_temp_file(
$file_name_prefix,
$file_name_extension = null,
$file_contents
) {
// Determine name for temporary-file
$temp_file_name = $temp_file_save_status = tempnam(
sys_get_temp_dir(),
$file_name_prefix
);
/*
* If temporary file should have an extension,
* make that happen by renaming the currently existing
* file.
*/
if (
( null !== $file_name_extension ) &&
( false !== $temp_file_name )
) {
$temp_file_name_old = $temp_file_name;
$temp_file_name .= '.' . $file_name_extension;
if ( true !== rename(
$temp_file_name_old,
$temp_file_name
) ) {
vipgoci_sysexit(
'Unable to rename temporary file',
array(
'temp_file_name_old' => $temp_file_name_old,
'temp_file_name_new' => $temp_file_name,
),
VIPGOCI_EXIT_SYSTEM_PROBLEM
);
}
unset( $temp_file_name_old );
}
if ( false !== $temp_file_name ) {
vipgoci_runtime_measure( VIPGOCI_RUNTIME_START, 'save_temp_file' );
$temp_file_save_status = file_put_contents(
$temp_file_name,
$file_contents
);
vipgoci_runtime_measure( VIPGOCI_RUNTIME_STOP, 'save_temp_file' );
}
// Detect possible errors when saving the temporary file
if ( false === $temp_file_save_status ) {
vipgoci_sysexit(
'Could not save file to disk, got ' .
'an error. Exiting...',
array(
'temp_file_name' => $temp_file_name,
),
VIPGOCI_EXIT_SYSTEM_PROBLEM
);
}
return $temp_file_name;
}
/*
* Determine file-extension of a particular file,
* and return it in lowercase. If it can not be
* determined, return null.
*/
function vipgoci_file_extension( $file_name ) {
$file_extension = pathinfo(
$file_name,
PATHINFO_EXTENSION
);
if ( empty( $file_extension ) ) {
return null;
}
$file_extension = strtolower(
$file_extension
);
return $file_extension;
}
/*
* Return ASCII-art for GitHub, which will then
* be turned into something more fancy. This is
* intended to be called when preparing messages/comments
* to be submitted to GitHub.
*/
function vipgoci_github_labels( $text_string ) {
switch( strtolower( $text_string ) ) {
case 'warning':
return ':warning:';
case 'error':
return ':no_entry_sign:';
case 'info':
return ':information_source:';
}
return '';
}
/*
* Determine if the presented file has an
* allowable file-ending, and if the file presented
* is in a directory that is can be scanned.
*/
function vipgoci_filter_file_path(
$filename,
$filter
) {
$file_info_extension = vipgoci_file_extension(
$filename
);
$file_dirs = pathinfo(
$filename,
PATHINFO_DIRNAME
);
/*
* If the file does not have an acceptable
* file-extension, flag it.
*/
$file_ext_match =
( null !== $filter ) &&
( isset( $filter['file_extensions'] ) ) &&
( ! in_array(
$file_info_extension,
$filter['file_extensions'],
true
) );
/*
* If path to the file contains any non-acceptable
* directory-names, skip it.
*/
$file_folders_match = false;
if (
( null !== $filter ) &&
( isset( $filter['skip_folders' ] ) )
) {
$file_dirs_arr = explode( '/', $file_dirs );
foreach ( $file_dirs_arr as $file_dir_item ) {
if ( in_array(
$file_dir_item,
$filter['skip_folders']
) ) {
$file_folders_match = true;
}
}
}
/*
* Do the actual skipping of file,
* if either of the conditions are fulfiled.
*/
if (
( true === $file_ext_match ) ||
( true === $file_folders_match )
) {
vipgoci_log(
'Skipping file that does not seem ' .
'to be a file matching ' .
'filter-criteria',
array(
'filename' =>
$filename,
'filter' =>
$filter,
'matches' => array(
'file_ext_match' => $file_ext_match,
'file_folders_match' => $file_folders_match,
),
),
2
);
return false;
}
return true;
}
/*
* Recursively scan the git repository,
* returning list of files that exist in
* it, making sure to filter the result
*/
function vipgoci_scandir_git_repo( $path, $filter ) {
$result = array();
vipgoci_log(
'Fetching git-tree using scandir()',
array(
'path' => $path,
'filter' => $filter,
),
2
);
vipgoci_runtime_measure( VIPGOCI_RUNTIME_START, 'git_repo_scandir' );
$cdir = scandir( $path );
vipgoci_runtime_measure( VIPGOCI_RUNTIME_STOP, 'git_repo_scandir' );
foreach ( $cdir as $key => $value ) {
if ( in_array(
$value,
array( '.', '..', '.git' )
) ) {
// Skip '.' and '..'
continue;
}
if ( is_dir(
$path . DIRECTORY_SEPARATOR . $value
) ) {
/*
* A directory, traverse into, get files,
* amend the results
*/
$tmp_result = vipgoci_scandir_git_repo(
$path . DIRECTORY_SEPARATOR . $value,
$filter
);
foreach ( $tmp_result as $tmp_result_item ) {
$result[] = $value .
DIRECTORY_SEPARATOR .
$tmp_result_item;
}
continue;
}
// Filter out files not with desired line-ending
if ( null !== $filter ) {
if ( false === vipgoci_filter_file_path(
$path . DIRECTORY_SEPARATOR . $value,
$filter
) ) {
continue;
}
}
// Not a directory, passed filter, save in array
$result[] = $value;
}
return $result;
}
/*
* Go through the given blame-log, and
* return only the items from the log that
* are found in $relevant_commit_ids.
*/
function vipgoci_blame_filter_commits(
$blame_log,
$relevant_commit_ids
) {
/*
* Loop through each file, get a
* 'git blame' log for the file, so
* so we can filter out issues not
* stemming from commits that are a
* part of the current Pull-Request.
*/
$blame_log_filtered = array();
foreach ( $blame_log as $blame_log_item ) {
if ( ! in_array(
$blame_log_item['commit_id'],
$relevant_commit_ids,
true
) ) {
continue;
}
$blame_log_filtered[] =
$blame_log_item;
}
return $blame_log_filtered;
}
/*
* Check if the specified comment exists
* within an array of other comments --
* this is used to understand if the specific
* comment has already been submitted earlier.
*/
function vipgoci_github_comment_match(
$file_issue_path,
$file_issue_line,
$file_issue_comment,
$comments_made
) {
/*
* Construct an index-key made of file:line.
*/
$comment_index_key =
$file_issue_path .
':' .
$file_issue_line;
if ( ! isset(
$comments_made[
$comment_index_key
]
)) {
/*
* No match on index-key within the
* associative array -- the comment has
* not been made, so return false.
*/
return false;
}
/*
* Some comment matching the file and line-number
* was found -- figure out if it is definately the
* same comment.
*/
foreach (
$comments_made[ $comment_index_key ] as
$comment_made
) {
/*
* The comment might contain formatting, such
* as "Warning: ..." -- remove all of that.
*/
$comment_made_body = str_replace(
array("**", "Warning", "Error", "Info", ":no_entry_sign:", ":warning:", ":information_source:"),
array("", "", "", "", ""),
$comment_made->body
);
/*
* The comment might be prefixed with ': ',
* remove that as well.
*/
$comment_made_body = ltrim(
$comment_made_body,
': '
);
/*
* The comment might include PHPCS source
* of the error at the end (e.g.
* "... (*WordPress.WP.AlternativeFunctions.json_encode_json_encode*)."
* -- remove the source, the brackets and the ending dot.
*/
$comment_made_body = preg_replace(
'/ \([\*_\.a-zA-Z0-9]+\)\.$/',
'',
$comment_made_body
);
/*
* Transform string to lowercase,
* remove ending '.' just in case if
* not removed earlier.
*/
$comment_made_body = strtolower(
$comment_made_body
);
$comment_made_body = rtrim(
$comment_made_body,
'.'
);
/*
* Transform the string to lowercase,
* and remove potential '.' at the end
* of it.
*/
$file_issue_comment = strtolower(
$file_issue_comment
);
$file_issue_comment = rtrim(
$file_issue_comment,
'.'
);
/*
* Check if comments match, including
* if we need to HTML-encode our new comment
* (GitHub encodes their comments when
* returning them.
*/
if (
(
$comment_made_body ==
$file_issue_comment
)
||
(
$comment_made_body ==
htmlentities( $file_issue_comment )
)
) {
/* Comment found, return true. */
return true;
}
}
return false;
}
/*
* Remove comments that exist on a GitHub Pull-Request from
* the results array. Will loop through each Pull-Request
* affected by the current commit, and remove any comment
* from the results array if it already exists.
*/
function vipgoci_remove_existing_github_comments_from_results(
$options,
$prs_implicated,
&$results,
$repost_comments_from_dismissed_reviews = false,
$prs_events_dismissed_by_team = array()
) {
vipgoci_log(
'Removing existing GitHub comments from results' .
' to be posted to GitHub API',
array(
'repo_owner' => $options['repo-owner'],
'repo_name' => $options['repo-name'],
'prs_implicated' => array_keys( $prs_implicated ),
'repost_comments_from_dismissed_reviews' => $repost_comments_from_dismissed_reviews,
'prs_events_dismissed_by_team' => $prs_events_dismissed_by_team,
)
);
$comments_removed = array();
foreach ( $prs_implicated as $pr_item ) {
$prs_comments = array();
if ( ! isset(
$comments_removed[ $pr_item->number ]
) ) {
$comments_removed[ $pr_item->number ] = array();
}
/*
* Get all commits related to the current
* Pull-Request.
*/
$pr_item_commits = vipgoci_github_prs_commits_list(
$options['repo-owner'],
$options['repo-name'],
$pr_item->number,
$options['token']
);
/*
* Loop through each commit, fetching all comments
* made in relation to that commit
*/
foreach ( $pr_item_commits as $pr_item_commit_id ) {
vipgoci_github_pr_reviews_comments_get(
$options,
$pr_item_commit_id,
$pr_item->created_at,
$prs_comments // pointer used
);
unset( $pr_item_commit_id );
}
/*
* Ignore dismissed reviews, if requested.
*/
if ( true === $repost_comments_from_dismissed_reviews ) {
vipgoci_log(
'Later on, will make sure comments ' .
'that are part of dismissed reviews ' .
'will be submitted again, if the ' .
'underlying issue was detected ' .
'during the run. In case of such a setting' .
'and such reviews existing, excluding ' .
'reviews (and thus comments) that are submitted ' .
'by members of a particular team ' .
'from this process',
array(
'teams' =>
$options['dismissed-reviews-exclude-reviews-from-team'],
'pr_number' =>
$pr_item->number,
)
);
/*
* Get dismissed reviews submitted by us
* and extract ID of each.
*/
$pr_reviews = vipgoci_github_pr_reviews_get(
$options['repo-owner'],
$options['repo-name'],
$pr_item->number,
$options['token'],
array(
'login' => 'myself',
'state' => array( 'DISMISSED' )
)
);
$dismissed_reviews = array_column(
$pr_reviews,
'id'
);
unset( $pr_reviews );
/*
* Some reviews (and comments) should not be posted,
* again, as per setting determined by our caller;
* honor this here.
*/
if ( ! empty(
$prs_events_dismissed_by_team[
$pr_item->number
]
) ) {
$all_review_ids = $dismissed_reviews;
$dismissed_reviews = array_diff(
$all_review_ids,
$prs_events_dismissed_by_team[
$pr_item->number
]
);
vipgoci_log(
'Excluding certain reviews from ' .
'list of previously gathered dismissed reviews; ' .
'will only keep reviews that were not dismissed by ' .
'members of a particular team. The comments of ' .
'the outstanding, kept, reviews might be posted again ' .
'if the underlying issue was detected',
array(
'prs_events_dismissed_by_team_and_pr' =>
$prs_events_dismissed_by_team[
$pr_item->number
],
'all_review_ids' =>
$all_review_ids,
'dismissed_reviews' =>
$dismissed_reviews,
)
);
unset( $all_review_ids );
}
/*
* Loop through each file to have comments
* submitted against, then look through each
* comment, looking for any comment associated
* with dismissed reviews.
*
* If we find a dismissed review, we will act
* as if the comment was never there by removing
* it from $prs_comments. This will ensure
* that our to-be posted review will contain
* such comments, even though they could be
* considered duplictes. The aim is to make
* them more visible and part of a blocking review.
*
* Note that some comments might be excluded
* from this, as per above.
*/
$removed_comments = array();
foreach(
$prs_comments as
$pr_comment_key => $pr_comments_items
) {
foreach(
$pr_comments_items as
$pr_review_key => $pr_review_comment
) {
if ( false === in_array(
$pr_review_comment->pull_request_review_id,
$dismissed_reviews
) ) {
continue;
}
$removed_comments[] = array(
'pr_number' =>
$pr_item->number,
'pull_request_review_id' =>
$pr_review_comment->pull_request_review_id,
'comment_id' =>
$pr_review_comment->id,
'message_body' =>
$pr_review_comment->body,
'message_created_at' =>
$pr_review_comment->created_at,
'message_updated_at' =>
$pr_review_comment->updated_at,
);
/*
* Comment is a part of a dismissed review
* (that was not excluded), now get
* rid of the comment -- act as if was
* never there.
*/
unset(
$prs_comments[
$pr_comment_key
][
$pr_review_key
]
);
}
}
vipgoci_log(
'Removed following comments from list of previously submitted ' .
'comments to older PR reviews, as they are ' .
'part of dismissed reviews. Note that some ' .
'dismissed reviews might have been excluded previously',
array(
'removed_comments' =>
$removed_comments,
)
);
unset( $removed_comments );
unset( $dismissed_reviews );
}
foreach(
$results['issues'][ $pr_item->number ] as
$tobe_submitted_cmt_key =>
$tobe_submitted_cmt
) {
/*
* Filter out issues that have already been
* reported to GitHub.
*/
if (
// Only do check if everything above is looking good
vipgoci_github_comment_match(
$tobe_submitted_cmt['file_name'],
$tobe_submitted_cmt['file_line'],
$tobe_submitted_cmt['issue']['message'],
$prs_comments
)
) {
/*
* Keep a record of what we remove.
*/
$comments_removed[ $pr_item->number ][] =
$tobe_submitted_cmt;