dprint 0.60.0

Binary for dprint code formatter—a pluggable and configurable code formatting platform.
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
use std::borrow::Cow;

use ignore::gitignore::GitignoreBuilder;

pub fn is_negated_glob(pattern: &str) -> bool {
  let mut chars = pattern.chars();
  let first_char = chars.next();
  let second_char = chars.next();

  first_char == Some('!') && second_char != Some('(')
}

pub fn non_negated_glob(pattern: &str) -> &str {
  if is_negated_glob(pattern) { &pattern[1..] } else { pattern }
}

pub fn is_pattern(pattern: &str) -> bool {
  if pattern.starts_with('!') {
    return true;
  }

  let mut was_last_escape = false;
  for c in pattern.chars() {
    if !was_last_escape && matches!(c, '*' | '{' | '?' | '[') {
      return true;
    }

    // consume backslashes in pairs the same way `unescape_glob_text` does so
    // an escaped backslash doesn't escape the character after it
    // (ex. the `*` in `a\\*b` is a glob star)
    was_last_escape = c == '\\' && !was_last_escape;
  }
  false
}

/// Expands the brace groups in a pattern that span path components into
/// separate patterns (ex. `{.,src/**,worker}/*.js` -> `./*.js`, `src/**/*.js`
/// and `worker/*.js`).
///
/// The glob engine only understands a brace group within a single path
/// component (ex. `*.{ts,js}`), so those are left for it to handle and the
/// provided pattern is returned as-is without allocating.
pub fn expand_braces(pattern: String) -> impl Iterator<Item = String> {
  let (pattern, expansions) = match try_expand_braces(&pattern) {
    Some(expansions) => (None, expansions),
    None => (Some(pattern), Vec::new()),
  };
  pattern.into_iter().chain(expansions)
}

/// Whether a single path component pattern (ex. `dist`, `su*`, `[sd]ist`)
/// names the given directory.
///
/// Matching goes through the same gitignore engine the exclude matcher uses so
/// a wildcard means here what it means when the pattern is finally matched.
pub fn pattern_names_dir(pattern: &str, dir_name: &str) -> bool {
  if !is_pattern(pattern) {
    return unescape_glob_text(pattern) == dir_name;
  }
  // a component pattern can't match a name containing a separator
  if dir_name.contains('/') || dir_name.contains('\\') {
    return false;
  }
  let mut builder = GitignoreBuilder::new("");
  if builder.add_line(None, pattern).is_err() {
    return false;
  }
  match builder.build() {
    Ok(gitignore) => gitignore.matched(dir_name, true).is_ignore(),
    Err(_) => false,
  }
}

/// Escapes glob metacharacters so the text matches literally
/// (ex. `routes/[id].svelte` -> `routes/\[id\].svelte`).
pub fn escape_glob_text(text: &str) -> String {
  let mut result = String::with_capacity(text.len());
  for c in text.chars() {
    if matches!(c, '\\' | '*' | '{' | '}' | '?' | '[' | ']' | '!') {
      result.push('\\');
    }
    result.push(c);
  }
  result
}

/// Escapes glob metacharacters using character classes (ex. `[` -> `[[]`) so
/// the result contains no backslashes and survives CLI pattern processing,
/// which converts backslashes to forward slashes.
pub fn escape_glob_text_for_cli(text: &str) -> String {
  let mut result = String::with_capacity(text.len());
  for c in text.chars() {
    match c {
      '[' | ']' | '{' | '}' | '*' | '?' => {
        result.push('[');
        result.push(c);
        result.push(']');
      }
      _ => result.push(c),
    }
  }
  result
}

/// Removes glob escapes (ex. `routes/\[id\].svelte` -> `routes/[id].svelte`).
pub fn unescape_glob_text(text: &str) -> Cow<'_, str> {
  if !text.contains('\\') {
    return Cow::Borrowed(text);
  }
  let mut result = String::with_capacity(text.len());
  let mut chars = text.chars();
  while let Some(c) = chars.next() {
    if c == '\\' {
      match chars.next() {
        Some(next) => result.push(next),
        None => result.push(c),
      }
    } else {
      result.push(c);
    }
  }
  Cow::Owned(result)
}

pub fn is_absolute_pattern(pattern: &str) -> bool {
  let pattern = if is_negated_glob(pattern) { &pattern[1..] } else { pattern };
  pattern.starts_with('/') || is_windows_absolute_pattern(pattern)
}

