Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Dec 18, 2025

  • Fix URI parsing with double percent signs (%%)
  • Add test case for URIs with %% sequences
  • Move %% replacement to input URI string (consistent with + handling)
  • All tests pass
Original prompt

This section details on the original issue you should resolve

<issue_title>Absolute.uri падает на парсинге uri с процентами</issue_title>
<issue_description>```
java.lang.IllegalArgumentException: java.lang.IllegalArgumentException: Malformed escape pair at index 80: file:/C%3A/git/aaa/aaaaa6%20(copy)/bit_user_functions/KPI%20ААА%20aaaaaaaa%2C%20%%20(более%2060%20дней)%2C%20руб.bsl


## Comments on the Issue (you are @copilot in this section)

<comments>
</comments>


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI self-assigned this Dec 18, 2025
@coderabbitai
Copy link

coderabbitai bot commented Dec 18, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Исправлена обработка URI-строк, содержащих двойные процентные знаки. В методе Absolute.uri() добавлена нормализация последовательностей "%%", которые преобразуются в "%25%" перед декодированием. Добавлен соответствующий тестовый случай для проверки этого поведения.

Changes

Когорта / Файл(ы) Описание изменений
Исправление обработки URI с двойными процентами
src/main/java/com/github/_1c_syntax/utils/Absolute.java
Добавлена замена "%%" на "%25%" в методе uri() для корректной нормализации кодирования перед декодированием строки URI
Тест для новой функциональности
src/test/java/com/github/_1c_syntax/utils/AbsoluteTest.java
Добавлен новый тест testUriWithDoublePercent(), проверяющий корректное парсирование URI с встроенными "%%" последовательностями

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Требуется проверить, что нормализация "%%" → "%25%" решает проблему malformed escape pair
  • Убедиться, что замена не нарушает обработку других закодированных символов (особенно существующей замены "+" → "%2B")
  • Валидировать, что новый тестовый случай адекватно проверяет граничные случаи

Possibly related PRs

Poem

Кролик прыгает с весельем, 🐰
"Процент, процент — вот мне беда!"
"%%" стал "%25%" с уменьем,
Теперь парсится всё, всегда! ✨
URI больше не упадёт,
Двойной процент спасенье ждёт! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Заголовок точно описывает основное изменение: исправление ошибки парсинга URI с двойными процентами (%%)
Description check ✅ Passed Описание связано с изменениями в коде: объясняет цель исправления, добавление теста и обработку %% последовательностей
Linked Issues check ✅ Passed Код обрабатывает требование #44 путём добавления замены %% на %25%% в методе Absolute.uri() и соответствующего теста для проверки
Out of Scope Changes check ✅ Passed Все изменения относятся к исправлению обработки %% при парсинге URI: изменение в основном коде и добавление теста
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch copilot/fix-absolute-uri-parsing

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.

Co-authored-by: nixel2007 <1132840+nixel2007@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix absolute.uri parsing issue with percent encoding Fix URI parsing failure on malformed percent encoding (double %%) Dec 18, 2025
Copilot AI requested a review from nixel2007 December 18, 2025 09:03
@nixel2007
Copy link
Member

@copilot я настроил тебе firewall, попробуй ещё раз

Copy link
Contributor Author

Copilot AI commented Dec 18, 2025

@copilot я настроил тебе firewall, попробуй ещё раз

Build completed successfully! All tests pass and javadoc generation works now. Commit: 63dd675

Co-authored-by: nixel2007 <1132840+nixel2007@users.noreply.github.com>
@sonarqubecloud
Copy link

@nixel2007 nixel2007 marked this pull request as ready for review December 18, 2025 09:25
Copilot AI review requested due to automatic review settings December 18, 2025 09:25
@nixel2007
Copy link
Member

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Dec 18, 2025

✅ Actions performed

Full review triggered.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a URI parsing failure that occurs when URIs contain double percent signs (%%), which was causing an IllegalArgumentException with "Malformed escape pair" errors. The fix addresses the issue by preprocessing the input URI string to handle the malformed encoding.

Key changes:

  • Modified Absolute.uri(String) to replace %% sequences with %25% before parsing
  • Added a test case verifying that URIs containing %%20 can be successfully parsed

Reviewed changes

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

File Description
src/main/java/com/github/_1c_syntax/utils/Absolute.java Added %% to %25% replacement in the URI preprocessing step alongside existing + handling
src/test/java/com/github/_1c_syntax/utils/AbsoluteTest.java Added test case for parsing URIs with double percent signs using the problematic URI from the issue report

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


@Test
void testUriWithDoublePercent() {
// given
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

Consider adding a comment explaining what behavior is being tested. For example, clarifying that %%20 in the original URI should be interpreted as a malformed encoding and how it should be handled (e.g., "Tests that double percent signs followed by valid hex are treated as percent-encoded percent sign followed by the decoded character").

Suggested change
// given
// given
// The sequence "%%20" should be interpreted as a percent-encoded '%' followed by a decoded space,
// so the resulting path contains the substring "% " rather than treating "%%20" as malformed encoding.

Copilot uses AI. Check for mistakes.
public static URI uri(@NonNull String uri) {
try {
var url = new URL(uri.replace("+", "%2B"));
var url = new URL(uri.replace("+", "%2B").replace("%%", "%25%"));
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

The replacement "%%" to "%25%" is problematic and will produce incorrect results. When %% appears in a URI, it should be replaced with %25%25 (two encoded percent signs), not %25%.

For example:

  • Input: %%20 (malformed: double percent followed by "20")
  • Current fix: %25%20 → decodes to % (percent followed by space)
  • Expected: User likely meant either %20 (space) or %%20 should be treated as literal %20

The current replacement creates an incomplete escape sequence (%25%) where the % at the end starts a new escape sequence. This could fail if followed by non-hex characters, or produce unexpected results if followed by hex characters.

Consider either:

  1. Replace %% with %25%25 to properly encode both percent signs
  2. Replace %% with %25 to treat it as a single escaped percent
  3. Clarify the intended behavior and add test cases for edge cases like %%%, %%25, %%xx (non-hex)
Suggested change
var url = new URL(uri.replace("+", "%2B").replace("%%", "%25%"));
var url = new URL(uri.replace("+", "%2B").replace("%%", "%25%25"));

Copilot uses AI. Check for mistakes.
Comment on lines +225 to +237
@Test
void testUriWithDoublePercent() {
// given
var uriString = "file:/C%3A/git/aaa/aaaaa6%20(copy)/bit_user_functions/KPI%20ААА%20aaaaaaaa%2C%20%%20(более%2060%20дней)%2C%20руб.bsl";

// when
var uri = Absolute.uri(uriString);

// then
assertThat(uri).hasScheme("file");
assertThat(uri.getPath()).contains("% ");
assertThat(uri.getPath()).endsWith(".bsl");
}
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

The test case only covers the specific reported issue (%%20 sequence) but doesn't verify edge cases that could expose issues with the replacement logic:

  1. Multiple consecutive %% sequences (e.g., %%%%)
  2. Triple percent signs (%%%)
  3. %% followed by non-hex characters (e.g., %%XX)
  4. %% followed by valid hex that forms another escape (e.g., %%25)
  5. %% at the end of the URI

Adding tests for these edge cases would help ensure the fix handles all scenarios correctly and doesn't introduce new parsing issues.

Copilot uses AI. Check for mistakes.
Copy link

@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: 0

🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/utils/AbsoluteTest.java (1)

225-237: Отличное покрытие тестом основного сценария.

Тест напрямую проверяет исправление из issue #44, используя реальный пример URI с последовательностью %%20. Проверки корректны: схема файла, наличие % в пути и правильное расширение файла.

Для повышения надёжности можно добавить дополнительные тестовые случаи:

🔎 Предлагаемые дополнительные тесты
@Test
void testUriWithMultipleDoublePercents() {
  // given - несколько последовательностей %%
  var uriString = "file:///path/%%20test%%20file.bsl";

  // when
  var uri = Absolute.uri(uriString);

  // then
  assertThat(uri).hasScheme("file");
  assertThat(uri.getPath()).endsWith(".bsl");
}

@Test
void testUriWithTriplePercent() {
  // given - тройной процент %%%
  var uriString = "file:///path/%%%20file.bsl";

  // when
  var uri = Absolute.uri(uriString);

  // then
  assertThat(uri).hasScheme("file");
  assertThat(uri.getPath()).endsWith(".bsl");
}
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8817a9a and 305df4f.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/utils/Absolute.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/utils/AbsoluteTest.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: CodeQL analysis (java)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
🔇 Additional comments (1)
src/main/java/com/github/_1c_syntax/utils/Absolute.java (1)

51-51: Правильное решение для обработки некорректно закодированных URI с двойными процентами.

Замена %% на %25% перед парсингом корректно обрабатывает последовательности вроде %%20. После декодирования URL %25%20 преобразуется в % (процент-пробел), что подтверждается тестом testUriWithDoublePercent(). Подход согласован с обработкой символа +%2B.

Примечание об граничных случаях: последовательности вроде %%% будут преобразованы в %25%% (по-прежнему содержат %%), однако такие случаи крайне редки и не покрыты тестами, так как они не представляют практическую проблему в реальных URI.

@nixel2007 nixel2007 merged commit c1e12f1 into master Dec 18, 2025
21 checks passed
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.

Absolute.uri падает на парсинге uri с процентами

2 participants