当前位置:网站首页>Static semantic check of clang tidy in cicd

Static semantic check of clang tidy in cicd

2022-07-07 10:56:00 Taylor lance

course ;
https://hokein.github.io/clang-tools-tutorial/
Use clang-tidy First, install clang-tools
Linux Ubuntu System

sudo apt install clang-tools

After installation, you can see clang-tidy And other related tools .

clang-tidy Official documents
Next we will use clang-tidy-8 --help, Pay attention to the back

Configuration files:
  clang-tidy attempts to read configuration for each source file from a
  .clang-tidy file located in the closest parent directory of the source
  file. If any configuration options have a corresponding command-line
  option, command-line option takes precedence. The effective
  configuration can be inspected using -dump-config:

    $ clang-tidy -dump-config
    ---
    Checks:          '-*,some-check'
    WarningsAsErrors: ''
    HeaderFilterRegex: ''
    FormatStyle:     none
    User:            user
    CheckOptions:
      - key:             some-check.SomeOption
        value:           'some value'
    ...

That is, you can create a file .clang-tidy To reduce the number of -checks= option The order of .

Create a file in the folder you need to check .clang-tidy
stay .clang-tidy in

{
    
Checks: "-*,bugprone-*,cert-*,clang-analyzer-*,cppcoreguidelines-avoid-goto,cppcoreguidelines-c-copy-assignment-signature,cppcoreguidelines-interfaces-global-init,cppcoreguidelines-narrowing-conversions,cppcoreguidelines-no-malloc,cppcoreguidelines-pro-bounds-constant-array-index,cppcoreguidelines-pro-type-const-cast,cppcoreguidelines-pro-type-cstyle-cast,cppcoreguidelines-pro-type-member-init,cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-static-cast-downcast,cppcoreguidelines-pro-type-union-access,cppcoreguidelines-slicing,cppcoreguidelines-special-member-functions,google-build-*,google-default-arguments,google-explicit-constructor,google-global-names-in-headers,google-objc-*,google-readability-casting,google-readability-function-size,google-readability-namespace-comments,google-readability-todo,google-runtime-operator,hicpp-avoid-goto,hicpp-deprecated-headers,hicpp-exception-baseclass,hicpp-explicit-conversions,hicpp-function-size,hicpp-invalid-access-moved,hicpp-member-init,hicpp-move-const-arg,hicpp-multiway-paths-covered,hicpp-named-parameter,hicpp-new-delete-operators,hicpp-no-assembler,hicpp-no-malloc,hicpp-noexcept-move,hicpp-special-member-functions,hicpp-static-assert,hicpp-undelegated-constructor,hicpp-use-*,misc-*,modernize-*,-modernize-use-trailing-return-type,performance-*,readability-avoid-const-params-in-decls,readability-container-size-empty,readability-delete-null-pointer,readability-deleted-default,readability-else-after-return,readability-function-size,readability-identifier-naming,readability-inconsistent-declaration-parameter-name,readability-misleading-indentation,readability-misplaced-array-index,readability-named-parameter,readability-non-const-parameter,readability-redundant-*,readability-simplify-*,readability-static-*,readability-string-compare,readability-uniqueptr-delete-release,readability-rary-objects"
}

These are the detection rules
And then execute :

clang-tidy-8 -p ${
    PWD} -dump-config

And then run clang-tidy

clant-tidy-8 --quite -p ./ src.cpp

Note here -p Parameters , stay help That's what Li said

-p <build-path> is used to read a compile command database.

	For example, it can be a CMake build directory in which a file named
	compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
	CMake option to get this output). When no build path is specified,
	a search for compile_commands.json will be attempted through all
	parent paths of the first input file . See:
	http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
	example of setting up Clang Tooling on a source tree.

Many children's shoes have a problem :

rror while trying to load a compilation database:
Could not auto-detect compilation database from directory "./"
No compilation database found in /builds/crystal/crystal-media/ or any parent directory

It is because of the above reasons , So we went through -p To specify the compile_commands.json The location of , Official documentation

z There's another problem here , If you're using qmake, So how to use qmake Come on clang-tidy Well ?
Problem solving entrance
howtouseclangtidyinQt

Specific inspection rules :
1、readability-identifier-naming ( The rules 2.1.1)

This rule is used to check the naming rules . Under this general rule , There are also specific items to be checked key and value. such as :

  • key: readability-identifier-naming.ClassCase

    value: CamelCase

here ClassCase The description checks the name of the class ,CamelCase The style required is the naming method of the big hump . The ark involves naming rules , There are CamelCase( The name of the great hump )、camelBack( Little hump nomenclature ) and lower_case( Lowercase nomenclature ). The inspection items involved mainly include ClassCase( class )、StructCase( Structure )、TypedefCase(Typedef)、EnumCase( enumeration )、EnumConstantCase( Enumeration constants )、UnionCase( union )、NamespaceCase( Namespace )、FunctionCase( function )、VariableCase( Variable )、ConstantCase( Constant ).

2、readability-function-size

This rule is used to check the size of functions . Under the general rules , It also includes two specific inspection items .

  • key: readability-function-size.StatementThreshold

    value: 50

Check that the statements in the function do not exceed 50 strip .( Suggest 8.1.1)

  • key: readability-function-size.ParameterThreshold

    value: 5

