1use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{ruby_string_literal, ruby_template_to_interpolation, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{
11 Assertion, CallbackAction, Fixture, FixtureGroup, TemplateReturnForm, ValidationErrorExpectation,
12};
13use alef_core::backend::GeneratedFile;
14use alef_core::config::ResolvedCrateConfig;
15use alef_core::hash::{self, CommentStyle};
16use alef_core::template_versions as tv;
17use anyhow::Result;
18use heck::ToSnakeCase;
19use std::collections::{HashMap, HashSet};
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24use super::client;
25
26pub struct RubyCodegen;
28
29impl E2eCodegen for RubyCodegen {
30 fn generate(
31 &self,
32 groups: &[FixtureGroup],
33 e2e_config: &E2eConfig,
34 config: &ResolvedCrateConfig,
35 _type_defs: &[alef_core::ir::TypeDef],
36 _enums: &[alef_core::ir::EnumDef],
37 ) -> Result<Vec<GeneratedFile>> {
38 let lang = self.language_name();
39 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
40
41 let mut files = Vec::new();
42
43 let call = &e2e_config.call;
45 let overrides = call.overrides.get(lang);
46 let module_path = overrides
47 .and_then(|o| o.module.as_ref())
48 .cloned()
49 .unwrap_or_else(|| call.module.clone());
50 let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
51 let options_type = overrides.and_then(|o| o.options_type.clone());
52 let empty_enum_fields = HashMap::new();
53 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
54 let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
55
56 let ruby_pkg = e2e_config.resolve_package("ruby");
58 let gem_name = ruby_pkg
59 .as_ref()
60 .and_then(|p| p.name.as_ref())
61 .cloned()
62 .unwrap_or_else(|| config.name.replace('-', "_"));
63 let gem_path = ruby_pkg
64 .as_ref()
65 .and_then(|p| p.path.as_ref())
66 .cloned()
67 .unwrap_or_else(|| "../../packages/ruby".to_string());
68 let gem_version = ruby_pkg
69 .as_ref()
70 .and_then(|p| p.version.as_ref())
71 .cloned()
72 .or_else(|| config.resolved_version())
73 .unwrap_or_else(|| "0.1.0".to_string());
74
75 files.push(GeneratedFile {
77 path: output_base.join("Gemfile"),
78 content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
79 generated_header: false,
80 });
81
82 files.push(GeneratedFile {
84 path: output_base.join(".rubocop.yaml"),
85 content: render_rubocop_yaml(),
86 generated_header: false,
87 });
88
89 let has_http_fixtures = groups
91 .iter()
92 .flat_map(|g| g.fixtures.iter())
93 .any(|f| f.needs_mock_server());
94
95 let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
97 let cc = e2e_config.resolve_call_for_fixture(
98 f.call.as_deref(),
99 &f.id,
100 &f.resolved_category(),
101 &f.tags,
102 &f.input,
103 );
104 cc.args
105 .iter()
106 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
107 });
108
109 if has_file_fixtures || has_http_fixtures {
111 files.push(GeneratedFile {
112 path: output_base.join("spec").join("spec_helper.rb"),
113 content: render_spec_helper(
114 has_file_fixtures,
115 has_http_fixtures,
116 &e2e_config.test_documents_relative_from(1),
117 ),
118 generated_header: true,
119 });
120 }
121
122 let spec_base = output_base.join("spec");
124
125 for group in groups {
126 let active: Vec<&Fixture> = group
127 .fixtures
128 .iter()
129 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
130 .collect();
131
132 if active.is_empty() {
133 continue;
134 }
135
136 let has_any_output = active.iter().any(|f| {
138 if f.is_http_test() {
140 return true;
141 }
142 let cc = e2e_config.resolve_call_for_fixture(
143 f.call.as_deref(),
144 &f.id,
145 &f.resolved_category(),
146 &f.tags,
147 &f.input,
148 );
149 let fr = FieldResolver::new(
150 e2e_config.effective_fields(cc),
151 e2e_config.effective_fields_optional(cc),
152 e2e_config.effective_result_fields(cc),
153 e2e_config.effective_fields_array(cc),
154 &std::collections::HashSet::new(),
155 );
156 let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
157 let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
158 expects_error || has_not_error || has_usable_assertion(f, &fr, result_is_simple)
159 });
160 if !has_any_output {
161 continue;
162 }
163
164 let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
165 let content = render_spec_file(
166 &group.category,
167 &active,
168 &module_path,
169 class_name.as_deref(),
170 &gem_name,
171 options_type.as_deref(),
172 enum_fields,
173 result_is_simple,
174 e2e_config,
175 has_file_fixtures || has_http_fixtures,
176 &config.adapters,
177 );
178 files.push(GeneratedFile {
179 path: spec_base.join(filename),
180 content,
181 generated_header: true,
182 });
183 }
184
185 Ok(files)
186 }
187
188 fn language_name(&self) -> &'static str {
189 "ruby"
190 }
191}
192
193fn render_gemfile(
198 gem_name: &str,
199 gem_path: &str,
200 gem_version: &str,
201 dep_mode: crate::config::DependencyMode,
202) -> String {
203 let gem_line = match dep_mode {
204 crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
205 crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
206 };
207 crate::template_env::render(
208 "ruby/Gemfile.jinja",
209 minijinja::context! {
210 gem_line => gem_line,
211 rspec => tv::gem::RSPEC_E2E,
212 rubocop => tv::gem::RUBOCOP_E2E,
213 rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
214 faraday => tv::gem::FARADAY,
215 },
216 )
217}
218
219fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
220 let header = hash::header(CommentStyle::Hash);
221 let mut out = header;
222 out.push_str("# frozen_string_literal: true\n");
223
224 if has_file_fixtures {
225 let _ = writeln!(out);
226 let _ = writeln!(
227 out,
228 "# Change to the configured test-documents directory so that fixture file paths like"
229 );
230 let _ = writeln!(
231 out,
232 "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
233 );
234 let _ = writeln!(
235 out,
236 "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
237 );
238 let _ = writeln!(
239 out,
240 "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
241 );
242 let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
243 }
244
245 if has_http_fixtures {
246 out.push_str(
247 r#"
248require 'json'
249require 'open3'
250
251# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
252RSpec.configure do |config|
253 config.before(:suite) do
254 bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
255 fixtures_dir = File.expand_path('../../../fixtures', __dir__)
256 unless File.exist?(bin)
257 warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
258 end
259 stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
260 # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
261 url = nil
262 8.times do
263 line = stdout.readline.strip rescue break
264 if line.start_with?('MOCK_SERVER_URL=')
265 url = line.split('=', 2).last
266 ENV['MOCK_SERVER_URL'] = url
267 elsif line.start_with?('MOCK_SERVERS=')
268 json_val = line.split('=', 2).last
269 ENV['MOCK_SERVERS'] = json_val
270 JSON.parse(json_val).each do |fid, furl|
271 ENV["MOCK_SERVER_#{fid.upcase}"] = furl
272 end
273 break
274 elsif url
275 break
276 end
277 end
278 # Drain stdout in background.
279 Thread.new { stdout.read }
280 # Store stdin so we can close it on teardown.
281 @_mock_server_stdin = stdin
282 end
283
284 config.after(:suite) do
285 @_mock_server_stdin&.close
286 end
287end
288"#,
289 );
290 }
291
292 out
293}
294
295fn render_rubocop_yaml() -> String {
296 crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
297}
298
299#[allow(clippy::too_many_arguments)]
300fn render_spec_file(
301 category: &str,
302 fixtures: &[&Fixture],
303 module_path: &str,
304 class_name: Option<&str>,
305 gem_name: &str,
306 options_type: Option<&str>,
307 enum_fields: &HashMap<String, String>,
308 result_is_simple: bool,
309 e2e_config: &E2eConfig,
310 needs_spec_helper: bool,
311 adapters: &[alef_core::config::extras::AdapterConfig],
312) -> String {
313 let client_factory = e2e_config
315 .call
316 .overrides
317 .get("ruby")
318 .and_then(|o| o.client_factory.as_deref());
319
320 let require_name = if module_path.is_empty() { gem_name } else { module_path };
322 let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
323
324 let has_http = fixtures.iter().any(|f| f.is_http_test());
325 if needs_spec_helper || has_http {
326 requires.push("spec_helper".to_string());
327 }
328
329 let ruby_module = ruby_module_name(module_path);
331 let call_receiver = class_name.map(|s| s.to_string()).unwrap_or_else(|| ruby_module.clone());
332
333 let has_array_contains = fixtures.iter().any(|fixture| {
335 let cc = e2e_config.resolve_call_for_fixture(
336 fixture.call.as_deref(),
337 &fixture.id,
338 &fixture.resolved_category(),
339 &fixture.tags,
340 &fixture.input,
341 );
342 let fr = FieldResolver::new(
343 e2e_config.effective_fields(cc),
344 e2e_config.effective_fields_optional(cc),
345 e2e_config.effective_result_fields(cc),
346 e2e_config.effective_fields_array(cc),
347 &std::collections::HashSet::new(),
348 );
349 fixture.assertions.iter().any(|a| {
350 matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
351 && a.field
352 .as_deref()
353 .is_some_and(|f| !f.is_empty() && fr.is_array(fr.resolve(f)))
354 })
355 });
356
357 let mut examples = Vec::new();
359 for fixture in fixtures {
360 if fixture.http.is_some() {
361 let mut out = String::new();
363 render_http_example(&mut out, fixture);
364 examples.push(out);
365 } else {
366 let fixture_call = e2e_config.resolve_call_for_fixture(
368 fixture.call.as_deref(),
369 &fixture.id,
370 &fixture.resolved_category(),
371 &fixture.tags,
372 &fixture.input,
373 );
374 let fixture_call_resolver = FieldResolver::new(
376 e2e_config.effective_fields(fixture_call),
377 e2e_config.effective_fields_optional(fixture_call),
378 e2e_config.effective_result_fields(fixture_call),
379 e2e_config.effective_fields_array(fixture_call),
380 &std::collections::HashSet::new(),
381 );
382 let field_resolver = &fixture_call_resolver;
383 let fixture_call_overrides = fixture_call.overrides.get("ruby");
384 let raw_function_name = fixture_call_overrides
385 .and_then(|o| o.function.as_ref())
386 .cloned()
387 .unwrap_or_else(|| fixture_call.function.clone());
388
389 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
390 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
391 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
392 let is_streaming = raw_function_name == "chat_stream";
393
394 if !expects_error && !has_usable && !has_not_error && !is_streaming && fixture.assertions.is_empty() {
399 let test_name = sanitize_ident(&fixture.id);
400 let description = fixture.description.replace('\'', "\\'");
401 let mut out = String::new();
402 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
403 out.push_str(" skip 'Fixture has no assertions to validate'\n");
404 out.push_str(" end\n");
405 examples.push(out);
406 } else {
407 let fixture_function_name = if is_streaming {
411 raw_function_name
412 } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
413 format!("{raw_function_name}_async")
414 } else {
415 raw_function_name
416 };
417 let fixture_result_var = &fixture_call.result_var;
418 let fixture_args = &fixture_call.args;
419 let fixture_client_factory = fixture_call_overrides
420 .and_then(|o| o.client_factory.as_deref())
421 .or(client_factory);
422 let fixture_options_type = fixture_call_overrides
423 .and_then(|o| o.options_type.as_deref())
424 .or(options_type);
425
426 let fixture_extra_args: Vec<String> =
427 fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
428 let fixture_result_is_simple =
431 fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
432 let fixture_enum_fields: &HashMap<String, String> =
436 fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
437 let adapter_req_type_owned: Option<String> = adapters
438 .iter()
439 .find(|a| a.name == fixture_call.function.as_str())
440 .and_then(|a| a.request_type.as_deref())
441 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
442 let example = if is_streaming {
443 render_chat_stream_example(
444 fixture,
445 &fixture_function_name,
446 &call_receiver,
447 &ruby_module,
448 fixture_args,
449 fixture_options_type,
450 fixture_enum_fields,
451 e2e_config,
452 fixture_client_factory,
453 &fixture_extra_args,
454 adapter_req_type_owned.as_deref(),
455 )
456 } else {
457 render_example(
458 fixture,
459 &fixture_function_name,
460 &call_receiver,
461 &ruby_module,
462 fixture_result_var,
463 fixture_args,
464 field_resolver,
465 fixture_options_type,
466 fixture_enum_fields,
467 e2e_config.effective_fields_enum(fixture_call),
468 fixture_result_is_simple,
469 fixture_call.returns_void,
470 e2e_config,
471 fixture_client_factory,
472 &fixture_extra_args,
473 adapter_req_type_owned.as_deref(),
474 )
475 };
476 examples.push(example);
477 }
478 }
479 }
480
481 let header = hash::header(CommentStyle::Hash);
482 crate::template_env::render(
483 "ruby/test_file.jinja",
484 minijinja::context! {
485 category => category,
486 requires => requires,
487 has_array_contains => has_array_contains,
488 has_http => has_http,
489 examples => examples,
490 header => header,
491 },
492 )
493}
494
495fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
498 fixture.assertions.iter().any(|a| {
499 if a.assertion_type == "not_error" || a.assertion_type == "error" {
501 return false;
502 }
503 if let Some(f) = &a.field {
505 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
506 return false;
507 }
508 if result_is_simple {
510 let f_lower = f.to_lowercase();
511 if !f.is_empty()
512 && f_lower != "content"
513 && (f_lower.starts_with("metadata")
514 || f_lower.starts_with("document")
515 || f_lower.starts_with("structure"))
516 {
517 return false;
518 }
519 }
520 }
521 true
522 })
523}
524
525struct RubyTestClientRenderer;
533
534impl client::TestClientRenderer for RubyTestClientRenderer {
535 fn language_name(&self) -> &'static str {
536 "ruby"
537 }
538
539 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
545 let escaped_description = description.replace('\'', "\\'");
546 let rendered = crate::template_env::render(
547 "ruby/http_test.jinja",
548 minijinja::context! {
549 fn_name => fn_name,
550 description => escaped_description,
551 skip_reason => skip_reason,
552 },
553 );
554 out.push_str(&rendered);
555 }
556
557 fn render_test_close(&self, out: &mut String) {
559 let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
560 out.push_str(&rendered);
561 }
562
563 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
565 let method = ctx.method.to_uppercase();
566 let method_class = http_method_class(&method);
567
568 let has_body = ctx
569 .body
570 .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
571
572 let ruby_body = if has_body {
573 json_to_ruby(ctx.body.unwrap())
574 } else {
575 String::new()
576 };
577
578 let headers: Vec<minijinja::Value> = ctx
579 .headers
580 .iter()
581 .filter(|(k, _)| {
582 !(has_body && k.to_lowercase() == "content-type")
584 })
585 .map(|(k, v)| {
586 minijinja::context! {
587 key_literal => ruby_string_literal(k),
588 value_literal => ruby_string_literal(v),
589 }
590 })
591 .collect();
592
593 let rendered = crate::template_env::render(
594 "ruby/http_request.jinja",
595 minijinja::context! {
596 method_class => method_class,
597 path => ctx.path,
598 has_body => has_body,
599 ruby_body => ruby_body,
600 headers => headers,
601 response_var => ctx.response_var,
602 },
603 );
604 out.push_str(&rendered);
605 }
606
607 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
612 out.push_str(&format!(" expect({response_var}.code.to_i).to eq({status})\n"));
613 }
614
615 fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
619 let header_key = name.to_lowercase();
620 let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
621 let assertion = match expected {
622 "<<present>>" => {
623 format!(" expect({header_expr}).not_to be_nil\n")
624 }
625 "<<absent>>" => {
626 format!(" expect({header_expr}).to be_nil\n")
627 }
628 "<<uuid>>" => {
629 format!(
630 " expect({header_expr}).to match(/\\A[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}\\z/i)\n"
631 )
632 }
633 literal => {
634 let ruby_val = ruby_string_literal(literal);
635 format!(" expect({header_expr}).to eq({ruby_val})\n")
636 }
637 };
638 out.push_str(&assertion);
639 }
640
641 fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
646 match expected {
647 serde_json::Value::String(s) => {
648 let ruby_val = ruby_string_literal(s);
649 out.push_str(&format!(" expect({response_var}.body).to eq({ruby_val})\n"));
650 }
651 _ => {
652 let ruby_val = json_to_ruby(expected);
653 out.push_str(&format!(
654 " _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
655 ));
656 out.push_str(&format!(" expect(_body).to eq({ruby_val})\n"));
657 }
658 }
659 }
660
661 fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
663 if let Some(obj) = expected.as_object() {
664 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
665 for (key, val) in obj {
666 let ruby_key = ruby_string_literal(key);
667 let ruby_val = json_to_ruby(val);
668 out.push_str(&format!(" expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
669 }
670 }
671 }
672
673 fn render_assert_validation_errors(
676 &self,
677 out: &mut String,
678 response_var: &str,
679 errors: &[ValidationErrorExpectation],
680 ) {
681 for err in errors {
682 let msg_lit = ruby_string_literal(&err.msg);
683 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
684 out.push_str(" _errors = _body['errors'] || []\n");
685 out.push_str(&format!(
686 " expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
687 ));
688 }
689 }
690}
691
692fn render_http_example(out: &mut String, fixture: &Fixture) {
698 if fixture
702 .http
703 .as_ref()
704 .is_some_and(|h| h.expected_response.status_code == 101)
705 {
706 if let Some(http) = fixture.http.as_ref() {
707 let description = fixture.description.replace('\'', "\\'");
708 let method = http.request.method.to_uppercase();
709 let path = &http.request.path;
710 let rendered = crate::template_env::render(
711 "ruby/http_101_skip.jinja",
712 minijinja::context! {
713 method => method,
714 path => path,
715 description => description,
716 },
717 );
718 out.push_str(&rendered);
719 }
720 return;
721 }
722
723 client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
724}
725
726fn http_method_class(method: &str) -> String {
729 let mut chars = method.chars();
730 match chars.next() {
731 None => String::new(),
732 Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
733 }
734}
735
736#[allow(clippy::too_many_arguments)]
748fn render_chat_stream_example(
749 fixture: &Fixture,
750 function_name: &str,
751 call_receiver: &str,
752 module_name: &str,
753 args: &[crate::config::ArgMapping],
754 options_type: Option<&str>,
755 enum_fields: &HashMap<String, String>,
756 e2e_config: &E2eConfig,
757 client_factory: Option<&str>,
758 extra_args: &[String],
759 adapter_request_type: Option<&str>,
760) -> String {
761 let test_name = sanitize_ident(&fixture.id);
762 let description = fixture.description.replace('\'', "\\'");
763 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
764 let fixture_id = fixture.id.clone();
765
766 let (mut setup_lines, args_str) = build_args_and_setup(
767 &fixture.input,
768 args,
769 call_receiver,
770 module_name,
771 options_type,
772 enum_fields,
773 false,
774 fixture,
775 adapter_request_type,
776 );
777
778 let mut final_args = args_str;
779 if !extra_args.is_empty() {
780 let extra_str = extra_args.join(", ");
781 if final_args.is_empty() {
782 final_args = extra_str;
783 } else {
784 final_args = format!("{final_args}, {extra_str}");
785 }
786 }
787
788 let mut needs_finish_reason = false;
791 let mut needs_tool_calls_json = false;
792 let mut needs_tool_calls_0_function_name = false;
793 let mut needs_total_tokens = false;
794 for a in &fixture.assertions {
795 if let Some(f) = a.field.as_deref() {
796 match f {
797 "finish_reason" => needs_finish_reason = true,
798 "tool_calls" => needs_tool_calls_json = true,
799 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
800 "usage.total_tokens" => needs_total_tokens = true,
801 _ => {}
802 }
803 }
804 }
805
806 let mut out = String::new();
807 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
808
809 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
811 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
812 if let Some(cf) = client_factory {
813 if has_mock && let Some(key_var) = api_key_var {
814 let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
815 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
816 out.push_str(" if api_key && !api_key.empty?\n");
817 out.push_str(&format!(
818 " warn \"{test_name}: using real API ({key_var} is set)\"\n"
819 ));
820 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
821 out.push_str(" else\n");
822 out.push_str(&format!(
823 " warn \"{test_name}: using mock server ({key_var} not set)\"\n"
824 ));
825 out.push_str(&format!(" mock_url = {mock_url_expr}\n"));
826 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key', mock_url)\n"));
827 out.push_str(" end\n");
828 } else if has_mock {
829 let base_url_expr = if fixture.has_host_root_route() {
830 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
831 format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
832 } else {
833 format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
834 };
835 out.push_str(&format!(
836 " client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
837 ));
838 } else if let Some(key_var) = api_key_var {
839 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
840 out.push_str(&format!(" skip '{key_var} not set' unless api_key\n"));
841 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
842 } else {
843 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key')\n"));
844 }
845 }
846
847 if let Some(visitor_spec) = &fixture.visitor {
849 let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
850 }
851 for line in &setup_lines {
852 out.push_str(&format!(" {line}\n"));
853 }
854
855 let call_expr = if client_factory.is_some() {
856 format!("client.{function_name}({final_args})")
857 } else {
858 format!("{call_receiver}.{function_name}({final_args})")
859 };
860
861 if expects_error {
862 out.push_str(&format!(" expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
863 out.push_str(" end\n");
864 return out;
865 }
866
867 out.push_str(" chunks = []\n");
869 out.push_str(" stream_content = ''.dup\n");
870 out.push_str(" stream_complete = false\n");
871 if needs_finish_reason {
872 out.push_str(" last_finish_reason = nil\n");
873 }
874 if needs_tool_calls_json {
875 out.push_str(" tool_calls_json = nil\n");
876 }
877 if needs_tool_calls_0_function_name {
878 out.push_str(" tool_calls_0_function_name = nil\n");
879 }
880 if needs_total_tokens {
881 out.push_str(" total_tokens = nil\n");
882 }
883 out.push_str(&format!(" {call_expr} do |chunk|\n"));
884 out.push_str(" chunks << chunk\n");
885 out.push_str(" choice = chunk.choices && chunk.choices[0]\n");
886 out.push_str(" if choice\n");
887 out.push_str(" delta = choice.delta\n");
888 out.push_str(" if delta && delta.content\n");
889 out.push_str(" stream_content << delta.content\n");
890 out.push_str(" end\n");
891 if needs_finish_reason {
892 out.push_str(" if choice.finish_reason\n");
893 out.push_str(" last_finish_reason = choice.finish_reason.to_s\n");
894 out.push_str(" end\n");
895 }
896 if needs_tool_calls_json || needs_tool_calls_0_function_name {
897 out.push_str(" tcs = delta && delta.tool_calls\n");
898 out.push_str(" if tcs && !tcs.empty?\n");
899 if needs_tool_calls_json {
900 out.push_str(
901 " tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
902 );
903 }
904 if needs_tool_calls_0_function_name {
905 out.push_str(
906 " tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
907 );
908 }
909 out.push_str(" end\n");
910 }
911 out.push_str(" end\n");
912 if needs_total_tokens {
913 out.push_str(" if chunk.usage && chunk.usage.total_tokens\n");
914 out.push_str(" total_tokens = chunk.usage.total_tokens\n");
915 out.push_str(" end\n");
916 }
917 out.push_str(" end\n");
918 out.push_str(" stream_complete = true\n");
919
920 for assertion in &fixture.assertions {
922 emit_chat_stream_assertion(&mut out, assertion, e2e_config);
923 }
924
925 if !fixture
928 .assertions
929 .iter()
930 .any(|a| a.field.as_deref() == Some("stream_complete"))
931 {
932 out.push_str(" expect(stream_complete).to be(true)\n");
933 }
934
935 out.push_str(" end\n");
936 out
937}
938
939fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
944 let atype = assertion.assertion_type.as_str();
945 if atype == "not_error" || atype == "error" {
946 return;
947 }
948 let field = assertion.field.as_deref().unwrap_or("");
949
950 enum Kind {
951 Chunks,
952 Bool,
953 Str,
954 IntTokens,
955 Json,
956 Unsupported,
957 }
958
959 let (expr, kind) = match field {
960 "chunks" => ("chunks", Kind::Chunks),
961 "stream_content" => ("stream_content", Kind::Str),
962 "stream_complete" => ("stream_complete", Kind::Bool),
963 "no_chunks_after_done" => ("stream_complete", Kind::Bool),
964 "finish_reason" => ("last_finish_reason", Kind::Str),
965 "tool_calls" => ("tool_calls_json", Kind::Json),
966 "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
967 "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
968 _ => ("", Kind::Unsupported),
969 };
970
971 if matches!(kind, Kind::Unsupported) {
972 out.push_str(&format!(
973 " # skipped: streaming assertion on unsupported field '{field}'\n"
974 ));
975 return;
976 }
977
978 match (atype, &kind) {
979 ("count_min", Kind::Chunks) => {
980 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
981 out.push_str(&format!(" expect({expr}.length).to be >= {n}\n"));
982 }
983 }
984 ("count_equals", Kind::Chunks) => {
985 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
986 out.push_str(&format!(" expect({expr}.length).to eq({n})\n"));
987 }
988 }
989 ("equals", Kind::Str) => {
990 if let Some(val) = &assertion.value {
991 let rb_val = json_to_ruby(val);
992 out.push_str(&format!(" expect({expr}.to_s.strip).to eq({rb_val}.strip)\n"));
996 }
997 }
998 ("contains", Kind::Str) => {
999 if let Some(val) = &assertion.value {
1000 let rb_val = json_to_ruby(val);
1001 out.push_str(&format!(" expect({expr}.to_s).to include({rb_val})\n"));
1002 }
1003 }
1004 ("not_empty", Kind::Str) => {
1005 out.push_str(&format!(" expect({expr}.to_s).not_to be_empty\n"));
1006 }
1007 ("not_empty", Kind::Json) => {
1008 out.push_str(&format!(" expect({expr}).not_to be_nil\n"));
1009 }
1010 ("is_empty", Kind::Str) => {
1011 out.push_str(&format!(" expect({expr}.to_s).to be_empty\n"));
1012 }
1013 ("is_true", Kind::Bool) => {
1014 out.push_str(&format!(" expect({expr}).to be(true)\n"));
1015 }
1016 ("is_false", Kind::Bool) => {
1017 out.push_str(&format!(" expect({expr}).to be(false)\n"));
1018 }
1019 ("greater_than_or_equal", Kind::IntTokens) => {
1020 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1021 out.push_str(&format!(" expect({expr}).to be >= {n}\n"));
1022 }
1023 }
1024 ("equals", Kind::IntTokens) => {
1025 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1026 out.push_str(&format!(" expect({expr}).to eq({n})\n"));
1027 }
1028 }
1029 _ => {
1030 out.push_str(&format!(
1031 " # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
1032 ));
1033 }
1034 }
1035}
1036
1037#[allow(clippy::too_many_arguments)]
1042fn render_example(
1043 fixture: &Fixture,
1044 function_name: &str,
1045 call_receiver: &str,
1046 module_name: &str,
1047 result_var: &str,
1048 args: &[crate::config::ArgMapping],
1049 field_resolver: &FieldResolver,
1050 options_type: Option<&str>,
1051 enum_fields: &HashMap<String, String>,
1052 fields_enum: &HashSet<String>,
1053 result_is_simple: bool,
1054 returns_void: bool,
1055 e2e_config: &E2eConfig,
1056 client_factory: Option<&str>,
1057 extra_args: &[String],
1058 adapter_request_type: Option<&str>,
1059) -> String {
1060 let test_name = sanitize_ident(&fixture.id);
1061 let description = fixture.description.replace('\'', "\\'");
1062 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1063 let fixture_id = fixture.id.clone();
1064
1065 let (mut setup_lines, args_str) = build_args_and_setup(
1066 &fixture.input,
1067 args,
1068 call_receiver,
1069 module_name,
1070 options_type,
1071 enum_fields,
1072 result_is_simple,
1073 fixture,
1074 adapter_request_type,
1075 );
1076
1077 let mut visitor_arg = String::new();
1079 if let Some(visitor_spec) = &fixture.visitor {
1080 visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1081 }
1082
1083 let mut final_args = if visitor_arg.is_empty() {
1084 args_str
1085 } else if args_str.is_empty() {
1086 visitor_arg
1087 } else {
1088 format!("{args_str}, {visitor_arg}")
1089 };
1090
1091 if !extra_args.is_empty() {
1093 let extra_str = extra_args.join(", ");
1094 if final_args.is_empty() {
1095 final_args = extra_str;
1096 } else {
1097 final_args = format!("{final_args}, {extra_str}");
1098 }
1099 }
1100
1101 let call_expr = if client_factory.is_some() {
1103 format!("client.{function_name}({final_args})")
1104 } else {
1105 format!("{call_receiver}.{function_name}({final_args})")
1106 };
1107
1108 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1110
1111 let mut assertions_rendered = String::new();
1113 for assertion in &fixture.assertions {
1114 render_assertion(
1115 &mut assertions_rendered,
1116 assertion,
1117 result_var,
1118 field_resolver,
1119 result_is_simple,
1120 e2e_config,
1121 fields_enum,
1122 enum_fields,
1123 );
1124 }
1125
1126 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1127 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1128 let has_mock_and_key = has_mock && api_key_var.is_some();
1129 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
1130 let is_only_not_error = has_not_error && !has_usable && !expects_error;
1131
1132 let is_clear_op = function_name.ends_with("_clear");
1134 let post_clear_list_call = if is_clear_op {
1135 let list_fn = function_name.replace("_clear", "_list");
1136 format!("{}.{}()", call_receiver, list_fn)
1137 } else {
1138 String::new()
1139 };
1140
1141 crate::template_env::render(
1142 "ruby/test_function.jinja",
1143 minijinja::context! {
1144 test_name => test_name,
1145 description => description,
1146 expects_error => expects_error,
1147 setup_lines => setup_lines,
1148 call_expr => call_expr,
1149 result_var => result_var,
1150 assertions_rendered => assertions_rendered,
1151 has_usable => has_usable,
1152 returns_void => returns_void,
1153 client_factory => client_factory,
1154 fixture_id => fixture_id,
1155 call_receiver => call_receiver,
1156 has_mock => has_mock,
1157 api_key_var => api_key_var,
1158 has_mock_and_key => has_mock_and_key,
1159 is_only_not_error => is_only_not_error,
1160 is_clear_op => is_clear_op,
1161 post_clear_list_call => post_clear_list_call,
1162 },
1163 )
1164}
1165
1166fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str, module_name: &str) -> String {
1171 if let Some(items) = arr.as_array() {
1172 let item_strs: Vec<String> = items
1173 .iter()
1174 .filter_map(|item| {
1175 if let Some(obj) = item.as_object() {
1176 match elem_type {
1177 "BatchBytesItem" => {
1178 let content = obj.get("content").and_then(|v| v.as_array());
1179 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1180 let config = obj.get("config");
1181 let content_code = if let Some(arr) = content {
1182 let bytes: Vec<String> =
1183 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1184 format!("[{}]", bytes.join(", "))
1186 } else {
1187 "[]".to_string()
1188 };
1189 let config_arg = if let Some(cfg) = config {
1190 if cfg.is_null() {
1191 "nil".to_string()
1192 } else {
1193 json_to_ruby(cfg)
1194 }
1195 } else {
1196 "nil".to_string()
1197 };
1198 Some(format!(
1199 "{}::{}.new(content: {}, mime_type: \"{}\", config: {})",
1200 module_name, elem_type, content_code, mime_type, config_arg
1201 ))
1202 }
1203 "BatchFileItem" => {
1204 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1205 let config = obj.get("config");
1206 let config_arg = if let Some(cfg) = config {
1207 if cfg.is_null() {
1208 "nil".to_string()
1209 } else {
1210 json_to_ruby(cfg)
1211 }
1212 } else {
1213 "nil".to_string()
1214 };
1215 Some(format!(
1216 "{}::{}.new(path: \"{}\", config: {})",
1217 module_name, elem_type, path, config_arg
1218 ))
1219 }
1220 _ => {
1221 Some(json_to_ruby(&serde_json::Value::Object(obj.clone())))
1224 }
1225 }
1226 } else {
1227 None
1228 }
1229 })
1230 .collect();
1231 format!("[{}]", item_strs.join(", "))
1232 } else {
1233 "[]".to_string()
1234 }
1235}
1236
1237#[allow(clippy::too_many_arguments)]
1238fn build_args_and_setup(
1239 input: &serde_json::Value,
1240 args: &[crate::config::ArgMapping],
1241 call_receiver: &str,
1242 module_name: &str,
1243 options_type: Option<&str>,
1244 enum_fields: &HashMap<String, String>,
1245 result_is_simple: bool,
1246 fixture: &crate::fixture::Fixture,
1247 adapter_request_type: Option<&str>,
1248) -> (Vec<String>, String) {
1249 let fixture_id = &fixture.id;
1250 if args.is_empty() {
1251 return (Vec::new(), String::new());
1255 }
1256
1257 let mut setup_lines: Vec<String> = Vec::new();
1258 let mut parts: Vec<String> = Vec::new();
1259 let mut skipped_optional_count: usize = 0;
1262
1263 for arg in args {
1264 if arg.arg_type == "mock_url" {
1265 for _ in 0..skipped_optional_count {
1267 parts.push("nil".to_string());
1268 }
1269 skipped_optional_count = 0;
1270 if fixture.has_host_root_route() {
1271 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1272 setup_lines.push(format!(
1273 "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1274 arg.name,
1275 ));
1276 } else {
1277 setup_lines.push(format!(
1278 "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1279 arg.name,
1280 ));
1281 }
1282 if let Some(req_type) = adapter_request_type {
1283 let req_var = format!("{}_req", arg.name);
1284 let mod_qualifier = ruby_module_name(module_name);
1286 setup_lines.push(format!(
1287 "{req_var} = {mod_qualifier}::{req_type}.new(url: {})",
1288 arg.name
1289 ));
1290 parts.push(req_var);
1291 } else {
1292 parts.push(arg.name.clone());
1293 }
1294 continue;
1295 }
1296
1297 if arg.arg_type == "mock_url_list" {
1298 for _ in 0..skipped_optional_count {
1306 parts.push("nil".to_string());
1307 }
1308 skipped_optional_count = 0;
1309 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1310 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1311 let val = input.get(field).unwrap_or(&serde_json::Value::Null);
1312 let paths: Vec<String> = if let Some(arr) = val.as_array() {
1313 arr.iter().filter_map(|v| v.as_str().map(ruby_string_literal)).collect()
1314 } else {
1315 Vec::new()
1316 };
1317 let paths_literal = paths.join(", ");
1318 let name = &arg.name;
1319 setup_lines.push(format!(
1320 "{name}_base = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\""
1321 ));
1322 setup_lines.push(format!(
1323 "{name} = [{paths_literal}].map {{ |p| p.start_with?('http') ? p : \"#{{{name}_base}}#{{p}}\" }}"
1324 ));
1325 parts.push(name.clone());
1326 continue;
1327 }
1328
1329 if arg.arg_type == "bytes" {
1331 for _ in 0..skipped_optional_count {
1333 parts.push("nil".to_string());
1334 }
1335 skipped_optional_count = 0;
1336 let resolved = resolve_field(input, &arg.field);
1337 if let Some(s) = resolved.as_str() {
1338 if is_file_path(s) {
1339 setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1341 } else if is_base64(s) {
1342 setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1344 } else {
1345 let escaped = ruby_string_literal(s);
1347 setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1348 }
1349 parts.push(arg.name.clone());
1350 } else {
1351 parts.push("nil".to_string());
1352 }
1353 continue;
1354 }
1355
1356 if arg.arg_type == "file_path" {
1358 for _ in 0..skipped_optional_count {
1360 parts.push("nil".to_string());
1361 }
1362 skipped_optional_count = 0;
1363 let resolved = resolve_field(input, &arg.field);
1364 if let Some(s) = resolved.as_str() {
1365 let escaped = ruby_string_literal(s);
1366 parts.push(escaped);
1367 } else if arg.optional {
1368 skipped_optional_count += 1;
1369 continue;
1370 } else {
1371 parts.push("''".to_string());
1372 }
1373 continue;
1374 }
1375
1376 if arg.arg_type == "handle" {
1377 for _ in 0..skipped_optional_count {
1379 parts.push("nil".to_string());
1380 }
1381 skipped_optional_count = 0;
1382 let constructor_name = format!("create_{}", arg.name.to_snake_case());
1384 let config_value = resolve_field(input, &arg.field);
1385 if config_value.is_null()
1386 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1387 {
1388 setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1389 } else {
1390 let literal = json_to_ruby(config_value);
1391 let name = &arg.name;
1392 setup_lines.push(format!("{name}_config = {literal}"));
1393 setup_lines.push(format!(
1394 "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1395 arg.name,
1396 name = name,
1397 ));
1398 }
1399 parts.push(arg.name.clone());
1400 continue;
1401 }
1402
1403 let resolved = resolve_field(input, &arg.field);
1404 let val = if resolved.is_null() { None } else { Some(resolved) };
1405 match val {
1406 None | Some(serde_json::Value::Null) if arg.optional => {
1407 skipped_optional_count += 1;
1409 continue;
1410 }
1411 None | Some(serde_json::Value::Null) => {
1412 for _ in 0..skipped_optional_count {
1414 parts.push("nil".to_string());
1415 }
1416 skipped_optional_count = 0;
1417 let default_val = match arg.arg_type.as_str() {
1418 "string" => "''".to_string(),
1419 "int" | "integer" => "0".to_string(),
1420 "float" | "number" => "0.0".to_string(),
1421 "bool" | "boolean" => "false".to_string(),
1422 _ => "nil".to_string(),
1423 };
1424 parts.push(default_val);
1425 }
1426 Some(v) => {
1427 for _ in 0..skipped_optional_count {
1429 parts.push("nil".to_string());
1430 }
1431 skipped_optional_count = 0;
1432 if arg.arg_type == "json_object" && !v.is_null() {
1435 if let Some(elem_type) = &arg.element_type {
1437 if v.is_array() {
1438 if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
1439 parts.push(emit_ruby_batch_item_array(v, elem_type, module_name));
1440 continue;
1441 } else if let Some(arr) = v.as_array() {
1442 if !arr.is_empty() && arr.iter().all(|item| item.is_object()) {
1445 let items: Vec<String> = arr
1446 .iter()
1447 .filter_map(|item| {
1448 item.as_object()
1449 .map(|obj| json_to_ruby(&serde_json::Value::Object(obj.clone())))
1450 })
1451 .collect();
1452 parts.push(format!("[{}]", items.join(", ")));
1453 continue;
1454 }
1455 }
1456 }
1458 }
1459 if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1461 let kwargs: Vec<String> = obj
1462 .iter()
1463 .filter_map(|(k, vv)| {
1464 if let Some(s) = vv.as_str() {
1466 if s.is_empty() {
1467 return None; }
1469 if enum_fields.contains_key(k) {
1471 let snake_key = k.to_snake_case();
1472 let snake_val = s.to_snake_case();
1473 return Some(format!("{snake_key}: '{snake_val}'"));
1474 }
1475 }
1476 let snake_key = k.to_snake_case();
1477 let rb_val = json_to_ruby(vv);
1478 Some(format!("{snake_key}: {rb_val}"))
1479 })
1480 .collect();
1481 if result_is_simple {
1482 parts.push(format!("{{{}}}", kwargs.join(", ")));
1483 } else {
1484 parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1485 }
1486 continue;
1487 }
1488 }
1489 parts.push(json_to_ruby(v));
1490 }
1491 }
1492 }
1493
1494 (setup_lines, parts.join(", "))
1495}
1496
1497#[allow(clippy::too_many_arguments)]
1498fn render_assertion(
1499 out: &mut String,
1500 assertion: &Assertion,
1501 result_var: &str,
1502 field_resolver: &FieldResolver,
1503 result_is_simple: bool,
1504 e2e_config: &E2eConfig,
1505 fields_enum: &HashSet<String>,
1506 per_call_enum_fields: &HashMap<String, String>,
1507) {
1508 if result_is_simple {
1512 if let Some(f) = &assertion.field {
1513 if !f.is_empty() {
1514 match assertion.assertion_type.as_str() {
1515 "not_empty" => {
1516 out.push_str(&format!(" expect({result_var}.to_s).not_to be_empty\n"));
1517 return;
1518 }
1519 "is_empty" => {
1520 out.push_str(&format!(" expect({result_var}.to_s).to be_empty\n"));
1521 return;
1522 }
1523 "count_equals" => {
1524 if let Some(val) = &assertion.value {
1525 let rb_val = json_to_ruby(val);
1526 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1527 }
1528 return;
1529 }
1530 "count_min" => {
1531 if let Some(val) = &assertion.value {
1532 let rb_val = json_to_ruby(val);
1533 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1534 }
1535 return;
1536 }
1537 _ => {
1538 out.push_str(&format!(
1539 " # skipped: field '{f}' not applicable for simple result type\n"
1540 ));
1541 return;
1542 }
1543 }
1544 }
1545 }
1546 }
1547 if let Some(f) = &assertion.field {
1550 if f.contains("metadata.format.") && f.contains(".") {
1553 out.push_str(&format!(
1554 " # skipped: enum variant accessor '{f}' not available on Ruby (serialized to Hash)\n"
1555 ));
1556 return;
1557 }
1558
1559 if f == "metadata.format" {
1562 out.push_str(" # skipped: metadata.format enum field serialization differs in Ruby\n");
1563 return;
1564 }
1565
1566 match f.as_str() {
1567 "chunks_have_content" => {
1568 let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1569 match assertion.assertion_type.as_str() {
1570 "is_true" => {
1571 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1572 }
1573 "is_false" => {
1574 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1575 }
1576 _ => {
1577 out.push_str(&format!(
1578 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1579 ));
1580 }
1581 }
1582 return;
1583 }
1584 "chunks_have_heading_context" | "first_chunk_starts_with_heading" => {
1585 out.push_str(&format!(
1586 " # skipped: synthetic field '{f}' not available on Ruby Chunk binding\n"
1587 ));
1588 return;
1589 }
1590 "chunks_have_embeddings" => {
1591 let pred =
1592 format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1593 match assertion.assertion_type.as_str() {
1594 "is_true" => {
1595 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1596 }
1597 "is_false" => {
1598 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1599 }
1600 _ => {
1601 out.push_str(&format!(
1602 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1603 ));
1604 }
1605 }
1606 return;
1607 }
1608 "embeddings" => {
1612 match assertion.assertion_type.as_str() {
1613 "count_equals" => {
1614 if let Some(val) = &assertion.value {
1615 let rb_val = json_to_ruby(val);
1616 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1617 }
1618 }
1619 "count_min" => {
1620 if let Some(val) = &assertion.value {
1621 let rb_val = json_to_ruby(val);
1622 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1623 }
1624 }
1625 "not_empty" => {
1626 out.push_str(&format!(" expect({result_var}).not_to be_empty\n"));
1627 }
1628 "is_empty" => {
1629 out.push_str(&format!(" expect({result_var}).to be_empty\n"));
1630 }
1631 _ => {
1632 out.push_str(" # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1633 }
1634 }
1635 return;
1636 }
1637 "embedding_dimensions" => {
1638 let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1639 match assertion.assertion_type.as_str() {
1640 "equals" => {
1641 if let Some(val) = &assertion.value {
1642 let rb_val = json_to_ruby(val);
1643 out.push_str(&format!(" expect({expr}).to eq({rb_val})\n"));
1644 }
1645 }
1646 "greater_than" => {
1647 if let Some(val) = &assertion.value {
1648 let rb_val = json_to_ruby(val);
1649 out.push_str(&format!(" expect({expr}).to be > {rb_val}\n"));
1650 }
1651 }
1652 _ => {
1653 out.push_str(
1654 " # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1655 );
1656 }
1657 }
1658 return;
1659 }
1660 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1661 let pred = match f.as_str() {
1662 "embeddings_valid" => {
1663 format!("{result_var}.all? {{ |e| !e.empty? }}")
1664 }
1665 "embeddings_finite" => {
1666 format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1667 }
1668 "embeddings_non_zero" => {
1669 format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1670 }
1671 "embeddings_normalized" => {
1672 format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1673 }
1674 _ => unreachable!(),
1675 };
1676 match assertion.assertion_type.as_str() {
1677 "is_true" => {
1678 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1679 }
1680 "is_false" => {
1681 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1682 }
1683 _ => {
1684 out.push_str(&format!(
1685 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1686 ));
1687 }
1688 }
1689 return;
1690 }
1691 "keywords" | "keywords_count" => {
1694 out.push_str(&format!(
1695 " # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1696 ));
1697 return;
1698 }
1699 _ => {}
1700 }
1701 }
1702
1703 if let Some(f) = &assertion.field {
1705 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1706 out.push_str(&format!(" # skipped: field '{f}' not available on result type\n"));
1707 return;
1708 }
1709 }
1710
1711 if result_is_simple {
1713 if let Some(f) = &assertion.field {
1714 let f_lower = f.to_lowercase();
1715 if !f.is_empty()
1716 && f_lower != "content"
1717 && (f_lower.starts_with("metadata")
1718 || f_lower.starts_with("document")
1719 || f_lower.starts_with("structure"))
1720 {
1721 return;
1722 }
1723 }
1724 }
1725
1726 let field_expr = match &assertion.field {
1730 Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1731 field_resolver.accessor(f, "ruby", result_var)
1732 }
1733 _ => result_var.to_string(),
1734 };
1735
1736 let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1744 let resolved = field_resolver.resolve(f);
1745 fields_enum.contains(f)
1746 || fields_enum.contains(resolved)
1747 || per_call_enum_fields.contains_key(f)
1748 || per_call_enum_fields.contains_key(resolved)
1749 });
1750 let expected_is_string = assertion.value.as_ref().is_some_and(|v| v.is_string());
1756 let stripped_field_expr = if result_is_simple && expected_is_string {
1757 format!("{field_expr}.to_s.strip")
1758 } else if field_is_enum {
1759 format!("{field_expr}.to_s")
1760 } else {
1761 field_expr.clone()
1762 };
1763
1764 let field_is_array = assertion
1767 .field
1768 .as_deref()
1769 .filter(|f| !f.is_empty())
1770 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1771
1772 match assertion.assertion_type.as_str() {
1773 "equals" => {
1774 if let Some(expected) = &assertion.value {
1775 let is_boolean_val = expected.as_bool().is_some();
1776 let bool_val = expected
1777 .as_bool()
1778 .map(|b| if b { "true" } else { "false" })
1779 .unwrap_or("");
1780 let rb_val = json_to_ruby(expected);
1781 let cmp_expr = if expected.is_string() && !field_is_enum {
1785 format!("{stripped_field_expr}.to_s.strip")
1786 } else {
1787 stripped_field_expr.clone()
1788 };
1789 let cmp_expected = if expected.is_string() && !field_is_enum {
1790 format!("{rb_val}.strip")
1791 } else {
1792 rb_val
1793 };
1794
1795 let rendered = crate::template_env::render(
1796 "ruby/assertion.jinja",
1797 minijinja::context! {
1798 assertion_type => "equals",
1799 stripped_field_expr => cmp_expr,
1800 is_boolean_val => is_boolean_val,
1801 bool_val => bool_val,
1802 expected_val => cmp_expected,
1803 },
1804 );
1805 out.push_str(&rendered);
1806 }
1807 }
1808 "contains" => {
1809 if let Some(expected) = &assertion.value {
1810 let rb_val = json_to_ruby(expected);
1811 let rendered = crate::template_env::render(
1812 "ruby/assertion.jinja",
1813 minijinja::context! {
1814 assertion_type => "contains",
1815 field_expr => field_expr.clone(),
1816 field_is_array => field_is_array && expected.is_string(),
1817 expected_val => rb_val,
1818 },
1819 );
1820 out.push_str(&rendered);
1821 }
1822 }
1823 "contains_all" => {
1824 if let Some(values) = &assertion.values {
1825 let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1826 let rendered = crate::template_env::render(
1827 "ruby/assertion.jinja",
1828 minijinja::context! {
1829 assertion_type => "contains_all",
1830 field_expr => field_expr.clone(),
1831 field_is_array => field_is_array,
1832 values_list => values_list,
1833 },
1834 );
1835 out.push_str(&rendered);
1836 }
1837 }
1838 "not_contains" => {
1839 if let Some(expected) = &assertion.value {
1840 let rb_val = json_to_ruby(expected);
1841 let rendered = crate::template_env::render(
1842 "ruby/assertion.jinja",
1843 minijinja::context! {
1844 assertion_type => "not_contains",
1845 field_expr => field_expr.clone(),
1846 field_is_array => field_is_array && expected.is_string(),
1847 expected_val => rb_val,
1848 },
1849 );
1850 out.push_str(&rendered);
1851 }
1852 }
1853 "not_empty" => {
1854 let rendered = crate::template_env::render(
1855 "ruby/assertion.jinja",
1856 minijinja::context! {
1857 assertion_type => "not_empty",
1858 field_expr => field_expr.clone(),
1859 },
1860 );
1861 out.push_str(&rendered);
1862 }
1863 "is_empty" => {
1864 let rendered = crate::template_env::render(
1865 "ruby/assertion.jinja",
1866 minijinja::context! {
1867 assertion_type => "is_empty",
1868 field_expr => field_expr.clone(),
1869 },
1870 );
1871 out.push_str(&rendered);
1872 }
1873 "contains_any" => {
1874 if let Some(values) = &assertion.values {
1875 let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1876 let rendered = crate::template_env::render(
1877 "ruby/assertion.jinja",
1878 minijinja::context! {
1879 assertion_type => "contains_any",
1880 field_expr => field_expr.clone(),
1881 values_list => items,
1882 },
1883 );
1884 out.push_str(&rendered);
1885 }
1886 }
1887 "greater_than" => {
1888 if let Some(val) = &assertion.value {
1889 let rb_val = json_to_ruby(val);
1890 let rendered = crate::template_env::render(
1891 "ruby/assertion.jinja",
1892 minijinja::context! {
1893 assertion_type => "greater_than",
1894 field_expr => field_expr.clone(),
1895 expected_val => rb_val,
1896 },
1897 );
1898 out.push_str(&rendered);
1899 }
1900 }
1901 "less_than" => {
1902 if let Some(val) = &assertion.value {
1903 let rb_val = json_to_ruby(val);
1904 let rendered = crate::template_env::render(
1905 "ruby/assertion.jinja",
1906 minijinja::context! {
1907 assertion_type => "less_than",
1908 field_expr => field_expr.clone(),
1909 expected_val => rb_val,
1910 },
1911 );
1912 out.push_str(&rendered);
1913 }
1914 }
1915 "greater_than_or_equal" => {
1916 if let Some(val) = &assertion.value {
1917 let rb_val = json_to_ruby(val);
1918 let rendered = crate::template_env::render(
1919 "ruby/assertion.jinja",
1920 minijinja::context! {
1921 assertion_type => "greater_than_or_equal",
1922 field_expr => field_expr.clone(),
1923 expected_val => rb_val,
1924 },
1925 );
1926 out.push_str(&rendered);
1927 }
1928 }
1929 "less_than_or_equal" => {
1930 if let Some(val) = &assertion.value {
1931 let rb_val = json_to_ruby(val);
1932 let rendered = crate::template_env::render(
1933 "ruby/assertion.jinja",
1934 minijinja::context! {
1935 assertion_type => "less_than_or_equal",
1936 field_expr => field_expr.clone(),
1937 expected_val => rb_val,
1938 },
1939 );
1940 out.push_str(&rendered);
1941 }
1942 }
1943 "starts_with" => {
1944 if let Some(expected) = &assertion.value {
1945 let rb_val = json_to_ruby(expected);
1946 let rendered = crate::template_env::render(
1947 "ruby/assertion.jinja",
1948 minijinja::context! {
1949 assertion_type => "starts_with",
1950 field_expr => field_expr.clone(),
1951 expected_val => rb_val,
1952 },
1953 );
1954 out.push_str(&rendered);
1955 }
1956 }
1957 "ends_with" => {
1958 if let Some(expected) = &assertion.value {
1959 let rb_val = json_to_ruby(expected);
1960 let rendered = crate::template_env::render(
1961 "ruby/assertion.jinja",
1962 minijinja::context! {
1963 assertion_type => "ends_with",
1964 field_expr => field_expr.clone(),
1965 expected_val => rb_val,
1966 },
1967 );
1968 out.push_str(&rendered);
1969 }
1970 }
1971 "min_length" | "max_length" | "count_min" | "count_equals" => {
1972 if let Some(val) = &assertion.value {
1973 if let Some(n) = val.as_u64() {
1974 let rendered = crate::template_env::render(
1975 "ruby/assertion.jinja",
1976 minijinja::context! {
1977 assertion_type => assertion.assertion_type.as_str(),
1978 field_expr => field_expr.clone(),
1979 check_n => n,
1980 },
1981 );
1982 out.push_str(&rendered);
1983 }
1984 }
1985 }
1986 "is_true" => {
1987 let rendered = crate::template_env::render(
1988 "ruby/assertion.jinja",
1989 minijinja::context! {
1990 assertion_type => "is_true",
1991 field_expr => field_expr.clone(),
1992 },
1993 );
1994 out.push_str(&rendered);
1995 }
1996 "is_false" => {
1997 let rendered = crate::template_env::render(
1998 "ruby/assertion.jinja",
1999 minijinja::context! {
2000 assertion_type => "is_false",
2001 field_expr => field_expr.clone(),
2002 },
2003 );
2004 out.push_str(&rendered);
2005 }
2006 "method_result" => {
2007 if let Some(method_name) = &assertion.method {
2008 let lang = "ruby";
2010 let call = &e2e_config.call;
2011 let overrides = call.overrides.get(lang);
2012 let module_path = overrides
2013 .and_then(|o| o.module.as_ref())
2014 .cloned()
2015 .unwrap_or_else(|| call.module.clone());
2016 let call_receiver = ruby_module_name(&module_path);
2017
2018 let call_expr =
2019 build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
2020 let check = assertion.check.as_deref().unwrap_or("is_true");
2021
2022 let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
2023 "equals" => {
2024 if let Some(val) = &assertion.value {
2025 let is_bool = val.as_bool().is_some();
2026 let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
2027 let rb_val = json_to_ruby(val);
2028 (rb_val, is_bool, bool_str.to_string(), 0)
2029 } else {
2030 (String::new(), false, String::new(), 0)
2031 }
2032 }
2033 "greater_than_or_equal" => {
2034 if let Some(val) = &assertion.value {
2035 (json_to_ruby(val), false, String::new(), 0)
2036 } else {
2037 (String::new(), false, String::new(), 0)
2038 }
2039 }
2040 "count_min" => {
2041 if let Some(val) = &assertion.value {
2042 let n = val.as_u64().unwrap_or(0);
2043 (String::new(), false, String::new(), n)
2044 } else {
2045 (String::new(), false, String::new(), 0)
2046 }
2047 }
2048 "contains" => {
2049 if let Some(val) = &assertion.value {
2050 (json_to_ruby(val), false, String::new(), 0)
2051 } else {
2052 (String::new(), false, String::new(), 0)
2053 }
2054 }
2055 _ => (String::new(), false, String::new(), 0),
2056 };
2057
2058 let rendered = crate::template_env::render(
2059 "ruby/assertion.jinja",
2060 minijinja::context! {
2061 assertion_type => "method_result",
2062 call_expr => call_expr,
2063 check => check,
2064 check_val => check_val_str,
2065 is_boolean_check => is_boolean_check,
2066 bool_check_val => bool_check_val,
2067 check_n => check_n_val,
2068 },
2069 );
2070 out.push_str(&rendered);
2071 } else {
2072 panic!("Ruby e2e generator: method_result assertion missing 'method' field");
2073 }
2074 }
2075 "matches_regex" => {
2076 if let Some(expected) = &assertion.value {
2077 let rb_val = json_to_ruby(expected);
2078 let rendered = crate::template_env::render(
2079 "ruby/assertion.jinja",
2080 minijinja::context! {
2081 assertion_type => "matches_regex",
2082 field_expr => field_expr.clone(),
2083 expected_val => rb_val,
2084 },
2085 );
2086 out.push_str(&rendered);
2087 }
2088 }
2089 "not_error" => {
2090 }
2092 "error" => {
2093 }
2095 other => {
2096 panic!("Ruby e2e generator: unsupported assertion type: {other}");
2097 }
2098 }
2099}
2100
2101fn build_ruby_method_call(
2104 call_receiver: &str,
2105 result_var: &str,
2106 method_name: &str,
2107 args: Option<&serde_json::Value>,
2108) -> String {
2109 match method_name {
2110 "root_child_count" => format!("{result_var}.root_node.child_count"),
2111 "root_node_type" => format!("{result_var}.root_node.type"),
2112 "named_children_count" => format!("{result_var}.root_node.named_child_count"),
2113 "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
2114 "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
2115 "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
2116 "contains_node_type" => {
2117 let node_type = args
2118 .and_then(|a| a.get("node_type"))
2119 .and_then(|v| v.as_str())
2120 .unwrap_or("");
2121 format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
2122 }
2123 "find_nodes_by_type" => {
2124 let node_type = args
2125 .and_then(|a| a.get("node_type"))
2126 .and_then(|v| v.as_str())
2127 .unwrap_or("");
2128 format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
2129 }
2130 "run_query" => {
2131 let query_source = args
2132 .and_then(|a| a.get("query_source"))
2133 .and_then(|v| v.as_str())
2134 .unwrap_or("");
2135 let language = args
2136 .and_then(|a| a.get("language"))
2137 .and_then(|v| v.as_str())
2138 .unwrap_or("");
2139 format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
2140 }
2141 _ => format!("{result_var}.{method_name}"),
2142 }
2143}
2144
2145fn ruby_module_name(module_path: &str) -> String {
2148 use heck::ToUpperCamelCase;
2149 module_path.to_upper_camel_case()
2150}
2151
2152fn json_to_ruby(value: &serde_json::Value) -> String {
2154 match value {
2155 serde_json::Value::String(s) => ruby_string_literal(s),
2156 serde_json::Value::Bool(true) => "true".to_string(),
2157 serde_json::Value::Bool(false) => "false".to_string(),
2158 serde_json::Value::Number(n) => n.to_string(),
2159 serde_json::Value::Null => "nil".to_string(),
2160 serde_json::Value::Array(arr) => {
2161 let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
2162 format!("[{}]", items.join(", "))
2163 }
2164 serde_json::Value::Object(map) => {
2165 let items: Vec<String> = map
2166 .iter()
2167 .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
2168 .collect();
2169 format!("{{ {} }}", items.join(", "))
2170 }
2171 }
2172}
2173
2174fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
2180 setup_lines.push("visitor = Class.new do".to_string());
2181 for (method_name, action) in &visitor_spec.callbacks {
2182 emit_ruby_visitor_method(setup_lines, method_name, action);
2183 }
2184 setup_lines.push("end.new".to_string());
2185 "visitor".to_string()
2186}
2187
2188fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2190 let params = match method_name {
2191 "visit_link" => "ctx, href, text, title",
2192 "visit_image" => "ctx, src, alt, title",
2193 "visit_heading" => "ctx, level, text, id",
2194 "visit_code_block" => "ctx, lang, code",
2195 "visit_code_inline"
2196 | "visit_strong"
2197 | "visit_emphasis"
2198 | "visit_strikethrough"
2199 | "visit_underline"
2200 | "visit_subscript"
2201 | "visit_superscript"
2202 | "visit_mark"
2203 | "visit_button"
2204 | "visit_summary"
2205 | "visit_figcaption"
2206 | "visit_definition_term"
2207 | "visit_definition_description" => "ctx, text",
2208 "visit_text" => "ctx, text",
2209 "visit_list_item" => "ctx, ordered, marker, text",
2210 "visit_blockquote" => "ctx, content, depth",
2211 "visit_table_row" => "ctx, cells, is_header",
2212 "visit_custom_element" => "ctx, tag_name, html",
2213 "visit_form" => "ctx, action_url, method",
2214 "visit_input" => "ctx, input_type, name, value",
2215 "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2216 "visit_details" => "ctx, is_open",
2217 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2218 "visit_list_start" => "ctx, ordered",
2219 "visit_list_end" => "ctx, ordered, output",
2220 _ => "ctx",
2221 };
2222
2223 let (action_type, action_value, return_form) = match action {
2225 CallbackAction::Skip => ("skip", String::new(), "dict"),
2226 CallbackAction::Continue => ("continue", String::new(), "dict"),
2227 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2228 CallbackAction::Custom { output } => {
2229 let escaped = ruby_string_literal(output);
2230 ("custom", escaped, "dict")
2231 }
2232 CallbackAction::CustomTemplate { template, return_form } => {
2233 let interpolated = ruby_template_to_interpolation(template);
2234 let form = match return_form {
2235 TemplateReturnForm::Dict => "dict",
2236 TemplateReturnForm::BareString => "bare_string",
2237 };
2238 ("custom_template", format!("\"{interpolated}\""), form)
2239 }
2240 };
2241
2242 let rendered = crate::template_env::render(
2243 "ruby/visitor_method.jinja",
2244 minijinja::context! {
2245 method_name => method_name,
2246 params => params,
2247 action_type => action_type,
2248 action_value => action_value,
2249 return_form => return_form,
2250 },
2251 );
2252 for line in rendered.lines() {
2253 setup_lines.push(line.to_string());
2254 }
2255}
2256
2257fn is_file_path(s: &str) -> bool {
2262 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2263 return false;
2264 }
2265
2266 let first = s.chars().next().unwrap_or('\0');
2267 if first.is_ascii_alphanumeric() || first == '_' {
2268 if let Some(slash_pos) = s.find('/') {
2269 if slash_pos > 0 {
2270 let after_slash = &s[slash_pos + 1..];
2271 if after_slash.contains('.') && !after_slash.is_empty() {
2272 return true;
2273 }
2274 }
2275 }
2276 }
2277
2278 false
2279}
2280
2281fn is_base64(s: &str) -> bool {
2284 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2285 return false;
2286 }
2287
2288 if is_file_path(s) {
2289 return false;
2290 }
2291
2292 true
2293}