1use schemars::{JsonSchema, Schema};
4use serde::{Deserialize, Deserializer, Serialize};
5
6use crate::live_index::search;
7
8pub(crate) fn lenient_u32<'de, D: Deserializer<'de>>(
10 deserializer: D,
11) -> Result<Option<u32>, D::Error> {
12 #[derive(Deserialize)]
13 #[serde(untagged)]
14 enum NumOrStr {
15 Num(u32),
16 Str(String),
17 Null,
18 }
19 match NumOrStr::deserialize(deserializer)? {
20 NumOrStr::Num(n) => Ok(Some(n)),
21 NumOrStr::Str(s) if s.is_empty() => Ok(None),
22 NumOrStr::Str(s) => s.parse::<u32>().map(Some).map_err(serde::de::Error::custom),
23 NumOrStr::Null => Ok(None),
24 }
25}
26
27pub(crate) fn lenient_bool<'de, D: Deserializer<'de>>(
29 deserializer: D,
30) -> Result<Option<bool>, D::Error> {
31 #[derive(Deserialize)]
32 #[serde(untagged)]
33 enum BoolOrStr {
34 Bool(bool),
35 Str(String),
36 Null,
37 }
38 match BoolOrStr::deserialize(deserializer)? {
39 BoolOrStr::Bool(b) => Ok(Some(b)),
40 BoolOrStr::Str(s) => match s.as_str() {
41 "true" | "1" => Ok(Some(true)),
42 "false" | "0" => Ok(Some(false)),
43 "" => Ok(None),
44 _ => Err(serde::de::Error::custom(format!(
45 "expected boolean or \"true\"/\"false\", got \"{s}\""
46 ))),
47 },
48 BoolOrStr::Null => Ok(None),
49 }
50}
51
52pub(crate) fn lenient_bool_required<'de, D: Deserializer<'de>>(
53 deserializer: D,
54) -> Result<bool, D::Error> {
55 lenient_bool(deserializer).map(|value| value.unwrap_or(false))
56}
57
58const INCLUDE_TESTS_SECTION_MARKER: &str = "__symforge_include_tests";
59
60pub(crate) fn encode_include_tests_marker(
61 mut sections: Option<Vec<String>>,
62 include_tests: bool,
63) -> Option<Vec<String>> {
64 if include_tests {
65 sections
66 .get_or_insert_with(Vec::new)
67 .push(INCLUDE_TESTS_SECTION_MARKER.to_string());
68 }
69 sections
70}
71
72pub(crate) fn include_tests_from_sections(sections: Option<&Vec<String>>) -> bool {
73 sections
74 .map(|items| {
75 items
76 .iter()
77 .any(|section| section == INCLUDE_TESTS_SECTION_MARKER)
78 })
79 .unwrap_or(false)
80}
81
82pub(crate) fn visible_sections(sections: &Option<Vec<String>>) -> Option<Vec<String>> {
83 sections.as_ref().and_then(|items| {
84 let had_marker = items
85 .iter()
86 .any(|section| section.as_str() == INCLUDE_TESTS_SECTION_MARKER);
87 let visible = items
88 .iter()
89 .filter(|section| section.as_str() != INCLUDE_TESTS_SECTION_MARKER)
90 .cloned()
91 .collect::<Vec<_>>();
92 if visible.is_empty() && had_marker {
93 None
94 } else {
95 Some(visible)
96 }
97 })
98}
99
100fn add_include_tests_schema(schema: &mut Schema) {
101 if let Some(serde_json::Value::Object(properties)) = schema.get_mut("properties") {
102 properties.insert(
103 "include_tests".to_string(),
104 serde_json::json!({
105 "type": "boolean",
106 "default": false,
107 "description": "Include expanded test modules in context output."
108 }),
109 );
110 }
111}
112
113pub(crate) fn lenient_u32_required<'de, D: Deserializer<'de>>(
114 deserializer: D,
115) -> Result<u32, D::Error> {
116 #[derive(Deserialize)]
117 #[serde(untagged)]
118 enum NumOrStr {
119 Num(u32),
120 Str(String),
121 }
122 match NumOrStr::deserialize(deserializer)? {
123 NumOrStr::Num(n) => Ok(n),
124 NumOrStr::Str(s) => s.parse::<u32>().map_err(serde::de::Error::custom),
125 }
126}
127
128pub(crate) fn lenient_u64<'de, D: Deserializer<'de>>(
130 deserializer: D,
131) -> Result<Option<u64>, D::Error> {
132 #[derive(Deserialize)]
133 #[serde(untagged)]
134 enum NumOrStr {
135 Num(u64),
136 Str(String),
137 Null,
138 }
139 match NumOrStr::deserialize(deserializer)? {
140 NumOrStr::Num(n) => Ok(Some(n)),
141 NumOrStr::Str(s) if s.is_empty() => Ok(None),
142 NumOrStr::Str(s) => s.parse::<u64>().map(Some).map_err(serde::de::Error::custom),
143 NumOrStr::Null => Ok(None),
144 }
145}
146
147pub(crate) fn lenient_i64<'de, D: Deserializer<'de>>(
149 deserializer: D,
150) -> Result<Option<i64>, D::Error> {
151 #[derive(Deserialize)]
152 #[serde(untagged)]
153 enum NumOrStr {
154 Num(i64),
155 Str(String),
156 Null,
157 }
158 match NumOrStr::deserialize(deserializer)? {
159 NumOrStr::Num(n) => Ok(Some(n)),
160 NumOrStr::Str(s) if s.is_empty() => Ok(None),
161 NumOrStr::Str(s) => s.parse::<i64>().map(Some).map_err(serde::de::Error::custom),
162 NumOrStr::Null => Ok(None),
163 }
164}
165
166pub(crate) fn lenient_option_vec<'de, D, T>(deserializer: D) -> Result<Option<Vec<T>>, D::Error>
170where
171 D: Deserializer<'de>,
172 T: serde::de::DeserializeOwned,
173{
174 #[derive(Deserialize)]
175 #[serde(untagged)]
176 enum VecOrStr {
177 Vec(Vec<serde_json::Value>),
178 Str(String),
179 Null,
180 }
181 match VecOrStr::deserialize(deserializer)? {
182 VecOrStr::Vec(values) => {
183 let result: Result<Vec<T>, _> = values
184 .into_iter()
185 .enumerate()
186 .map(|(i, v)| match serde_json::from_value::<T>(v.clone()) {
187 Ok(item) => Ok(item),
188 Err(direct_err) => {
189 if let serde_json::Value::String(ref s) = v {
190 serde_json::from_str::<T>(s).map_err(|_| {
191 serde::de::Error::custom(format!("element {i}: {direct_err}"))
192 })
193 } else {
194 Err(serde::de::Error::custom(format!(
195 "element {i}: {direct_err}"
196 )))
197 }
198 }
199 })
200 .collect();
201 result.map(Some)
202 }
203 VecOrStr::Str(s) if s.is_empty() || s == "null" => Ok(None),
204 VecOrStr::Str(s) => serde_json::from_str::<Vec<T>>(&s)
205 .map(Some)
206 .map_err(serde::de::Error::custom),
207 VecOrStr::Null => Ok(None),
208 }
209}
210
211pub(crate) fn lenient_vec_required<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
215where
216 D: Deserializer<'de>,
217 T: serde::de::DeserializeOwned,
218{
219 #[derive(Deserialize)]
220 #[serde(untagged)]
221 enum VecOrStr {
222 Vec(Vec<serde_json::Value>),
224 Str(String),
226 }
227 match VecOrStr::deserialize(deserializer)? {
228 VecOrStr::Vec(values) => {
229 values
232 .into_iter()
233 .enumerate()
234 .map(|(i, v)| {
235 match serde_json::from_value::<T>(v.clone()) {
237 Ok(item) => Ok(item),
238 Err(direct_err) => {
239 if let serde_json::Value::String(ref s) = v {
241 serde_json::from_str::<T>(s).map_err(|_| {
242 serde::de::Error::custom(format!("element {i}: {direct_err}"))
243 })
244 } else {
245 Err(serde::de::Error::custom(format!(
246 "element {i}: {direct_err}"
247 )))
248 }
249 }
250 }
251 })
252 .collect()
253 }
254 VecOrStr::Str(s) => serde_json::from_str::<Vec<T>>(&s).map_err(serde::de::Error::custom),
255 }
256}
257
258#[derive(Deserialize, Serialize, JsonSchema)]
260pub struct GetSymbolInput {
261 #[serde(default)]
263 pub path: String,
264 #[serde(default)]
266 pub name: String,
267 pub kind: Option<String>,
269 #[serde(default, deserialize_with = "lenient_u32")]
272 pub symbol_line: Option<u32>,
273 #[serde(default, deserialize_with = "lenient_option_vec")]
276 #[schemars(with = "Vec<SymbolTarget>")]
277 pub targets: Option<Vec<SymbolTarget>>,
278 #[serde(default, deserialize_with = "lenient_bool")]
281 pub estimate: Option<bool>,
282 #[serde(default)]
284 pub max_tokens: Option<u64>,
285 #[serde(default, deserialize_with = "lenient_bool")]
287 pub force_refresh: Option<bool>,
288}
289
290#[derive(Deserialize, Serialize, JsonSchema)]
294pub struct SymbolTarget {
295 pub path: String,
297 pub name: Option<String>,
299 pub kind: Option<String>,
301 #[serde(default, deserialize_with = "lenient_u32")]
303 pub symbol_line: Option<u32>,
304 #[serde(default, deserialize_with = "lenient_u32")]
306 pub start_byte: Option<u32>,
307 #[serde(default, deserialize_with = "lenient_u32")]
309 pub end_byte: Option<u32>,
310}
311
312#[derive(Deserialize, Serialize, JsonSchema)]
314#[serde(deny_unknown_fields)]
315pub struct GetFileContentInput {
316 pub path: String,
318 #[serde(default)]
322 pub mode: Option<String>,
323 #[serde(default, deserialize_with = "lenient_u32")]
325 pub start_line: Option<u32>,
326 #[serde(default, deserialize_with = "lenient_u32")]
328 pub end_line: Option<u32>,
329 #[serde(default, deserialize_with = "lenient_u32")]
331 pub chunk_index: Option<u32>,
332 #[serde(default, deserialize_with = "lenient_u32")]
334 pub max_lines: Option<u32>,
335 #[serde(default, deserialize_with = "lenient_u32")]
337 pub around_line: Option<u32>,
338 pub around_match: Option<String>,
340 #[serde(default, deserialize_with = "lenient_u32")]
342 pub match_occurrence: Option<u32>,
343 pub around_symbol: Option<String>,
345 #[serde(default, deserialize_with = "lenient_u32")]
347 pub symbol_line: Option<u32>,
348 #[serde(default, deserialize_with = "lenient_u32")]
350 pub context_lines: Option<u32>,
351 #[serde(default, deserialize_with = "lenient_bool")]
353 pub show_line_numbers: Option<bool>,
354 #[serde(default, deserialize_with = "lenient_bool")]
356 pub header: Option<bool>,
357 #[serde(default, deserialize_with = "lenient_bool")]
359 pub estimate: Option<bool>,
360 #[serde(default, deserialize_with = "lenient_u32")]
365 pub offset: Option<u32>,
366 #[serde(default, deserialize_with = "lenient_u32")]
370 pub limit: Option<u32>,
371 #[serde(default)]
373 pub max_tokens: Option<u64>,
374 #[serde(default, deserialize_with = "lenient_bool")]
376 pub force_refresh: Option<bool>,
377}
378
379#[derive(Deserialize, Serialize, JsonSchema)]
381pub struct SymforgeRetrieveInput {
382 pub hash: String,
384}
385
386#[derive(Debug, Deserialize, Serialize, JsonSchema)]
387pub(crate) struct ValidateFileSyntaxInput {
388 pub path: String,
389 #[serde(default, deserialize_with = "lenient_bool")]
391 pub estimate: Option<bool>,
392}
393
394#[derive(Deserialize, Serialize, JsonSchema)]
396pub struct FindDependentsInput {
397 pub path: String,
399 #[serde(default)]
405 pub name: Option<String>,
406 #[serde(default, deserialize_with = "lenient_u32")]
408 pub limit: Option<u32>,
409 #[serde(default, deserialize_with = "lenient_u32")]
411 pub max_per_file: Option<u32>,
412 pub format: Option<String>,
414 #[serde(default, deserialize_with = "lenient_bool")]
418 pub compact: Option<bool>,
419 #[serde(default, deserialize_with = "lenient_bool")]
421 pub estimate: Option<bool>,
422 #[serde(default, deserialize_with = "lenient_u64")]
424 pub max_tokens: Option<u64>,
425}
426
427#[derive(Deserialize, Serialize, JsonSchema)]
429pub struct GetRepoMapInput {
430 pub detail: Option<String>,
432 pub path: Option<String>,
434 #[serde(default, deserialize_with = "lenient_u32")]
436 pub depth: Option<u32>,
437 #[serde(default, deserialize_with = "lenient_u32")]
439 pub max_files: Option<u32>,
440 #[serde(default, deserialize_with = "lenient_bool")]
442 pub estimate: Option<bool>,
443 #[serde(default, deserialize_with = "lenient_u64")]
445 pub max_tokens: Option<u64>,
446}
447
448#[derive(Serialize, JsonSchema)]
450#[schemars(transform = add_include_tests_schema)]
451pub struct GetFileContextInput {
452 pub path: String,
454 #[serde(default, deserialize_with = "lenient_u64")]
456 pub max_tokens: Option<u64>,
457 #[serde(default, deserialize_with = "lenient_option_vec")]
459 #[schemars(with = "Vec<String>")]
460 pub sections: Option<Vec<String>>,
461 #[serde(default, deserialize_with = "lenient_bool")]
463 pub estimate: Option<bool>,
464 #[serde(default, deserialize_with = "lenient_bool")]
466 pub force_refresh: Option<bool>,
467}
468
469impl<'de> Deserialize<'de> for GetFileContextInput {
470 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
471 #[derive(Deserialize)]
472 struct Raw {
473 path: String,
474 #[serde(default, deserialize_with = "lenient_u64")]
475 max_tokens: Option<u64>,
476 #[serde(default, deserialize_with = "lenient_option_vec")]
477 sections: Option<Vec<String>>,
478 #[serde(default, deserialize_with = "lenient_bool_required")]
479 include_tests: bool,
480 #[serde(default, deserialize_with = "lenient_bool")]
481 estimate: Option<bool>,
482 #[serde(default, deserialize_with = "lenient_bool")]
483 force_refresh: Option<bool>,
484 }
485
486 let raw = Raw::deserialize(deserializer)?;
487 Ok(Self {
488 path: raw.path,
489 max_tokens: raw.max_tokens,
490 sections: encode_include_tests_marker(raw.sections, raw.include_tests),
491 estimate: raw.estimate,
492 force_refresh: raw.force_refresh,
493 })
494 }
495}
496
497#[derive(Serialize, JsonSchema)]
499#[schemars(transform = add_include_tests_schema)]
500pub struct GetSymbolContextInput {
501 pub name: String,
503 pub file: Option<String>,
505 pub path: Option<String>,
507 pub symbol_kind: Option<String>,
509 #[serde(default, deserialize_with = "lenient_u32")]
511 pub symbol_line: Option<u32>,
512 pub verbosity: Option<String>,
514 #[serde(default, deserialize_with = "lenient_bool")]
516 pub bundle: Option<bool>,
517 #[serde(default, deserialize_with = "lenient_option_vec")]
522 #[schemars(with = "Vec<String>")]
523 pub sections: Option<Vec<String>>,
524 #[serde(default, deserialize_with = "lenient_u64")]
529 pub max_tokens: Option<u64>,
530 #[serde(default, deserialize_with = "lenient_bool")]
533 pub estimate: Option<bool>,
534}
535
536impl<'de> Deserialize<'de> for GetSymbolContextInput {
537 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
538 #[derive(Deserialize)]
539 struct Raw {
540 name: String,
541 file: Option<String>,
542 path: Option<String>,
543 symbol_kind: Option<String>,
544 #[serde(default, deserialize_with = "lenient_u32")]
545 symbol_line: Option<u32>,
546 verbosity: Option<String>,
547 #[serde(default, deserialize_with = "lenient_bool")]
548 bundle: Option<bool>,
549 #[serde(default, deserialize_with = "lenient_option_vec")]
550 sections: Option<Vec<String>>,
551 #[serde(default, deserialize_with = "lenient_bool_required")]
552 include_tests: bool,
553 #[serde(default, deserialize_with = "lenient_u64")]
554 max_tokens: Option<u64>,
555 #[serde(default, deserialize_with = "lenient_bool")]
556 estimate: Option<bool>,
557 }
558
559 let raw = Raw::deserialize(deserializer)?;
560 let sections = match raw.sections {
561 Some(sections) => encode_include_tests_marker(Some(sections), raw.include_tests),
562 None => None,
563 };
564 Ok(Self {
565 name: raw.name,
566 file: raw.file,
567 path: raw.path,
568 symbol_kind: raw.symbol_kind,
569 symbol_line: raw.symbol_line,
570 verbosity: raw.verbosity,
571 bundle: raw.bundle,
572 sections,
573 max_tokens: raw.max_tokens,
574 estimate: raw.estimate,
575 })
576 }
577}
578
579#[derive(Deserialize, Serialize, JsonSchema)]
581pub struct TraceSymbolInput {
582 pub path: String,
584 pub name: String,
586 pub kind: Option<String>,
588 #[serde(default, deserialize_with = "lenient_u32")]
590 pub symbol_line: Option<u32>,
591 #[serde(default, deserialize_with = "lenient_option_vec")]
594 pub sections: Option<Vec<String>>,
595 pub verbosity: Option<String>,
597 #[serde(default, deserialize_with = "lenient_u64")]
599 pub max_tokens: Option<u64>,
600 #[serde(default, deserialize_with = "lenient_bool")]
602 pub estimate: Option<bool>,
603}
604
605#[derive(Deserialize, Serialize, JsonSchema)]
607pub struct InspectMatchInput {
608 pub path: String,
610 #[serde(deserialize_with = "lenient_u32_required")]
612 pub line: u32,
613 #[serde(default, deserialize_with = "lenient_u32")]
615 pub context: Option<u32>,
616 #[serde(default, deserialize_with = "lenient_u32")]
618 pub sibling_limit: Option<u32>,
619 #[serde(default, deserialize_with = "lenient_bool")]
621 pub estimate: Option<bool>,
622 #[serde(default, deserialize_with = "lenient_u64")]
624 pub max_tokens: Option<u64>,
625}
626
627pub(crate) fn normalize_file_content_aliases(
628 input: &mut GetFileContentInput,
629) -> Result<(), String> {
630 if input.offset.is_none() && input.limit.is_none() {
631 return Ok(());
632 }
633
634 let mut conflicts: Vec<&str> = Vec::new();
636 if input.start_line.is_some() {
637 conflicts.push("`start_line`");
638 }
639 if input.end_line.is_some() {
640 conflicts.push("`end_line`");
641 }
642 if input.around_line.is_some() {
643 conflicts.push("`around_line`");
644 }
645 if input.around_match.is_some() {
646 conflicts.push("`around_match`");
647 }
648 if input.around_symbol.is_some() {
649 conflicts.push("`around_symbol`");
650 }
651 if input.chunk_index.is_some() {
652 conflicts.push("`chunk_index`");
653 }
654 if input.mode.is_some() {
655 conflicts.push("`mode`");
656 }
657 if !conflicts.is_empty() {
658 return Err(format!(
659 "Invalid get_file_content request: `offset`/`limit` aliases cannot be combined with {}. Use native params instead.",
660 conflicts.join(", ")
661 ));
662 }
663
664 if input.limit == Some(0) {
665 return Err("Invalid get_file_content request: `limit` must be 1 or greater.".to_string());
666 }
667
668 let offset = input.offset.unwrap_or(0);
669 input.start_line = Some(offset.saturating_add(1));
670 if let Some(limit) = input.limit {
671 input.end_line = Some(offset.saturating_add(limit));
672 }
673 input.offset = None;
674 input.limit = None;
675 Ok(())
676}
677
678pub(crate) fn file_content_options_from_input(
679 input: &GetFileContentInput,
680) -> Result<search::FileContentOptions, String> {
681 let show_line_numbers = input.show_line_numbers.unwrap_or(false);
682 let header = input.header.unwrap_or(false);
683
684 if let Some(mode) = &input.mode {
686 let mode_str = mode.as_str();
687 let result = match mode_str {
688 "lines" => validate_lines_mode(input),
689 "symbol" => validate_symbol_mode(input),
690 "match" => validate_match_mode(input),
691 "chunk" => validate_chunk_mode(input),
692 "search" => Err("mode 'search' is not yet implemented".to_string()),
693 other => Err(format!(
694 "Unknown mode '{other}'. Valid modes: lines, symbol, match, chunk."
695 )),
696 };
697 return result.map(|mut opts| {
698 opts.content_context.mode_name = Some(mode_str.to_string());
699 opts.content_context.mode_explicit = true;
700 opts
701 });
702 }
703 if input.symbol_line.is_some() && input.around_symbol.is_none() {
706 return Err(
707 "Invalid get_file_content request: `symbol_line` requires `around_symbol`.".to_string(),
708 );
709 }
710
711 if input.match_occurrence.is_some() && input.around_match.is_none() {
712 return Err(
713 "Invalid get_file_content request: `match_occurrence` requires `around_match`."
714 .to_string(),
715 );
716 }
717
718 if matches!(input.match_occurrence, Some(0)) {
719 return Err(
720 "Invalid get_file_content request: `match_occurrence` must be 1 or greater."
721 .to_string(),
722 );
723 }
724
725 if let Some(raw_around_symbol) = input.around_symbol.as_deref() {
726 let around_symbol = raw_around_symbol.trim();
727 if around_symbol.is_empty() {
728 return Err(
729 "Invalid get_file_content request: `around_symbol` must not be empty.".to_string(),
730 );
731 }
732
733 if input.start_line.is_some()
734 || input.end_line.is_some()
735 || input.around_line.is_some()
736 || input.around_match.is_some()
737 || input.chunk_index.is_some()
738 {
739 return Err(
740 "Invalid get_file_content request: `around_symbol` cannot be combined with `start_line`, `end_line`, `around_line`, `around_match`, or `chunk_index`. Valid with `around_symbol`: `symbol_line`, `context_lines`, `max_lines`."
741 .to_string(),
742 );
743 }
744
745 let mut opts = search::FileContentOptions::for_explicit_path_read_around_symbol(
746 input.path.clone(),
747 around_symbol,
748 input.symbol_line,
749 input.context_lines,
750 input.max_lines,
751 show_line_numbers,
752 header,
753 );
754 opts.content_context.mode_name = Some("symbol".to_string());
755 opts.content_context.mode_explicit = false;
756 return Ok(opts);
757 }
758
759 if input.max_lines.is_some() && input.chunk_index.is_none() {
760 return Err(
761 "Invalid get_file_content request: `max_lines` requires `chunk_index`.".to_string(),
762 );
763 }
764
765 if let Some(chunk_index) = input.chunk_index {
766 let Some(max_lines) = input.max_lines else {
767 return Err(
768 "Invalid get_file_content request: `chunk_index` requires `max_lines`.".to_string(),
769 );
770 };
771
772 if chunk_index == 0 {
773 return Err(
774 "Invalid get_file_content request: `chunk_index` must be 1 or greater.".to_string(),
775 );
776 }
777
778 if max_lines == 0 {
779 return Err(
780 "Invalid get_file_content request: `max_lines` must be 1 or greater.".to_string(),
781 );
782 }
783
784 if input.start_line.is_some()
785 || input.end_line.is_some()
786 || input.around_line.is_some()
787 || input.around_match.is_some()
788 {
789 return Err(
790 "Invalid get_file_content request: chunked reads (`chunk_index` + `max_lines`) cannot be combined with `start_line`, `end_line`, `around_line`, or `around_match`."
791 .to_string(),
792 );
793 }
794
795 let mut opts = search::FileContentOptions::for_explicit_path_read_chunk(
796 input.path.clone(),
797 chunk_index,
798 max_lines,
799 );
800 opts.content_context.mode_name = Some("chunk".to_string());
801 opts.content_context.mode_explicit = false;
802 return Ok(opts);
803 }
804
805 if let Some(raw_around_match) = input.around_match.as_deref() {
809 let around_match = raw_around_match.trim();
810 if around_match.is_empty() {
811 return Err(
812 "Invalid get_file_content request: `around_match` must not be empty.".to_string(),
813 );
814 }
815
816 if input.start_line.is_some() || input.end_line.is_some() || input.around_line.is_some() {
817 return Err(
818 "Invalid get_file_content request: `around_match` cannot be combined with `start_line`, `end_line`, or `around_line`. Valid with `around_match`: `context_lines`."
819 .to_string(),
820 );
821 }
822
823 let mut opts = search::FileContentOptions::for_explicit_path_read_around_match(
824 input.path.clone(),
825 around_match,
826 input.match_occurrence,
827 input.context_lines,
828 show_line_numbers,
829 header,
830 );
831 opts.content_context.mode_name = Some("match".to_string());
832 opts.content_context.mode_explicit = false;
833 return Ok(opts);
834 }
835
836 if input.around_line.is_some() && (input.start_line.is_some() || input.end_line.is_some()) {
837 return Err(
838 "Invalid get_file_content request: `around_line` cannot be combined with `start_line` or `end_line`. Valid with `around_line`: `context_lines`."
839 .to_string(),
840 );
841 }
842
843 let mut opts = match input.around_line {
844 Some(around_line) => search::FileContentOptions::for_explicit_path_read_around_line(
845 input.path.clone(),
846 around_line,
847 input.context_lines,
848 show_line_numbers,
849 header,
850 ),
851 None => search::FileContentOptions::for_explicit_path_read_with_format(
852 input.path.clone(),
853 input.start_line,
854 input.end_line,
855 show_line_numbers,
856 header,
857 ),
858 };
859 opts.content_context.mode_name = Some("lines".to_string());
860 opts.content_context.mode_explicit = false;
861 Ok(opts)
862}
863
864fn describe_received_flags(input: &GetFileContentInput) -> String {
868 let mut flags = Vec::new();
869 if input.start_line.is_some() {
870 flags.push("start_line");
871 }
872 if input.end_line.is_some() {
873 flags.push("end_line");
874 }
875 if input.around_line.is_some() {
876 flags.push("around_line");
877 }
878 if input.around_match.is_some() {
879 flags.push("around_match");
880 }
881 if input.match_occurrence.is_some() {
882 flags.push("match_occurrence");
883 }
884 if input.around_symbol.is_some() {
885 flags.push("around_symbol");
886 }
887 if input.symbol_line.is_some() {
888 flags.push("symbol_line");
889 }
890 if input.chunk_index.is_some() {
891 flags.push("chunk_index");
892 }
893 if input.max_lines.is_some() {
894 flags.push("max_lines");
895 }
896 if input.context_lines.is_some() {
897 flags.push("context_lines");
898 }
899 if input.show_line_numbers.is_some() {
900 flags.push("show_line_numbers");
901 }
902 if input.header.is_some() {
903 flags.push("header");
904 }
905 flags.join(", ")
906}
907
908fn validate_lines_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
909 let cross: Vec<&str> = [
910 input.around_symbol.as_ref().map(|_| "around_symbol"),
911 input.around_match.as_ref().map(|_| "around_match"),
912 input.match_occurrence.map(|_| "match_occurrence"),
913 input.chunk_index.map(|_| "chunk_index"),
914 ]
915 .into_iter()
916 .flatten()
917 .collect();
918
919 if !cross.is_empty() {
920 return Err(format!(
921 "mode=lines conflicts with {}. Use mode={}. Received: {}",
922 cross.join(", "),
923 if input.around_symbol.is_some() {
924 "symbol"
925 } else if input.around_match.is_some() || input.match_occurrence.is_some() {
926 "match"
927 } else {
928 "chunk"
929 },
930 describe_received_flags(input),
931 ));
932 }
933
934 let show_line_numbers = input.show_line_numbers.unwrap_or(false);
935 let header = input.header.unwrap_or(false);
936
937 if input.around_line.is_some() && (input.start_line.is_some() || input.end_line.is_some()) {
938 return Err(
939 "Invalid get_file_content request: `around_line` cannot be combined with `start_line` or `end_line`. Valid with `around_line`: `context_lines`."
940 .to_string(),
941 );
942 }
943
944 Ok(match input.around_line {
945 Some(around_line) => search::FileContentOptions::for_explicit_path_read_around_line(
946 input.path.clone(),
947 around_line,
948 input.context_lines,
949 show_line_numbers,
950 header,
951 ),
952 None => search::FileContentOptions::for_explicit_path_read_with_format(
953 input.path.clone(),
954 input.start_line,
955 input.end_line,
956 show_line_numbers,
957 header,
958 ),
959 })
960}
961
962fn validate_symbol_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
963 let Some(raw_around_symbol) = input.around_symbol.as_deref() else {
964 return Err("mode=symbol requires around_symbol".to_string());
965 };
966 let around_symbol = raw_around_symbol.trim();
967 if around_symbol.is_empty() {
968 return Err("mode=symbol requires around_symbol".to_string());
969 }
970
971 let cross: Vec<&str> = [
972 input.start_line.map(|_| "start_line"),
973 input.end_line.map(|_| "end_line"),
974 input.around_line.map(|_| "around_line"),
975 input.around_match.as_ref().map(|_| "around_match"),
976 input.match_occurrence.map(|_| "match_occurrence"),
977 input.chunk_index.map(|_| "chunk_index"),
978 ]
979 .into_iter()
980 .flatten()
981 .collect();
982
983 if !cross.is_empty() {
984 return Err(format!(
985 "mode=symbol conflicts with {}. Received: {}",
986 cross.join(", "),
987 describe_received_flags(input),
988 ));
989 }
990
991 let show_line_numbers = input.show_line_numbers.unwrap_or(false);
992 let header = input.header.unwrap_or(false);
993
994 Ok(
995 search::FileContentOptions::for_explicit_path_read_around_symbol(
996 input.path.clone(),
997 around_symbol,
998 input.symbol_line,
999 input.context_lines,
1000 input.max_lines,
1001 show_line_numbers,
1002 header,
1003 ),
1004 )
1005}
1006
1007fn validate_match_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
1008 let Some(raw_around_match) = input.around_match.as_deref() else {
1009 return Err("mode=match requires around_match".to_string());
1010 };
1011 let around_match = raw_around_match.trim();
1012 if around_match.is_empty() {
1013 return Err("mode=match requires around_match".to_string());
1014 }
1015 if matches!(input.match_occurrence, Some(0)) {
1016 return Err(
1017 "Invalid get_file_content request: `match_occurrence` must be 1 or greater."
1018 .to_string(),
1019 );
1020 }
1021
1022 let cross: Vec<&str> = [
1023 input.start_line.map(|_| "start_line"),
1024 input.end_line.map(|_| "end_line"),
1025 input.around_line.map(|_| "around_line"),
1026 input.around_symbol.as_ref().map(|_| "around_symbol"),
1027 input.chunk_index.map(|_| "chunk_index"),
1028 ]
1029 .into_iter()
1030 .flatten()
1031 .collect();
1032
1033 if !cross.is_empty() {
1034 return Err(format!(
1035 "mode=match conflicts with {}. Use mode={}. Received: {}",
1036 cross.join(", "),
1037 if input.around_symbol.is_some() {
1038 "symbol"
1039 } else if input.start_line.is_some()
1040 || input.end_line.is_some()
1041 || input.around_line.is_some()
1042 {
1043 "lines"
1044 } else {
1045 "chunk"
1046 },
1047 describe_received_flags(input),
1048 ));
1049 }
1050
1051 let show_line_numbers = input.show_line_numbers.unwrap_or(false);
1052 let header = input.header.unwrap_or(false);
1053
1054 Ok(
1055 search::FileContentOptions::for_explicit_path_read_around_match(
1056 input.path.clone(),
1057 around_match,
1058 input.match_occurrence,
1059 input.context_lines,
1060 show_line_numbers,
1061 header,
1062 ),
1063 )
1064}
1065
1066fn validate_chunk_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
1067 let chunk_index = input
1068 .chunk_index
1069 .ok_or_else(|| "mode=chunk requires chunk_index".to_string())?;
1070 let max_lines = input
1071 .max_lines
1072 .ok_or_else(|| "mode=chunk requires max_lines".to_string())?;
1073
1074 if chunk_index == 0 {
1075 return Err(
1076 "Invalid get_file_content request: `chunk_index` must be 1 or greater.".to_string(),
1077 );
1078 }
1079 if max_lines == 0 {
1080 return Err(
1081 "Invalid get_file_content request: `max_lines` must be 1 or greater.".to_string(),
1082 );
1083 }
1084
1085 let cross: Vec<&str> = [
1086 input.around_symbol.as_ref().map(|_| "around_symbol"),
1087 input.around_match.as_ref().map(|_| "around_match"),
1088 input.match_occurrence.map(|_| "match_occurrence"),
1089 input.around_line.map(|_| "around_line"),
1090 input.start_line.map(|_| "start_line"),
1091 input.end_line.map(|_| "end_line"),
1092 ]
1093 .into_iter()
1094 .flatten()
1095 .collect();
1096
1097 if !cross.is_empty() {
1098 return Err(format!(
1099 "mode=chunk conflicts with {}. Use mode={}. Received: {}",
1100 cross.join(", "),
1101 if input.around_symbol.is_some() {
1102 "symbol"
1103 } else if input.around_match.is_some() || input.match_occurrence.is_some() {
1104 "match"
1105 } else {
1106 "lines"
1107 },
1108 describe_received_flags(input),
1109 ));
1110 }
1111
1112 Ok(search::FileContentOptions::for_explicit_path_read_chunk(
1113 input.path.clone(),
1114 chunk_index,
1115 max_lines,
1116 ))
1117}