Skip to content

fix #1514 Замена dotnetzip на другой форк#1558

Merged
EvilBeaver merged 5 commits into
developfrom
feature/dotnetzip-replacement
Aug 3, 2025
Merged

fix #1514 Замена dotnetzip на другой форк#1558
EvilBeaver merged 5 commits into
developfrom
feature/dotnetzip-replacement

Conversation

@EvilBeaver

@EvilBeaver EvilBeaver commented Aug 3, 2025

Copy link
Copy Markdown
Owner

Заменена реализация DotNetZip на ту в которой уязвимость отсутствует.

Summary by CodeRabbit

  • New Features

    • Improved error messages for missing native API proxy libraries, now including the full file path.
    • Enhanced test coverage with a new procedure for verifying Unicode characters in ZIP file names (currently disabled due to a known issue).
  • Bug Fixes

    • Corrected file path and filename assertions in ZIP-related tests to ensure proper test execution.
  • Refactor

    • Updated ZIP file handling to use a new method for setting default encoding, improving reliability and thread safety.
    • Expanded encoding comparison logic for better compatibility with different encoding instances.
  • Chores

    • Replaced the DotNetZip library dependency with ProDotNetZip for ZIP operations.
    • Disabled special Git handling for .zip files.

@coderabbitai

coderabbitai Bot commented Aug 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes update ZIP file handling by replacing the DotNetZip library with ProDotNetZip, introducing a new thread-safe mechanism for setting ZIP encoding, and improving encoding detection logic. Test files are adjusted for better diagnostics and to account for known library issues. Minor project and attribute configuration updates are also included.

Changes

Cohort / File(s) Change Summary
Git Attributes Update
.gitattributes
Comments out the .zip pattern, disabling Git LFS handling for .zip files.
NuGet Package Migration
src/OneScript.StandardLibrary/OneScript.StandardLibrary.csproj
Replaces the "DotNetZip" NuGet dependency with "ProDotNetZip" version 1.20.0.
Encoding Comparison Enhancement
src/OneScript.StandardLibrary/Text/TextEncodingEnum.cs
Broadens encoding matching logic for code pages 866 and 1251; improves exception context.
ZIP Encoding Management
src/OneScript.StandardLibrary/Zip/DotNetZipEncoding.cs
Adds a new internal static class to set ZIP default encoding in a thread-safe, one-time manner.
ZIP Reader/Writer Refactor
src/OneScript.StandardLibrary/Zip/ZipReader.cs, src/OneScript.StandardLibrary/Zip/ZipWriter.cs
Refactors encoding setup to use the new DotNetZipEncoding class; adds null check and exception for ZIP entry extraction.
Test Improvements and Adjustments
tests/native-api.os, tests/zip/test-zip.os
Improves error messages with file paths, disables a Unicode filename test due to a library issue, corrects file path and assertion in ZIP tests, and adds a new test procedure.

Sequence Diagram(s)

sequenceDiagram
    participant ZipReader
    participant DotNetZipEncoding
    participant ZipFile

    ZipReader->>DotNetZipEncoding: SetDefault(Encoding.GetEncoding(866))
    DotNetZipEncoding->>ZipFile: Set DefaultEncoding (thread-safe, once)
    ZipReader->>ZipFile: Open ZIP file with default encoding
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

In the warren of code, a ZIP file hops,
With encodings set—no more sudden stops!
ProDotNetZip now leads the way,
Tests refined for a brighter day.
A bunny’s delight, with bugs in retreat,
Our software garden grows ever neat! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/dotnetzip-replacement

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (3)
src/OneScript.StandardLibrary/Zip/DotNetZipEncoding.cs (2)

20-23: Упростите конструктор.

Инициализация _encodingIsSet = false избыточна, так как это значение по умолчанию для bool. Конструктор можно убрать.

-        static DotNetZipEncoding()
-        {
-            _encodingIsSet = false;
-        }

45-60: Рассмотрите удаление неиспользуемого кода.

