Skip to content

StringUtils.chompLast: fix StringIndexOutOfBoundsException when sep longer than str#401

Open
elharo wants to merge 1 commit into
masterfrom
fix/stringutils-chomplast-iob
Open

StringUtils.chompLast: fix StringIndexOutOfBoundsException when sep longer than str#401
elharo wants to merge 1 commit into
masterfrom
fix/stringutils-chomplast-iob

Conversation

@elharo

@elharo elharo commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

StringUtils.chompLast(String str, String sep) at line 857 computes str.substring(str.length() - sep.length()) without checking whether sep is longer than str. When sep.length() > str.length(), the start index is negative, throwing StringIndexOutOfBoundsException.

Fix: Added || sep.length() > str.length() to the existing guard, returning str unchanged when the separator is longer than the string (since it can't possibly end with that separator).

Fixes #400

Copilot AI 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.

Pull request overview

Fixes StringUtils.chompLast(String str, String sep) to avoid StringIndexOutOfBoundsException when sep.length() > str.length() by returning str unchanged in that case (consistent with “can’t possibly end with sep”). This aligns with the reported behavior in Issue #400.

Changes:

  • Added a guard in StringUtils.chompLast(str, sep) to return early when the separator is longer than the input string.
  • Added a regression test covering chompLast("x", "ab").

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/main/java/org/apache/maven/shared/utils/StringUtils.java Adds length guard to prevent negative substring start index when sep is longer than str.
src/test/java/org/apache/maven/shared/utils/StringUtilsTest.java Adds a regression test to verify chompLast returns the original string when sep is longer.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@elharo elharo requested a review from gnodet July 1, 2026 14:17
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.

StringUtils.chompLast throws StringIndexOutOfBoundsException when sep is longer than str

2 participants