Skip to content

Code cleanup and refactoring#14

Merged
mvazquezc merged 3 commits intoopenshift-kni:mainfrom
mvazquezc:code-cleanup
Apr 28, 2026
Merged

Code cleanup and refactoring#14
mvazquezc merged 3 commits intoopenshift-kni:mainfrom
mvazquezc:code-cleanup

Conversation

@mvazquezc
Copy link
Copy Markdown
Collaborator

No description provided.

Signed-off-by: Mario Vazquez <mavazque@redhat.com>
Co-authored-by: Claude <noreply@anthropic.com>
@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Apr 24, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: mvazquezc

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Apr 24, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 24, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 84f10c4f-0cfb-41d3-8709-f12241b5a979

📥 Commits

Reviewing files that changed from the base of the PR and between f40fcf2 and 80df51a.

📒 Files selected for processing (1)
  • AGENTS.md
✅ Files skipped from review due to trivial changes (1)
  • AGENTS.md

📝 Walkthrough

Walkthrough

Consolidates ANSI/color handling into report packages, promotes several helpers to package scope, makes analyzer output-mode validation explicit with an error on unsupported modes, updates HTML escaping, and adjusts tests to match refactored helpers and escaping behavior.

Changes

Cohort / File(s) Summary
Analyzer output-mode
pkg/analyzer/analyzer.go
Replaced implicit fallback with explicit switch on mode: "reporting" and "simple" route to distinct generators; invalid modes now return an error.
Parser color constants removed
pkg/parser/diff.go
Removed file-level ANSI color constant block used for terminal formatting; diff parsing APIs unchanged.
Text report & tests
pkg/report/text.go, pkg/report/text_test.go
Added local ANSI constants and ansiRegex/stripANSI; removed dependency on parser color constants and ColorOrange; introduced minimalDiffCheck and shared matchingRuleIDs helper; tests updated to use local color identifiers.
HTML report & tests
pkg/report/html.go, pkg/report/html_test.go
Switched escapeHTML to html.EscapeString; use minimalDiffCheck for empty diffs; ignore condition matches with empty/whitespace MatchedText; test updated to expect single-quote escaping.
Reporting generator & tests
pkg/report/reporting.go, pkg/report/reporting_test.go
Moved several helpers to package-level (matchingRuleIDs, stripANSI, minimalDiffCheck); removed ReportingGenerator-bound helpers and extractDiffChecks; tests adjusted to call package helpers and remove two extract-check tests.
Rules engine & tests
pkg/rules/engine.go, pkg/rules/engine_test.go
Promoted pure helpers to package scope (detectSectionHeader, createSectionHeaderResult, globToRegex, matchesGlob); added highestVersionFromImpacts and centralized impactPriority; unified label/annotation defaulting; tests updated to use *All checker variants and capture full match slices.
Docs
AGENTS.md
Added “Conscious Design Choices” noting intentional omission of error checks for CLI fmt.Fprint* calls in report generators.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 64.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The PR title 'Code cleanup and refactoring' is generic and does not convey specific information about the actual changes made across multiple packages and systems. Consider using a more specific title that highlights the primary focus, such as 'Refactor report generators and rules engine helpers' or 'Extract common patterns and simplify report generation logic'.
Description check ❓ Inconclusive No pull request description was provided by the author, making it impossible to assess whether the intended changes align with the actual modifications. Add a pull request description explaining the key refactoring objectives, such as consolidating helper functions, improving code reusability, or other specific goals achieved in this changeset.
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/report/html.go`:
- Around line 450-468: The current condByID map groups ConditionResult by
condResult.RuleID so multiple matched conditions for the same rule overwrite
each other; change the map to key by a condition-unique identifier (use the
ConditionResult's unique field if available, e.g. condResult.ID or
condResult.ConditionID; if none exists, use a composite key like
condResult.RuleID + "#" + index) when populating condByID from
ruleResult.Conditions, and then look up cond := condByID[id] using that
condition-unique id when building ruleTags so each RuleTagData (ID, Comment,
Impact, ImpactCSS via getImpactCSS) preserves the specific condition's metadata.

In `@pkg/report/text.go`:
- Line 332: The fmt.Fprint/Fprintf/Fprintln calls (e.g., fmt.Fprint(g.writer,
ColorGreen+line+ColorReset) in the package) currently ignore write errors;
replace these direct calls with small wrapper methods on the generator (e.g.,
g.write, g.writef, g.writeln) that call fmt.Fprint/Fprintf/Fprintln into
g.writer, capture the first non-nil error into a field like g.writeErr and
short-circuit further writes, and then change Generate(...) to return g.writeErr
instead of nil; apply the same replacement for the other occurrences noted (the
other fmt.* calls around the file/lines) so all write failures are propagated.
- Around line 490-499: In matchingRuleIDs, empty or whitespace
condResult.MatchedText causes strings.Contains to always return true; update the
function (matchingRuleIDs) to trim condResult.MatchedText into trimmedMatched
and skip the condition if trimmedMatched == "" before calling strings.Contains,
so only non-empty matches are considered (preserve the existing seen map logic
and RuleID deduplication for condResult.RuleID).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 3194d3e7-7c20-40d6-8a61-57381488110c

📥 Commits

Reviewing files that changed from the base of the PR and between 8de9f8b and 911840c.

📒 Files selected for processing (10)
  • pkg/analyzer/analyzer.go
  • pkg/parser/diff.go
  • pkg/report/html.go
  • pkg/report/html_test.go
  • pkg/report/reporting.go
  • pkg/report/reporting_test.go
  • pkg/report/text.go
  • pkg/report/text_test.go
  • pkg/rules/engine.go
  • pkg/rules/engine_test.go
💤 Files with no reviewable changes (1)
  • pkg/parser/diff.go

Comment thread pkg/report/html.go Outdated
Comment on lines +450 to +468
// Build a lookup from rule ID to condition details.
condByID := make(map[string]rules.ConditionResult)
for _, condResult := range ruleResult.Conditions {
if condResult.ConditionType == diffType && condResult.Matched {
trimmedMatched := strings.TrimSpace(condResult.MatchedText)
if strings.Contains(trimmedLine, trimmedMatched) || strings.Contains(trimmedMatched, trimmedLine) {
if !seen[condResult.RuleID] {
seen[condResult.RuleID] = true
ruleTags = append(ruleTags, RuleTagData{
ID: condResult.RuleID,
Comment: condResult.Comment,
Impact: condResult.Impact,
ImpactCSS: getImpactCSS(condResult.Impact),
})
}
if condResult.Matched {
if _, exists := condByID[condResult.RuleID]; !exists {
condByID[condResult.RuleID] = condResult
}
}
}

var ruleTags []RuleTagData
for _, id := range ids {
cond := condByID[id]
ruleTags = append(ruleTags, RuleTagData{
ID: id,
Comment: cond.Comment,
Impact: cond.Impact,
ImpactCSS: getImpactCSS(cond.Impact),
})
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Preserve per-condition metadata when building rule tags.

Line 451 stores a single ConditionResult per RuleID, and Line 462 reuses it for every matched line. If one rule has multiple matched conditions, the UI can show the wrong tooltip/impact for that specific line.

💡 Suggested fix
 func getMatchingRulesHTML(line, diffType string, ruleResult rules.EvaluationResult) []RuleTagData {
 	ids := matchingRuleIDs(line, diffType, ruleResult)
 	if len(ids) == 0 {
 		return nil
 	}
 
-	// Build a lookup from rule ID to condition details.
-	condByID := make(map[string]rules.ConditionResult)
-	for _, condResult := range ruleResult.Conditions {
-		if condResult.Matched {
-			if _, exists := condByID[condResult.RuleID]; !exists {
-				condByID[condResult.RuleID] = condResult
-			}
-		}
-	}
-
 	var ruleTags []RuleTagData
+	trimmedLine := strings.TrimSpace(line)
 	for _, id := range ids {
-		cond := condByID[id]
+		var cond rules.ConditionResult
+		found := false
+		for _, c := range ruleResult.Conditions {
+			if !c.Matched || c.RuleID != id || c.ConditionType != diffType {
+				continue
+			}
+			trimmedMatched := strings.TrimSpace(c.MatchedText)
+			if strings.Contains(trimmedLine, trimmedMatched) || strings.Contains(trimmedMatched, trimmedLine) {
+				cond = c
+				found = true
+				break
+			}
+		}
+		if !found {
+			continue
+		}
+
 		ruleTags = append(ruleTags, RuleTagData{
 			ID:        id,
 			Comment:   cond.Comment,
 			Impact:    cond.Impact,
 			ImpactCSS: getImpactCSS(cond.Impact),
 		})
 	}
 	return ruleTags
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/report/html.go` around lines 450 - 468, The current condByID map groups
ConditionResult by condResult.RuleID so multiple matched conditions for the same
rule overwrite each other; change the map to key by a condition-unique
identifier (use the ConditionResult's unique field if available, e.g.
condResult.ID or condResult.ConditionID; if none exists, use a composite key
like condResult.RuleID + "#" + index) when populating condByID from
ruleResult.Conditions, and then look up cond := condByID[id] using that
condition-unique id when building ruleTags so each RuleTagData (ID, Comment,
Impact, ImpactCSS via getImpactCSS) preserves the specific condition's metadata.