fn is_windows_absolute_pattern(pattern: &str) -> bool {
  // ex. D:/
  let mut chars = pattern.chars();

  // ensure the first character is alphabetic
  let next_char = chars.next();
  if next_char.is_none() || !next_char.unwrap().is_ascii_alphabetic() {
    return false;
  }

  // skip over the remaining alphabetic characters
  let mut next_char = chars.next();
  while next_char.is_some() && next_char.unwrap().is_ascii_alphabetic() {
    next_char = chars.next();
  }

  // ensure colon
  if next_char != Some(':') {
    return false;
  }

  // now check for the last slash
  let next_char = chars.next();
  matches!(next_char, Some('/'))
}

fn try_expand_braces(pattern: &str) -> Option<Vec<String>> {
  let is_negated = is_negated_glob(pattern);
  let text = non_negated_glob(pattern);
  find_brace_group_spanning_path_components(text, 0)?;

  let mut expansions = Vec::new();
  expand_braces_from(text.to_string(), 0, &mut expansions);

  // a pattern with a slash only matches relative to its base directory, so
  // keep it that way when an expansion ends up without one (ex. `{a/b,c}`)
  let is_anchored = text.trim_end_matches('/').contains('/');
  for expansion in &mut expansions {
    // a `.` alternative names the directory it's in (ex. `src/{.,sub}/*.js`)
    while let Some(index) = expansion.find("/./") {
      expansion.replace_range(index..index + 2, "");
    }
    if expansion.len() > "./.".len() && expansion.ends_with("/.") {
      expansion.truncate(expansion.len() - "/.".len());
    }
    // an empty alternative at the start doesn't make the pattern absolute
    // (ex. `{,sub}/*.js`)
    if expansion.starts_with('/') && !text.starts_with('/') {
      expansion.insert(0, '.');
    }
    if is_anchored && !expansion.trim_end_matches('/').contains('/') {
      expansion.insert_str(0, "./");
    }
    if is_negated {
      expansion.insert(0, '!');
    }
  }
  Some(expansions)
}

fn expand_braces_from(text: String, start: usize, expansions: &mut Vec<String>) {
  let Some(group) = find_brace_group_spanning_path_components(&text, start) else {
    expansions.push(text);
    return;
  };
  let (before, after) = (&text[..group.open], &text[group.close + 1..]);
  let body = &text[group.open + 1..group.close];
  let mut alternative_start = 0;
  for comma_index in top_level_comma_indexes(body).chain(std::iter::once(body.len())) {
    let alternative = &body[alternative_start..comma_index];
    let mut expanded = String::with_capacity(before.len() + alternative.len() + after.len());
    expanded.push_str(before);
    expanded.push_str(alternative);
    expanded.push_str(after);
    // start at the alternative because it might contain a nested group
    expand_braces_from(expanded, group.open, expansions);
    alternative_start = comma_index + 1;
  }
}

struct BraceGroup {
  /// Index of the opening brace.
  open: usize,
  /// Index of the closing brace.
  close: usize,
  has_alternatives: bool,
}

impl BraceGroup {
  fn spans_path_components(&self, text: &str) -> bool {
    let body = &text[self.open + 1..self.close];
    self.has_alternatives && (body.contains('/') || body.split(['{', '}', ',']).any(|part| matches!(part, "." | "..")))
  }
}

fn find_brace_group_spanning_path_components(text: &str, start: usize) -> Option<BraceGroup> {
  let mut start = start;
  loop {
    let group = find_brace_group(text, start)?;
    if group.spans_path_components(text) {
      return Some(group);
    }
    // look within the group because it might only be wrapping a nested
    // group that does (ex. `{{a/b,c}}`)
    start = group.open + 1;
  }
}

/// Finds the first brace group at or after the start index, skipping over
/// escaped characters and character classes (ex. `[{]`).
fn find_brace_group(text: &str, start: usize) -> Option<BraceGroup> {
  let bytes = text.as_bytes();
  let mut index = start;
  while index < bytes.len() {
    match bytes[index] {
      b'\\' => index += 2,
      b'[' => index = skip_char_class(bytes, index),
      b'{' => {
        // when unbalanced, leave it for the glob engine to error on
        let mut tokens = BraceTokens::new(&text[index + 1..]);
        let has_alternatives = tokens.by_ref().count() > 0;
        return tokens.close.map(|close| BraceGroup {
          open: index,
          close: index + 1 + close,
          has_alternatives,
        });
      }
      _ => index += 1,
    }
  }
  None
}