Check that the parameters of the function do not exceed 5 individual .( Suggest 8.3.3)

3、readability-braces-around-statements

The statement must be within braces . Here are mainly statements executed after condition judgment , such as if-else, Even if there is only one sentence , It should also be in brackets .( The rules 3.6.1, The rules 3.7.1)

4、readability-magic-numbers

Devil number check .( Suggest 9.1.3)

5、misc-unused-parameters

Function parameter check is not used .

6、modernize-use-nullptr

Check the use of nullptr, instead of NULL or 0.( The rules 10.1.3)

7、modernize-replace-auto-ptr

Check that it is forbidden to use auto_ptr.( The rules 9.5.2)

8、modernize-use-noexcept

Check that no exception mechanism is used .( The rules 11.4.1)

9、modernize-use-override

Check to use override keyword .( The rules 10.1.1)

10、performance-move-const-arg

Check that it is forbidden to use std::move operation const object .( The rules 10.1.4)

11、cppcoreguidelines-pro-type-cstyle-cast

Don't use C Style conversion check .( The rules 9.3.1)

12、cppcoreguidelines-pro-type-reinterpret-cast

Don't use reinterpret_cast Check .( Suggest 9.3.2)

13、cppcoreguidelines-pro-type-const-cast

Don't use const_cast Check .( Suggest 9.3.3) author : My dear father - You know https://www.bilibili.com/read/cv5153605 Source :bilibili
The specific script is as follows :

#/bin/bash
# check code quality with clang-tidy
#crystalmedia

VERSION=debug
cd ./${CI_PROJECT_NAME}_${VERSION}
DIR_BUILD=${
    PWD}
echo PWD:${
    PWD}
ls

echo "${PROMPT}================= Check with Clang-tidy ======================"
chk_report="${DIR_BUILD}/clang-tidy-check.txt"
rm -f $chk_report
touch $chk_report
echo "${PROMPT}Report filename: $chk_report"
echo "${PROMPT}Current directory: ${
     PWD}"
echo "${PROMPT}Clang-tidy configuration:"
clang-tidy-8 -p ${DIR_BUILD} -dump-config

fifo="/tmp/$$.fifo" # a file for pipe
mkfifo $fifo # a pipe as the process queue
exec 6<>$fifo # attach fd #6 to the pipe
thread_num=8 # max processes number
count=0;

while [[ $count -lt $thread_num ]]; do
  echo >&6
  #let count=count+1
  count=$((count + 1 ))
done

fail_flag_file="./quality-failed.txt"
file_list=$(find -name '*.cpp' )
#file_list=$(find \( -path './ptz' -o -path './vcnkit' \) -prune -o -name '*.cpp' -print)
echo -e ${file_list}
for src_file in $file_list; do
  read -u6
  {
    
      if [[ $(basename $src_file) != moc_* && $(basename $src_file) != test_* && $(basename $src_file) != qrc_* && $(basename $src_file) != AES* ]]; then
          time_start=$(date +%s)
          echo "${PROMPT}Analyzing: $src_file"
          eval "clang-tidy-8 --quiet -p ./ $src_file >>$chk_report"

          [ $? -ne 0 ] && echo "FAIL" > $fail_flag_file

          time_end=$(date +%s)
          duration=$[${time_end}-${time_start}]
          if [[ ${print_job_duration} == "on" ]]; then
            echo ${PROMPT}"Task duration time: ${duration}"
          fi
          if [[ ${duration} -gt ${task_duration_limit} ]]; then
            echo ${PROMPT}"Warning: This task takes time more than ${task_duration_limit} seconds."
          fi
      fi
      # produce a cook
      echo >&6
  }&
done
wait
exec 6>&-
rm $fifo

if  [ -f $fail_flag_file ];then
    CHECK_PASS=NO
else
    CHECK_PASS=YES
fi


# check report
[ $(cat $chk_report | wc -l) -gt 0 ] && CHECK_PASS=NO

echo "${PROMPT}=================== Clang-tidy Report ========================"
cat $chk_report
echo "${PROMPT}=============================================================="

#cp $chk_report ${DIR_BUILD}/*check.txt ${DIR_BUILD}/
#cp ${DIR_BUILD}/compile_commands.json ../compile_commands.json

# exit
if [ "#$CHECK_PASS" = "#NO" ]; then
    exit 1;
    echo ${PROMPT}Cod Quality check failed.
fi
exit 0

clang-tidy Static semantic check , install 、 Use 、 Inspection item annotation

So let's see clang And LLVM The difference and connection between
LLVM And Clang Overview and relationship of

In simple terms, let you understand what is LLVM

 Insert picture description here
One more clang-format
.clang-format

# Installation:
# sudo apt install clang-format-8
# Reference:
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
# Clang-format understands also special comments that switch formatting in a
# delimited range. The code between a comment:
# '// clang-format off' or '/* clang-format off */' up to a comment
# '// clang-format on' or '/* clang-format on */' will not be formatted.
# The comments themselves will be formatted (aligned) normally.

BasedOnStyle: LLVM

Cpp11BracedListStyle: true

Language: Cpp

# Cpp03, Cpp11, Auto
Standard: Cpp14
原网站

版权声明
本文为[Taylor lance]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130622069164.html