Comment thread pkg/report/text.go
hasNeedsReview = true
}
fmt.Fprint(g.writer, parser.ColorGreen+line+parser.ColorReset)
fmt.Fprint(g.writer, ColorGreen+line+ColorReset)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Propagate write failures instead of silently continuing

These fmt.Fprint calls ignore write errors, and Generate(...) still returns nil. On broken pipes/files, report output can be truncated without surfacing failure.

Suggested direction
 type TextGenerator struct {
 	ruleEngine *rules.Engine
 	writer     io.Writer
+	writeErr   error
 }
+
+func (g *TextGenerator) write(parts ...string) {
+	if g.writeErr != nil {
+		return
+	}
+	_, g.writeErr = fmt.Fprint(g.writer, strings.Join(parts, ""))
+}

Then replace direct fmt.Fprint/Fprintf/Fprintln incrementally with wrapper methods and return g.writeErr from Generate.

Also applies to: 351-351, 409-409

🧰 Tools
🪛 golangci-lint (2.11.4)

[error] 332-332: Error return value of fmt.Fprint is not checked

(errcheck)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/report/text.go` at line 332, The fmt.Fprint/Fprintf/Fprintln calls (e.g.,
fmt.Fprint(g.writer, ColorGreen+line+ColorReset) in the package) currently
ignore write errors; replace these direct calls with small wrapper methods on
the generator (e.g., g.write, g.writef, g.writeln) that call
fmt.Fprint/Fprintf/Fprintln into g.writer, capture the first non-nil error into
a field like g.writeErr and short-circuit further writes, and then change
Generate(...) to return g.writeErr instead of nil; apply the same replacement
for the other occurrences noted (the other fmt.* calls around the file/lines) so
all write failures are propagated.

Comment thread pkg/report/text.go
Signed-off-by: Mario Vazquez <mavazque@redhat.com>
Co-authored-by: Claude <noreply@anthropic.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
pkg/report/text.go (1)

332-332: ⚠️ Potential issue | 🟠 Major

Propagate writer failures instead of silently continuing.

These writes still ignore returned errors, so output can be truncated without surfacing failure, and Generate(...) still returns nil.

Suggested fix
 type TextGenerator struct {
 	ruleEngine *rules.Engine
 	writer     io.Writer
+	writeErr   error
 }

+func (g *TextGenerator) write(parts ...string) {
+	if g.writeErr != nil {
+		return
+	}
+	_, g.writeErr = fmt.Fprint(g.writer, strings.Join(parts, ""))
+}
+
 func (g *TextGenerator) Generate(w io.Writer, report types.ValidationReport) error {
 	g.writer = w
+	g.writeErr = nil
 	...
-	return nil
+	return g.writeErr
 }

-	fmt.Fprint(g.writer, ColorGreen+line+ColorReset)
+	g.write(ColorGreen, line, ColorReset)

Also applies to: 351-351, 409-409

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/report/text.go` at line 332, The writes in the text report code are
ignoring fmt.Fprint errors (e.g., the call that prints
ColorGreen+line+ColorReset and the other writes at the other noted locations),
so change those calls to check and return or wrap the error instead of
discarding it; update the containing function (e.g., Generate(...) / the writer
methods in pkg/report/text.go) to propagate the fmt.Fprint / fmt.Fprintln errors
up to the caller (return the error or wrap with context) so that Generate(...)
no longer returns nil when a write fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@pkg/report/text.go`:
- Line 332: The writes in the text report code are ignoring fmt.Fprint errors
(e.g., the call that prints ColorGreen+line+ColorReset and the other writes at
the other noted locations), so change those calls to check and return or wrap
the error instead of discarding it; update the containing function (e.g.,
Generate(...) / the writer methods in pkg/report/text.go) to propagate the
fmt.Fprint / fmt.Fprintln errors up to the caller (return the error or wrap with
context) so that Generate(...) no longer returns nil when a write fails.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 7ad7dbcb-69bd-49c2-9582-055612d9734b

📥 Commits

Reviewing files that changed from the base of the PR and between 911840c and f40fcf2.

📒 Files selected for processing (2)
  • pkg/report/html.go
  • pkg/report/text.go

Signed-off-by: Mario Vazquez <mavazque@redhat.com>
@mvazquezc mvazquezc merged commit 28cc22d into openshift-kni:main Apr 28, 2026
5 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant