Skip to content
Snippets Groups Projects
score.sh 2.32 KiB
Newer Older
Gauthier HEISS's avatar
Gauthier HEISS committed
#!/bin/bash

###  Bash file scorer, using shellcheck
###  Gauthier HEISS, 24/11/2023
###  gauthier.heiss@esiea.fr
###
###  Usage : ./score.sh [file]
###  If there is no file argument, the scorer will find recurcively all .sh and .bash files

# Clear "output.txt" file
echo "" > output.txt

# If there is no launching argument, find all files
if [[ $# -eq 0 ]]; then
    # Run shellcheck on all .sh and .bash files recursively, and append results to output.txt while preserving colors
    script -q -c "find . -type f \( -name \"*.sh\" -o -name \"*.bash\" \) ! -name \"score.sh\" -exec shellcheck --color=always {} -o all \;" output.txt
    # Count all line of codes in all .sh and .bash files recurcively, ignoring comments and empty lines
    count=$(find . -type f \( -name "*.sh" -o -name "*.bash" \) -exec grep -vE '^\s*$|^\s*#' {} \; | wc -l)
else
    if [[ -f $1 ]]; then
        # Run shellcheck only on asked file
        script -q -c "shellcheck --color=always $1 -o all" output.txt
        # Count lines in the asked file, ignoring comments and empty lines
        count=$(grep -c -vE '^\s*$|^\s*#' "$1")
    else
        echo -e "\e[31mNo such file or directory \"$1\"\e[0m"
        echo "---- Final score: ----"
        echo "0.00"
        exit
    fi
fi

# Line break
echo -e "\n"

# If there is no code, give 0 as score
if [[ ${count} == 0 ]]; then
    echo -e "\e[31mNo code to analyze. Do you have .sh or .bash files in this directory or its subdirectories?\e[0m"
    echo "---- Final score: ----"
    echo "0.00"
    exit
fi

# If there is a parsing error (which is fatal), give 0 as score
if grep -q "Parsing stopped here" output.txt; then
    echo -e "\e[31mFatal error in parsing\e[0m"
    echo "---- Final score: ----"
    echo "0.00"
    exit
fi

# Count stlye, info, warning and errors
errors=$(grep -c "31m[[:blank:]]*^cl" < output.txt)
warnings=$(grep -c "33m[[:blank:]]*^" < output.txt)
infos=$(grep -c "32m[[:blank:]]*^" < output.txt)

# Displaying errors count
echo "---- Results: ----"
echo "Lines: ${count}"
echo "Errors: ${errors}"
echo "Warnings: ${warnings}"
echo "Style: ${infos}"

# Compute score
score=$(echo "scale=2; 10 - ((5 * ${errors} + ${warnings} + ${infos}) / ${count} * 10)" | bc)

# If score is negative, set to 0
if [[ ${score} == *-* ]]; then
    score="0.00"
fi

# Show score
echo -e "\n---- Final score: ----"
echo "${score}"