From 9f8a83e492412d1c2e5dc12cf7a2fd2899563386 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Thu, 22 Jan 2026 17:31:26 -0300 Subject: [PATCH 01/19] feat(DVT-1005): corrige falsos positivos e exibe priority das violacoes CodeNarc --- Dockerfile | 23 +++- entrypoint.sh | 261 +++++++++++++++++++++++------------- testdata/aBCd32/test.groovy | 13 ++ testdata/basic.xml | 259 ++++++++++++++++++++++++++++------- testdata/test.groovy | 38 +++++- 5 files changed, 447 insertions(+), 147 deletions(-) create mode 100644 testdata/aBCd32/test.groovy diff --git a/Dockerfile b/Dockerfile index 4514f41..76de114 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,24 @@ -FROM codenarc/codenarc:3.6.0-groovy3.0.23 +# Build CodeNarc from source +FROM gradle:8.5-jdk17 AS builder + +WORKDIR /build +RUN git clone https://github.com/CodeNarc/CodeNarc.git && \ + cd CodeNarc && \ + git checkout master && \ + ./gradlew shadowJar && \ + ls -la build/libs/ + +# Runtime image +FROM eclipse-temurin:11-jre-jammy RUN DEBIAN_FRONTEND=noninteractive \ -apt-get update && \ -apt-get install --no-install-recommends -y wget git && \ -apt-get clean && rm -rf /var/lib/apt/lists/* + apt-get update && \ + apt-get install --no-install-recommends -y wget git jq && \ + apt-get clean && rm -rf /var/lib/apt/lists/* + +COPY --from=builder /build/CodeNarc/build/libs/CodeNarc-*.jar /lib/codenarc-all.jar -ENV REVIEWDOG_VERSION=v0.13.0 +ENV REVIEWDOG_VERSION=v0.20.3 SHELL ["/bin/bash", "-o", "pipefail", "-c"] RUN wget -O - -q https://raw.githubusercontent.com/reviewdog/reviewdog/master/install.sh| sh -s -- -b /usr/local/bin/ ${REVIEWDOG_VERSION} diff --git a/entrypoint.sh b/entrypoint.sh index 5d353fd..bd6ce00 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,7 +1,10 @@ #!/bin/sh set -e -CODENARC_RESULT="result.txt" +CODENARC_SARIF="result.sarif.json" +CODENARC_SARIF_LINE="result_line.sarif.json" +CODENARC_SARIF_FILE="result_file.sarif.json" +CODENARC_COMPACT="result.txt" LINE_VIOLATIONS="line_violations.txt" FILE_VIOLATIONS="file_violations.txt" VIOLATIONS_FLAG="/tmp/found_violations.txt" @@ -10,99 +13,132 @@ CHANGED_LINES_CACHE="/tmp/changed_lines.txt" CHANGED_FILES_CACHE="/tmp/changed_files.txt" cleanup_temp_files() { - rm -f "$CODENARC_RESULT" "$LINE_VIOLATIONS" "$FILE_VIOLATIONS" "$VIOLATIONS_FLAG" \ - "$ALL_DIFF" "$CHANGED_LINES_CACHE" "$CHANGED_FILES_CACHE" \ + rm -f "$CODENARC_SARIF" "$CODENARC_SARIF_LINE" "$CODENARC_SARIF_FILE" "$CODENARC_COMPACT" "$LINE_VIOLATIONS" "$FILE_VIOLATIONS" \ + "$VIOLATIONS_FLAG" "$ALL_DIFF" "$CHANGED_LINES_CACHE" "$CHANGED_FILES_CACHE" \ "${FILE_VIOLATIONS}.formatted" >/dev/null 2>&1 } trap 'cleanup_temp_files' EXIT run_codenarc() { - report="${INPUT_REPORT:-compact:stdout}" includes_arg="" - [ -n "$INPUT_SOURCE_FILES" ] && includes_arg="-includes=${INPUT_SOURCE_FILES}" echo "🔍 Executando CodeNarc..." java -jar /lib/codenarc-all.jar \ - -report="$report" \ + -report="sarif:${CODENARC_SARIF}" \ -rulesetfiles="${INPUT_RULESETFILES}" \ -basedir="." \ - $includes_arg \ - > "$CODENARC_RESULT" + $includes_arg + convert_sarif_to_compact + split_sarif_by_type + echo "" + echo "📋 Violações encontradas:" echo "" - echo "📋 Saída do CodeNarc:" - echo "" - echo "" - cat "$CODENARC_RESULT" - echo "" + cat "$CODENARC_COMPACT" echo "" } -run_reviewdog_with_config() { - input_file="$1" - efm="$2" - reporter="$3" - name="$4" - filter_mode="$5" - level="$6" - - < "$input_file" reviewdog \ - -efm="$efm" \ - -reporter="$reporter" \ - -name="$name" \ - -filter-mode="$filter_mode" \ - -fail-on-error="false" \ - -level="$level" \ - ${INPUT_REVIEWDOG_FLAGS} || true +convert_sarif_to_compact() { + if ! command -v jq >/dev/null 2>&1; then + echo "⚠️ jq não encontrado" + return + fi + + jq -r ' + .runs[0]? as $run | + ($run.tool.driver.rules // []) as $rules | + ($run.results // [])[] | + .ruleId as $ruleId | + ($rules | map(select(.id == $ruleId)) | .[0].properties.priority // 2) as $priority | + (.locations[0].physicalLocation // {}) as $loc | + ($loc.artifactLocation.uri // "unknown") as $file | + ($loc.region.startLine // null) as $line | + (.message.text // "No message") as $msg | + if $line == null then + "\($file):\($ruleId) \($msg) => Priority \($priority)" + else + "\($file):\($line):\($ruleId) \($msg) => Priority \($priority)" + end + ' "$CODENARC_SARIF" > "$CODENARC_COMPACT" 2>/dev/null || echo "" > "$CODENARC_COMPACT" } -separate_violations() { - grep -E ':[0-9]+:' "$CODENARC_RESULT" > "$LINE_VIOLATIONS" || true - grep -E ':null:|\|\|' "$CODENARC_RESULT" > "$FILE_VIOLATIONS" || true +split_sarif_by_type() { + if ! command -v jq >/dev/null 2>&1; then + return + fi + + # Line-based + jq '{ + "$schema": ."$schema", + "version": .version, + "runs": [ + .runs[0] | { + "tool": .tool, + "results": [.results[] | select(.locations[0].physicalLocation.region.startLine != null)] + } + ] + }' "$CODENARC_SARIF" > "$CODENARC_SARIF_LINE" 2>/dev/null + + # File-based + jq '{ + "$schema": ."$schema", + "version": .version, + "runs": [ + .runs[0] | { + "tool": .tool, + "results": [.results[] | select(.locations[0].physicalLocation.region.startLine == null)] + } + ] + }' "$CODENARC_SARIF" > "$CODENARC_SARIF_FILE" 2>/dev/null } run_reviewdog() { echo "📤 Enviando resultados para reviewdog..." - separate_violations - - if [ -s "$LINE_VIOLATIONS" ]; then - echo "📤 Enviando violações line-based (${INPUT_REPORTER:-github-pr-check})..." - run_reviewdog_with_config "$LINE_VIOLATIONS" "%f:%l:%m" \ - "${INPUT_REPORTER:-github-pr-check}" "codenarc" \ - "${INPUT_FILTER_MODE}" "${INPUT_LEVEL}" + if [ ! -s "$CODENARC_SARIF" ]; then + echo "⚠️ Nenhum resultado SARIF encontrado" + return fi - - if [ -s "$FILE_VIOLATIONS" ]; then - true > "${FILE_VIOLATIONS}.formatted" - while read -r violation; do - if echo "$violation" | grep -q '||'; then - echo "$violation" | sed 's/||/::/' - else - echo "$violation" | sed 's/:null:/::/' - fi - done < "$FILE_VIOLATIONS" > "${FILE_VIOLATIONS}.formatted" - - if [ "${INPUT_REPORTER}" = "local" ]; then - echo "📤 Enviando violações file-based (local)..." - run_reviewdog_with_config "${FILE_VIOLATIONS}.formatted" "%f::%m" \ - "local" "codenarc" "nofilter" "${INPUT_LEVEL}" - else - echo "📤 Enviando violações file-based (github-pr-check)..." - run_reviewdog_with_config "${FILE_VIOLATIONS}.formatted" "%f::%m" \ - "github-pr-check" "codenarc" "nofilter" "warning" - fi + + if [ "${INPUT_REPORTER}" = "local" ]; then + echo "🏠 Executando reviewdog em modo local..." + < "$CODENARC_SARIF" reviewdog \ + -f=sarif \ + -reporter="local" \ + -name="codenarc" \ + -filter-mode="${INPUT_FILTER_MODE}" \ + -level="${INPUT_LEVEL}" \ + ${INPUT_REVIEWDOG_FLAGS} || true + return fi - - # fallback se nao houver violacoes categorizadas - if [ ! -s "$LINE_VIOLATIONS" ] && [ ! -s "$FILE_VIOLATIONS" ]; then - echo "📝 Executando reviewdog padrão..." - run_reviewdog_with_config "$CODENARC_RESULT" "%f:%l:%m" \ - "${INPUT_REPORTER:-github-pr-check}" "codenarc" \ - "${INPUT_FILTER_MODE}" "${INPUT_LEVEL}" + + # line-based github-pr-review + if [ -s "$CODENARC_SARIF_LINE" ] && [ "$(jq '.runs[0].results | length' "$CODENARC_SARIF_LINE")" -gt 0 ]; then + echo "📍 Enviando violações line-based para github-pr-review..." + < "$CODENARC_SARIF_LINE" reviewdog \ + -f=sarif \ + -reporter="github-pr-review" \ + -name="codenarc" \ + -filter-mode="${INPUT_FILTER_MODE}" \ + -fail-on-error="false" \ + -level="${INPUT_LEVEL}" \ + ${INPUT_REVIEWDOG_FLAGS} || true + fi + + # file-based github-pr-check + if [ -s "$CODENARC_SARIF_FILE" ] && [ "$(jq '.runs[0].results | length' "$CODENARC_SARIF_FILE")" -gt 0 ]; then + echo "📄 Enviando violações file-based para github-pr-check..." + < "$CODENARC_SARIF_FILE" reviewdog \ + -f=sarif \ + -reporter="github-pr-check" \ + -name="codenarc" \ + -filter-mode="nofilter" \ + -fail-on-error="false" \ + -level="warning" \ + ${INPUT_REVIEWDOG_FLAGS} || true fi } @@ -159,11 +195,6 @@ build_changed_lines_cache() { done < "$ALL_DIFF" } -get_p1_count() { - p1_count=$(grep -Eo "p1=[0-9]+" "$CODENARC_RESULT" | cut -d'=' -f2 | head -1) - echo "${p1_count:-0}" -} - get_allowed_patterns() { [ -n "$INPUT_SOURCE_FILES" ] && echo "$INPUT_SOURCE_FILES" | tr ',' '\n' | sed 's/\*\*/.*/g' } @@ -171,9 +202,7 @@ get_allowed_patterns() { file_matches_patterns() { file="$1" patterns="$2" - [ -z "$patterns" ] && return 0 - for pattern in $patterns; do echo "$file" | grep -Eq "$pattern" && return 0 done @@ -188,46 +217,98 @@ is_file_changed() { grep -q "^$1$" "$CHANGED_FILES_CACHE" } +extract_p1_violations_from_sarif() { + if ! command -v jq >/dev/null 2>&1; then + grep 'Priority 1' "$CODENARC_COMPACT" 2>/dev/null || echo "" + return + fi + + jq -r ' + .runs[0]? as $run | + ($run.tool.driver.rules // []) as $rules | + ($run.results // [])[] | + .ruleId as $ruleId | + ($rules | map(select(.id == $ruleId)) | .[0].properties.priority // 2) as $priority | + select($priority == 1) | + (.locations[0].physicalLocation // {}) as $loc | + ($loc.artifactLocation.uri // "unknown") as $file | + ($loc.region.startLine // null) as $line | + (.message.text // "No message") as $msg | + if $line == null then + "\($file)::\($ruleId) \($msg)" + else + "\($file):\($line):\($ruleId) \($msg)" + end + ' "$CODENARC_SARIF" 2>/dev/null || echo "" +} + check_blocking_rules() { echo "🔎 Verificando violações bloqueantes (priority 1)..." - [ ! -f "$CODENARC_RESULT" ] && echo "❌ Resultado não encontrado" && return 1 + [ ! -f "$CODENARC_SARIF" ] && echo "❌ Resultado não encontrado" && return 1 + + p1_violations=$(extract_p1_violations_from_sarif) - p1_count=$(get_p1_count) + if [ -z "$p1_violations" ]; then + echo "✅ Nenhuma P1 detectada → merge permitido" + return 0 + fi + + p1_count=$(echo "$p1_violations" | wc -l | tr -d ' ') echo "📊 Total de P1 encontradas: $p1_count" + echo "" + echo "⛔ Violações P1:" + echo "$p1_violations" + echo "" - [ "$p1_count" -eq 0 ] && echo "✅ Nenhuma P1 detectada → merge permitido" && return 0 + if [ "${INPUT_REPORTER}" = "local" ]; then + echo "🏠 Modo local - não é possível verificar linhas alteradas" + echo "⚠️ Todas as P1s serão consideradas bloqueantes" + echo "" + echo "⛔ Violação P1 encontrada → bloqueando execução" + echo "💡 Corrija as violações antes de prosseguir." + exit 1 + fi - echo "⚠️ Verificando P1s em linhas alteradas..." + echo "⚠️ Verificando se P1s estão em linhas alteradas..." build_changed_lines_cache + if [ ! -s "$ALL_DIFF" ]; then + echo "⚠️ Não foi possível gerar diff - considerando todas as P1s como bloqueantes" + echo "" + echo "⛔ Violação P1 encontrada → bloqueando merge" + echo "💡 Corrija as violações ou use o bypass autorizado pelo coordenador." + exit 1 + fi + allowed_patterns=$(get_allowed_patterns) - [ -n "$allowed_patterns" ] && echo "🧩 Analisando apenas arquivos filtrados por INPUT_SOURCE_FILES" + [ -n "$allowed_patterns" ] && echo "🧩 Analisando apenas arquivos filtrados" echo "0" > "$VIOLATIONS_FLAG" - grep -E ':[0-9]+:|:null:|\|\|' "$CODENARC_RESULT" | while IFS=: read -r file line rest; do - if echo "$file" | grep -q '||'; then - file=$(echo "$file" | cut -d'|' -f1) - line="" - fi + echo "$p1_violations" | while IFS=: read -r file line rest; do [ -z "$file" ] && continue file_matches_patterns "$file" "$allowed_patterns" || continue - if [ -z "$line" ] || [ "$line" = "null" ]; then + if [ "$line" = "" ] || [ -z "$line" ]; then if is_file_changed "$file"; then - echo "📍 Violação file-based em arquivo alterado: $file" - echo "1" > "$VIOLATIONS_FLAG" && break + echo "⛔ Violação P1 file-based em arquivo alterado: $file" + echo " $rest" + echo "1" > "$VIOLATIONS_FLAG" + break fi elif is_line_changed "$line" "$file"; then - echo "📍 Violação em linha alterada: $file:$line" - echo "1" > "$VIOLATIONS_FLAG" && break + echo "⛔ Violação P1 em linha alterada: $file:$line" + echo " $rest" + echo "1" > "$VIOLATIONS_FLAG" + break fi done if [ "$(cat "$VIOLATIONS_FLAG")" -eq 1 ]; then - echo "⛔ P1s existem E há violações em linhas alteradas" - echo "💡 Corrija as violacoes ou use o bypass autorizado pelo coordenador." + echo "" + echo "⛔ Violação P1 encontrada em linha alterada → bloqueando merge" + echo "💡 Corrija as violações ou use o bypass autorizado pelo coordenador." exit 1 else echo "✅ P1s existem mas fora das linhas alteradas → merge permitido" diff --git a/testdata/aBCd32/test.groovy b/testdata/aBCd32/test.groovy new file mode 100644 index 0000000..c874594 --- /dev/null +++ b/testdata/aBCd32/test.groovy @@ -0,0 +1,13 @@ +package aBCd32 + +class Test { + + boolean before() { + return true + } + + boolean after() { true } + + void after() { + } +} diff --git a/testdata/basic.xml b/testdata/basic.xml index 54df9b7..1acf357 100644 --- a/testdata/basic.xml +++ b/testdata/basic.xml @@ -1,52 +1,217 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://codenarc.org/ruleset/1.0 http://codenarc.org/ruleset-schema.xsd" + xsi:noNamespaceSchemaLocation="http://codenarc.org/ruleset-schema.xsd"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testdata/test.groovy b/testdata/test.groovy index 0897f5c..0755601 100644 --- a/testdata/test.groovy +++ b/testdata/test.groovy @@ -1,13 +1,41 @@ -package test +package testdata + +import org.springframework.web.util.UriComponentsBuilder class Test { + // P1 - ForceHttps + String url = "http://example.com" + + // P1 - VerifyUriComponentsBuilderVulnerability + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("test") + boolean before() { - return true + return true // P2 - ImplicitReturnStatement + } + + boolean after() { true } // P2 - ImplicitReturnStatement + + void after() { // P2 - EmptyMethod } - boolean after() { true } + // P2 - Multiple violations + def x = new ArrayList() // P2 - ExplicitArrayListInstantiation + String msg = 'Hello ${name}' // P2 - GStringExpressionWithinString + + void testMethod() { + if (true) { // P2 - ConstantIfExpression + println "test" // P2 - PrintlnRule + } + + // P2 - AssignmentInConditional + if (x = 5) { + return + } - void after() { + // P2 - ComparisonWithSelf + if (x == x) { + return + } } -} +} \ No newline at end of file From 06b70d6117567518902d8096db3d89591e669fe9 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Thu, 22 Jan 2026 19:02:57 -0300 Subject: [PATCH 02/19] debug --- entrypoint.sh | 3 +-- testdata/test.groovy | 48 ++++++++++---------------------------------- 2 files changed, 12 insertions(+), 39 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index bd6ce00..9222695 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -316,8 +316,7 @@ check_blocking_rules() { } if [ -n "${GITHUB_WORKSPACE}" ]; then - cd "${GITHUB_WORKSPACE}/${INPUT_WORKDIR}" || exit - git config --global --add safe.directory "$GITHUB_WORKSPACE" + git config --global --add safe.directory "$GITHUB_WORKSPACE" 2>/dev/null || true fi export REVIEWDOG_GITHUB_API_TOKEN="${INPUT_GITHUB_TOKEN}" diff --git a/testdata/test.groovy b/testdata/test.groovy index 0755601..01d70d0 100644 --- a/testdata/test.groovy +++ b/testdata/test.groovy @@ -1,41 +1,15 @@ -package testdata +package com.test -import org.springframework.web.util.UriComponentsBuilder - -class Test { - - // P1 - ForceHttps - String url = "http://example.com" - - // P1 - VerifyUriComponentsBuilderVulnerability - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("test") - - boolean before() { - return true // P2 - ImplicitReturnStatement +class TestCase2 { + + void existingMethod() { + println "existing" } - - boolean after() { true } // P2 - ImplicitReturnStatement - - void after() { // P2 - EmptyMethod - } - - // P2 - Multiple violations - def x = new ArrayList() // P2 - ExplicitArrayListInstantiation - String msg = 'Hello ${name}' // P2 - GStringExpressionWithinString - - void testMethod() { - if (true) { // P2 - ConstantIfExpression - println "test" // P2 - PrintlnRule - } - - // P2 - AssignmentInConditional - if (x = 5) { - return - } - - // P2 - ComparisonWithSelf - if (x == x) { - return - } + + // ADICIONAR ESTAS LINHAS - P1 dentro do diff + String insecureUrl = "http://api.example.com" + + void callApi() { + // usar insecureUrl } } \ No newline at end of file From adddbf9de6f57ec348b08fbbf0a36f021ca21176 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 09:41:46 -0300 Subject: [PATCH 03/19] alterando de sarif para json --- Dockerfile | 20 +--- entrypoint.sh | 297 +++++++++++++++----------------------------------- 2 files changed, 92 insertions(+), 225 deletions(-) diff --git a/Dockerfile b/Dockerfile index 76de114..5cfb166 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,28 +1,16 @@ -# Build CodeNarc from source -FROM gradle:8.5-jdk17 AS builder - -WORKDIR /build -RUN git clone https://github.com/CodeNarc/CodeNarc.git && \ - cd CodeNarc && \ - git checkout master && \ - ./gradlew shadowJar && \ - ls -la build/libs/ - -# Runtime image -FROM eclipse-temurin:11-jre-jammy +FROM codenarc/codenarc:3.6.0-groovy3.0.23 RUN DEBIAN_FRONTEND=noninteractive \ apt-get update && \ apt-get install --no-install-recommends -y wget git jq && \ apt-get clean && rm -rf /var/lib/apt/lists/* -COPY --from=builder /build/CodeNarc/build/libs/CodeNarc-*.jar /lib/codenarc-all.jar - -ENV REVIEWDOG_VERSION=v0.20.3 +ENV REVIEWDOG_VERSION=v0.13.0 SHELL ["/bin/bash", "-o", "pipefail", "-c"] -RUN wget -O - -q https://raw.githubusercontent.com/reviewdog/reviewdog/master/install.sh| sh -s -- -b /usr/local/bin/ ${REVIEWDOG_VERSION} +RUN wget -O - -q https://raw.githubusercontent.com/reviewdog/reviewdog/master/install.sh | sh -s -- -b /usr/local/bin/ ${REVIEWDOG_VERSION} COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] \ No newline at end of file diff --git a/entrypoint.sh b/entrypoint.sh index 9222695..c8d382e 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,21 +1,15 @@ #!/bin/sh set -e -CODENARC_SARIF="result.sarif.json" -CODENARC_SARIF_LINE="result_line.sarif.json" -CODENARC_SARIF_FILE="result_file.sarif.json" +CODENARC_JSON="result.json" CODENARC_COMPACT="result.txt" -LINE_VIOLATIONS="line_violations.txt" -FILE_VIOLATIONS="file_violations.txt" -VIOLATIONS_FLAG="/tmp/found_violations.txt" ALL_DIFF="/tmp/all_diff.txt" CHANGED_LINES_CACHE="/tmp/changed_lines.txt" CHANGED_FILES_CACHE="/tmp/changed_files.txt" cleanup_temp_files() { - rm -f "$CODENARC_SARIF" "$CODENARC_SARIF_LINE" "$CODENARC_SARIF_FILE" "$CODENARC_COMPACT" "$LINE_VIOLATIONS" "$FILE_VIOLATIONS" \ - "$VIOLATIONS_FLAG" "$ALL_DIFF" "$CHANGED_LINES_CACHE" "$CHANGED_FILES_CACHE" \ - "${FILE_VIOLATIONS}.formatted" >/dev/null 2>&1 + rm -f "$CODENARC_JSON" "$CODENARC_COMPACT" "$ALL_DIFF" \ + "$CHANGED_LINES_CACHE" "$CHANGED_FILES_CACHE" >/dev/null 2>&1 } trap 'cleanup_temp_files' EXIT @@ -26,117 +20,65 @@ run_codenarc() { echo "🔍 Executando CodeNarc..." java -jar /lib/codenarc-all.jar \ - -report="sarif:${CODENARC_SARIF}" \ + -report="json:${CODENARC_JSON}" \ -rulesetfiles="${INPUT_RULESETFILES}" \ -basedir="." \ $includes_arg - convert_sarif_to_compact - split_sarif_by_type - echo "" echo "📋 Violações encontradas:" echo "" + convert_json_to_compact cat "$CODENARC_COMPACT" echo "" } -convert_sarif_to_compact() { - if ! command -v jq >/dev/null 2>&1; then - echo "⚠️ jq não encontrado" - return - fi - +convert_json_to_compact() { jq -r ' - .runs[0]? as $run | - ($run.tool.driver.rules // []) as $rules | - ($run.results // [])[] | - .ruleId as $ruleId | - ($rules | map(select(.id == $ruleId)) | .[0].properties.priority // 2) as $priority | - (.locations[0].physicalLocation // {}) as $loc | - ($loc.artifactLocation.uri // "unknown") as $file | - ($loc.region.startLine // null) as $line | - (.message.text // "No message") as $msg | - if $line == null then - "\($file):\($ruleId) \($msg) => Priority \($priority)" + .packages[]? | + .path as $pkg_path | + .files[]? | + ($pkg_path // "") as $rawpath | + .name as $filename | + (if $rawpath == "" then $filename else ($rawpath | ltrimstr("/")) + "/" + $filename end) as $file | + ($file | ltrimstr("/")) as $cleanfile | + .violations[]? | + if .lineNumber then + "\($cleanfile):\(.lineNumber):\(.ruleName) \(.message // "") [P\(.priority)]" else - "\($file):\($line):\($ruleId) \($msg) => Priority \($priority)" + "\($cleanfile)::\(.ruleName) \(.message // "") [P\(.priority)]" end - ' "$CODENARC_SARIF" > "$CODENARC_COMPACT" 2>/dev/null || echo "" > "$CODENARC_COMPACT" -} - -split_sarif_by_type() { - if ! command -v jq >/dev/null 2>&1; then - return - fi - - # Line-based - jq '{ - "$schema": ."$schema", - "version": .version, - "runs": [ - .runs[0] | { - "tool": .tool, - "results": [.results[] | select(.locations[0].physicalLocation.region.startLine != null)] - } - ] - }' "$CODENARC_SARIF" > "$CODENARC_SARIF_LINE" 2>/dev/null - - # File-based - jq '{ - "$schema": ."$schema", - "version": .version, - "runs": [ - .runs[0] | { - "tool": .tool, - "results": [.results[] | select(.locations[0].physicalLocation.region.startLine == null)] - } - ] - }' "$CODENARC_SARIF" > "$CODENARC_SARIF_FILE" 2>/dev/null + ' "$CODENARC_JSON" > "$CODENARC_COMPACT" 2>/dev/null || true } run_reviewdog() { + [ ! -s "$CODENARC_COMPACT" ] && return + echo "📤 Enviando resultados para reviewdog..." - - if [ ! -s "$CODENARC_SARIF" ]; then - echo "⚠️ Nenhum resultado SARIF encontrado" - return - fi if [ "${INPUT_REPORTER}" = "local" ]; then - echo "🏠 Executando reviewdog em modo local..." - < "$CODENARC_SARIF" reviewdog \ - -f=sarif \ + < "$CODENARC_COMPACT" reviewdog \ + -efm="%f:%l:%m" \ + -efm="%f::%m" \ -reporter="local" \ -name="codenarc" \ -filter-mode="${INPUT_FILTER_MODE}" \ -level="${INPUT_LEVEL}" \ ${INPUT_REVIEWDOG_FLAGS} || true - return - fi - - # line-based github-pr-review - if [ -s "$CODENARC_SARIF_LINE" ] && [ "$(jq '.runs[0].results | length' "$CODENARC_SARIF_LINE")" -gt 0 ]; then - echo "📍 Enviando violações line-based para github-pr-review..." - < "$CODENARC_SARIF_LINE" reviewdog \ - -f=sarif \ + else + grep -E ':[0-9]+:' "$CODENARC_COMPACT" | reviewdog \ + -efm="%f:%l:%m" \ -reporter="github-pr-review" \ -name="codenarc" \ -filter-mode="${INPUT_FILTER_MODE}" \ - -fail-on-error="false" \ -level="${INPUT_LEVEL}" \ ${INPUT_REVIEWDOG_FLAGS} || true - fi - # file-based github-pr-check - if [ -s "$CODENARC_SARIF_FILE" ] && [ "$(jq '.runs[0].results | length' "$CODENARC_SARIF_FILE")" -gt 0 ]; then - echo "📄 Enviando violações file-based para github-pr-check..." - < "$CODENARC_SARIF_FILE" reviewdog \ - -f=sarif \ + grep -E '::' "$CODENARC_COMPACT" | reviewdog \ + -efm="%f::%m" \ -reporter="github-pr-check" \ -name="codenarc" \ -filter-mode="nofilter" \ - -fail-on-error="false" \ -level="warning" \ ${INPUT_REVIEWDOG_FLAGS} || true fi @@ -152,171 +94,108 @@ generate_git_diff() { fi } -parse_diff_range() { - range="$1" - if echo "$range" | grep -q ","; then - echo "$(echo "$range" | cut -d',' -f1) $(echo "$range" | cut -d',' -f2)" - else - echo "$range 1" - fi -} + build_changed_lines_cache() { - true > "$CHANGED_LINES_CACHE" - true > "$CHANGED_FILES_CACHE" - - generate_git_diff > "$ALL_DIFF" 2>/dev/null || true - [ ! -s "$ALL_DIFF" ] && return 0 - - current_file="" - while read -r line; do - case "$line" in - "diff --git"*) - current_file=$(echo "$line" | sed 's|^diff --git a/\(.*\) b/.*|\1|') - [ -n "$current_file" ] && echo "$current_file" >> "$CHANGED_FILES_CACHE" - ;; - "@@"*) - [ -z "$current_file" ] && continue - range=$(echo "$line" | sed 's/.*+\([0-9,]*\).*/\1/') - range_info=$(parse_diff_range "$range") - start=$(echo "$range_info" | cut -d' ' -f1) - count=$(echo "$range_info" | cut -d' ' -f2) - - case "$start" in ''|*[!0-9]*) continue ;; esac - case "$count" in ''|*[!0-9]*) continue ;; esac - - i="$start" - while [ "$i" -lt "$((start + count))" ]; do - echo "$current_file:$i" >> "$CHANGED_LINES_CACHE" - i=$((i + 1)) - done - ;; - esac - done < "$ALL_DIFF" + generate_git_diff > "$ALL_DIFF" 2>/dev/null || return + [ ! -s "$ALL_DIFF" ] && return + + awk ' + /^diff --git/ { file = $3; sub(/^a\//, "", file); print file > "/tmp/changed_files.txt" } + /^@@/ { + match($0, /\+([0-9]+)(,([0-9]+))?/, arr) + start = arr[1] + count = arr[3] ? arr[3] : 1 + for (i = start; i < start + count; i++) + print file ":" i > "/tmp/changed_lines.txt" + } + ' "$ALL_DIFF" } -get_allowed_patterns() { - [ -n "$INPUT_SOURCE_FILES" ] && echo "$INPUT_SOURCE_FILES" | tr ',' '\n' | sed 's/\*\*/.*/g' +file_matches_filter() { + [ -z "$INPUT_SOURCE_FILES" ] && return 0 + echo "$INPUT_SOURCE_FILES" | tr ',' '\n' | sed 's/\*\*/.*/g' | grep -qE "$(echo "$1" | sed 's/\./\\./g')" } -file_matches_patterns() { - file="$1" - patterns="$2" - [ -z "$patterns" ] && return 0 - for pattern in $patterns; do - echo "$file" | grep -Eq "$pattern" && return 0 - done +is_changed() { + [ -f "$CHANGED_LINES_CACHE" ] && grep -q "^$1:$2$" "$CHANGED_LINES_CACHE" && return 0 + [ -f "$CHANGED_FILES_CACHE" ] && grep -q "^$1$" "$CHANGED_FILES_CACHE" && return 0 return 1 } -is_line_changed() { - grep -q "^$2:$1$" "$CHANGED_LINES_CACHE" -} - -is_file_changed() { - grep -q "^$1$" "$CHANGED_FILES_CACHE" -} - -extract_p1_violations_from_sarif() { - if ! command -v jq >/dev/null 2>&1; then - grep 'Priority 1' "$CODENARC_COMPACT" 2>/dev/null || echo "" - return - fi - +extract_p1_violations() { jq -r ' - .runs[0]? as $run | - ($run.tool.driver.rules // []) as $rules | - ($run.results // [])[] | - .ruleId as $ruleId | - ($rules | map(select(.id == $ruleId)) | .[0].properties.priority // 2) as $priority | - select($priority == 1) | - (.locations[0].physicalLocation // {}) as $loc | - ($loc.artifactLocation.uri // "unknown") as $file | - ($loc.region.startLine // null) as $line | - (.message.text // "No message") as $msg | - if $line == null then - "\($file)::\($ruleId) \($msg)" + .packages[]? | + .path as $pkg_path | + .files[]? | + ($pkg_path // "") as $rawpath | + .name as $filename | + (if $rawpath == "" then $filename else ($rawpath | ltrimstr("/")) + "/" + $filename end) as $file | + ($file | ltrimstr("/")) as $cleanfile | + .violations[]? | select(.priority == 1) | + if .lineNumber then + "\($cleanfile):\(.lineNumber):\(.ruleName) \(.message // "")" else - "\($file):\($line):\($ruleId) \($msg)" + "\($cleanfile)::\(.ruleName) \(.message // "")" end - ' "$CODENARC_SARIF" 2>/dev/null || echo "" + ' "$CODENARC_JSON" 2>/dev/null } check_blocking_rules() { echo "🔎 Verificando violações bloqueantes (priority 1)..." - - [ ! -f "$CODENARC_SARIF" ] && echo "❌ Resultado não encontrado" && return 1 - - p1_violations=$(extract_p1_violations_from_sarif) - + + [ ! -f "$CODENARC_JSON" ] && echo "❌ Resultado não encontrado" && return 1 + + p1_violations=$(extract_p1_violations) + if [ -z "$p1_violations" ]; then echo "✅ Nenhuma P1 detectada → merge permitido" return 0 fi - + p1_count=$(echo "$p1_violations" | wc -l | tr -d ' ') echo "📊 Total de P1 encontradas: $p1_count" echo "" echo "⛔ Violações P1:" echo "$p1_violations" echo "" - + if [ "${INPUT_REPORTER}" = "local" ]; then - echo "🏠 Modo local - não é possível verificar linhas alteradas" - echo "⚠️ Todas as P1s serão consideradas bloqueantes" - echo "" - echo "⛔ Violação P1 encontrada → bloqueando execução" + echo "🏠 Modo local - todas as P1s são bloqueantes" echo "💡 Corrija as violações antes de prosseguir." exit 1 fi - + echo "⚠️ Verificando se P1s estão em linhas alteradas..." build_changed_lines_cache - + if [ ! -s "$ALL_DIFF" ]; then - echo "⚠️ Não foi possível gerar diff - considerando todas as P1s como bloqueantes" - echo "" - echo "⛔ Violação P1 encontrada → bloqueando merge" - echo "💡 Corrija as violações ou use o bypass autorizado pelo coordenador." + echo "⚠️ Diff vazio - considerando todas as P1s como bloqueantes" + echo "💡 Corrija as violações ou use o bypass autorizado." exit 1 fi - - allowed_patterns=$(get_allowed_patterns) - [ -n "$allowed_patterns" ] && echo "🧩 Analisando apenas arquivos filtrados" - - echo "0" > "$VIOLATIONS_FLAG" - + + [ -n "$INPUT_SOURCE_FILES" ] && echo "🧩 Analisando apenas arquivos filtrados" + echo "$p1_violations" | while IFS=: read -r file line rest; do [ -z "$file" ] && continue - file_matches_patterns "$file" "$allowed_patterns" || continue - - if [ "$line" = "" ] || [ -z "$line" ]; then - if is_file_changed "$file"; then - echo "⛔ Violação P1 file-based em arquivo alterado: $file" - echo " $rest" - echo "1" > "$VIOLATIONS_FLAG" - break - fi - elif is_line_changed "$line" "$file"; then - echo "⛔ Violação P1 em linha alterada: $file:$line" - echo " $rest" - echo "1" > "$VIOLATIONS_FLAG" - break + file_matches_filter "$file" || continue + + if [ -z "$line" ]; then + is_changed "$file" "" && echo "⛔ $file (file-level): $rest" && exit 1 + else + is_changed "$file" "$line" && echo "⛔ $file:$line: $rest" && exit 1 fi done - - if [ "$(cat "$VIOLATIONS_FLAG")" -eq 1 ]; then - echo "" - echo "⛔ Violação P1 encontrada em linha alterada → bloqueando merge" - echo "💡 Corrija as violações ou use o bypass autorizado pelo coordenador." - exit 1 - else - echo "✅ P1s existem mas fora das linhas alteradas → merge permitido" - fi + + [ $? -eq 1 ] && echo "" && echo "💡 Corrija as violações ou use o bypass autorizado." && exit 1 + + echo "✅ P1s existem mas fora das linhas alteradas → merge permitido" } if [ -n "${GITHUB_WORKSPACE}" ]; then - git config --global --add safe.directory "$GITHUB_WORKSPACE" 2>/dev/null || true + cd "${GITHUB_WORKSPACE}/${INPUT_WORKDIR}" || exit + git config --global --add safe.directory "$GITHUB_WORKSPACE" fi export REVIEWDOG_GITHUB_API_TOKEN="${INPUT_GITHUB_TOKEN}" From e97cd32c27f7b5f01ee4be063b74ec1f0a940ead Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 10:04:01 -0300 Subject: [PATCH 04/19] alterando de sarif para json --- entrypoint.sh | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index c8d382e..0f36d59 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -66,21 +66,27 @@ run_reviewdog() { -level="${INPUT_LEVEL}" \ ${INPUT_REVIEWDOG_FLAGS} || true else - grep -E ':[0-9]+:' "$CODENARC_COMPACT" | reviewdog \ - -efm="%f:%l:%m" \ - -reporter="github-pr-review" \ - -name="codenarc" \ - -filter-mode="${INPUT_FILTER_MODE}" \ - -level="${INPUT_LEVEL}" \ - ${INPUT_REVIEWDOG_FLAGS} || true + line_violations=$(grep -E ':[0-9]+:' "$CODENARC_COMPACT" || true) + if [ -n "$line_violations" ]; then + echo "$line_violations" | reviewdog \ + -efm="%f:%l:%m" \ + -reporter="github-pr-review" \ + -name="codenarc" \ + -filter-mode="${INPUT_FILTER_MODE}" \ + -level="${INPUT_LEVEL}" \ + ${INPUT_REVIEWDOG_FLAGS} || true + fi - grep -E '::' "$CODENARC_COMPACT" | reviewdog \ - -efm="%f::%m" \ - -reporter="github-pr-check" \ - -name="codenarc" \ - -filter-mode="nofilter" \ - -level="warning" \ - ${INPUT_REVIEWDOG_FLAGS} || true + file_violations=$(grep -E '::' "$CODENARC_COMPACT" || true) + if [ -n "$file_violations" ]; then + echo "$file_violations" | reviewdog \ + -efm="%f::%m" \ + -reporter="github-pr-check" \ + -name="codenarc" \ + -filter-mode="nofilter" \ + -level="warning" \ + ${INPUT_REVIEWDOG_FLAGS} || true + fi fi } @@ -94,8 +100,6 @@ generate_git_diff() { fi } - - build_changed_lines_cache() { generate_git_diff > "$ALL_DIFF" 2>/dev/null || return [ ! -s "$ALL_DIFF" ] && return @@ -105,7 +109,7 @@ build_changed_lines_cache() { /^@@/ { match($0, /\+([0-9]+)(,([0-9]+))?/, arr) start = arr[1] - count = arr[3] ? arr[3] : 1 + count = (arr[3] != "" ? arr[3] : 1) for (i = start; i < start + count; i++) print file ":" i > "/tmp/changed_lines.txt" } From 961e7340c4c8c55e39b31733add143311673c2ea Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 10:08:48 -0300 Subject: [PATCH 05/19] alterando de sarif para json --- entrypoint.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/entrypoint.sh b/entrypoint.sh index 0f36d59..066c682 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -109,7 +109,11 @@ build_changed_lines_cache() { /^@@/ { match($0, /\+([0-9]+)(,([0-9]+))?/, arr) start = arr[1] - count = (arr[3] != "" ? arr[3] : 1) + if (arr[3] == "") { + count = 1 + } else { + count = arr[3] + } for (i = start; i < start + count; i++) print file ":" i > "/tmp/changed_lines.txt" } From 5b6c74ec33adebf2073e608c5df6bf033d77f2e4 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 10:19:42 -0300 Subject: [PATCH 06/19] alterando de sarif para json --- entrypoint.sh | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 066c682..cc37298 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -105,15 +105,19 @@ build_changed_lines_cache() { [ ! -s "$ALL_DIFF" ] && return awk ' - /^diff --git/ { file = $3; sub(/^a\//, "", file); print file > "/tmp/changed_files.txt" } + /^diff --git/ { + file = $3 + sub(/^a\//, "", file) + print file > "/tmp/changed_files.txt" + } /^@@/ { - match($0, /\+([0-9]+)(,([0-9]+))?/, arr) - start = arr[1] - if (arr[3] == "") { - count = 1 - } else { - count = arr[3] - } + match($0, /\+([0-9]+)(,([0-9]+))?/) + range = substr($0, RSTART, RLENGTH) + sub(/^\+/, "", range) + split(range, parts, ",") + start = parts[1] + count = parts[2] + if (count == "") count = 1 for (i = start; i < start + count; i++) print file ":" i > "/tmp/changed_lines.txt" } From ad8b325468a65c0cfe2c75361ae007525a5ad6ea Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 10:23:12 -0300 Subject: [PATCH 07/19] ajuste analise do diff --- entrypoint.sh | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/entrypoint.sh b/entrypoint.sh index cc37298..375f5a4 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -188,6 +188,13 @@ check_blocking_rules() { fi [ -n "$INPUT_SOURCE_FILES" ] && echo "🧩 Analisando apenas arquivos filtrados" + + echo "📝 Debug - Linhas alteradas:" + cat "$CHANGED_LINES_CACHE" 2>/dev/null || echo "(cache vazio)" + echo "" + echo "📝 Debug - Arquivos alterados:" + cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" + echo "" echo "$p1_violations" | while IFS=: read -r file line rest; do [ -z "$file" ] && continue From fd9c3aa4d89297bb2bbf927bdf27c51cc383dc9e Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 11:11:58 -0300 Subject: [PATCH 08/19] ajuste analise do diff --- entrypoint.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/entrypoint.sh b/entrypoint.sh index 375f5a4..2f40b72 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -200,10 +200,15 @@ check_blocking_rules() { [ -z "$file" ] && continue file_matches_filter "$file" || continue + echo "🔍 Verificando: $file:$line" + if [ -z "$line" ]; then is_changed "$file" "" && echo "⛔ $file (file-level): $rest" && exit 1 else - is_changed "$file" "$line" && echo "⛔ $file:$line: $rest" && exit 1 + if is_changed "$file" "$line"; then + echo "⛔ $file:$line: $rest" + exit 1 + fi fi done From 9417d0743dbb0d0541b1294a21b30527c5e31abb Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 11:57:36 -0300 Subject: [PATCH 09/19] ajuste analise do diff --- entrypoint.sh | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 2f40b72..f6f533b 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -196,23 +196,33 @@ check_blocking_rules() { cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" echo "" + blocking_found=0 echo "$p1_violations" | while IFS=: read -r file line rest; do [ -z "$file" ] && continue file_matches_filter "$file" || continue echo "🔍 Verificando: $file:$line" - + if [ -z "$line" ]; then - is_changed "$file" "" && echo "⛔ $file (file-level): $rest" && exit 1 + if is_changed "$file" ""; then + echo "⛔ $file (file-level): $rest" + blocking_found=1 + break + fi else if is_changed "$file" "$line"; then echo "⛔ $file:$line: $rest" - exit 1 + blocking_found=1 + break fi fi done - [ $? -eq 1 ] && echo "" && echo "💡 Corrija as violações ou use o bypass autorizado." && exit 1 + if [ "$blocking_found" -eq 1 ]; then + echo "" + echo "💡 Corrija as violações ou use o bypass autorizado." + exit 1 + fi echo "✅ P1s existem mas fora das linhas alteradas → merge permitido" } From 6fc6594cdc6a187eec68c3c39f008c9864648d27 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 12:15:05 -0300 Subject: [PATCH 10/19] ajuste analise do diff --- entrypoint.sh | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index f6f533b..cec0a60 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -196,8 +196,7 @@ check_blocking_rules() { cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" echo "" - blocking_found=0 - echo "$p1_violations" | while IFS=: read -r file line rest; do + while IFS=: read -r file line rest; do [ -z "$file" ] && continue file_matches_filter "$file" || continue @@ -206,23 +205,21 @@ check_blocking_rules() { if [ -z "$line" ]; then if is_changed "$file" ""; then echo "⛔ $file (file-level): $rest" - blocking_found=1 - break + echo "" + echo "💡 Corrija as violações ou use o bypass autorizado." + exit 1 fi else if is_changed "$file" "$line"; then echo "⛔ $file:$line: $rest" - blocking_found=1 - break + echo "" + echo "💡 Corrija as violações ou use o bypass autorizado." + exit 1 fi fi - done - - if [ "$blocking_found" -eq 1 ]; then - echo "" - echo "💡 Corrija as violações ou use o bypass autorizado." - exit 1 - fi + done < Date: Fri, 23 Jan 2026 12:20:35 -0300 Subject: [PATCH 11/19] ajuste analise do diff --- entrypoint.sh | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index cec0a60..698af33 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -130,8 +130,15 @@ file_matches_filter() { } is_changed() { - [ -f "$CHANGED_LINES_CACHE" ] && grep -q "^$1:$2$" "$CHANGED_LINES_CACHE" && return 0 - [ -f "$CHANGED_FILES_CACHE" ] && grep -q "^$1$" "$CHANGED_FILES_CACHE" && return 0 + local file="$1" + local line="$2" + + if [ -z "$line" ]; then + [ -f "$CHANGED_FILES_CACHE" ] && grep -qF "$file" "$CHANGED_FILES_CACHE" && return 0 + return 1 + fi + + [ -f "$CHANGED_LINES_CACHE" ] && grep -qF "${file}:${line}" "$CHANGED_LINES_CACHE" && return 0 return 1 } @@ -196,7 +203,7 @@ check_blocking_rules() { cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" echo "" - while IFS=: read -r file line rest; do + echo "$p1_violations" | while IFS=: read -r file line rest; do [ -z "$file" ] && continue file_matches_filter "$file" || continue @@ -217,9 +224,11 @@ check_blocking_rules() { exit 1 fi fi - done < Date: Fri, 23 Jan 2026 12:23:36 -0300 Subject: [PATCH 12/19] ajuste analise do diff --- entrypoint.sh | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 698af33..ec5edb4 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -203,7 +203,9 @@ check_blocking_rules() { cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" echo "" - echo "$p1_violations" | while IFS=: read -r file line rest; do + found_blocking=0 + + while IFS=: read -r file line rest; do [ -z "$file" ] && continue file_matches_filter "$file" || continue @@ -213,20 +215,24 @@ check_blocking_rules() { if is_changed "$file" ""; then echo "⛔ $file (file-level): $rest" echo "" - echo "💡 Corrija as violações ou use o bypass autorizado." - exit 1 + found_blocking=1 + break fi else if is_changed "$file" "$line"; then echo "⛔ $file:$line: $rest" echo "" - echo "💡 Corrija as violações ou use o bypass autorizado." - exit 1 + found_blocking=1 + break fi fi - done - - if [ $? -eq 1 ]; then + done < Date: Fri, 23 Jan 2026 12:26:16 -0300 Subject: [PATCH 13/19] debug --- entrypoint.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/entrypoint.sh b/entrypoint.sh index ec5edb4..58a5b90 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -210,20 +210,28 @@ check_blocking_rules() { file_matches_filter "$file" || continue echo "🔍 Verificando: $file:$line" + echo " Debug - file='$file' line='$line'" if [ -z "$line" ]; then + echo " → File-based violation" if is_changed "$file" ""; then echo "⛔ $file (file-level): $rest" echo "" found_blocking=1 break + else + echo " → Arquivo não está no diff" fi else + echo " → Line-based violation" + echo " → Procurando por: '${file}:${line}'" if is_changed "$file" "$line"; then echo "⛔ $file:$line: $rest" echo "" found_blocking=1 break + else + echo " → Linha não está no diff" fi fi done < Date: Fri, 23 Jan 2026 12:43:53 -0300 Subject: [PATCH 14/19] debug --- entrypoint.sh | 50 ++++++++++++++++++++------------------------------ 1 file changed, 20 insertions(+), 30 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 58a5b90..0d8c104 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -17,7 +17,7 @@ trap 'cleanup_temp_files' EXIT run_codenarc() { includes_arg="" [ -n "$INPUT_SOURCE_FILES" ] && includes_arg="-includes=${INPUT_SOURCE_FILES}" - + echo "🔍 Executando CodeNarc..." java -jar /lib/codenarc-all.jar \ -report="json:${CODENARC_JSON}" \ @@ -101,6 +101,9 @@ generate_git_diff() { } build_changed_lines_cache() { + > "$CHANGED_FILES_CACHE" + > "$CHANGED_LINES_CACHE" + generate_git_diff > "$ALL_DIFF" 2>/dev/null || return [ ! -s "$ALL_DIFF" ] && return @@ -108,7 +111,7 @@ build_changed_lines_cache() { /^diff --git/ { file = $3 sub(/^a\//, "", file) - print file > "/tmp/changed_files.txt" + print file >> "'"$CHANGED_FILES_CACHE"'" } /^@@/ { match($0, /\+([0-9]+)(,([0-9]+))?/) @@ -119,20 +122,15 @@ build_changed_lines_cache() { count = parts[2] if (count == "") count = 1 for (i = start; i < start + count; i++) - print file ":" i > "/tmp/changed_lines.txt" + print file ":" i >> "'"$CHANGED_LINES_CACHE"'" } ' "$ALL_DIFF" } -file_matches_filter() { - [ -z "$INPUT_SOURCE_FILES" ] && return 0 - echo "$INPUT_SOURCE_FILES" | tr ',' '\n' | sed 's/\*\*/.*/g' | grep -qE "$(echo "$1" | sed 's/\./\\./g')" -} - is_changed() { local file="$1" local line="$2" - + if [ -z "$line" ]; then [ -f "$CHANGED_FILES_CACHE" ] && grep -qF "$file" "$CHANGED_FILES_CACHE" && return 0 return 1 @@ -163,8 +161,8 @@ extract_p1_violations() { check_blocking_rules() { echo "🔎 Verificando violações bloqueantes (priority 1)..." - [ ! -f "$CODENARC_JSON" ] && echo "❌ Resultado não encontrado" && return 1 - + [ ! -f "$CODENARC_JSON" ] && echo "❌ Resultado do CodeNarc não encontrado. Não é possível verificar P1s." && return 1 + p1_violations=$(extract_p1_violations) if [ -z "$p1_violations" ]; then @@ -189,49 +187,40 @@ check_blocking_rules() { build_changed_lines_cache if [ ! -s "$ALL_DIFF" ]; then - echo "⚠️ Diff vazio - considerando todas as P1s como bloqueantes" + echo "⚠️ Diff vazio - considerando todas as P1s como bloqueantes (sem informações de linhas alteradas)." echo "💡 Corrija as violações ou use o bypass autorizado." exit 1 fi - [ -n "$INPUT_SOURCE_FILES" ] && echo "🧩 Analisando apenas arquivos filtrados" - echo "📝 Debug - Linhas alteradas:" cat "$CHANGED_LINES_CACHE" 2>/dev/null || echo "(cache vazio)" - echo "" echo "📝 Debug - Arquivos alterados:" cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" echo "" - + found_blocking=0 - while IFS=: read -r file line rest; do [ -z "$file" ] && continue - file_matches_filter "$file" || continue - echo "🔍 Verificando: $file:$line" - echo " Debug - file='$file' line='$line'" + echo "🔍 Verificando violação: $file:$line" if [ -z "$line" ]; then - echo " → File-based violation" + echo " → Violação a nível de arquivo." if is_changed "$file" ""; then - echo "⛔ $file (file-level): $rest" - echo "" + echo "⛔ BLOQUEANDO: $file (nível de arquivo): $rest" found_blocking=1 break else - echo " → Arquivo não está no diff" + echo " → Arquivo não foi alterado no diff, ignorando P1." fi else - echo " → Line-based violation" - echo " → Procurando por: '${file}:${line}'" + echo " → Violação a nível de linha." if is_changed "$file" "$line"; then - echo "⛔ $file:$line: $rest" - echo "" + echo "⛔ BLOQUEANDO: $file:$line: $rest" found_blocking=1 break else - echo " → Linha não está no diff" + echo " → Linha não está no diff, ignorando P1." fi fi done < Date: Fri, 23 Jan 2026 12:58:24 -0300 Subject: [PATCH 15/19] ajustes nos logs --- entrypoint.sh | 58 +++++++++++++++++++-------------------------------- 1 file changed, 21 insertions(+), 37 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 0d8c104..845e843 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -18,15 +18,15 @@ run_codenarc() { includes_arg="" [ -n "$INPUT_SOURCE_FILES" ] && includes_arg="-includes=${INPUT_SOURCE_FILES}" - echo "🔍 Executando CodeNarc..." + echo "🔍 Executando CodeNarc para análise estática..." java -jar /lib/codenarc-all.jar \ -report="json:${CODENARC_JSON}" \ -rulesetfiles="${INPUT_RULESETFILES}" \ -basedir="." \ - $includes_arg - + $includes_arg >/dev/null 2>&1 + echo "" - echo "📋 Violações encontradas:" + echo "📋 Processando violações encontradas:" echo "" convert_json_to_compact cat "$CODENARC_COMPACT" @@ -55,7 +55,7 @@ run_reviewdog() { [ ! -s "$CODENARC_COMPACT" ] && return echo "📤 Enviando resultados para reviewdog..." - + if [ "${INPUT_REPORTER}" = "local" ]; then < "$CODENARC_COMPACT" reviewdog \ -efm="%f:%l:%m" \ @@ -92,8 +92,8 @@ run_reviewdog() { generate_git_diff() { if [ -n "$GITHUB_BASE_SHA" ] && [ -n "$GITHUB_HEAD_SHA" ]; then - git fetch origin "$GITHUB_BASE_SHA" --depth=1 2>/dev/null || true - git fetch origin "$GITHUB_HEAD_SHA" --depth=1 2>/dev/null || true + git fetch origin "$GITHUB_BASE_SHA" --depth=1 >/dev/null 2>&1 || true + git fetch origin "$GITHUB_HEAD_SHA" --depth=1 >/dev/null 2>&1 || true git diff -U0 "$GITHUB_BASE_SHA" "$GITHUB_HEAD_SHA" -- '*.groovy' else git diff -U0 HEAD~1 -- '*.groovy' @@ -130,7 +130,7 @@ build_changed_lines_cache() { is_changed() { local file="$1" local line="$2" - + if [ -z "$line" ]; then [ -f "$CHANGED_FILES_CACHE" ] && grep -qF "$file" "$CHANGED_FILES_CACHE" && return 0 return 1 @@ -159,14 +159,12 @@ extract_p1_violations() { } check_blocking_rules() { - echo "🔎 Verificando violações bloqueantes (priority 1)..." - - [ ! -f "$CODENARC_JSON" ] && echo "❌ Resultado do CodeNarc não encontrado. Não é possível verificar P1s." && return 1 + echo "🔎 Verificando violações bloqueantes (P1)..." + [ ! -f "$CODENARC_JSON" ] && echo "❌ Erro: Resultado do CodeNarc não encontrado. Não é possível verificar P1s." && return 1 p1_violations=$(extract_p1_violations) - if [ -z "$p1_violations" ]; then - echo "✅ Nenhuma P1 detectada → merge permitido" + echo "✅ Nenhuma violação P1 detectada → merge permitido" return 0 fi @@ -178,49 +176,35 @@ check_blocking_rules() { echo "" if [ "${INPUT_REPORTER}" = "local" ]; then - echo "🏠 Modo local - todas as P1s são bloqueantes" + echo "🏠 Modo de execução local: todas as violações P1 são bloqueantes." echo "💡 Corrija as violações antes de prosseguir." exit 1 fi - echo "⚠️ Verificando se P1s estão em linhas alteradas..." + echo "⚠️ Analisando se as P1s estão em linhas alteradas..." build_changed_lines_cache if [ ! -s "$ALL_DIFF" ]; then - echo "⚠️ Diff vazio - considerando todas as P1s como bloqueantes (sem informações de linhas alteradas)." - echo "💡 Corrija as violações ou use o bypass autorizado." + echo "⚠️ Diff vazio: Sem informações de linhas alteradas. Todas as P1s são consideradas bloqueantes." + echo "💡 Corrija as violações ou use um bypass autorizado." exit 1 fi - - echo "📝 Debug - Linhas alteradas:" - cat "$CHANGED_LINES_CACHE" 2>/dev/null || echo "(cache vazio)" - echo "📝 Debug - Arquivos alterados:" - cat "$CHANGED_FILES_CACHE" 2>/dev/null || echo "(cache vazio)" - echo "" found_blocking=0 while IFS=: read -r file line rest; do [ -z "$file" ] && continue - - echo "🔍 Verificando violação: $file:$line" if [ -z "$line" ]; then - echo " → Violação a nível de arquivo." if is_changed "$file" ""; then - echo "⛔ BLOQUEANDO: $file (nível de arquivo): $rest" + echo "🚨 BLOQUEADO: Violação P1 a nível de arquivo encontrada no arquivo alterado: $file" found_blocking=1 break - else - echo " → Arquivo não foi alterado no diff, ignorando P1." fi else - echo " → Violação a nível de linha." if is_changed "$file" "$line"; then - echo "⛔ BLOQUEANDO: $file:$line: $rest" + echo "🚨 BLOQUEADO: Violação P1 encontrada na linha alterada: $file:$line" found_blocking=1 break - else - echo " → Linha não está no diff, ignorando P1." fi fi done < Date: Fri, 23 Jan 2026 13:04:34 -0300 Subject: [PATCH 16/19] ajustes nos logs --- entrypoint.sh | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 845e843..946aabf 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -25,12 +25,9 @@ run_codenarc() { -basedir="." \ $includes_arg >/dev/null 2>&1 - echo "" echo "📋 Processando violações encontradas:" - echo "" convert_json_to_compact cat "$CODENARC_COMPACT" - echo "" } convert_json_to_compact() { @@ -53,7 +50,6 @@ convert_json_to_compact() { run_reviewdog() { [ ! -s "$CODENARC_COMPACT" ] && return - echo "📤 Enviando resultados para reviewdog..." if [ "${INPUT_REPORTER}" = "local" ]; then @@ -64,7 +60,7 @@ run_reviewdog() { -name="codenarc" \ -filter-mode="${INPUT_FILTER_MODE}" \ -level="${INPUT_LEVEL}" \ - ${INPUT_REVIEWDOG_FLAGS} || true + ${INPUT_REVIEWDOG_FLAGS} >/dev/null || true else line_violations=$(grep -E ':[0-9]+:' "$CODENARC_COMPACT" || true) if [ -n "$line_violations" ]; then @@ -74,9 +70,8 @@ run_reviewdog() { -name="codenarc" \ -filter-mode="${INPUT_FILTER_MODE}" \ -level="${INPUT_LEVEL}" \ - ${INPUT_REVIEWDOG_FLAGS} || true + ${INPUT_REVIEWDOG_FLAGS} >/dev/null || true fi - file_violations=$(grep -E '::' "$CODENARC_COMPACT" || true) if [ -n "$file_violations" ]; then echo "$file_violations" | reviewdog \ @@ -85,7 +80,7 @@ run_reviewdog() { -name="codenarc" \ -filter-mode="nofilter" \ -level="warning" \ - ${INPUT_REVIEWDOG_FLAGS} || true + ${INPUT_REVIEWDOG_FLAGS} >/dev/null || true fi fi } @@ -170,7 +165,6 @@ check_blocking_rules() { p1_count=$(echo "$p1_violations" | wc -l | tr -d ' ') echo "📊 Total de P1 encontradas: $p1_count" - echo "" echo "⛔ Violações P1:" echo "$p1_violations" echo "" From 1c4c7869fc9bfa608184570d05be919df4584558 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 13:08:32 -0300 Subject: [PATCH 17/19] ajustes nos logs --- entrypoint.sh | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/entrypoint.sh b/entrypoint.sh index 946aabf..7ed793f 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -18,6 +18,7 @@ run_codenarc() { includes_arg="" [ -n "$INPUT_SOURCE_FILES" ] && includes_arg="-includes=${INPUT_SOURCE_FILES}" + echo "" echo "🔍 Executando CodeNarc para análise estática..." java -jar /lib/codenarc-all.jar \ -report="json:${CODENARC_JSON}" \ @@ -25,6 +26,7 @@ run_codenarc() { -basedir="." \ $includes_arg >/dev/null 2>&1 + echo "" echo "📋 Processando violações encontradas:" convert_json_to_compact cat "$CODENARC_COMPACT" @@ -50,6 +52,7 @@ convert_json_to_compact() { run_reviewdog() { [ ! -s "$CODENARC_COMPACT" ] && return + echo "" echo "📤 Enviando resultados para reviewdog..." if [ "${INPUT_REPORTER}" = "local" ]; then @@ -154,6 +157,7 @@ extract_p1_violations() { } check_blocking_rules() { + echo "" echo "🔎 Verificando violações bloqueantes (P1)..." [ ! -f "$CODENARC_JSON" ] && echo "❌ Erro: Resultado do CodeNarc não encontrado. Não é possível verificar P1s." && return 1 @@ -167,18 +171,20 @@ check_blocking_rules() { echo "📊 Total de P1 encontradas: $p1_count" echo "⛔ Violações P1:" echo "$p1_violations" - echo "" if [ "${INPUT_REPORTER}" = "local" ]; then + echo "" echo "🏠 Modo de execução local: todas as violações P1 são bloqueantes." echo "💡 Corrija as violações antes de prosseguir." exit 1 fi + echo "" echo "⚠️ Analisando se as P1s estão em linhas alteradas..." build_changed_lines_cache if [ ! -s "$ALL_DIFF" ]; then + echo "" echo "⚠️ Diff vazio: Sem informações de linhas alteradas. Todas as P1s são consideradas bloqueantes." echo "💡 Corrija as violações ou use um bypass autorizado." exit 1 @@ -212,6 +218,7 @@ EOF exit 1 fi + echo "" echo "✅ Todas as violações P1 estão fora das linhas alteradas → merge permitido" } From 24c8b2ed2893d3fcf2b1e5e0edf636bbc4d2cc22 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 14:24:29 -0300 Subject: [PATCH 18/19] ajustes shellcheck --- entrypoint.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 7ed793f..d4b74db 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -99,8 +99,8 @@ generate_git_diff() { } build_changed_lines_cache() { - > "$CHANGED_FILES_CACHE" - > "$CHANGED_LINES_CACHE" + true > "$CHANGED_FILES_CACHE" + true > "$CHANGED_LINES_CACHE" generate_git_diff > "$ALL_DIFF" 2>/dev/null || return [ ! -s "$ALL_DIFF" ] && return @@ -126,8 +126,8 @@ build_changed_lines_cache() { } is_changed() { - local file="$1" - local line="$2" + file="$1" + line="$2" if [ -z "$line" ]; then [ -f "$CHANGED_FILES_CACHE" ] && grep -qF "$file" "$CHANGED_FILES_CACHE" && return 0 From 76d59b0ad42d5be84c5af8f9b0a53eddfe15bc20 Mon Sep 17 00:00:00 2001 From: "ana.alves" Date: Fri, 23 Jan 2026 16:14:31 -0300 Subject: [PATCH 19/19] ajustes --- testdata/test.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testdata/test.groovy b/testdata/test.groovy index 01d70d0..3e777fa 100644 --- a/testdata/test.groovy +++ b/testdata/test.groovy @@ -6,7 +6,7 @@ class TestCase2 { println "existing" } - // ADICIONAR ESTAS LINHAS - P1 dentro do diff + // P1 String insecureUrl = "http://api.example.com" void callApi() {