/// Gets the indexes of the commas separating the alternatives of a brace
/// group's body (so not the ones in a nested group).
fn top_level_comma_indexes(body: &str) -> impl Iterator<Item = usize> + '_ {
  BraceTokens::new(body)
}

/// Iterates over the indexes of the commas separating the alternatives in the
/// text following an opening brace, stopping at the group's closing brace.
struct BraceTokens<'a> {
  bytes: &'a [u8],
  index: usize,
  depth: usize,
  /// Index of the closing brace once found.
  close: Option<usize>,
}

impl<'a> BraceTokens<'a> {
  fn new(text: &'a str) -> Self {
    Self {
      bytes: text.as_bytes(),
      index: 0,
      depth: 1,
      close: None,
    }
  }
}

impl Iterator for BraceTokens<'_> {
  type Item = usize;

  fn next(&mut self) -> Option<usize> {
    if self.close.is_some() {
      return None;
    }
    while self.index < self.bytes.len() {
      let index = self.index;
      match self.bytes[index] {
        b'\\' => {
          self.index += 2;
          continue;
        }
        b'[' => {
          self.index = skip_char_class(self.bytes, index);
          continue;
        }
        b'{' => self.depth += 1,
        b'}' => {
          self.depth -= 1;
          if self.depth == 0 {
            self.close = Some(index);
            return None;
          }
        }
        b',' if self.depth == 1 => {
          self.index += 1;
          return Some(index);
        }
        _ => {}
      }
      self.index += 1;
    }
    None
  }
}

