|
| 1 | +use std::str::Lines; |
| 2 | + |
| 3 | +use anyhow::bail; |
| 4 | + |
| 5 | +const RANGE_SEPARATOR: &'static str = ":"; |
| 6 | +const DEFAULT_RANGE: &'static str = "start:end"; |
| 7 | + |
| 8 | +fn parse_range_point(point: &str, lines: &Vec<&str>) -> anyhow::Result<usize> { |
| 9 | + let point = match point { |
| 10 | + "start" => 0, |
| 11 | + "end" => lines.len(), |
| 12 | + _ => point.parse::<usize>()?, |
| 13 | + }; |
| 14 | + |
| 15 | + Ok(point) |
| 16 | +} |
| 17 | + |
| 18 | +pub fn cut_code_snippet_by_range( |
| 19 | + code_snippet: &str, |
| 20 | + range: &Option<String>, |
| 21 | +) -> anyhow::Result<String> { |
| 22 | + let range = range.clone().unwrap_or(String::from(DEFAULT_RANGE)); |
| 23 | + let range_points = range.split(RANGE_SEPARATOR).collect::<Vec<_>>(); |
| 24 | + |
| 25 | + if range_points.len() != 2 { |
| 26 | + bail!("Invalid range format"); |
| 27 | + } |
| 28 | + |
| 29 | + let code_snippet_lines = code_snippet.lines(); |
| 30 | + let (start, end) = parse_range(&range_points, &code_snippet_lines)?; |
| 31 | + let code_snippet = code_snippet_lines |
| 32 | + .skip(start) |
| 33 | + .take(end - start) |
| 34 | + .collect::<Vec<&str>>() |
| 35 | + .join("\n"); |
| 36 | + |
| 37 | + Ok(code_snippet) |
| 38 | +} |
| 39 | + |
| 40 | +// Prepare range string by following rules: |
| 41 | +// |
| 42 | +// If raw_range is equal to "n:", which means x:end |
| 43 | +// If raw_range is equal to ":n", which means start:n |
| 44 | +pub fn prepare_range(raw_range: &str) -> String { |
| 45 | + if raw_range.starts_with(RANGE_SEPARATOR) { |
| 46 | + format!("{}{}", "start", raw_range) |
| 47 | + } else if raw_range.ends_with(RANGE_SEPARATOR) { |
| 48 | + format!("{}{}", raw_range, "end") |
| 49 | + } else { |
| 50 | + raw_range.to_string() |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// Parse "start" to 0, "end" to lines.len(), and other values to usize |
| 55 | +pub fn parse_range( |
| 56 | + range_points: &Vec<&str>, |
| 57 | + code_snippet_lines: &Lines, |
| 58 | +) -> anyhow::Result<(usize, usize)> { |
| 59 | + let lines = code_snippet_lines.clone().collect::<Vec<&str>>(); |
| 60 | + let start = parse_range_point(range_points[0], &lines)?; |
| 61 | + let end = parse_range_point(range_points[1], &lines)?; |
| 62 | + let points = if start > end { |
| 63 | + (end, start) |
| 64 | + } else { |
| 65 | + (start, end) |
| 66 | + }; |
| 67 | + |
| 68 | + Ok(points) |
| 69 | +} |
0 commit comments