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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use std::hash::Hash;

use indexmap::IndexMap;
use serde::Deserialize;
use serde::Serialize;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseConfigurationError(pub String);

impl std::fmt::Display for ParseConfigurationError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    format!("Found invalid value '{}'.", self.0).fmt(f)
  }
}

#[macro_export]
macro_rules! generate_str_to_from {
    ($enum_name:ident, $([$member_name:ident, $string_value:expr]),* ) => {
        impl std::str::FromStr for $enum_name {
            type Err = ParseConfigurationError;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $($string_value => Ok($enum_name::$member_name)),*,
                    _ => Err(ParseConfigurationError(String::from(s))),
                }
            }
        }

        impl std::fmt::Display for $enum_name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    $($enum_name::$member_name => write!(f, $string_value)),*,
                }
            }
        }
    };
}

#[derive(Clone, PartialEq, Eq, Debug, Copy, Serialize, Deserialize, Hash)]
pub enum RawNewLineKind {
  /// Decide which newline kind to use based on the last newline in the file.
  #[serde(rename = "auto")]
  Auto,
  /// Use slash n new lines.
  #[serde(rename = "lf")]
  LineFeed,
  /// Use slash r slash n new lines.
  #[serde(rename = "crlf")]
  CarriageReturnLineFeed,
  /// Use the system standard (ex. crlf on Windows)
  #[serde(rename = "system")]
  System,
}

generate_str_to_from![
  RawNewLineKind,
  [Auto, "auto"],
  [LineFeed, "lf"],
  [CarriageReturnLineFeed, "crlf"],
  [System, "system"]
];

#[derive(Clone, PartialEq, Eq, Debug, Copy, Serialize, Deserialize, Hash)]
pub enum NewLineKind {
  /// Decide which newline kind to use based on the last newline in the file.
  #[serde(rename = "auto")]
  Auto,
  /// Use slash n new lines.
  #[serde(rename = "lf")]
  LineFeed,
  /// Use slash r slash n new lines.
  #[serde(rename = "crlf")]
  CarriageReturnLineFeed,
}

generate_str_to_from![NewLineKind, [Auto, "auto"], [LineFeed, "lf"], [CarriageReturnLineFeed, "crlf"]];

/// Represents a problem within the configuration.
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ConfigurationDiagnostic {
  /// The property name the problem occurred on.
  pub property_name: String,
  /// The diagnostic message that should be displayed to the user
  pub message: String,
}

impl std::fmt::Display for ConfigurationDiagnostic {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{} ({})", self.message, self.property_name)
  }
}

pub type ConfigKeyMap = IndexMap<String, ConfigKeyValue>;

#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ConfigKeyValue {
  String(String),
  Number(i32),
  Bool(bool),
  Array(Vec<ConfigKeyValue>),
  Object(ConfigKeyMap),
  Null,
}

impl ConfigKeyValue {
  pub fn as_string(&self) -> Option<&String> {
    match self {
      ConfigKeyValue::String(value) => Some(value),
      _ => None,
    }
  }

  pub fn as_number(&self) -> Option<i32> {
    match self {
      ConfigKeyValue::Number(value) => Some(*value),
      _ => None,
    }
  }

  pub fn as_bool(&self) -> Option<bool> {
    match self {
      ConfigKeyValue::Bool(value) => Some(*value),
      _ => None,
    }
  }

  pub fn as_array(&self) -> Option<&Vec<ConfigKeyValue>> {
    match self {
      ConfigKeyValue::Array(values) => Some(values),
      _ => None,
    }
  }

  pub fn as_object(&self) -> Option<&ConfigKeyMap> {
    match self {
      ConfigKeyValue::Object(values) => Some(values),
      _ => None,
    }
  }

  pub fn into_string(self) -> Option<String> {
    match self {
      ConfigKeyValue::String(value) => Some(value),
      _ => None,
    }
  }

  pub fn into_number(self) -> Option<i32> {
    match self {
      ConfigKeyValue::Number(value) => Some(value),
      _ => None,
    }
  }

  pub fn into_bool(self) -> Option<bool> {
    match self {
      ConfigKeyValue::Bool(value) => Some(value),
      _ => None,
    }
  }

  pub fn into_array(self) -> Option<Vec<ConfigKeyValue>> {
    match self {
      ConfigKeyValue::Array(values) => Some(values),
      _ => None,
    }
  }

  pub fn into_object(self) -> Option<ConfigKeyMap> {
    match self {
      ConfigKeyValue::Object(values) => Some(values),
      _ => None,
    }
  }

  pub fn is_null(&self) -> bool {
    matches!(self, ConfigKeyValue::Null)
  }

  /// Gets a hash of the configuration value. This is used for incremental formatting
  /// and the Hash trait is not implemented to discourage using this in other places.
  #[allow(clippy::should_implement_trait)]
  pub fn hash(&self, hasher: &mut impl std::hash::Hasher) {
    match self {
      ConfigKeyValue::String(value) => {
        hasher.write_u8(0);
        hasher.write(value.as_bytes())
      }
      ConfigKeyValue::Number(value) => {
        hasher.write_u8(1);
        hasher.write_i32(*value)
      }
      ConfigKeyValue::Bool(value) => {
        hasher.write_u8(2);
        hasher.write_u8(if *value { 1 } else { 0 })
      }
      ConfigKeyValue::Array(values) => {
        hasher.write_u8(3);
        for value in values {
          value.hash(hasher);
        }
      }
      ConfigKeyValue::Object(key_values) => {
        hasher.write_u8(4);
        for (key, value) in key_values {
          hasher.write(key.as_bytes());
          value.hash(hasher);
        }
      }
      ConfigKeyValue::Null => {
        hasher.write_u8(5);
      }
    }
  }

  pub fn from_i32(value: i32) -> ConfigKeyValue {
    ConfigKeyValue::Number(value)
  }

  #[allow(clippy::should_implement_trait)]
  pub fn from_str(value: &str) -> ConfigKeyValue {
    ConfigKeyValue::String(value.to_string())
  }

  pub fn from_bool(value: bool) -> ConfigKeyValue {
    ConfigKeyValue::Bool(value)
  }
}

impl From<i32> for ConfigKeyValue {
  fn from(item: i32) -> Self {
    ConfigKeyValue::from_i32(item)
  }
}

impl From<bool> for ConfigKeyValue {
  fn from(item: bool) -> Self {
    ConfigKeyValue::from_bool(item)
  }
}

impl From<String> for ConfigKeyValue {
  fn from(item: String) -> Self {
    ConfigKeyValue::from_str(&item)
  }
}

impl From<&str> for ConfigKeyValue {
  fn from(item: &str) -> Self {
    ConfigKeyValue::from_str(item)
  }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug, Default, Hash)]
#[serde(rename_all = "camelCase")]
pub struct GlobalConfiguration {
  pub line_width: Option<u32>,
  pub use_tabs: Option<bool>,
  pub indent_width: Option<u8>,
  pub new_line_kind: Option<NewLineKind>,
}

pub const RECOMMENDED_GLOBAL_CONFIGURATION: RecommendedGlobalConfiguration = RecommendedGlobalConfiguration {
  line_width: 120,
  indent_width: 2,
  use_tabs: false,
  new_line_kind: NewLineKind::LineFeed,
};

pub struct RecommendedGlobalConfiguration {
  pub line_width: u32,
  pub use_tabs: bool,
  pub indent_width: u8,
  pub new_line_kind: NewLineKind,
}

impl From<RecommendedGlobalConfiguration> for GlobalConfiguration {
  fn from(config: RecommendedGlobalConfiguration) -> Self {
    Self {
      line_width: Some(config.line_width),
      use_tabs: Some(config.use_tabs),
      indent_width: Some(config.indent_width),
      new_line_kind: Some(config.new_line_kind),
    }
  }
}

#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveConfigurationResult<T>
where
  T: Clone + Serialize,
{
  /// The configuration diagnostics.
  pub diagnostics: Vec<ConfigurationDiagnostic>,

  /// The configuration derived from the unresolved configuration
  /// that can be used to format a file.
  pub config: T,
}

