Skip to content

feat!: Move run logic in separate subcommand#9

Merged
thumbrise merged 2 commits into
mainfrom
separate-from-root
May 28, 2026
Merged

feat!: Move run logic in separate subcommand#9
thumbrise merged 2 commits into
mainfrom
separate-from-root

Conversation

@thumbrise
Copy link
Copy Markdown
Owner

@thumbrise thumbrise commented May 28, 2026

Summary by CodeRabbit

  • New Features

    • Added a run subcommand to validate commit messages over a specified range.
    • Support for --from, --to, --verbose, --no-color and --json; outputs either colored/text or JSON results.
  • Refactor

    • CLI reorganized to use a dedicated subcommand structure for clearer command organization.
  • Bug Fixes / Behavior

    • Nonzero exit (code 2) when violations are found.
    • Improved fatal error output formatting to stderr.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 28, 2026

📝 Walkthrough

Walkthrough

The PR extracts the run flow from the inline root command into a dedicated RunCMD subcommand (cmd/commands/run.go) with flag handling, logger setup, validator orchestration, and text/JSON output helpers; adds a ViolationsFoundError type; and simplifies cmd/root.go to delegate to the new subcommand with an exit error handler.

Changes

CLI Subcommand Refactoring

Layer / File(s) Summary
Run command definition with flags and action
cmd/commands/run.go
Flag variables (--from, --to, --verbose, --no-color, --json) are declared, and RunCMD export wires them to an action that configures logging, loads validator config, constructs a validator, runs commit range validation, and formats output based on violation presence and flag state.
Output formatters and logger configuration
cmd/commands/run.go
textOutput renders violations with SHA headers and outsider file paths; jsonOutput encodes violations as indented JSON; configureLogger creates a slog text handler that switches between info/debug levels and optionally enables source annotations based on --verbose.
Violations error type
cmd/errs/violations_found_error.go
Introduces ViolationsFoundError with a violation count, Error() string, constructor, and ExitCode() returning 2.
Root command simplification and exit handler
cmd/root.go
Root is simplified to a thin delegator registering commands.RunCMD and adding ExitErrHandler that derives an exit code, prints the error and exit code to stderr, and calls os.Exit.
Main stderr message update
main.go
Changes the stderr prefix for fatal CLI run failures from error: to fatal error:.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant RunCMD
  participant Logger
  participant Config
  participant Validator
  participant Output
  User->>RunCMD: invoke `commitlint-scope run` with flags (--from/--to/--json/--no-color/--verbose)
  RunCMD->>Logger: configureLogger (sets debug & AddSource if --verbose)
  RunCMD->>Config: validator.LoadConfig()
  RunCMD->>Validator: validator.NewValidator(cfg, nil, nil)
  RunCMD->>Validator: Validate(commit range)
  alt violations found
    Validator-->>RunCMD: []violations
    alt --json flag set
      RunCMD->>Output: jsonOutput(violations)
      Output-->>User: indented JSON
    else
      RunCMD->>Output: textOutput(violations)
      Output-->>User: colored grouped text
    end
  else no violations
    RunCMD-->>User: exit success
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

released

Poem

🐰 A rabbit hops through code so tight,
Flags now scurry into their own light,
Run took the reins and trimmed the root,
Errors count violations in tidy suit,
Hooray — clean paths and logger bright!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: moving validation logic from the root command into a separate 'run' subcommand, which is the primary refactoring across all modified files.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch separate-from-root

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@thumbrise thumbrise self-assigned this May 28, 2026
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/commands/run.go`:
- Around line 99-116: When violations are found (the violations slice is
non-empty in the run command), return a non-nil error instead of nil so the
process exits with status 1; add a sentinel error (e.g., ErrViolationsFound =
errors.New("violations found")) at package scope and, after printing the red
header and calling jsonOutput or textOutput (referencing flagRunJSON,
jsonOutput, textOutput, cmd.ErrWriter and cmd.Writer), return that sentinel
error (or wrap it) so callers (main.go) can trigger os.Exit(1).
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4dfabf69-95f5-452c-9d68-d67733b2aceb

📥 Commits

Reviewing files that changed from the base of the PR and between 8d4e62a and 199b960.

📒 Files selected for processing (2)
  • cmd/commands/run.go
  • cmd/root.go

Comment thread cmd/commands/run.go
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/errs/violations_found_error.go`:
- Around line 11-13: Update NewViolationsFound to validate that num > 0 and
return an error when it's not: change the signature to NewViolationsFound(num
int) (*ViolationsFoundError, error), check if num <= 0 and return (nil,
fmt.Errorf("invalid num: %d, must be > 0", num)), otherwise return the
constructed &ViolationsFoundError{num: num}, and update any callers (e.g., sites
that pass len(violations)) to handle the (value, error) return accordingly.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7b8e9a02-6626-4443-a572-2a1759bb9908

📥 Commits

Reviewing files that changed from the base of the PR and between 199b960 and 3323bc4.

📒 Files selected for processing (4)
  • cmd/commands/run.go
  • cmd/errs/violations_found_error.go
  • cmd/root.go
  • main.go
✅ Files skipped from review due to trivial changes (1)
  • main.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/root.go
  • cmd/commands/run.go

Comment on lines +11 to +13
func NewViolationsFound(num int) *ViolationsFoundError {
return &ViolationsFoundError{num: num}
}
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 | 🟡 Minor | ⚡ Quick win

Validate that num is positive.

The constructor should validate that num > 0 because a "violations found" error is semantically meaningless with zero or negative violations. While the current call site passes len(violations) (always non-negative), the exported constructor could be misused by future callers.

🛡️ Proposed fix to add validation
 func NewViolationsFound(num int) *ViolationsFoundError {
+	if num <= 0 {
+		panic(fmt.Sprintf("ViolationsFoundError requires num > 0, got %d", num))
+	}
 	return &ViolationsFoundError{num: num}
 }

Alternatively, return an error from the constructor:

-func NewViolationsFound(num int) *ViolationsFoundError {
+func NewViolationsFound(num int) (*ViolationsFoundError, error) {
+	if num <= 0 {
+		return nil, fmt.Errorf("violations count must be positive, got %d", num)
+	}
 	return &ViolationsFoundError{num: num}, nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func NewViolationsFound(num int) *ViolationsFoundError {
return &ViolationsFoundError{num: num}
}
func NewViolationsFound(num int) *ViolationsFoundError {
if num <= 0 {
panic(fmt.Sprintf("ViolationsFoundError requires num > 0, got %d", num))
}
return &ViolationsFoundError{num: num}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/errs/violations_found_error.go` around lines 11 - 13, Update
NewViolationsFound to validate that num > 0 and return an error when it's not:
change the signature to NewViolationsFound(num int) (*ViolationsFoundError,
error), check if num <= 0 and return (nil, fmt.Errorf("invalid num: %d, must be
> 0", num)), otherwise return the constructed &ViolationsFoundError{num: num},
and update any callers (e.g., sites that pass len(violations)) to handle the
(value, error) return accordingly.

@thumbrise thumbrise merged commit 8d31e12 into main May 28, 2026
4 checks passed
@thumbrise thumbrise deleted the separate-from-root branch May 28, 2026 21:20
@github-actions
Copy link
Copy Markdown

🎉 This PR is included in version 2.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@github-actions
Copy link
Copy Markdown

🎉 This PR is included in version 2.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant