Skip to content

chore: dead code removal, extract helpers, deduplicate logic - #98

Merged
sake92 merged 1 commit into
mainfrom
chore/codebase-cleanup-dead-code-and-refactors
Jun 18, 2026
Merged

chore: dead code removal, extract helpers, deduplicate logic#98
sake92 merged 1 commit into
mainfrom
chore/codebase-cleanup-dead-code-and-refactors

Conversation

@sake92

@sake92 sake92 commented Jun 18, 2026

Copy link
Copy Markdown
Owner

Dead code removal:

  • Remove unused closeStaleClassLoaders/closeClassLoader in DederProjectState
  • Remove unused expectedCredentialType in CredentialsResolver
  • Remove unused @tailrec import in PluginLoader
  • Remove TODO about plugin task namespacing (rely on prefix convention)

Refactors:

  • Extract withCliSpan helper in CliClientMessageHandler (13+ OTEL blocks → 1)
  • Extract ifHelpThenShow helper for --help flag checks (8 repeated blocks)
  • Extract scalafixTask private method in CoreTasks (fix/fixCheck 90% deduped)
  • Move shellSplit from TabCompleter to ShellUtils.scala
  • Deduplicate META-INF/services entries in JarUtils fat JAR assembly

Fix:

  • shellSplit: handle cursor in middle of last token (was missing currentWordIndex)

Tests:

  • Add ShellUtilsSuite with 11 tests for shellSplit

Summary by CodeRabbit

  • Refactor

    • Consolidated scalafix task execution for improved consistency
    • Enhanced CLI command handling structure for better reliability
    • Improved JAR file merging with optimized service file deduplication
  • Tests

    • Added comprehensive test coverage for shell command parsing

Dead code removal:
- Remove unused closeStaleClassLoaders/closeClassLoader in DederProjectState
- Remove unused expectedCredentialType in CredentialsResolver
- Remove unused @tailrec import in PluginLoader
- Remove TODO about plugin task namespacing (rely on prefix convention)

Refactors:
- Extract withCliSpan helper in CliClientMessageHandler (13+ OTEL blocks → 1)
- Extract ifHelpThenShow helper for --help flag checks (8 repeated blocks)
- Extract scalafixTask private method in CoreTasks (fix/fixCheck 90% deduped)
- Move shellSplit from TabCompleter to ShellUtils.scala
- Deduplicate META-INF/services entries in JarUtils fat JAR assembly

Fix:
- shellSplit: handle cursor in middle of last token (was missing currentWordIndex)

Tests:
- Add ShellUtilsSuite with 11 tests for shellSplit
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Five independent refactoring changes: ShellUtils.shellSplit is extracted from TabCompleter into its own object with tests; CliClientMessageHandler introduces withCliSpan/ifHelpThenShow helpers replacing repeated inline span blocks across all command handlers; CoreTasks consolidates fixTask/fixCheckTask into a single scalafixTask helper; JarUtils.mergeJars adds line-level deduplication for META-INF/services/* entries; and several dead-code items are removed from DederProjectState, PluginLoader, and CredentialsResolver.

Changes

Multi-area Refactoring and Cleanup

Layer / File(s) Summary
ShellUtils extraction and TabCompleter delegation
server/src/ba/sake/deder/cli/ShellUtils.scala, server/src/ba/sake/deder/cli/TabCompleter.scala, server/test/src/ba/sake/deder/cli/ShellUtilsSuite.scala
New ShellUtils object hosts shellSplit (with quote/escape/cursor-index tracking); TabCompleter.shellSplit is reduced to a one-line delegate; ShellUtilsSuite adds munit tests for tokenization and cursor-index edge cases.
CliClientMessageHandler span/help helper centralization
server/src/ba/sake/deder/cli/CliClientMessageHandler.scala
Adds private withCliSpan and ifHelpThenShow helpers; updates OTEL imports; rewrites all command handlers (help, version, modules, tasks, plugins, plan, exec, cancel, clean, import, complete, shutdown, tool) to use the new helpers instead of repeating inline span/help scaffolding.
CoreTasks scalafixTask helper
server/src/ba/sake/deder/CoreTasks.scala
Introduces private scalafixTask(name, extraArgs, watch) parameterizing scalafix task construction; fixTask and fixCheckTask become thin wrappers passing fixed watch values.
JarUtils META-INF/services deduplication
server/src/ba/sake/deder/jvm/JarUtils.scala
Adds deduplicateServiceLines helper and wires it into the META-INF/services/* write path, deduplicating provider entries while preserving comment lines using explicit UTF-8 encoding.
Dead-code and unused-import removal
server/src/ba/sake/deder/DederProjectState.scala, server/src/ba/sake/deder/plugin/PluginLoader.scala, server/src/ba/sake/deder/publish/CredentialsResolver.scala
Removes closeStaleClassLoaders/closeClassLoader methods and the URLClassLoader import from DederProjectState; removes the tailrec import from PluginLoader; removes the unused expectedCredentialType helper from CredentialsResolver.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • sake92/deder#91: Modifies the same fixTask/fixCheckTask subprocess construction in CoreTasks.scala, switching the java invocation to use an @argfile; directly overlaps with the scalafixTask helper introduced here.

Poem

🐇 Hop hop, the code grows neat,
Helpers shared, no more repeat!
ShellUtils splits the tokens right,
Spans now shine with uniform light.
Dead imports swept and cleanly gone —
The warren's tidy, hopping on! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: dead code removal, helper extraction, and logic deduplication across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
  • Commit unit tests in branch chore/codebase-cleanup-dead-code-and-refactors

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
server/src/ba/sake/deder/cli/CliClientMessageHandler.scala (1)

584-589: ⚡ Quick win

Trace the help fast path before exiting.

ifHelpThenShow emits Output + Exit(0) before callers enter withCliSpan, so requests like modules --help, tasks -h, etc. produce no CLI span with clientId/request.id. Pass the command name into this helper and wrap the help branch with withCliSpan(...), or call it from inside each command span. As per coding guidelines, **/*.scala: “Use traced() / javaFuture() wrappers from OTEL.scala for tracing spans in BSP/CLI requests with OpenTelemetry.”

Suggested direction
-  private def ifHelpThenShow(args: Seq[String], helpText: => String): Boolean =
+  private def ifHelpThenShow(command: String, args: Seq[String], helpText: => String): Boolean =
     if args == Seq("--help") || args == Seq("-h") then {
-      serverMessages.put(CliServerMessage.Output(helpText))
-      serverMessages.put(CliServerMessage.Exit(0))
+      withCliSpan(command) { _ =>
+        serverMessages.put(CliServerMessage.Output(helpText))
+        serverMessages.put(CliServerMessage.Exit(0))
+      }
       true
     } else false

Callers would then use e.g. ifHelpThenShow("modules", m.args, ...).

🤖 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 `@server/src/ba/sake/deder/cli/CliClientMessageHandler.scala` around lines 584
- 589, The `ifHelpThenShow` method emits messages and exits before callers can
establish an OpenTelemetry span, so help requests lack proper tracing context.
Update the method signature to accept a command name parameter, then wrap the
help branch (where Output and Exit messages are put) with `withCliSpan(...)`
using that command name. Update all callers of `ifHelpThenShow` to pass the
command name as the first argument (e.g., "modules", "tasks", etc.).

Source: Coding guidelines

server/test/src/ba/sake/deder/cli/ShellUtilsSuite.scala (1)

59-70: ⚡ Quick win

Add a regression test for cursor-before-first-word with leading spaces.

The suite currently misses the documented cursorTokenIndex = -1 case when cursor is before the first token (e.g., " deder", cursor 0).