/// Resolves a collection of key value pairs to a GlobalConfiguration.
pub fn resolve_global_config(config: &mut ConfigKeyMap) -> ResolveConfigurationResult<GlobalConfiguration> {
  let mut diagnostics = Vec::new();

  let raw_new_line_kind = get_nullable_value::<RawNewLineKind>(config, "newLineKind", &mut diagnostics);

  let resolved_config = GlobalConfiguration {
    line_width: get_nullable_value(config, "lineWidth", &mut diagnostics),
    use_tabs: get_nullable_value(config, "useTabs", &mut diagnostics),
    indent_width: get_nullable_value(config, "indentWidth", &mut diagnostics),
    new_line_kind: raw_new_line_kind.map(|kind| match kind {
      RawNewLineKind::Auto => NewLineKind::Auto,
      RawNewLineKind::LineFeed => NewLineKind::LineFeed,
      RawNewLineKind::CarriageReturnLineFeed => NewLineKind::CarriageReturnLineFeed,
      RawNewLineKind::System => {
        if cfg!(windows) {
          NewLineKind::CarriageReturnLineFeed
        } else {
          NewLineKind::LineFeed
        }
      }
    }),
  };

  ResolveConfigurationResult {
    config: resolved_config,
    diagnostics,
  }
}

/// If the provided key exists, takes its value from the provided config and returns it.
/// If the provided key does not exist, it returns the default value.
/// Adds a diagnostic if there is any problem deserializing the value.
pub fn get_value<T>(config: &mut ConfigKeyMap, key: &str, default_value: T, diagnostics: &mut Vec<ConfigurationDiagnostic>) -> T
where
  T: std::str::FromStr,
  <T as std::str::FromStr>::Err: std::fmt::Display,
{
  get_nullable_value(config, key, diagnostics).unwrap_or(default_value)
}

/// If the provided key exists, takes its value from the provided config and returns it.
/// If the provided key does not exist, it returns None.
/// Adds a diagnostic if there is any problem deserializing the value.
pub fn get_nullable_value<T>(config: &mut ConfigKeyMap, key: &str, diagnostics: &mut Vec<ConfigurationDiagnostic>) -> Option<T>
where
  T: std::str::FromStr,
  <T as std::str::FromStr>::Err: std::fmt::Display,
{
  if let Some(raw_value) = config.shift_remove(key) {
    // not exactly the best, but can't think of anything better at the moment
    let parsed_value = match raw_value {
      ConfigKeyValue::Bool(value) => value.to_string().parse::<T>().map_err(|e| e.to_string()),
      ConfigKeyValue::Number(value) => value.to_string().parse::<T>().map_err(|e| e.to_string()),
      ConfigKeyValue::String(value) => value.parse::<T>().map_err(|e| e.to_string()),
      ConfigKeyValue::Object(_) | ConfigKeyValue::Array(_) => Err("Arrays and objects are not supported for this value".to_string()),
      ConfigKeyValue::Null => return None,
    };
    match parsed_value {
      Ok(parsed_value) => Some(parsed_value),
      Err(message) => {
        diagnostics.push(ConfigurationDiagnostic {
          property_name: key.to_string(),
          message,
        });
        None
      }
    }
  } else {
    None
  }
}

/// If it exists, moves over the configuration value over from the old key
/// to the new key and adds a diagnostic.
pub fn handle_renamed_config_property(config: &mut ConfigKeyMap, old_key: &str, new_key: &str, diagnostics: &mut Vec<ConfigurationDiagnostic>) {
  if let Some(raw_value) = config.shift_remove(old_key) {
    if !config.contains_key(new_key) {
      config.insert(new_key.to_string(), raw_value);
    }
    diagnostics.push(ConfigurationDiagnostic {
      property_name: old_key.to_string(),
      message: format!("The configuration key was renamed to '{}'", new_key),
    });
  }
}

/// Resolves the `NewLineKind` text from the provided file text and `NewLineKind`.
pub fn resolve_new_line_kind(file_text: &str, new_line_kind: NewLineKind) -> &'static str {
  match new_line_kind {
    NewLineKind::LineFeed => "\n",
    NewLineKind::CarriageReturnLineFeed => "\r\n",
    NewLineKind::Auto => {
      let mut found_slash_n = false;
      for c in file_text.as_bytes().iter().rev() {
        if found_slash_n {
          if c == &(b'\r') {
            return "\r\n";
          } else {
            return "\n";
          }
        }

        if c == &(b'\n') {
          found_slash_n = true;
        }
      }

      "\n"
    }
  }
}

