1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#[derive(PartialEq, Eq, Debug)]
pub struct Spec {
  pub file_name: String,
  pub message: String,
  pub file_text: String,
  pub expected_text: String,
  pub is_only: bool,
  pub is_trace: bool,
  pub skip: bool,
  pub skip_format_twice: bool,
  pub config: SpecConfigMap,
}

pub type SpecConfigMap = serde_json::Map<String, serde_json::Value>;

#[derive(Debug, Clone)]
pub struct ParseSpecOptions {
  /// The default file name for a parsed spec.
  pub default_file_name: &'static str,
}

pub fn parse_specs(file_text: String, options: &ParseSpecOptions) -> Vec<Spec> {
  // this function needs a rewrite
  let file_text = file_text.replace("\r\n", "\n");
  let (file_path, file_text) = parse_file_path(file_text, options);
  let (config, file_text) = parse_config(file_text);
  let lines = file_text.split('\n').collect::<Vec<_>>();
  let spec_starts = get_spec_starts(&file_path, &lines);
  let mut specs = Vec::new();

  for i in 0..spec_starts.len() {
    let start_index = spec_starts[i];
    let end_index = if spec_starts.len() == i + 1 { lines.len() } else { spec_starts[i + 1] };
    let message_line = lines[start_index];
    let spec = parse_single_spec(&file_path, message_line, &lines[(start_index + 1)..end_index], &config);

    specs.push(spec);
  }

  return specs;

  fn parse_file_path(file_text: String, options: &ParseSpecOptions) -> (String, String) {
    if !file_text.starts_with("--") {
      return (options.default_file_name.into(), file_text);
    }
    let last_index = file_text.find("--\n").expect("Could not find final --");

    (file_text["--".len()..last_index].trim().into(), file_text[(last_index + "--\n".len())..].into())
  }

  fn parse_config(file_text: String) -> (SpecConfigMap, String) {
    if !file_text.starts_with("~~") {
      return (Default::default(), file_text);
    }
    let last_index = file_text.find("~~\n").expect("Could not find final ~~\\n");

    let config_text = file_text["~~".len()..last_index].replace('\n', "");
    let config_text = config_text.trim();
    let mut config: SpecConfigMap = Default::default();

    if config_text.starts_with('{') {
      config = serde_json::from_str(config_text).expect("Error parsing config json.");
    } else {
      for item in config_text.split(',') {
        let first_colon = item.find(':').expect("Could not find colon in config option.");
        let key = item[0..first_colon].trim();
        let value = item[first_colon + ":".len()..].trim();

        config.insert(
          key.into(),
          match value.parse::<bool>() {
            Ok(value) => value.into(),
            Err(_) => match value.parse::<i32>() {
              Ok(value) => value.into(),
              Err(_) => value.into(),
            },
          },
        );
      }
    }

    (config, file_text[(last_index + "~~\n".len())..].into())
  }

  fn get_spec_starts(file_name: &str, lines: &[&str]) -> Vec<usize> {
    let mut result = Vec::new();
    let message_separator = get_message_separator(file_name);

    if !lines.first().unwrap().starts_with(message_separator) {
      panic!("All spec files should start with a message. (ex. {0} Message {0})", message_separator);
    }

    for (i, line) in lines.iter().enumerate() {
      if line.starts_with(message_separator) {
        result.push(i);
      }
    }

    result
  }

  fn parse_single_spec(file_name: &str, message_line: &str, lines: &[&str], config: &SpecConfigMap) -> Spec {
    let file_text = lines.join("\n");
    let parts = file_text.split("[expect]").collect::<Vec<&str>>();
    let start_text = parts[0][0..parts[0].len() - "\n".len()].into(); // remove last newline
    let expected_text = parts[1]["\n".len()..].into(); // remove first newline
    let lower_case_message_line = message_line.to_ascii_lowercase();
    let message_separator = get_message_separator(file_name);
    let is_trace = lower_case_message_line.contains("(trace)");

    Spec {
      file_name: String::from(file_name),
      message: message_line[message_separator.len()..message_line.len() - message_separator.len()]
        .trim()
        .into(),
      file_text: start_text,
      expected_text,
      is_only: lower_case_message_line.contains("(only)") || is_trace,
      is_trace,
      skip: lower_case_message_line.contains("(skip)"),
      skip_format_twice: lower_case_message_line.contains("(skip-format-twice)"),
      config: config.clone(),
    }
  }

  fn get_message_separator(file_name: &str) -> &'static str {
    if file_name.ends_with(".md") {
      "!!"
    } else {
      "=="
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn it_parses() {
    let specs = parse_specs(
      vec![
        "== message 1 ==",
        "start",
        "multiple",
        "",
        "[expect]",
        "expected",
        "multiple",
        "",
        "== message 2 (only) (skip) (skip-format-twice) ==",
        "start2",
        "",
        "[expect]",
        "expected2",
        "",
        "== message 3 (trace) ==",
        "test",
        "",
        "[expect]",
        "test",
        "",
      ]
      .join("\n"),
      &ParseSpecOptions { default_file_name: "test.ts" },
    );

    assert_eq!(specs.len(), 3);
    assert_eq!(
      specs[0],
      Spec {
        file_name: "test.ts".into(),
        file_text: "start\nmultiple\n".into(),
        expected_text: "expected\nmultiple\n".into(),
        message: "message 1".into(),
        is_only: false,
        is_trace: false,
        skip: false,
        skip_format_twice: false,
        config: Default::default(),
      }
    );
    assert_eq!(
      specs[1],
      Spec {
        file_name: "test.ts".into(),
        file_text: "start2\n".into(),
        expected_text: "expected2\n".into(),
        message: "message 2 (only) (skip) (skip-format-twice)".into(),
        is_only: true,
        is_trace: false,
        skip: true,
        skip_format_twice: true,
        config: Default::default(),
      }
    );
    assert_eq!(
      specs[2],
      Spec {
        file_name: "test.ts".into(),
        file_text: "test\n".into(),
        expected_text: "test\n".into(),
        message: "message 3 (trace)".into(),
        is_only: true,
        is_trace: true,
        skip: false,
        skip_format_twice: false,
        config: Default::default(),
      }
    );
  }

  #[test]
  fn it_parses_with_file_name() {
    let specs = parse_specs(
      vec!["-- asdf.ts --", "== message ==", "start", "[expect]", "expected"].join("\n"),
      &ParseSpecOptions { default_file_name: "test.ts" },
    );

    assert_eq!(specs.len(), 1);
    assert_eq!(
      specs[0],
      Spec {
        file_name: "asdf.ts".into(),
        file_text: "start".into(),
        expected_text: "expected".into(),
        message: "message".into(),
        is_only: false,
        is_trace: false,
        skip: false,
        skip_format_twice: false,
        config: Default::default(),
      }
    );
  }

  #[test]
  fn it_parses_with_config() {
    let specs = parse_specs(
      vec![
        "-- asdf.ts --",
        "~~ test.test: other, lineWidth: 40 ~~",
        "== message ==",
        "start",
        "[expect]",
        "expected",
      ]
      .join("\n"),
      &ParseSpecOptions { default_file_name: "test.ts" },
    );

    assert_eq!(specs.len(), 1);
    assert_eq!(
      specs[0],
      Spec {
        file_name: "asdf.ts".into(),
        file_text: "start".into(),
        expected_text: "expected".into(),
        message: "message".into(),
        is_only: false,
        is_trace: false,
        skip: false,
        skip_format_twice: false,
        config: [("test.test".into(), "other".into()), ("lineWidth".into(), 40.into())]
          .iter()
          .cloned()
          .collect(),
      }
    );
  }

  #[test]
  fn it_parses_markdown() {
    let specs = parse_specs(
      vec![
        "!! message 1 !!",
        "start",
        "multiple",
        "",
        "[expect]",
        "expected",
        "multiple",
        "",
        "!! message 2 (only) (skip) (skip-format-twice) !!",
        "start2",
        "",
        "[expect]",
        "expected2",
        "",
      ]
      .join("\n"),
      &ParseSpecOptions { default_file_name: "test.md" },
    );

    assert_eq!(specs.len(), 2);
    assert_eq!(
      specs[0],
      Spec {
        file_name: "test.md".into(),
        file_text: "start\nmultiple\n".into(),
        expected_text: "expected\nmultiple\n".into(),
        message: "message 1".into(),
        is_only: false,
        is_trace: false,
        skip: false,
        skip_format_twice: false,
        config: Default::default(),
      }
    );
    assert_eq!(
      specs[1],
      Spec {
        file_name: "test.md".into(),
        file_text: "start2\n".into(),
        expected_text: "expected2\n".into(),
        message: "message 2 (only) (skip) (skip-format-twice)".into(),
        is_only: true,
        is_trace: false,
        skip: true,
        skip_format_twice: true,
        config: Default::default(),
      }
    );
  }
}