Метод SetDefaultEncodingViaReflection определен но не используется. Если он предназначен как резервный вариант для других версий библиотеки, добавьте комментарий с объяснением. Иначе рассмотрите его удаление.

src/OneScript.StandardLibrary/Zip/ZipWriter.cs (1)

55-55: Отличная интеграция с новым механизмом управления кодировками.

Использование DotNetZipEncoding.SetDefault() вместо прямого присваивания обеспечивает потокобезопасность и централизованное управление кодировкой.

Рассмотрите улучшение комментария:

-            DotNetZipEncoding.SetDefault(Encoding.GetEncoding(866)); // fuck non-russian encodings on non-ascii files
+            DotNetZipEncoding.SetDefault(Encoding.GetEncoding(866)); // default encoding for non-ASCII file names
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0cc0345 and 2ab4e87.

⛔ Files ignored due to path filters (1)
  • tests/zip/fixtures/testUTF8.zip is excluded by !**/*.zip
📒 Files selected for processing (8)
  • .gitattributes (1 hunks)
  • src/OneScript.StandardLibrary/OneScript.StandardLibrary.csproj (1 hunks)
  • src/OneScript.StandardLibrary/Text/TextEncodingEnum.cs (2 hunks)
  • src/OneScript.StandardLibrary/Zip/DotNetZipEncoding.cs (1 hunks)
  • src/OneScript.StandardLibrary/Zip/ZipReader.cs (2 hunks)
  • src/OneScript.StandardLibrary/Zip/ZipWriter.cs (1 hunks)
  • tests/native-api.os (1 hunks)
  • tests/zip/test-zip.os (4 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: EvilBeaver
PR: EvilBeaver/OneScript#0
File: :0-0
Timestamp: 2024-08-05T18:27:08.563Z
Learning: For each new pull request in the EvilBeaver/OneScript repository, include a poem in Russian.
Learnt from: EvilBeaver
PR: EvilBeaver/OneScript#1557
File: src/VSCode.DebugAdapter/Transport/RpcOperationException.cs:11-11
Timestamp: 2025-07-18T12:25:24.078Z
Learning: EvilBeaver prefers to preserve original namespaces for types involved in binary serialization or cross-version compatibility, even if the type is not directly serialized, to maintain overall system compatibility.
Learnt from: EvilBeaver
PR: EvilBeaver/OneScript#1557
File: src/VSCode.DebugAdapter/Transport/DebugClientFactory.cs:60-0
Timestamp: 2025-07-16T12:44:12.167Z
Learning: EvilBeaver prefers fail-fast error handling in debugging contexts - when stream operations fail in debug client factories, exceptions should be thrown to terminate the process rather than handled gracefully with fallback mechanisms.
Learnt from: EvilBeaver
PR: EvilBeaver/OneScript#1555
File: Build.csproj:35-38
Timestamp: 2025-07-10T11:08:13.756Z
Learning: EvilBeaver prefers to see documentation links when technical claims are made about MSBuild syntax and property functions.
📚 Learning: в репозитории evilbeaver/onescript всегда нужно говорить по-русски....
Learnt from: nixel2007
PR: EvilBeaver/OneScript#0
File: :0-0
Timestamp: 2024-08-28T16:51:21.322Z
Learning: В репозитории EvilBeaver/OneScript всегда нужно говорить по-русски.

Applied to files:

  • tests/zip/test-zip.os
📚 Learning: в коде кэширования скриптов onescript файлы кэша и метаданных создаются в той же директории, что и и...
Learnt from: EvilBeaver
PR: EvilBeaver/OneScript#1555
File: src/ScriptEngine.HostedScript/LibraryCache/FileSystemScriptCache.cs:158-166
Timestamp: 2025-07-10T11:06:46.818Z
Learning: В коде кэширования скриптов OneScript файлы кэша и метаданных создаются в той же директории, что и исходный файл, поэтому если исходный файл существует, то директория гарантированно существует и дополнительные проверки не нужны.

Applied to files:

  • tests/zip/test-zip.os
🔇 Additional comments (13)
tests/native-api.os (1)

53-53: Отличное улучшение диагностики!

Добавление полного пути к сообщению об ошибке значительно упростит отладку при отсутствии прокси-библиотеки NativeApi.

src/OneScript.StandardLibrary/Zip/DotNetZipEncoding.cs (1)

25-38: LGTM! Отличная реализация double-checked locking.

Правильное использование паттерна double-checked locking с volatile полем обеспечивает потокобезопасность и производительность.

.gitattributes (1)

4-4: No large .zip files detected; disabling LFS is safe

  • Only one .zip present: tests/zip/fixtures/testUTF8.zip (~196 B)
    Disabling Git LFS for .zip files won’t meaningfully bloat the repository.
src/OneScript.StandardLibrary/OneScript.StandardLibrary.csproj (1)

28-28: Подтвердите совместимость API ProDotNetZip

Заменили DotNetZip на ProDotNetZip (v1.20.0). Код ссылается на Ionic.Zip и ZipFile.* в следующих файлах:

  • src/OneScript.StandardLibrary/NativeApi/NativeApiPackage.cs
  • src/OneScript.StandardLibrary/Zip/ZipFileEntriesCollection.cs
  • src/OneScript.StandardLibrary/Zip/ZipFileEntryContext.cs
  • src/OneScript.StandardLibrary/Zip/DotNetZipEncoding.cs
  • src/OneScript.StandardLibrary/Zip/ZipReader.cs
  • src/OneScript.StandardLibrary/Zip/ZipWriter.cs

Убедитесь, что ProDotNetZip сохраняет прежний API (DefaultEncoding, Read/Write, AlternateEncoding и отражение поля _defaultEncoding), и прогоните интеграционные тесты. Если никаких несовместимостей не обнаружится, можно смело мёржить изменения.

src/OneScript.StandardLibrary/Zip/ZipReader.cs (2)

55-55: LGTM! Improved encoding management.

The change from directly setting ZipFile.DefaultEncoding to using DotNetZipEncoding.SetDefault() centralizes encoding configuration and likely provides thread-safe initialization. This aligns well with the library replacement objective.


107-112: LGTM! Added necessary null validation.

The null check for the entry parameter prevents runtime exceptions and provides a more descriptive error message. The TODO comment indicates awareness of broader marshaling improvements needed.

tests/zip/test-zip.os (4)

34-36: Временное отключение теста оправдано.

Отключение теста Unicode имен файлов с ссылкой на конкретную проблему (#870) - правильное решение до исправления библиотеки.


108-109: Исправлена ошибка в утверждениях теста.

Правильно исправлены имена файлов с "zip.os" на "test-zip.os" для соответствия фактическому имени тестового файла.


360-360: Исправлен путь к тестовому файлу.

Изменение пути с "testlib" на "../testlib" обеспечивает правильное расположение русского файла для тестирования.


710-727: Реализация Unicode теста готова к использованию.

Тест правильно извлекает файлы из UTF-8 архива с корректной обработкой исключений. Готов к активации после исправления библиотеки.

src/OneScript.StandardLibrary/Text/TextEncodingEnum.cs (3)

58-58: Улучшена надежность определения кодировки OEM.

Добавление проверки encoding.CodePage == 866 обеспечивает корректное распознавание кодировки даже при различных экземплярах Encoding.


61-61: Улучшена надежность определения кодировки ANSI.

Добавление проверки encoding.CodePage == 1251 повышает надежность распознавания кодировки Windows-1251.


76-76: Улучшена диагностика ошибок.

Передача объекта encoding в исключение обеспечивает лучший контекст для отладки неизвестных кодировок.

@EvilBeaver
EvilBeaver merged commit 3972cb8 into develop Aug 3, 2025
2 of 4 checks passed
@EvilBeaver
EvilBeaver deleted the feature/dotnetzip-replacement branch August 3, 2025 07:12
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