/// Gets a diagnostic for each remaining key value pair in the hash map.
///
/// This should be done last, so it swallows the hashmap.
pub fn get_unknown_property_diagnostics(config: ConfigKeyMap) -> Vec<ConfigurationDiagnostic> {
  let mut diagnostics = Vec::new();
  for (key, _) in config {
    diagnostics.push(ConfigurationDiagnostic {
      property_name: key.to_string(),
      message: "Unknown property in configuration".to_string(),
    });
  }
  diagnostics
}

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

  #[test]
  fn get_default_config_when_empty() {
    let config_result = resolve_global_config(&mut ConfigKeyMap::new());
    let config = config_result.config;
    assert_eq!(config_result.diagnostics.len(), 0);
    assert_eq!(config.line_width, None);
    assert_eq!(config.indent_width, None);
    assert!(config.new_line_kind.is_none());
    assert_eq!(config.use_tabs, None);
  }

  #[test]
  fn get_values_when_filled() {
    let mut global_config = ConfigKeyMap::from([
      (String::from("lineWidth"), ConfigKeyValue::from_i32(80)),
      (String::from("indentWidth"), ConfigKeyValue::from_i32(8)),
      (String::from("newLineKind"), ConfigKeyValue::from_str("crlf")),
      (String::from("useTabs"), ConfigKeyValue::from_bool(true)),
    ]);
    let config_result = resolve_global_config(&mut global_config);
    let config = config_result.config;
    assert_eq!(config_result.diagnostics.len(), 0);
    assert_eq!(config.line_width, Some(80));
    assert_eq!(config.indent_width, Some(8));
    assert_eq!(config.new_line_kind, Some(NewLineKind::CarriageReturnLineFeed));
    assert_eq!(config.use_tabs, Some(true));
  }

  #[test]
  fn get_diagnostic_for_invalid_enum_config() {
    let mut global_config = ConfigKeyMap::from([(String::from("newLineKind"), ConfigKeyValue::from_str("something"))]);
    let diagnostics = resolve_global_config(&mut global_config).diagnostics;
    assert_eq!(diagnostics.len(), 1);
    assert_eq!(diagnostics[0].message, "Found invalid value 'something'.");
    assert_eq!(diagnostics[0].property_name, "newLineKind");
  }

  #[test]
  fn get_diagnostic_for_invalid_primitive() {
    let mut global_config = ConfigKeyMap::from([(String::from("useTabs"), ConfigKeyValue::from_str("something"))]);
    let diagnostics = resolve_global_config(&mut global_config).diagnostics;
    assert_eq!(diagnostics.len(), 1);
    assert_eq!(diagnostics[0].message, "provided string was not `true` or `false`");
    assert_eq!(diagnostics[0].property_name, "useTabs");
  }

  #[test]
  fn get_diagnostic_for_excess_property() {
    let global_config = ConfigKeyMap::from([(String::from("something"), ConfigKeyValue::from_str("value"))]);
    let diagnostics = get_unknown_property_diagnostics(global_config);
    assert_eq!(diagnostics.len(), 1);
    assert_eq!(diagnostics[0].message, "Unknown property in configuration");
    assert_eq!(diagnostics[0].property_name, "something");
  }

  #[test]
  fn add_diagnostic_for_renamed_property() {
    let mut config = ConfigKeyMap::new();
    let mut diagnostics = Vec::new();
    config.insert("oldProp".to_string(), ConfigKeyValue::from_str("value"));
    handle_renamed_config_property(&mut config, "oldProp", "newProp", &mut diagnostics);
    assert_eq!(config.len(), 1);
    assert_eq!(config.remove("newProp").unwrap(), ConfigKeyValue::from_str("value"));
    assert_eq!(diagnostics.len(), 1);
    assert_eq!(diagnostics[0].message, "The configuration key was renamed to 'newProp'");
    assert_eq!(diagnostics[0].property_name, "oldProp");
  }

  #[test]
  fn add_diagnostic_for_renamed_property_when_already_exists() {
    let mut config = ConfigKeyMap::new();
    let mut diagnostics = Vec::new();
    config.insert("oldProp".to_string(), ConfigKeyValue::from_str("new_value"));
    config.insert("newProp".to_string(), ConfigKeyValue::from_str("value"));
    handle_renamed_config_property(&mut config, "oldProp", "newProp", &mut diagnostics);
    assert_eq!(config.len(), 1);
    assert_eq!(config.remove("newProp").unwrap(), ConfigKeyValue::from_str("value"));
    assert_eq!(diagnostics.len(), 1);
    assert_eq!(diagnostics[0].message, "The configuration key was renamed to 'newProp'");
    assert_eq!(diagnostics[0].property_name, "oldProp");
  }
}