Suggested test
+  test("cursor before first word after leading spaces") {
+    val (tokens, cursorIdx) = ShellUtils.shellSplit("   deder", 0)
+    assertEquals(tokens, Seq("deder"))
+    assertEquals(cursorIdx, -1)
+  }
🤖 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 `@server/test/src/ba/sake/deder/cli/ShellUtilsSuite.scala` around lines 59 -
70, The test suite is missing a regression test for the documented case where
the cursor is positioned before the first word with leading spaces (e.g., cursor
at position 0 in "   deder"), which should return cursorTokenIndex = -1. Add a
new test case in the ShellUtilsSuite that calls ShellUtils.shellSplit with a
string containing leading whitespace followed by a word, with the cursor
positioned at 0, and verify using assertEquals that tokens contains the word(s)
and cursorIdx equals -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 `@server/src/ba/sake/deder/cli/ShellUtils.scala`:
- Around line 25-27: The condition at line 25 that sets isCurrentWord = true
based on the cursor position does not properly account for leading whitespace
before the first word. When the cursor is in leading whitespace (e.g., at
position 0 in "   deder"), the code incorrectly identifies it as the current
word and then maps it to the wrong token index at lines 60-63, returning 0
instead of the documented -1. Fix this by ensuring isCurrentWord is only set to
true when the cursor position is actually within a word token, not in leading
whitespace before any words. Adjust the condition at line 25 to check that the
cursor position falls within a valid token's boundaries before setting
isCurrentWord to true.

In `@server/src/ba/sake/deder/jvm/JarUtils.scala`:
- Around line 198-206: The deduplicateServiceLines method does not trim
whitespace from lines before partitioning and filtering, which violates the Java
ServiceLoader specification and prevents proper deduplication. Modify the method
to trim each line immediately after splitting the raw string, ensuring that
entries with leading or trailing whitespace are normalized before being
partitioned into comments and entries, and that whitespace-only lines are
properly filtered out by the .nonEmpty check. Apply the trim operation to the
lines sequence right after calling linesIterator.toSeq.

---

Nitpick comments:
In `@server/src/ba/sake/deder/cli/CliClientMessageHandler.scala`:
- Around line 584-589: The `ifHelpThenShow` method emits messages and exits
before callers can establish an OpenTelemetry span, so help requests lack proper
tracing context. Update the method signature to accept a command name parameter,
then wrap the help branch (where Output and Exit messages are put) with
`withCliSpan(...)` using that command name. Update all callers of
`ifHelpThenShow` to pass the command name as the first argument (e.g.,
"modules", "tasks", etc.).

In `@server/test/src/ba/sake/deder/cli/ShellUtilsSuite.scala`:
- Around line 59-70: The test suite is missing a regression test for the
documented case where the cursor is positioned before the first word with
leading spaces (e.g., cursor at position 0 in "   deder"), which should return
cursorTokenIndex = -1. Add a new test case in the ShellUtilsSuite that calls
ShellUtils.shellSplit with a string containing leading whitespace followed by a
word, with the cursor positioned at 0, and verify using assertEquals that tokens
contains the word(s) and cursorIdx equals -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: 7a767b1e-61dd-4184-8a6c-cb2d7e62baff

📥 Commits

Reviewing files that changed from the base of the PR and between a31c628 and 096e79d.

📒 Files selected for processing (9)
  • server/src/ba/sake/deder/CoreTasks.scala
  • server/src/ba/sake/deder/DederProjectState.scala
  • server/src/ba/sake/deder/cli/CliClientMessageHandler.scala
  • server/src/ba/sake/deder/cli/ShellUtils.scala
  • server/src/ba/sake/deder/cli/TabCompleter.scala
  • server/src/ba/sake/deder/jvm/JarUtils.scala
  • server/src/ba/sake/deder/plugin/PluginLoader.scala
  • server/src/ba/sake/deder/publish/CredentialsResolver.scala
  • server/test/src/ba/sake/deder/cli/ShellUtilsSuite.scala
💤 Files with no reviewable changes (3)
  • server/src/ba/sake/deder/plugin/PluginLoader.scala
  • server/src/ba/sake/deder/publish/CredentialsResolver.scala
  • server/src/ba/sake/deder/DederProjectState.scala

Comment on lines +25 to +27
if i == cursorPos then {
isCurrentWord = true
}

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

Cursor-before-first-word case can return the wrong token index.