/// Gets the index after the character class opening at the provided index,
/// or after the bracket when it doesn't open a character class.
fn skip_char_class(bytes: &[u8], open: usize) -> usize {
  let mut index = open + 1;
  if matches!(bytes.get(index), Some(b'!' | b'^')) {
    index += 1;
  }
  // a closing bracket at the start of a class is a literal (ex. `[]]`)
  if bytes.get(index) == Some(&b']') {
    index += 1;
  }
  while index < bytes.len() {
    if bytes[index] == b']' {
      return index + 1;
    }
    index += 1;
  }
  open + 1
}

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

  #[test]
  fn should_escape_and_unescape_glob_text() {
    assert_eq!(escape_glob_text("routes/[id].svelte"), "routes/\\[id\\].svelte");
    assert_eq!(escape_glob_text("{{myfile}}.yaml"), "\\{\\{myfile\\}\\}.yaml");
    assert_eq!(escape_glob_text("a*b?c!d\\e"), "a\\*b\\?c\\!d\\\\e");
    assert_eq!(escape_glob_text("plain/file.txt"), "plain/file.txt");

    assert_eq!(escape_glob_text_for_cli("/[app]/dir"), "/[[]app[]]/dir");
    assert_eq!(escape_glob_text_for_cli("/plain/dir"), "/plain/dir");

    assert_eq!(unescape_glob_text("routes/\\[id\\].svelte"), "routes/[id].svelte");
    assert_eq!(unescape_glob_text("plain/file.txt"), "plain/file.txt");
    assert_eq!(unescape_glob_text("a\\\\b"), "a\\b");
    // a trailing lone backslash stays as-is
    assert_eq!(unescape_glob_text("a\\"), "a\\");

    // escaped text is not considered a pattern and round trips
    assert!(is_pattern("routes/[id].svelte"));
    assert!(!is_pattern(&escape_glob_text("routes/[id].svelte")));
    assert_eq!(unescape_glob_text(&escape_glob_text("a*b?c!d\\e[]{}")), "a*b?c!d\\e[]{}");

    // an escaped backslash doesn't escape the character after it, so the
    // star in `a\\*b` is a glob star (matching `unescape_glob_text`)
    assert!(is_pattern("a\\\\*b"));
    assert_eq!(unescape_glob_text("a\\\\*b"), "a\\*b");
    // ...while `a\*b` is an escaped star and so not a pattern
    assert!(!is_pattern("a\\*b"));
    assert_eq!(unescape_glob_text("a\\*b"), "a*b");
  }

  #[test]
  fn should_expand_braces_spanning_path_components() {
    #[track_caller]
    fn run(pattern: &str, expected: &[&str]) {
      assert_eq!(expand_braces(pattern.to_string()).collect::<Vec<_>>(), expected);
    }

    run("{.,src/**,worker}/*.js", &["./*.js", "src/**/*.js", "worker/*.js"]);
    run("!{.,src/**}/*.js", &["!./*.js", "!src/**/*.js"]);
    run("src/{.,sub}/*.js", &["src/*.js", "src/sub/*.js"]);
    run("{a/b,c}/*.{ts,js}", &["a/b/*.{ts,js}", "c/*.{ts,js}"]);
    run("**/*.{ts,js}/{a/b,c}", &["**/*.{ts,js}/a/b", "**/*.{ts,js}/c"]);
    // nested
    run("{a,b/{c,d/e}}/f", &["a/f", "b/c/f", "b/d/e/f"]);
    run("{a/{b,c},d}", &["a/{b,c}", "./d"]);
    run("{a,{.,b/c}}/d", &["a/d", "./d", "b/c/d"]);
    // multiple groups
    run("{a/b,c}/{d/e,f}", &["a/b/d/e", "a/b/f", "c/d/e", "c/f"]);
    // stays relative to the base directory
    run("{a/b,c}", &["a/b", "./c"]);
    run("{,src/}*.js", &["./*.js", "src/*.js"]);
    run("./{a/b,c}", &["./a/b", "./c"]);
    run("{,sub/dir}/*.js", &["./*.js", "sub/dir/*.js"]);
    run("/{a/b,c}", &["/a/b", "/c"]);
    // `.` and `..` alternatives
    run("src/{.,sub}", &["./src", "src/sub"]);
    run("{..,src}/*.js", &["../*.js", "src/*.js"]);
    run("a/{b/c,}/d", &["a/b/c/d", "a//d"]);
    // group only wrapping a nested group
    run("{{a/b,c}}/x", &["{a/b}/x", "{c}/x"]);
    // multi-byte characters
    run("é{ü/ñ,日本}/x", &["éü/ñ/x", "é日本/x"]);

    // left for the glob engine
    run("**/*.ts", &["**/*.ts"]);
    run("**/*.{ts,js}", &["**/*.{ts,js}"]);
    run("{a,b}/*.ts", &["{a,b}/*.ts"]);
    run("{{myfile}}.yaml", &["{{myfile}}.yaml"]);
    run("{a/b}/c", &["{a/b}/c"]);
    run("a/[{]b/c,d}", &["a/[{]b/c,d}"]);
    run("a/[]{]b/c,d}", &["a/[]{]b/c,d}"]);
    run("a/\\{b/c,d\\}", &["a/\\{b/c,d\\}"]);
    run("{a/b,c", &["{a/b,c"]);
  }

  #[test]
  fn should_get_if_pattern_names_dir() {
    assert!(pattern_names_dir("dist", "dist"));
    assert!(!pattern_names_dir("dist", "other"));
    // wildcards mean what they mean when the pattern is finally matched
    assert!(pattern_names_dir("su*", "sub"));
    assert!(!pattern_names_dir("su*", "other"));
    assert!(pattern_names_dir("?ub", "sub"));
    assert!(pattern_names_dir("[sd]ist", "dist"));
    assert!(!pattern_names_dir("[sd]ist", "list"));
    assert!(pattern_names_dir("*", "anything"));
    assert!(pattern_names_dir("*.min.js", "a.min.js"));
    // both ways of escaping a glob character match the literal name
    assert!(pattern_names_dir("\\[id\\]", "[id]"));
    assert!(pattern_names_dir("[[]id[]]", "[id]"));
    // a single component pattern never matches across a separator
    assert!(!pattern_names_dir("dist", "dist/sub"));
    assert!(!pattern_names_dir("*", "dist/sub"));
  }

  #[test]
  fn should_get_if_absolute_pattern() {
    assert_eq!(is_absolute_pattern("test.ts"), false);
    assert_eq!(is_absolute_pattern("!test.ts"), false);
    assert_eq!(is_absolute_pattern("/test.ts"), true);
    assert_eq!(is_absolute_pattern("!/test.ts"), true);
    assert_eq!(is_absolute_pattern("D:/test.ts"), true);
    assert_eq!(is_absolute_pattern("!D:/test.ts"), true);
  }
}