This repository has been archived by the owner on Jun 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 196
/
static-checks.sh
executable file
·1450 lines (1120 loc) · 37.8 KB
/
static-checks.sh
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
# Copyright (c) 2017-2019 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
# Description: Central script to run all static checks.
# This script should be called by all other repositories to ensure
# there is only a single source of all static checks.
set -e
[ -n "$DEBUG" ] && set -x
cidir=$(realpath $(dirname "$0"))
source "${cidir}/lib.sh"
# By default in Golang >= 1.16 GO111MODULE is set to "on",
# some subprojects in this repo may not support "go modules",
# set GO111MODULE to "auto" to enable module-aware mode only when
# a go.mod file is present in the current directory.
export GO111MODULE="auto"
export tests_repo="${tests_repo:-github.com/kata-containers/tests}"
export tests_repo_dir="${GOPATH}/src/${tests_repo}"
# List of files to delete on exit
files_to_remove=()
script_name=${0##*/}
# Static check functions must follow the following naming conventions:
#
# All static check function names must match this pattern.
typeset -r check_func_regex="^static_check_"
# All architecture-specific static check functions must match this pattern.
typeset -r arch_func_regex="_arch_specific$"
repo=""
specific_branch="false"
force="false"
branch=${branch:-main}
# Which static check functions to consider.
handle_funcs="all"
single_func_only="false"
list_only="false"
# number of seconds to wait for curl to check a URL
typeset url_check_timeout_secs="${url_check_timeout_secs:-60}"
# number of attempts that will be made to check an individual URL.
typeset url_check_max_tries="${url_check_max_tries:-3}"
typeset -A long_options
# Generated code
ignore_clh_generated_code="virtcontainers/pkg/cloud-hypervisor/client"
paths_to_skip=(
"${ignore_clh_generated_code}"
"vendor"
)
# Skip paths that are not statically checked
# $1 : List of paths to check, space separated list
# If you have a list in a bash array call in this way:
# list=$(skip_paths "${list[@]}")
# If you still want to use it as an array do:
# list=(${list})
skip_paths(){
local list_param="${1}"
[ -z "$list_param" ] && return
local list=(${list_param})
for p in "${paths_to_skip[@]}"; do
new_list=()
for l in "${list[@]}"; do
if echo "${l}" | grep -qv "${p}"; then
new_list=("${new_list[@]}" "${l}")
fi
done
list=("${new_list[@]}")
done
echo "${list[@]}"
}
long_options=(
[all]="Force checking of all changes, including files in the base branch"
[branch]="Specify upstream branch to compare against (default '$branch')"
[docs]="Check document files"
[dockerfiles]="Check dockerfiles"
[files]="Check files"
[force]="Force a skipped test to run"
[golang]="Check '.go' files"
[help]="Display usage statement"
[json]="Check JSON files"
[labels]="Check labels databases"
[licenses]="Check licenses"
[list]="List tests that would run"
[no-arch]="Run/list all tests except architecture-specific ones"
[only-arch]="Only run/list architecture-specific tests"
[repo:]="Specify GitHub URL of repo to use (github.com/user/repo)"
[scripts]="Check script files"
[vendor]="Check vendor files"
[versions]="Check versions files"
[xml]="Check XML files"
)
yamllint_cmd="yamllint"
have_yamllint_cmd=$(command -v "$yamllint_cmd" || true)
chronic=chronic
# Disable chronic on OSX to avoid having to update the Travis config files
# for additional packages on that platform.
[ "$(uname -s)" == "Darwin" ] && chronic=
usage()
{
cat <<EOF
Usage: $script_name help
$script_name [options] repo-name [true]
Options:
EOF
local option
local description
local long_option_names="${!long_options[@]}"
# Sort space-separated list by converting to newline separated list
# and back again.
long_option_names=$(echo "$long_option_names"|tr ' ' '\n'|sort|tr '\n' ' ')
# Display long options
for option in ${long_option_names}
do
description=${long_options[$option]}
# Remove any trailing colon which is for getopt(1) alone.
option=$(echo "$option"|sed 's/:$//g')
printf " --%-10.10s # %s\n" "$option" "$description"
done
cat <<EOF
Parameters:
help : Show usage.
repo-name : GitHub URL of repo to check in form "github.com/user/repo"
(equivalent to "--repo \$URL").
true : Specify as "true" if testing a specific branch, else assume a
PR branch (equivalent to "--all").
Notes:
- If no options are specified, all non-skipped tests will be run.
- Some required tools may be installed in \$GOPATH/bin, so you should ensure
that it is in your \$PATH.
Examples:
- Run all tests on a specific branch (stable or main) of kata-containers repo:
$ $script_name github.com/kata-containers/kata-containers true
- Auto-detect repository and run golang tests for current repository:
$ KATA_DEV_MODE=true $script_name --golang
- Run all tests on the kata-containers repository, forcing the tests to
consider all files, not just those changed by a PR branch:
$ $script_name github.com/kata-containers/kata-containers --all
EOF
}
# Calls die() if the specified function is not valid.
func_is_valid() {
local name="$1"
type -t "$name" &>/dev/null || die "function '$name' does not exist"
}
# Calls die() if the specified function is not valid or not a check function.
ensure_func_is_check_func() {
local name="$1"
func_is_valid "$name"
{ echo "$name" | grep -q "${check_func_regex}"; ret=$?; }
[ "$ret" = 0 ] || die "function '$name' is not a check function"
}
# Returns "yes" if the specified function needs to run on all architectures,
# else "no".
func_is_arch_specific() {
local name="$1"
ensure_func_is_check_func "$name"
{ echo "$name" | grep -q "${arch_func_regex}"; ret=$?; }
if [ "$ret" = 0 ]; then
echo "yes"
else
echo "no"
fi
}
function remove_tmp_files() {
rm -rf "${files_to_remove[@]}"
}
# Convert a golang package to a full path
pkg_to_path()
{
local pkg="$1"
go list -f '{{.Dir}}' "$pkg"
}
# Check that chronic is installed, otherwise die.
need_chronic() {
local first_word
[ -z "$chronic" ] && return
first_word="${chronic%% *}"
command -v chronic &>/dev/null || \
die "chronic command not found. You must have it installed to run this check." \
"Usually it is distributed with the 'moreutils' package of your Linux distribution."
}
static_check_go_arch_specific()
{
local go_packages
local submodule_packages
local all_packages
# List of all golang packages found in all submodules
#
# These will be ignored: since they are references to other
# repositories, we assume they are tested independently in their
# repository so do not need to be re-tested here.
submodule_packages=$(mktemp)
git submodule -q foreach "go list ./..." | sort > "$submodule_packages" || true
# all packages
all_packages=$(mktemp)
go list ./... | sort > "$all_packages" || true
files_to_remove+=("$submodule_packages" "$all_packages")
# List of packages to consider which is defined as:
#
# "all packages" - "submodule packages"
#
# Note: the vendor filtering is required for versions of go older than 1.9
go_packages=$(comm -3 "$all_packages" "$submodule_packages" || true)
go_packages=$(skip_paths "${go_packages[@]}")
# No packages to test
[ -z "$go_packages" ] && return
local linter="golangci-lint"
# Run golang checks
if [ ! "$(command -v $linter)" ]
then
info "Installing ${linter}"
local linter_url=$(get_test_version "externals.golangci-lint.url")
local linter_version=$(get_test_version "externals.golangci-lint.version")
info "Forcing ${linter} version ${linter_version}"
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin "${linter_version}"
command -v $linter &>/dev/null || \
die "$linter command not found. Ensure that \"\$GOPATH/bin\" is in your \$PATH."
fi
local linter_args="run -c ${cidir}/.golangci.yml"
# Non-option arguments other than "./..." are
# considered to be directories by $linter, not package names.
# Hence, we need to obtain a list of package directories to check,
# excluding any that relate to submodules.
local dirs
for pkg in $go_packages
do
path=$(pkg_to_path "$pkg")
makefile="${path}/Makefile"
# perform a basic build since some repos generate code which
# is required for the package to be buildable (and thus
# checkable).
[ -f "$makefile" ] && (cd "$path" && make)
dirs+=" $path"
done
info "Running $linter checks on the following packages:\n"
echo "$go_packages"
echo
info "Package paths:\n"
echo "$dirs" | sed 's/^ *//g' | tr ' ' '\n'
for d in ${dirs};do
info "Running $linter on $d"
(cd $d && GO111MODULE=auto eval "$linter" "${linter_args}" ".")
done
}
# Install yamllint in the different Linux distributions
install_yamllint()
{
source /etc/os-release || source /usr/lib/os-release
package="yamllint"
case "$ID" in
centos|rhel) sudo yum -y install $package ;;
ubuntu) sudo apt-get -y install $package ;;
fedora) sudo dnf -y install $package ;;
*) die "Please install yamllint on $ID" ;;
esac
have_yamllint_cmd=$(command -v "$yamllint_cmd" || true)
if [ -z "$have_yamllint_cmd" ]; then
info "Cannot install $package" && return
fi
}
# Check the "versions database".
#
# Some repositories use a versions database to maintain version information
# about non-golang dependencies. If found, check it for validity.
static_check_versions()
{
local db="versions.yaml"
if [ -z "$have_yamllint_cmd" ]; then
info "Installing yamllint"
install_yamllint
fi
[ ! -e "$db" ] && return
if [ -n "$have_yamllint_cmd" ]; then
eval "$yamllint_cmd" "$db"
else
info "Cannot check versions as $yamllint_cmd not available"
fi
}
static_check_labels()
{
[ $(uname -s) != Linux ] && info "Can only check labels under Linux" && return
# Handle SLES which doesn't provide the required command.
[ -z "$have_yamllint_cmd" ] && info "Cannot check labels as $yamllint_cmd not available" && return
# Since this script is called from another repositories directory,
# ensure the utility is built before the script below (which uses it) is run.
(cd "${tests_repo_dir}" && make github-labels)
tmp=$(mktemp)
files_to_remove+=("${tmp}")
info "Checking labels for repo ${repo} using temporary combined database ${tmp}"
bash -f "${tests_repo_dir}/cmd/github-labels/github-labels.sh" "generate" "${repo}" "${tmp}"
}
# Ensure all files (where possible) contain an SPDX license header
static_check_license_headers()
{
# The branch is the baseline - ignore it.
[ "$specific_branch" = "true" ] && return
# See: https://spdx.org/licenses/Apache-2.0.html
local -r spdx_tag="SPDX-License-Identifier"
local -r spdx_license="Apache-2.0"
local -r license_pattern="${spdx_tag}: ${spdx_license}"
local -r copyright_pattern="Copyright"
local header_checks=()
header_checks+=("SPDX license header::${license_pattern}")
header_checks+=("Copyright header:-i:${copyright_pattern}")
files=$(get_pr_changed_file_details || true)
# Strip off status
files=$(echo "$files"|awk '{print $NF}')
# no files were changed
[ -z "$files" ] && info "No files found" && return
local header_check
for header_check in "${header_checks[@]}"
do
local desc=$(echo "$header_check"|cut -d: -f1)
local extra_args=$(echo "$header_check"|cut -d: -f2)
local pattern=$(echo "$header_check"|cut -d: -f3-)
info "Checking $desc"
local missing=$(egrep \
--exclude=".git/*" \
--exclude=".gitignore" \
--exclude=".dockerignore" \
--exclude="Gopkg.lock" \
--exclude="*.gpl.c" \
--exclude="*.ipynb" \
--exclude="*.jpg" \
--exclude="*.json" \
--exclude="LICENSE*" \
--exclude="THIRD-PARTY" \
--exclude="*.md" \
--exclude="*.pb.go" \
--exclude="*pb_test.go" \
--exclude="*.bin" \
--exclude="*.png" \
--exclude="*.pub" \
--exclude="*.service" \
--exclude="*.svg" \
--exclude="*.drawio" \
--exclude="*.toml" \
--exclude="*.txt" \
--exclude="*.dtd" \
--exclude="vendor/*" \
--exclude="VERSION" \
--exclude="kata_config_version" \
--exclude="tools/packaging/kernel/configs/*" \
--exclude="virtcontainers/pkg/firecracker/*" \
--exclude="${ignore_clh_generated_code}*" \
--exclude="*.xml" \
--exclude="*.yaml" \
--exclude="*.yml" \
--exclude="go.mod" \
--exclude="go.sum" \
--exclude="*.lock" \
--exclude="grpc-rs/*" \
--exclude="target/*" \
--exclude="*.patch" \
--exclude="*.diff" \
--exclude="tools/packaging/static-build/qemu.blacklist" \
--exclude="tools/packaging/qemu/default-configs/*" \
--exclude="src/libs/protocols/protos/gogo/*.proto" \
--exclude="src/libs/protocols/protos/google/*.proto" \
--exclude="src/libs/*/test/texture/*" \
--exclude="*.dic" \
-EL $extra_args "\<${pattern}\>" \
$files || true)
if [ -n "$missing" ]; then
cat >&2 <<-EOF
ERROR: Required $desc check ('$pattern') failed for the following files:
$missing
EOF
exit 1
fi
done
}
run_url_check_cmd()
{
local url="${1:-}"
[ -n "$url" ] || die "need URL"
local out_file="${2:-}"
[ -n "$out_file" ] || die "need output file"
# Can be blank
local extra_args="${3:-}"
local curl_extra_args=()
curl_extra_args+=("$extra_args")
# Authenticate for github to increase threshold for rate limiting
if [[ "$url" =~ github\.com && -n "$GITHUB_USER" && -n "$GITHUB_TOKEN" ]]; then
curl_extra_args+=("-u ${GITHUB_USER}:${GITHUB_TOKEN}")
fi
# Some endpoints return 403 to HEAD but 200 for GET,
# so perform a GET but only read headers.
curl \
${curl_extra_args[*]} \
-sIL \
-X GET \
-c - \
-H "Accept-Encoding: zstd, none, gzip, deflate" \
--max-time "$url_check_timeout_secs" \
--retry "$url_check_max_tries" \
"$url" \
&>"$out_file"
}
check_url()
{
local url="$1"
local invalid_urls_dir="$2"
local curl_out=$(mktemp)
files_to_remove+=("${curl_out}")
info "Checking URL $url"
# Process specific file to avoid out-of-order writes
local invalid_file=$(printf "%s/%d" "$invalid_urls_dir" "$$")
local ret
local -a errors=()
local -a user_agents=()
# Test an unspecified UA (curl default)
user_agents+=('')
# Test an explictly blank UA
user_agents+=('""')
# Single space
user_agents+=(' ')
# CLI HTTP tools
user_agents+=('Wget')
user_agents+=('curl')
# console based browsers
# Hopefully, these will always be supported for a11y.
user_agents+=('Lynx')
user_agents+=('Elinks')
# Emacs' w3m browser
user_agents+=('Emacs')
# The full craziness
user_agents+=('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36')
local user_agent
local success='false'
# Cycle through the user agents until we find one that works.
#
# Note that we also test an unspecified user agent
# (no '-A <value>').
for user_agent in "${user_agents[@]}"
do
local curl_ua_args
[ -n "$user_agent" ] && curl_ua_args="-A '$user_agent'"
{ run_url_check_cmd "$url" "$curl_out" "$curl_ua_args"; ret=$?; } || true
# A transitory error, or the URL is incorrect,
# but capture either way.
if [ "$ret" -ne 0 ]; then
echo "$url" >> "${invalid_file}"
errors+=("Failed to check URL '$url' (user agent: '$user_agent', return code $ret)")
# Give up
break
fi
local http_statuses
http_statuses=$(grep -E "^HTTP" "$curl_out" |\
awk '{print $2}' || true)
if [ -z "$http_statuses" ]; then
echo "$url" >> "${invalid_file}"
errors+=("no HTTP status codes for URL '$url' (user agent: '$user_agent')")
continue
fi
local status
local -i fail_count=0
# Check all HTTP status codes
for status in $http_statuses
do
# Ignore the following ranges of status codes:
#
# - 1xx: Informational codes.
# - 2xx: Success codes.
# - 3xx: Redirection codes.
# - 405: Specifically to handle some sites
# which get upset by "curl -L" when the
# redirection is not required.
#
# Anything else is considered an error.
#
# See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
{ grep -qE "^(1[0-9][0-9]|2[0-9][0-9]|3[0-9][0-9]|405)" <<< "$status"; ret=$?; } || true
[ "$ret" -eq 0 ] && continue
if grep -q '^4' <<< "$status"; then
case "$status" in
# Awkward: these codes signify that the URL is
# valid, but we can't check them:
#
# 401: Unauthorized (need to login to the site).
# 402: Payment Required.
# 403: Forbidden (possibley the same as 401).
#
# If they did not exist, we'd get a 404, so since
# they have been "semi validated" by the server by
# simply returning these codes, we'll assume they
# are valid.
401|402|403) success='true' ;;
esac
# Client error: most likely the document isn't valid
# or the server won't give us access, so there is no
# point trying other user agents [*].
# ---
# [*] - we make the assumption that the server is not
# returning this error code _based_ on the UA
# presented of course, which theoretically it _could_.
break 2
else
fail_count+=1
echo "$url" >> "$invalid_file"
errors+=("found HTTP error status codes for URL $url (status: '$status', user agent: '$user_agent')")
fi
done
[ "$fail_count" -eq 0 ] && success='true' && break
done
[ "$success" = 'true' ] && return 0
die "failed to check URL '$url': errors: '${errors[*]}'"
}
# Perform basic checks on documentation files
static_check_docs()
{
local cmd="xurls"
if [ ! "$(command -v $cmd)" ]
then
info "Installing $cmd utility"
local version
local url
version=$(get_test_version "externals.xurls.version")
url=$(get_test_version "externals.xurls.url")
# xurls is very fussy about how it's built.
go install "${url}@${version}"
command -v xurls &>/dev/null ||
die 'xurls not found. Ensure that "$GOPATH/bin" is in your $PATH'
fi
info "Checking documentation"
local doc
local all_docs
local docs
local docs_status
local new_docs
local new_urls
local url
all_docs=$(git ls-files "*.md" | grep -Ev "(grpc-rs|target)/" | sort || true)
all_docs=$(skip_paths "${all_docs[@]}")
if [ "$specific_branch" = "true" ]
then
info "Checking all documents in $branch branch"
docs="$all_docs"
else
info "Checking local branch for changed documents only"
docs_status=$(get_pr_changed_file_details || true)
docs_status=$(echo "$docs_status" | grep "\.md$" || true)
docs=$(echo "$docs_status" | awk '{print $NF}' | sort)
docs=$(skip_paths "${docs[@]}")
# Newly-added docs
new_docs=$(echo "$docs_status" | awk '/^A/ {print $NF}' | sort)
new_docs=$(skip_paths "${new_docs[@]}")
for doc in $new_docs
do
# A new document file has been added. If that new doc
# file is referenced by any files on this PR, checking
# its URL will fail since the PR hasn't been merged
# yet. We could construct the URL based on the users
# original PR branch and validate that. But it's
# simpler to just construct the URL that the "pending
# document" *will* result in when the PR has landed
# and then check docs for that new URL and exclude
# them from the real URL check.
url="https://${repo}/blob/${branch}/${doc}"
new_urls+=" ${url}"
done
fi
[ -z "$docs" ] && info "No documentation to check" && return
local urls
local url_map=$(mktemp)
local invalid_urls=$(mktemp)
local md_links=$(mktemp)
files_to_remove+=("${url_map}" "${invalid_urls}" "${md_links}")
info "Checking document markdown references"
local md_docs_to_check
# All markdown docs are checked (not just those changed by a PR). This
# is necessary to guarantee that all docs are referenced.
md_docs_to_check="$all_docs"
(cd "${tests_repo_dir}" && make check-markdown)
command -v kata-check-markdown &>/dev/null || \
die 'kata-check-markdown command not found. Ensure that "$GOPATH/bin" is in your $PATH.'
for doc in $md_docs_to_check
do
kata-check-markdown check "$doc"
# Get a link of all other markdown files this doc references
kata-check-markdown list links --format tsv --no-header "$doc" |\
grep "external-link" |\
awk '{print $3}' |\
sort -u >> "$md_links"
done
# clean the list of links
local tmp
tmp=$(mktemp)
sort -u "$md_links" > "$tmp"
mv "$tmp" "$md_links"
# A list of markdown files that do not have to be referenced by any
# other markdown file.
exclude_doc_regexs+=()
exclude_doc_regexs+=(^CODE_OF_CONDUCT\.md$)
exclude_doc_regexs+=(^CONTRIBUTING\.md$)
# Magic github template files
exclude_doc_regexs+=(^\.github/.*\.md$)
# The top level README doesn't need to be referenced by any other
# since it displayed by default when visiting the repo.
exclude_doc_regexs+=(^README\.md$)
# Exclude READMEs for tools for static checks migration
exclude_doc_regexs+=(^\tests/cmd/.*/README\.md$)
local exclude_pattern
# Convert the list of files into an egrep(1) alternation pattern.
exclude_pattern=$(echo "${exclude_doc_regexs[@]}"|sed 's, ,|,g')
# Every document in the repo (except a small handful of exceptions)
# should be referenced by another document.
for doc in $md_docs_to_check
do
# Check the ignore list for markdown files that do not need to
# be referenced by others.
echo "$doc"|egrep -q "(${exclude_pattern})" && continue
grep -q "$doc" "$md_links" || die "Document $doc is not referenced"
done
info "Checking document code blocks"
local doc_to_script_cmd="${cidir}/kata-doc-to-script.sh"
for doc in $docs
do
bash "${doc_to_script_cmd}" -csv "$doc"
# Look for URLs in the document
urls=$("${doc_to_script_cmd}" -i "$doc" - | "$cmd")
# Gather URLs
for url in $urls
do
printf "%s\t%s\n" "${url}" "${doc}" >> "$url_map"
done
done
# Get unique list of URLs
urls=$(awk '{print $1}' "$url_map" | sort -u)
info "Checking all document URLs"
local invalid_urls_dir=$(mktemp -d)
files_to_remove+=("${invalid_urls_dir}")
for url in $urls
do
if [ "$specific_branch" != "true" ]
then
# If the URL is new on this PR, it cannot be checked.
echo "$new_urls" | egrep -q "\<${url}\>" && \
info "ignoring new (but correct) URL: $url" && continue
fi
# Ignore local URLs. The only time these are used is in
# examples (meaning these URLs won't exist).
echo "$url" | grep -q "^file://" && continue
echo "$url" | grep -q "^http://localhost" && continue
# Ignore the install guide URLs that contain a shell variable
echo "$url" | grep -q "\\$" && continue
# This prefix requires the client to be logged in to github, so ignore
echo "$url" | grep -q 'https://github.com/pulls' && continue
# Sigh.
echo "$url"|grep -q 'https://example.com' && continue
# Google APIs typically require an auth token.
echo "$url"|grep -q 'https://www.googleapis.com' && continue
# Git repo URL check
if echo "$url"|grep -q '^https.*git'
then
timeout "${KATA_NET_TIMEOUT}" git ls-remote "$url" > /dev/null 2>&1 && continue
fi
# Check the URL, saving it if invalid
#
# Each URL is checked in a separate process as each unique URL
# requires us to hit the network.
check_url "$url" "$invalid_urls_dir" &
done
# Synchronisation point
wait
# Combine all the separate invalid URL files into one
local invalid_files=$(ls "$invalid_urls_dir")
if [ -n "$invalid_files" ]; then
pushd "$invalid_urls_dir" &>/dev/null
cat $(echo "$invalid_files"|tr '\n' ' ') > "$invalid_urls"
popd &>/dev/null
fi
if [ -s "$invalid_urls" ]
then
local files
sort -u "$invalid_urls" | while read -r url
do
files=$(grep "^${url}" "$url_map" | awk '{print $2}' | sort -u)
echo >&2 -e "ERROR: Invalid URL '$url' found in the following files:\n"
for file in $files
do
echo >&2 "$file"
done
done
exit 1
fi
# Now, spell check the docs
cmd="${tests_repo_dir}/cmd/check-spelling/kata-spell-check.sh"
local docs_failed=0
for doc in $docs
do
"$cmd" check "$doc" || { info "spell check failed for document $doc" && docs_failed=1; }
static_check_eof "$doc"
done
[ $docs_failed -eq 0 ] || die "spell check failed, See https://github.com/kata-containers/kata-containers/blob/main/docs/Documentation-Requirements.md#spelling for more information."
}
static_check_eof()
{
local file="$1"
local anchor="EOF"
[ -z "$file" ] && info "No files to check" && return
# Skip the itself
[ "$file" == "$script_name" ] && return
# Skip the Vagrantfile
[ "$file" == "Vagrantfile" ] && return
local invalid=$(cat "$file" |\
egrep -o '<<-* *\w*' |\
sed -e 's/^<<-*//g' |\
tr -d ' ' |\
sort -u |\
egrep -v '^$' |\
egrep -v "$anchor" || true)
[ -z "$invalid" ] || die "Expected '$anchor' here anchor, in $file found: $invalid"
}
# Tests to apply to all files.
#
# Currently just looks for TODO/FIXME comments that should be converted to
# (or annotated with) an Issue URL.
static_check_files()
{
local file
local files
if [ "$force" = "false" ]
then
info "Skipping check_files: see https://github.com/kata-containers/tests/issues/469"
return
else
info "Force override of check_files skip"
fi
info "Checking files"
if [ "$specific_branch" = "true" ]
then
info "Checking all files in $branch branch"
files=$(git ls-files | egrep -v "/(.git|vendor|grpc-rs|target)/" || true)
else
info "Checking local branch for changed files only"
files=$(get_pr_changed_file_details || true)
# Strip off status
files=$(echo "$files"|awk '{print $NF}')
fi
[ -z "$files" ] && info "No files changed" && return
local matches=""
for file in $files
do
local match
# Look for files containing the specified comment tags but
# which do not include a github URL.
match=$(egrep -H "\<FIXME\>|\<TODO\>" "$file" |\
grep -v "https://github.com/.*/issues/[0-9]" |\
cut -d: -f1 |\
sort -u || true)
[ -z "$match" ] && continue
# Don't fail if this script contains the patterns
# (as it is guaranteed to ;)
echo "$file" | grep -q "${script_name}$" && info "Ignoring special file $file" && continue
# We really only care about comments in code. But to avoid
# having to hard-code the list of file extensions to search,
# invert the problem by simply ignoring document files and
# considering all other file types.
echo "$file" | grep -q ".md$" && info "Ignoring comment tag in document $file" && continue
matches+=" $match"
done
[ -z "$matches" ] && return
echo >&2 -n \