Skip to content

[WIP] fix #1679: добавлен метод ОткрытьПоток() объекта ЧтениеJSON#1680

Open
Mr-Rm wants to merge 1 commit into
EvilBeaver:developfrom
Mr-Rm:v2/fix-1679
Open

[WIP] fix #1679: добавлен метод ОткрытьПоток() объекта ЧтениеJSON#1680
Mr-Rm wants to merge 1 commit into
EvilBeaver:developfrom
Mr-Rm:v2/fix-1679

Conversation

@Mr-Rm
Copy link
Copy Markdown
Collaborator

@Mr-Rm Mr-Rm commented May 13, 2026

Summary by CodeRabbit

  • New Features

    • JSON reader can now open and read from stream contexts (file streams, memory streams) with optional encoding parameter support, enabling more flexible data input handling.
  • Tests

    • Added test coverage for stream-based JSON reading functionality.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

📝 Walkthrough

Walkthrough

JSONReader adds stream-context support via a new OpenStream method that accepts file, memory, or generic stream contexts, validates the input, selects encoding, and initializes the internal JSON reader. The implementation is tested with a memory-stream test case verifying JSON parsing from buffered content.

Changes

JSON stream reading support

Layer / File(s) Summary
OpenStream method implementation
src/OneScript.StandardLibrary/Json/JSONReader.cs
OpenStream context method (aliases ОткрытьПоток, OpenStream) closes existing reader, extracts underlying Stream from supported context types, validates input, selects encoding (defaulting to UTF-8), and initializes JsonReaderInternal with StreamReader configured for multiple content support. Import of OneScript.StandardLibrary.Binary added.
Stream reading test coverage
tests/json/test-json_reader.os
New test Тест_Должен_ПроверитьОткрытиеПотока registered and implemented: creates JSON binary buffer, opens via ПотокВПамяти in JSONReader, reads JSON, and verifies field Ответ equals 42.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

  • EvilBeaver/OneScript#1679: Directly addresses the missing JSONReader.ОткрытьПоток (OpenStream) method implementation.

Possibly related PRs

  • EvilBeaver/OneScript#1408: JSONReader's new OpenStream integrates the refactored JsonReaderInternal from this PR's earlier JSONReader/internal architecture updates.

Poem

A rabbit hops through JSON streams so clear, 🐰
Opening buffers without a fear,
Memory and files now unified—
OneScript's reading amplified! 📖✨

🚥 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 clearly describes the main change: adding the OpenStream() method to the JSONReader object, which is the primary focus of both file modifications.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

Copy link
Copy Markdown
Contributor

@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.

🧹 Nitpick comments (2)
tests/json/test-json_reader.os (1)

225-233: ⚖️ Poor tradeoff

Consider expanding test coverage.

The test correctly validates the basic happy path with ПотокВПамяти (MemoryStreamContext). To improve robustness, consider adding tests for:

  • The optional encoding parameter with non-UTF-8 encodings
  • Error cases: invalid stream context type, null argument
  • Other stream context types (FileStreamContext or GenericStream)
  • Stream state after reading (verify Close() behavior)

These additions would help ensure the implementation handles edge cases correctly.

🤖 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 `@tests/json/test-json_reader.os` around lines 225 - 233, Add additional test
cases alongside Тест_Должен_ПроверитьОткрытиеПотока to cover edge cases: create
a test that passes a ПотокВПамяти with a non-UTF8 encoding and assert correct
parsing using ЧтениеJSON and ПрочитатьJSON; add tests that call
Чтение.ОткрытьПоток with an invalid stream context type and with null and assert
that the right exceptions are raised; add a test using FileStreamContext or
GenericStream to ensure file-backed streams parse the same way; and add a test
that reads then checks stream state/Close() behavior after ПрочитатьJSON to
verify the stream is closed or left open as intended.
src/OneScript.StandardLibrary/Json/JSONReader.cs (1)

280-300: ⚡ Quick win

Add exception handling for consistency with OpenFile.

The OpenFile method (lines 252-262) wraps all file and encoding operations in a try-catch block and converts exceptions to RuntimeException. For API consistency, OpenStream should follow the same pattern, since GetUnderlyingStream(), TextEncodingEnum.GetEncoding(), and the StreamReader constructor can all throw exceptions.

🔄 Proposed exception handling
 public void OpenStream(IValue streamContext, IValue encoding = null)
 {
     if (IsOpen())
         Close();
 
+    try
+    {
         var stream = streamContext switch
         {
             GenericStream s => s.GetUnderlyingStream(),
             FileStreamContext s => s.GetUnderlyingStream(),
             MemoryStreamContext s => s.GetUnderlyingStream(),
 
             _ => throw RuntimeException.InvalidNthArgumentType(1)
         };
 
         var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;
 
         _reader = new JsonReaderInternal(new StreamReader(stream, enc))
         {
             SupportMultipleContent = true
         };
+    }
+    catch (Exception e)
+    {
+        throw new RuntimeException(e.Message, e);
+    }
 }
🤖 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 `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 280 - 300,
OpenStream lacks the try-catch used in OpenFile, so exceptions from
GetUnderlyingStream, TextEncodingEnum.GetEncoding or
StreamReader/JsonReaderInternal are not converted to RuntimeException; wrap the
body of OpenStream in a try-catch that mirrors OpenFile: catch any Exception and
rethrow as RuntimeException (use the same message/format used in OpenFile),
while keeping the same behavior of closing an already open reader via
IsOpen()/Close() and preserving SupportMultipleContent on JsonReaderInternal.
🤖 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.

Nitpick comments:
In `@src/OneScript.StandardLibrary/Json/JSONReader.cs`:
- Around line 280-300: OpenStream lacks the try-catch used in OpenFile, so
exceptions from GetUnderlyingStream, TextEncodingEnum.GetEncoding or
StreamReader/JsonReaderInternal are not converted to RuntimeException; wrap the
body of OpenStream in a try-catch that mirrors OpenFile: catch any Exception and
rethrow as RuntimeException (use the same message/format used in OpenFile),
while keeping the same behavior of closing an already open reader via
IsOpen()/Close() and preserving SupportMultipleContent on JsonReaderInternal.

In `@tests/json/test-json_reader.os`:
- Around line 225-233: Add additional test cases alongside
Тест_Должен_ПроверитьОткрытиеПотока to cover edge cases: create a test that
passes a ПотокВПамяти with a non-UTF8 encoding and assert correct parsing using
ЧтениеJSON and ПрочитатьJSON; add tests that call Чтение.ОткрытьПоток with an
invalid stream context type and with null and assert that the right exceptions
are raised; add a test using FileStreamContext or GenericStream to ensure
file-backed streams parse the same way; and add a test that reads then checks
stream state/Close() behavior after ПрочитатьJSON to verify the stream is closed
or left open as intended.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a309e50b-9baa-46fc-8be3-1f4f577b6437

📥 Commits

Reviewing files that changed from the base of the PR and between a541e3e and 777fac1.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
  • tests/json/test-json_reader.os

@nixel2007
Copy link
Copy Markdown
Collaborator

Огонь огонь!

if (IsOpen())
Close();

var stream = streamContext switch
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

а просто IStreamWrapper не пойдет? Они все его реализуют

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.

3 participants