Line 25 sets isCurrentWord even when the cursor is still in leading whitespace, and Line 60-63 can then map that to the last token. For " deder" at cursor 0, this returns 0 instead of documented -1.

Suggested fix
-      } else if isCurrentWord && tokens.nonEmpty then {
+      } else if isCurrentWord && tokens.nonEmpty
+          && commandLine.indexWhere(ch => !ch.isWhitespace) <= cursorPos then {
         // cursor is in the middle of the last token (no trailing whitespace)
         currentWordIndex = tokens.length - 1
       }

Also applies to: 60-63

🤖 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 `@server/src/ba/sake/deder/cli/ShellUtils.scala` around lines 25 - 27, The
condition at line 25 that sets isCurrentWord = true based on the cursor position
does not properly account for leading whitespace before the first word. When the
cursor is in leading whitespace (e.g., at position 0 in "   deder"), the code
incorrectly identifies it as the current word and then maps it to the wrong
token index at lines 60-63, returning 0 instead of the documented -1. Fix this
by ensuring isCurrentWord is only set to true when the cursor position is
actually within a word token, not in leading whitespace before any words. Adjust
the condition at line 25 to check that the cursor position falls within a valid
token's boundaries before setting isCurrentWord to true.

Comment on lines +198 to +206
/** Deduplicate lines in a META-INF/services/ file.
* Keeps comments (#) and non-empty unique service provider entries.
*/
private def deduplicateServiceLines(raw: String): String = {
val lines = raw.linesIterator.toSeq
val (comments, entries) = lines.partition(_.startsWith("#"))
val uniqueEntries = entries.filter(_.nonEmpty).distinct
(comments ++ uniqueEntries).mkString("\n")
}

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

Trim lines before partitioning and filtering.

The Java ServiceLoader specification requires whitespace to be trimmed from each line. Without trimming:

  • Entries like "com.example.Provider" and " com.example.Provider" won't be deduplicated.
  • Whitespace-only lines (e.g., " ") won't be filtered out by .nonEmpty.

This defeats the purpose of deduplication and violates the services file format.

🛠️ Proposed fix
 private def deduplicateServiceLines(raw: String): String = {
-  val lines = raw.linesIterator.toSeq
+  val lines = raw.linesIterator.map(_.trim).filter(_.nonEmpty).toSeq
   val (comments, entries) = lines.partition(_.startsWith("#"))
-  val uniqueEntries = entries.filter(_.nonEmpty).distinct
+  val uniqueEntries = entries.distinct
   (comments ++ uniqueEntries).mkString("\n")
 }
📝 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
/** Deduplicate lines in a META-INF/services/ file.
* Keeps comments (#) and non-empty unique service provider entries.
*/
private def deduplicateServiceLines(raw: String): String = {
val lines = raw.linesIterator.toSeq
val (comments, entries) = lines.partition(_.startsWith("#"))
val uniqueEntries = entries.filter(_.nonEmpty).distinct
(comments ++ uniqueEntries).mkString("\n")
}
private def deduplicateServiceLines(raw: String): String = {
val lines = raw.linesIterator.map(_.trim).filter(_.nonEmpty).toSeq
val (comments, entries) = lines.partition(_.startsWith("#"))
val uniqueEntries = entries.distinct
(comments ++ uniqueEntries).mkString("\n")
}
🤖 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 `@server/src/ba/sake/deder/jvm/JarUtils.scala` around lines 198 - 206, The
deduplicateServiceLines method does not trim whitespace from lines before
partitioning and filtering, which violates the Java ServiceLoader specification
and prevents proper deduplication. Modify the method to trim each line
immediately after splitting the raw string, ensuring that entries with leading
or trailing whitespace are normalized before being partitioned into comments and
entries, and that whitespace-only lines are properly filtered out by the
.nonEmpty check. Apply the trim operation to the lines sequence right after
calling linesIterator.toSeq.

@sake92
sake92 merged commit 6dec2bb into main Jun 18, 2026
2 of 4 checks passed
@sake92
sake92 deleted the chore/codebase-cleanup-dead-code-and-refactors branch June 18, 2026 10:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant