Skip to content

Instantly share code, notes, and snippets.

@rstriquer
Last active August 4, 2022 07:47
Show Gist options
  • Save rstriquer/38b076d95130920bcad0c01df4e718d6 to your computer and use it in GitHub Desktop.
Save rstriquer/38b076d95130920bcad0c01df4e718d6 to your computer and use it in GitHub Desktop.
Git command automation shell

Script for git command automation

Script to automate git day-to-day and validate of Pull Request code.

It presented some inconsistencies when used on windows (I had some problems, mainly with the command git stash).

For Linux it seems to be very functional, regardless of the installation.

It does not let you execute commands if you are in the middle of the merge. E. g., let's say you were doing a complicated merge and went out for lunch, then you came back and try to run it with an update, it won't let you do that and will tell you need to get yourself togehter beforehand you go on.

Analyze

Use "--analyse-branch" parameter for PR analysis

It validates PHP files, for Java, XML and SQL files validations check the md.java.sh file.

Just download and set the current branch to the PR branch and run the script in the project's root directory with this command. It uses PHPMD and "php -l" to validate the files. It greatly speeds up code validation for simpler errors and general recommendations for improvements according PSRs and other community recommendations, etc.

For the analyze and analyze-branch to work phpmd must be installed in the shell and must return something in "command -v phpmd" on you operation system shell.

Commit

It can also be used to checkout files before commit'em

Just stage the files yout want to commit and before commit'em run the script with "--check" parameter. It validates the staged files only. If everything is ok them you are free to conclude the commit. This is good, especially when yout end up making big commits.

Update

To update the current branch, run the "--update" parameter. It completely stashs the changes (including untracked files), changes the branch to master, pushes and fetches everything, returns to the original branch and merges it with master. If there is an inconsistency in any moment (like when you create a local file with the same name of a remote newly created) it notifies what happened and quit the execution.

In addition

If you have feedbacks about the script I am happy to receive them.

If you want to contribute to the "project" (or fork it kkkk) I'm also happy.

#!/bin/bash
# repositório interessante para GIT: https://gist.github.com/kelvinst/331aff32508e2517afbd
# Actual operating branch name
BRANCH_ATUAL="";
# saves stash name if some stash are created during workflow
STASH="";
# autorized utf8 mime types
AUTHORIZED_MIMES=("us-ascii" "utf-8" "ASCII" "text/plain")
GIT=$(command -v git)
if [ -z "$GIT" ]; then
message "You do not have GIT installed"
exit 1
fi
usage()
{
cat << EO
Usage: $PROGNAME --check
$PROGNAME --update
$PROGNAME --help
Automatiza procedimentos no git
Options:
EO
cat <<EO | column -s\& -t
-h | --help & show this output
-c | --check & Checa se os arquivos em stage possuem algum erro de sintaxe
-u | --update & Realiza o update do master e o merge do branch atual, caso não esteja no master
-a | --analyze & Analyzes the code structure to check out if file is ok can't be used in conjunction with "analyze-branch"
--pr-changes & Show PR changes on local actual branch compared to local master
--analyze-branch & Used instead of "analyze", makes the script check the diferencies into the used branch agains the main branch
--full-validation & Validade all options of the phpms script into the changed file
EO
}
QUIT_ON_MERGE() {
git merge HEAD &> /dev/null
result=$?
if [ $result -ne 0 ]
then
echo "Merge em execução, favor concluir ou decartar para continuar"
echo "Caso deseje descartar o procedimento realizar o comando: git merge --abort"
exit
fi
}
QUIT_ON_STAGED() {
git diff --cached --quiet &> /dev/null
result=$?
if [ $result -ne 0 ]
then
echo "Código em stage, favor concluir o commit."
echo "Caso deseje retirar os códigos de stage realizar o comando: git reset HEAD <file>"
exit
fi
}
GET_BRANCH_ATUAL() {
BRANCH_ATUAL=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`;
}
PULL_REMOTE() {
local BRANCH_NAME=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`,
DO_PULL="no";
if [ "$BRANCH_NAME" == "master" ]; then
DO_PULL="yes";
else
# Verifica se o branch atual tem uma contra-partida remota
git ls-remote --heads --exit-code origin $BRANCH_ATUAL &> /dev/null
if [ $? -eq 0 ]; then
DO_PULL="yes";
fi
fi
if [ "$DO_PULL" == "no" ]; then
echo "===================================> Branch local/"$BRANCH_NAME" apenas local, seguindo para update do master";
else
echo "===================================> Sincronizando local/"$BRANCH_NAME" com origin/"$BRANCH_NAME;
# - Implementar "git pull origin branchOnRemote" para evitar erros de estrutura. ex: "git pull origin dev/1.4" onde "dev/1.4"
# é um branch no repositório remoto e origin é o repositório remoto.
# - Antes de realizar o pull tem que validar se o branch está no origin, se não estiver tem que pular par ao outro passo
# - Adicionar o --rebase
git pull ;
if [ "$BRANCH_NAME" == "master" ]; then
git fetch -pt;
fi
fi
}
QUIT_ON_CONFLICTS() {
if [ "`git ls-files -m`" != "" ];
then
echo "===================================> Conflito identificado!";
echo "Favor resolver os conflitos e realizar novamente o procedimento \"git.sh -u\" novamente";
if [ "$STASH" != "" ];
then
echo "IMPORTANTE! Não esqueça de restaurar as modificações não comitadas que estão no stash apontado abaixo após concluir o outro processo do \"git.sh -u\"";
git stash list | head -n1
fi
exit;
fi
}
VALID_UTF8_FILE() {
FILE_ENCODING=$(file -b --mime-encoding $file)
if [[ ! " ${AUTHORIZED_MIMES[@]} " =~ " ${FILE_ENCODING} " ]]; then
let errors_md++
echo -e "\tWARNONG: ==> NOT valid utf8 - encoding <== : $FILE_ENCODING - arquivo: $file"
fi
}
# Transform long options to short ones
for arg in "$@"; do
shift
case "$arg" in
"--update") set -- "$@" "-u" ;;
"--analyze") set -- "$@" "-a" ;;
"--help") set -- "$@" "-h" ;;
*) set -- "$@" "$arg"
esac
done
ARGS=$(getopt -s bash --options h,a,u --longoptions update,analyze,help,full-validation,analyze-branch,pr-changes,no-unit-test, -q -- "$@" )
eval set -- "$ARGS"
SUBACTION="none"
while true; do
case $1 in
--help)
usage
exit 0
;;
-a|--analyze)
if [ "$ACTION" != "" ]; then
echo $ACTION" can't be used with \"--analyze\" or \"-a\" option";
exit
fi
ACTION="analyze"
;;
--analyze-branch)
if [ "$ACTION" != "" ]; then
echo $ACTION" can't be used with \"--analyze\" or \"-a\" option";
exit
fi
ACTION="analyze-branch"
;;
-u|--update)
ACTION="update"
;;
--checkout)
ACTION="checkout"
BRANCH_TO=$2;
;;
--full-validation)
SUBACTION="full-validation"
;;
--no-unit-test)
SUBACTION="no-unit-test"
;;
--pr-changes)
ACTION="pr-changes"
;;
--)
shift
break
;;
*)
shift
break
;;
esac
shift
done
if [ "$ACTION" == "" ]; then
usage
echo
echo " Nenhum parametro identificado, favor tentar novamente";
exit 0
fi
if [ "$ACTION" == "pr-changes" ]; then
git log --oneline HEAD ^master
git diff --stat HEAD ^master
fi
if [ "$ACTION" == "checkout" ]; then
QUIT_ON_MERGE;
QUIT_ON_STAGED;
GET_BRANCH_ATUAL;
echo "===================================> Salvando alteracoes locais no stash";
STASH=`git stash --include-untracked`;
echo "===================================> Checking out to "$BRANCH_TO;
git checkout $BRANCH_TO
fi
if [ "$ACTION" == "analyze" ] || [ "$ACTION" == "analyze-branch" ]; then
PHP=$(command -v php)
if [ -z "$PHP" ]; then
message "You do not have PHP installed"
exit 1
fi
PHPMD=$(command -v phpmd)
if [ -z "$PHPMD" ]; then
message "You do not have \"phpmd\" (PHP Mess Detector) installed"
exit 1
fi
if [ "$ACTION" == "analyze-branch" ]; then
GET_BRANCH_ATUAL;
echo "Analisando branch "$BRANCH_ATUAL
files=`git diff --name-only $BRANCH_ATUAL $(git merge-base $BRANCH_ATUAL master)`
else
files=`git diff --cached --name-only`
fi
# quantidade de elementos encontrados no branch/stage
counter=0
erros=0;
errors_md=0
errors_code=0;
for file in $files
do
let counter++
if [ -f "$file" ]; then
VALID_UTF8_FILE
if [[ ${file##*.} == "sql" ]]; then
FILE_ENCODING=$(file -b --mime-encoding $file)
# implementar o uso do queryReview
# (cd ~/src/projeto.me/bin ; java queryReview $PWD_PROJETO/$file)
# echo
elif [[ ${file##*.} == "css" ]]; then
# use try to use w3c-validator-runner https://github.com/ysangkok/w3c-validator-runner
# or http://validator.nu/ with script http://about.validator.nu/html5check.py as described here https://about.validator.nu/#alt-input
echo "CSS file!"
elif [[ ${file##*.} == "json" ]]; then
# use jsonlint
echo "Json file!"
elif [[ ${file##*.} == "java" ]] && [[ $file != "*Test.java" ]]; then
echo "Arquivo JAVA"
exit
# https://pmd.github.io/latest/pmd_rules_java.html
pmd_marks=$(~/app/pmd-bin-6.25.0/bin/run.sh pmd -d $file -R ~/src/projeto.me/bin/codeReview.xml 2> /dev/null)
#pmd_marks=$(~/app/pmd-bin-6.25.0/bin/run.sh pmd -d $file -R rulesets/java/quickstart.xml 2> /dev/null)
if [ ! -z "$pmd_marks" ]; then
let errors_md++
echo $file
while IFS= read -r line
do
IFS=':'; line=($line); unset IFS;
echo -e "\t"${line[2]}": "${line[3]}
done <<< "$pmd_marks"
fi
# tentativa de avaliar apenas partes do arquivos que foram alteradas e não uma análise do arquivo como um todo.
# O que pode ser identificado neste bloco:
# READ_UNCOMMITED não é suportado pelo Oracle
#FILE_DIFF=$(git diff $BRANCH_TRUNK $file | tail -n +6 | grep -P "^\+(.*)$")
#for line in $FILE_DIFF
#do
#echo $line
# if [[ $line =~ " class " ]]; then
# echo $file
# echo -e "\t - \"$line\""
# fi
#done
elif [[ ${file##*.} == "php" ]]; then
if ! php -l $file &> /dev/null; then
echo "Erro PHP identificado no arquivo: " $file
php -l $file
exit;
let errors_code++
fi
echo
echo "Calculando phpmd de "$file
if ! phpmd $file text unusedcode &> /dev/null; then
echo '--> unusedcode'
phpmd $file text unusedcode
let errors_md++
fi
if [ "$ACTION" == "analyze-branch" ]; then
acao="A"
else
acao=(`git diff --cached --name-status $file`)
fi
acao=${acao[0]}
if [ "$acao" == "A" ] || [ "$SUBACTION" == "full-validation" ]; then
if ! phpmd $file text cleancode &> /dev/null; then
echo '--> cleancode'
phpmd $file text cleancode
let errors_md++
fi
if ! phpmd $file text codesize &> /dev/null; then
echo '--> codesize'
phpmd $file text codesize
let errors_md++
fi
if ! phpmd $file text controversial &> /dev/null; then
echo '--> controversial'
phpmd $file text controversial
let errors_md++
fi
if ! phpmd $file text design &> /dev/null; then
echo '--> design'
phpmd $file text design
let errors_md++
fi
if ! phpmd $file text naming &> /dev/null; then
echo '--> naming'
phpmd $file text naming
let errors_md++
fi
fi
fi
fi
done
if [ $counter -eq 0 ];
then
echo "Nenhum arquivo em stage";
else
errors=$((errors_md+errors_code))
echo
echo 'Resultado final --------------------------------------------'
if [ "$errors" -gt 0 ];
then
echo 'Resultado final'
echo "Total de "$errors_code" de "$counter" arquivos com erro de sintaxe!"
if [ "$SUBACTION" != "analyze-full" ]; then
echo "Total de "$errors_md" de "$counter" arquivos com avisos do mess detector!"
fi
else
echo "Total de "$counter" arquivos avaliados, nenhum erro encontrado!"
echo "Se possível, para concluir a análise, execute Testes Unitários"
fi
if [ "$SUBACTION" != "no-unit-test" ] && [ -x ./vendor/bin/phpunit ];
then
php -dmemory_limit=2048M vendor/bin/phpunit -c phpunit.xml
fi
fi
exit;
fi
if [ "$ACTION" == "update" ]; then
QUIT_ON_MERGE;
QUIT_ON_STAGED;
GET_BRANCH_ATUAL;
if [ "`git ls-files -m`" != "" ];
then
echo "===================================> Identificado alterações nos seguintes arquivos. Salvando no stash";
git ls-files -m
STASH=`git stash --include-untracked`;
fi
# Sincroniza o branch atual
PULL_REMOTE;
if [ "$BRANCH_ATUAL" != "master" ];
then
QUIT_ON_CONFLICTS;
git checkout master;
# sincroniza o branch master
PULL_REMOTE;
echo "===================================> Realizando update do local/"$BRANCH_ATUAL" com o conteúdo do local/master";
git checkout $BRANCH_ATUAL ;
# =========================================== @todo neste merge pode ser checado se o rep está online, se ele existir apenas no local então podemos fazer um rebase
git merge master
files=`git diff --name-only --cached --name-only`
if [ "$files" != "" ];
then
echo "===================================> Erro do merge master! O merge precisa de sua atenção! Para cancelar merge execute: git merge --abort"
if [ "$STASH" != "" ];
then
echo "IMPORTANTE! Não esqueça de restaurar as modificações não comitadas que estão no stash apontado abaixo";
git stash list | head -n1
fi
fi
fi
echo "===================================> Update concluído!"
if [ "$STASH" != "" ] && [ "$files" == "" ];
then
echo "===================================> Resgatando stash";
# - Uma opção é utilizar o "git stash show -p | git apply" pois no windows,
# utilizando o "git pull --rebase origin <branch>" ele acabava gerando erro ao utilizar
# o pop
git stash pop
echo "===================================> Situacao atual do repositório";
git status
fi
exit;
fi
#!/usr/bin/bash
# script para primeiro estudo de Code Review em java
# @todo
# - ignorar arquivos no diretórios PT que possuam o conteúdo @javax.annotation.Generated(value = "class br.com.api.gen.Generator$1")
# - ignorar arquivos no diretórios PT que possuam o conteúdo @Generated(value = "class br.com.api.gen.Generator$1")
usage()
{
cat << EO
Usage: $PROGNAME [project] [branchName]
$PROGNAME --help
Automatiza code review
Options:
EO
cat <<EO | column -s\& -t
-h | --help & show this output
EO
}
GET_BRANCH_ATUAL() {
BRANCH_ATUAL=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`;
}
if [ -z "$1" ]; then
usage
exit 0;
fi
PROJECTS=("analytics" "crypto-api" "access-control" "template")
AUTHORIZED_MIMES=("us-ascii" "utf-8" "ASCII")
PROJECT=$1
BRANCH_ATUAL=$2 # Branch a ser avaliado
BRANCH_TRUNK=$3 # Branch destino do PR. Padrão é o master
PWD_ORIGINAL=$(pwd)
PWD_PROJETO=~/src/projeto.me/$PROJECT
if [[ -z "$BRANCH_TRUNK" ]]; then
BRANCH_TRUNK="master"
fi
if [[ ! " ${PROJECTS[@]} " =~ " ${PROJECT} " ]]; then
usage
echo ""
echo -e "\tProblemas encontrados:"
echo -e "\t\t - Projeto não existente";
exit 0;
fi
cd ~/src/projeto.me
echo ""
echo "(codeReview) Preparando ambiente para análise de branch"
if [[ ! -d $1 ]]; then
git clone http://sample%40mail.com@domain.com:port/scm/project/$1.git
fi
cd $PWD_PROJETO
echo "(codeReview) Realizando pull do $BRANCH_TRUNK"
if [[ "$BRANCH_TRUNK" == "master" ]]; then
git checkout master
git fetch -pt
git pull
else
git checkout -t origin/$BRANCH_TRUNK
if [[ -z $(git branch --list $BRANCH_TRUNK) ]]; then
git checkout -t origin/$BRANCH_TRUNK
else
git checkout $BRANCH_TRUNK
git pull
fi
fi
if [[ -z $(git branch --list $BRANCH_ATUAL) ]]; then
git checkout -t origin/$BRANCH_ATUAL
else
git checkout $BRANCH_ATUAL
git pull
fi
echo ""
echo "(codeReview) Avaliando diff entre \"$BRANCH_ATUAL\" e \"$BRANCH_TRUNK\" e identificando arquivos a serem considerados"
files=`git diff --name-only $BRANCH_ATUAL $(git merge-base $BRANCH_ATUAL $BRANCH_TRUNK)`
#files=`find -name \*.java`
counter=0
erros=0;
errors_md=0
errors_code=0;
echo ""
echo "(codeReview) Iniciando avaliação arquivo-a-arquivo"
echo "--------------------------------------------------------------------------------------"
#files=("src/main/java/br/com/proposal/evaluation/controller/ProposalController.java")
#files=("src/main/java/br/com/proposal/evaluation/controller/ProposalController.java" "src/main/java/br/com/proposal/evaluation/controller/ProposalControllerTest.java")
for file in $files
do
if [ -f "$file" ]; then
if [[ ${file##*.} == "sql" ]]; then
let counter++
FILE_ENCODING=$(file -b --mime-encoding $file)
echo $file
if [[ ! " ${AUTHORIZED_MIMES[@]} " =~ " ${FILE_ENCODING} " ]]; then
let errors_md++
echo -e "\tNOT valid utf8 - encoding: $FILE_ENCODING - arquivo: $file"
fi
(cd ~/src/projeto.me/bin ; java queryReview $PWD_PROJETO/$file)
echo
elif [[ ${file##*.} == "json" ]]; then
let counter++
FILE_ENCODING=$(file -b --mime-encoding $file)
if [[ ! " ${AUTHORIZED_MIMES[@]} " =~ " ${FILE_ENCODING} " ]]; then
let errors_md++
echo -e "\tNOT valid utf8 - encoding: $FILE_ENCODING - arquivo: $file"
fi
elif [[ ${file##*.} == "java" ]] && [[ $file != "*Test.java" ]]; then
let counter++
FILE_ENCODING=$(file -b --mime-encoding $file)
if [[ ! " ${AUTHORIZED_MIMES[@]} " =~ " ${FILE_ENCODING} " ]]; then
let errors_md++
echo -e "\tNOT valid utf8 - encoding: $FILE_ENCODING - arquivo: $file"
fi
# https://pmd.github.io/latest/pmd_rules_java.html
pmd_marks=$(~/app/pmd-bin-6.25.0/bin/run.sh pmd -d $file -R ~/src/projeto.me/bin/md.java.xml 2> /dev/null)
#pmd_marks=$(~/app/pmd-bin-6.25.0/bin/run.sh pmd -d $file -R rulesets/java/quickstart.xml 2> /dev/null)
if [ ! -z "$pmd_marks" ]; then
let errors_md++
echo $file
while IFS= read -r line
do
IFS=':'; line=($line); unset IFS;
echo -e "\t"${line[2]}": "${line[3]}
done <<< "$pmd_marks"
fi
# tentativa de avaliar apenas partes do arquivos que foram alteradas e não uma análise do arquivo como um todo.
# O que pode ser identificado neste bloco:
# READ_UNCOMMITED não é suportado pelo Oracle
#FILE_DIFF=$(git diff $BRANCH_TRUNK $file | tail -n +6 | grep -P "^\+(.*)$")
#for line in $FILE_DIFF
#do
#echo $line
# if [[ $line =~ " class " ]]; then
# echo $file
# echo -e "\t - \"$line\""
# fi
#done
else
let counter++
FILE_ENCODING=$(file -b --mime-encoding $file)
if [[ ! " ${AUTHORIZED_MIMES[@]} " =~ " ${FILE_ENCODING} " ]]; then
let errors_md++
echo $file
echo -e "\tNOT valid utf8 - encoding: $FILE_ENCODING - arquivo: $file"
fi
fi
fi
done
echo "Encontrados $errors_md em $counter arquivos validados"
cd $PWD_ORIGINAL
<?xml version="1.0"?>
<ruleset name="Custom Rules"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
My custom rules
</description>
<rule ref="category/java/errorprone.xml/DetachedTestCase" />
<rule ref="category/java/errorprone.xml/JUnitSpelling" />
<rule ref="category/java/errorprone.xml/JUnitStaticSuite" />
<rule ref="category/java/errorprone.xml/UnnecessaryBooleanAssertion" />
<rule ref="category/java/bestpractices.xml/LiteralsFirstInComparisons" />
<rule ref="category/java/bestpractices.xml/LooseCoupling" />
<rule ref="category/java/bestpractices.xml/AbstractClassWithoutAbstractMethod" />
<rule ref="category/java/bestpractices.xml/ArrayIsStoredDirectly" />
<rule ref="category/java/bestpractices.xml/AvoidPrintStackTrace" />
<rule ref="category/java/bestpractices.xml/AvoidReassigningLoopVariables" />
<rule ref="category/java/bestpractices.xml/AvoidStringBufferField" />
<rule ref="category/java/bestpractices.xml/AvoidUsingHardCodedIP" />
<rule ref="category/java/bestpractices.xml/ConstantsInInterface" />
<rule ref="category/java/bestpractices.xml/DefaultLabelNotLastInSwitchStmt" />
<rule ref="category/java/bestpractices.xml/ForLoopCanBeForeach" />
<rule ref="category/java/bestpractices.xml/MethodReturnsInternalArray" />
<rule ref="category/java/bestpractices.xml/MissingOverride" />
<rule ref="category/java/bestpractices.xml/PreserveStackTrace" />
<rule ref="category/java/bestpractices.xml/ReplaceHashtableWithMap" />
<rule ref="category/java/bestpractices.xml/ReplaceVectorWithList" />
<rule ref="category/java/bestpractices.xml/SwitchStmtsShouldHaveDefault" />
<rule ref="category/java/bestpractices.xml/SystemPrintln" />
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter" />
<rule ref="category/java/bestpractices.xml/UnusedImports" />
<rule ref="category/java/bestpractices.xml/UnusedLocalVariable" />
<rule ref="category/java/bestpractices.xml/UseCollectionIsEmpty" />
<rule ref="category/java/bestpractices.xml/WhileLoopWithLiteralBoolean" />
<!-- rule ref="category/java/bestpractices.xml/UnusedPrivateField" /-->
<rule ref="category/java/bestpractices.xml/UnusedPrivateField">
<properties>
<property name="ignoredAnnotations" value="lombok.Setter|lombok.Getter|lombok.Builder|lombok.Data|lombok.RequiredArgsConstructor|lombok.AllArgsConstructor|lombok.Value|lombok.NoArgsConstructor|java.lang.Deprecated|javafx.fxml.FXML|lombok.experimental.Delegate" />
</properties>
</rule>
<rule ref="category/java/codestyle.xml/AvoidProtectedFieldInFinalClass" />
<rule ref="category/java/codestyle.xml/AvoidProtectedMethodInFinalClassNotExtending" />
<rule ref="category/java/codestyle.xml/AvoidUsingNativeCode" />
<rule ref="category/java/codestyle.xml/CallSuperInConstructor" />
<rule ref="category/java/codestyle.xml/ClassNamingConventions" />
<rule ref="category/java/codestyle.xml/ConfusingTernary">
<properties>
<property name="ignoreElseIf" value="false" />
</properties>
</rule>
<rule ref="category/java/codestyle.xml/ControlStatementBraces" />
<rule ref="category/java/codestyle.xml/DontImportJavaLang" />
<rule ref="category/java/codestyle.xml/DuplicateImports" />
<rule ref="category/java/codestyle.xml/ExtendsObject" />
<rule ref="category/java/codestyle.xml/FieldDeclarationsShouldBeAtStartOfClass" />
<rule ref="category/java/codestyle.xml/ForLoopShouldBeWhileLoop" />
<rule ref="category/java/codestyle.xml/IdenticalCatchBranches" />
<rule ref="category/java/codestyle.xml/LinguisticNaming" />
<rule ref="category/java/codestyle.xml/LongVariable">
<properties>
<property name="minimum" value="50" />
</properties>
</rule>
<rule ref="category/java/codestyle.xml/MDBAndSessionBeanNamingConvention" />
<rule ref="category/java/codestyle.xml/NoPackage" />
<rule ref="category/java/codestyle.xml/PackageCase" />
<rule ref="category/java/codestyle.xml/PrematureDeclaration" />
<rule ref="category/java/codestyle.xml/ShortClassName" />
<rule ref="category/java/codestyle.xml/ShortMethodName" />
<rule ref="category/java/codestyle.xml/ShortVariable" />
<!--
Por regra de segurança o Next recomenda o uso de import específico por
isso eliminar essa regra
rule ref="category/java/codestyle.xml/TooManyStaticImports">
<properties>
<property name="maximumStaticImports" value="4" />
</properties>
</rule -->
<rule ref="category/java/codestyle.xml/UnnecessaryCast" />
<rule ref="category/java/codestyle.xml/UnnecessaryConstructor" />
<rule ref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName" />
<rule ref="category/java/codestyle.xml/UnnecessaryLocalBeforeReturn" />
<rule ref="category/java/codestyle.xml/UnnecessaryModifier" />
<rule ref="category/java/codestyle.xml/UnnecessaryReturn" />
<rule ref="category/java/codestyle.xml/UseDiamondOperator" />
<rule ref="category/java/codestyle.xml/UselessParentheses" />
<rule ref="category/java/codestyle.xml/UselessQualifiedThis" />
<rule ref="category/java/codestyle.xml/UseShortArrayInitializer" />
<rule ref="category/java/codestyle.xml/UseUnderscoresInNumericLiterals" />
<rule ref="category/java/design.xml/AbstractClassWithoutAnyMethod" />
<rule ref="category/java/design.xml/AvoidDeeplyNestedIfStmts" />
<rule ref="category/java/design.xml/AvoidRethrowingException" />
<rule ref="category/java/design.xml/AvoidThrowingNewInstanceOfSameException" />
<rule ref="category/java/errorprone.xml/AssignmentInOperand" />
<rule ref="category/java/errorprone.xml/AssignmentToNonFinalStatic" />
<rule ref="category/java/errorprone.xml/AvoidAssertAsIdentifier" />
<rule ref="category/java/errorprone.xml/AvoidCallingFinalize" />
<rule ref="category/java/errorprone.xml/AvoidCatchingThrowable" />
<rule ref="category/java/errorprone.xml/AvoidCatchingNPE" />
<rule ref="category/java/errorprone.xml/AvoidEnumAsIdentifier" />
<rule ref="category/java/errorprone.xml/AvoidFieldNameMatchingMethodName" />
<rule ref="category/java/errorprone.xml/AvoidFieldNameMatchingTypeName" />
<rule ref="category/java/errorprone.xml/AvoidInstanceofChecksInCatchClause" />
<rule ref="category/java/errorprone.xml/AvoidMultipleUnaryOperators" />
<rule ref="category/java/errorprone.xml/AvoidUsingOctalValues" />
<rule ref="category/java/errorprone.xml/BadComparison" />
<rule ref="category/java/errorprone.xml/BrokenNullCheck" />
<rule ref="category/java/errorprone.xml/ClassCastExceptionWithToArray" />
<rule ref="category/java/errorprone.xml/CloneMethodMustBePublic" />
<rule ref="category/java/errorprone.xml/CloneMethodMustImplementCloneable" />
<rule ref="category/java/errorprone.xml/CompareObjectsWithEquals" />
<rule ref="category/java/errorprone.xml/ConstructorCallsOverridableMethod" />
<rule ref="category/java/errorprone.xml/DataflowAnomalyAnalysis" />
<rule ref="category/java/errorprone.xml/DoNotExtendJavaLangThrowable" />
<rule ref="category/java/errorprone.xml/DoNotHardCodeSDCard" />
<rule ref="category/java/errorprone.xml/DontImportSun" />
<rule ref="category/java/errorprone.xml/DontUseFloatTypeForLoopIndices" />
<rule ref="category/java/errorprone.xml/EmptyCatchBlock" />
<rule ref="category/java/errorprone.xml/EmptyFinalizer" />
<rule ref="category/java/errorprone.xml/EmptyFinallyBlock" />
<rule ref="category/java/errorprone.xml/EmptyIfStmt" />
<rule ref="category/java/errorprone.xml/EmptyInitializer" />
<rule ref="category/java/errorprone.xml/EmptyStatementBlock" />
<rule ref="category/java/errorprone.xml/EmptyStatementNotInLoop" />
<rule ref="category/java/errorprone.xml/EmptySwitchStatements" />
<rule ref="category/java/errorprone.xml/EmptySynchronizedBlock" />
<rule ref="category/java/errorprone.xml/EmptyTryBlock" />
<rule ref="category/java/errorprone.xml/EmptyWhileStmt" />
<rule ref="category/java/errorprone.xml/EqualsNull" />
<rule ref="category/java/errorprone.xml/IdempotentOperations" />
<rule ref="category/java/errorprone.xml/ImportFromSamePackage" />
<rule ref="category/java/errorprone.xml/InstantiationToGetClass" />
<rule ref="category/java/errorprone.xml/InvalidLogMessageFormat" />
<rule ref="category/java/errorprone.xml/JumbledIncrementer" />
<rule ref="category/java/errorprone.xml/MethodWithSameNameAsEnclosingClass" />
<rule ref="category/java/errorprone.xml/MisplacedNullCheck" />
<rule ref="category/java/errorprone.xml/MissingBreakInSwitch" />
<rule ref="category/java/errorprone.xml/MissingSerialVersionUID" />
<rule ref="category/java/errorprone.xml/MissingStaticMethodInNonInstantiatableClass">
<properties>
<property name="annotations" value="org.springframework.beans.factory.annotation.Autowired, javax.inject.Inject" />
</properties>
</rule>
<rule ref="category/java/errorprone.xml/MoreThanOneLogger" />
<rule ref="category/java/errorprone.xml/NonCaseLabelInSwitchStatement" />
<rule ref="category/java/errorprone.xml/NonStaticInitializer" />
<rule ref="category/java/errorprone.xml/NullAssignment" />
<rule ref="category/java/errorprone.xml/ProperCloneImplementation" />
<rule ref="category/java/errorprone.xml/ReturnEmptyArrayRatherThanNull" />
<rule ref="category/java/errorprone.xml/ReturnFromFinallyBlock" />
<rule ref="category/java/errorprone.xml/SimpleDateFormatNeedsLocale" />
<rule ref="category/java/errorprone.xml/SingleMethodSingleton" />
<rule ref="category/java/errorprone.xml/SingletonClassReturningNewInstance" />
<rule ref="category/java/errorprone.xml/StaticEJBFieldShouldBeFinal" />
<rule ref="category/java/errorprone.xml/StringBufferInstantiationWithChar" />
<rule ref="category/java/errorprone.xml/SuspiciousEqualsMethodName" />
<rule ref="category/java/errorprone.xml/SuspiciousHashcodeMethodName" />
<rule ref="category/java/errorprone.xml/SuspiciousOctalEscape" />
<rule ref="category/java/errorprone.xml/TestClassWithoutTestCases" />
<rule ref="category/java/errorprone.xml/UnconditionalIfStatement" />
<rule ref="category/java/errorprone.xml/UnnecessaryCaseChange" />
<rule ref="category/java/errorprone.xml/UnnecessaryConversionTemporary" />
<rule ref="category/java/errorprone.xml/UnusedNullCheckInEquals" />
<rule ref="category/java/errorprone.xml/UseEqualsToCompareStrings" />
<rule ref="category/java/errorprone.xml/UselessOperationOnImmutable" />
<rule ref="category/java/errorprone.xml/UseLocaleWithCaseConversions" />
<rule ref="category/java/errorprone.xml/UseProperClassLoader" />
<rule ref="category/java/multithreading.xml/AvoidSynchronizedAtMethodLevel" />
<rule ref="category/java/multithreading.xml/AvoidThreadGroup" />
<rule ref="category/java/multithreading.xml/AvoidUsingVolatile" />
<rule ref="category/java/multithreading.xml/DoNotUseThreads" />
<rule ref="category/java/multithreading.xml/DontCallThreadRun" />
<rule ref="category/java/multithreading.xml/DoubleCheckedLocking" />
<rule ref="category/java/multithreading.xml/NonThreadSafeSingleton" />
<rule ref="category/java/multithreading.xml/UseConcurrentHashMap" />
<rule ref="category/java/multithreading.xml/UseNotifyAllInsteadOfNotify" />
<rule ref="category/java/performance.xml/AddEmptyString" />
<rule ref="category/java/performance.xml/AppendCharacterWithChar" />
<rule ref="category/java/performance.xml/AvoidArrayLoops" />
<rule ref="category/java/performance.xml/AvoidCalendarDateCreation" />
<rule ref="category/java/performance.xml/AvoidFileStream" />
<rule ref="category/java/performance.xml/AvoidInstantiatingObjectsInLoops" />
<rule ref="category/java/performance.xml/AvoidUsingShortType" />
<rule ref="category/java/performance.xml/BigIntegerInstantiation" />
<rule ref="category/java/performance.xml/BooleanInstantiation" />
<rule ref="category/java/performance.xml/ByteInstantiation" />
<rule ref="category/java/performance.xml/ConsecutiveAppendsShouldReuse" />
<rule ref="category/java/performance.xml/ConsecutiveLiteralAppends" />
<rule ref="category/java/performance.xml/InefficientEmptyStringCheck" />
<rule ref="category/java/performance.xml/InefficientStringBuffering" />
<rule ref="category/java/performance.xml/InsufficientStringBufferDeclaration" />
<rule ref="category/java/performance.xml/IntegerInstantiation" />
<rule ref="category/java/performance.xml/LongInstantiation" />
<rule ref="category/java/performance.xml/OptimizableToArrayCall" />
<rule ref="category/java/performance.xml/RedundantFieldInitializer" />
<rule ref="category/java/performance.xml/ShortInstantiation" />
<rule ref="category/java/performance.xml/SimplifyStartsWith" />
<rule ref="category/java/performance.xml/StringInstantiation" />
<rule ref="category/java/performance.xml/StringToString" />
<rule ref="category/java/performance.xml/TooFewBranchesForASwitchStatement" />
<rule ref="category/java/performance.xml/UnnecessaryWrapperObjectCreation" />
<rule ref="category/java/performance.xml/UseArrayListInsteadOfVector" />
<rule ref="category/java/performance.xml/UseArraysAsList" />
<rule ref="category/java/performance.xml/UseIndexOfChar" />
<rule ref="category/java/performance.xml/UseIOStreamsWithApacheCommonsFileItem" />
<rule ref="category/java/performance.xml/UselessStringValueOf" />
<rule ref="category/java/performance.xml/UseStringBufferForStringAppends" />
<rule ref="category/java/performance.xml/UseStringBufferLength" />
<rule ref="category/java/security.xml/HardCodedCryptoKey" />
<rule ref="category/java/security.xml/InsecureCryptoIv" />
</ruleset>
@rstriquer
Copy link
Author

https://pmd.github.io/pmd-6.23.0/index.html
Ferramenta interessante para análise de código dos seguintes linguagens: Apex; Ecmascript; Java; Java Server Pages; Maven POM; Modelica; PLSQL; Salesforce VisualForce; VM; XML; XSL; Scala

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment