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
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
use anyhow::Result;
use anyhow::bail;
use std::borrow::Cow;
use std::ffi::OsString;
use std::io;
use std::io::Read;
use std::io::Write;
use std::num::NonZeroUsize;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use url::Url;

use dprint_core::async_runtime::async_trait;
use sys_traits::BaseEnvVar;
use sys_traits::BaseFsCreateDir;
use sys_traits::BaseFsMetadata;
use sys_traits::BaseFsOpen;
use sys_traits::BaseFsRead;
use sys_traits::BaseFsRemoveFile;
use sys_traits::BaseFsRename;
use sys_traits::BaseFsSetPermissions;
use sys_traits::SystemRandom;
use sys_traits::SystemTimeNow;
use sys_traits::ThreadSleep;

use crate::plugins::CompilationResult;
use crate::utils::BasicShowConfirmStrategy;
use crate::utils::LogLevel;
use crate::utils::MultiSelectItem;
use crate::utils::ProgressBars;
use crate::utils::ShowConfirmStrategy;

use super::CanonicalizedPathBuf;

#[derive(Debug)]
pub enum DirEntry {
  Directory(PathBuf),
  File { name: std::ffi::OsString, path: PathBuf },
}

/// The kind of entry at a path on the file system.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathKind {
  File,
  Dir,
  Symlink,
}

#[derive(Debug, Clone)]
pub enum FilePermissions {
  Std(std::fs::Permissions),
  #[allow(dead_code)]
  Test(TestFilePermissions),
}

impl FilePermissions {
  pub fn readonly(&self) -> bool {
    match self {
      FilePermissions::Std(p) => p.readonly(),
      FilePermissions::Test(p) => p.readonly,
    }
  }
}

#[derive(Default, Debug, Clone)]
pub struct TestFilePermissions {
  pub readonly: bool,
}

pub struct DownloadedFile {
  pub headers: std::collections::HashMap<String, String>,
  pub content: Vec<u8>,
}

/// How a file should be requested.
#[derive(Debug, Default, Clone, Copy)]
pub struct DownloadOptions<'a> {
  /// Value of the `Authorization` header to send.
  pub auth: Option<&'a str>,
  pub proxy: DownloadProxy<'a>,
}

/// What a request is sent through.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum DownloadProxy<'a> {
  /// The proxy found in the environment (ex. `HTTPS_PROXY`), if any.
  #[default]
  Environment,
  /// This proxy instead of the one found in the environment.
  Url(&'a str),
  /// No proxy, even when the environment has one.
  Direct,
}

#[async_trait(?Send)]
pub trait UrlDownloader {
  /// Downloads a file without following redirects. Returns the raw response
  /// headers and content. A redirect response will have a `location` header
  /// and empty content.
  async fn download_file_no_redirects(&self, url: &Url, options: DownloadOptions<'_>) -> Result<Option<DownloadedFile>>;

  /// Downloads a file, following redirects, and returns `None` on 404.
  async fn download_file<'a>(&self, url: &'a Url, options: DownloadOptions<'_>) -> Result<(Cow<'a, Url>, Option<DownloadedFile>)> {
    let original_origin = (url.scheme().to_string(), url.host_str().map(|h| h.to_string()), url.port_or_known_default());
    let mut current_url = Cow::Borrowed(url);
    let mut current_options = options;
    for _ in 0..=10 {
      let result = match self.download_file_no_redirects(&current_url, current_options).await? {
        Some(r) => r,
        None => return Ok((current_url, None)),
      };
      if let Some(location) = result.headers.get("location") {
        current_url = Cow::Owned(current_url.join(location)?);
        // drop the auth on a cross-origin redirect
        let new_origin = (
          current_url.scheme().to_string(),
          current_url.host_str().map(|h| h.to_string()),
          current_url.port_or_known_default(),
        );
        if new_origin != original_origin {
          current_options.auth = None;
        }
        continue;
      }
      return Ok((current_url, Some(result)));
    }
    bail!("Too many redirects for {}", url)
  }

  /// Downloads a file, following redirects, and errors when not found.
  async fn download_file_err_404<'a>(&self, url: &'a Url, options: DownloadOptions<'_>) -> Result<(Cow<'a, Url>, DownloadedFile)> {
    match self.download_file(url, options).await {
      Ok((url, Some(value))) => Ok((url, value)),
      Ok((url, None)) => bail!("Error downloading {} - 404 Not Found", url),
      Err(err) => Err(err),
    }
  }
}

// use a macro here so the expression provided is only evaluated when in debug mode
macro_rules! log_debug {
  ($logger:expr, $($arg:tt)*) => {
    if $logger.log_level().is_debug() {
      let mut text = String::from("[DEBUG] ");
      text.push_str(&format!($($arg)*));
      $logger.__log_stderr__(&text);
    }
  }
}

macro_rules! log_stderr_info {
  ($logger:expr, $single_arg:expr $(,)? ) => {
    if $logger.log_level().is_info() {
      $logger.__log_stderr__($single_arg);
    }
  };
  ($logger:expr, $($arg:tt)*) => {
    if $logger.log_level().is_info() {
      $logger.__log_stderr__(&format!($($arg)*));
    }
  }
}

macro_rules! log_stdout_info {
  ($logger:expr, $single_arg:expr $(,)? ) => {
    if $logger.log_level().is_info() {
      $logger.__log__($single_arg);
    }
  };
  ($logger:expr, $($arg:tt)*) => {
    if $logger.log_level().is_info() {
      $logger.__log__(&format!($($arg)*));
    }
  }
}

macro_rules! log_warn {
  ($logger:expr, $single_arg:expr $(,)? ) => {
    if $logger.log_level().is_warn() {
      $logger.__log_stderr__($single_arg);
    }
  };
  ($logger:expr, $($arg:tt)*) => {
    if $logger.log_level().is_warn() {
      $logger.__log_stderr__(&format!($($arg)*));
    }
  }
}

macro_rules! log_error {
  ($logger:expr, $single_arg:expr $(,)? ) => {
    if $logger.log_level().is_error() {
      $logger.__log_stderr__($single_arg);
    }
  };
  ($logger:expr, $($arg:tt)*) => {
    if $logger.log_level().is_error() {
      $logger.__log_stderr__(&format!($($arg)*));
    }
  }
}

macro_rules! log_all {
  ($logger:expr, $single_arg:expr $(,)? ) => {
    $logger.__log_stderr__($single_arg);
  };
  ($logger:expr, $($arg:tt)*) => {
    $logger.__log_stderr__(&format!($($arg)*));
  }
}

#[async_trait]
pub trait Environment:
  Clone
  + Send
  + Sync
  + std::fmt::Debug
  + UrlDownloader
  + BaseEnvVar
  + BaseFsCreateDir
  + BaseFsMetadata
  + BaseFsOpen
  + BaseFsRead
  + BaseFsRemoveFile
  + BaseFsRename
  + BaseFsSetPermissions
  + ThreadSleep
  + SystemRandom
  + SystemTimeNow
  + 'static
{
  fn is_real(&self) -> bool;

  fn env_var(&self, name: &str) -> Option<OsString>;

  fn get_staged_files(&self) -> Result<Vec<PathBuf>>;
  /// Resolves the files that have uncommitted changes in the git working
  /// directory: staged, unstaged, and untracked (but not gitignored) files.
  fn get_dirty_files(&self) -> Result<Vec<PathBuf>>;
  /// Resolves the path to git's global excludes file (the `core.excludesFile`
  /// config value, falling back to `$XDG_CONFIG_HOME/git/ignore`). Used only when
  /// global gitignore support is opted into via `DPRINT_GLOBAL_GITIGNORE`. The
  /// path is not guaranteed to exist; the caller handles a missing file when
  /// reading it. Returns `None` only when no path can be resolved at all.
  fn global_gitignore_path(&self) -> Option<PathBuf>;
  fn read_file(&self, file_path: impl AsRef<Path>) -> io::Result<String>;
  fn maybe_read_file(&self, file_path: impl AsRef<Path>) -> io::Result<Option<String>> {
    match self.read_file(file_path) {
      Ok(value) => Ok(Some(value)),
      Err(err) => match err.kind() {
        std::io::ErrorKind::NotFound => Ok(None),
        _ => Err(err),
      },
    }
  }
  fn read_file_bytes(&self, file_path: impl AsRef<Path>) -> io::Result<Vec<u8>>;
  fn write_file(&self, file_path: impl AsRef<Path>, file_text: &str) -> io::Result<()> {
    self.write_file_bytes(file_path, file_text.as_bytes())
  }
  fn write_file_bytes(&self, file_path: impl AsRef<Path>, bytes: &[u8]) -> io::Result<()>;
  /// An atomic write, which will write to a temporary file and then rename it to the destination.
  fn atomic_write_file_bytes(&self, file_path: impl AsRef<Path>, bytes: &[u8]) -> io::Result<()> {
    crate::utils::fs::atomic_write_file_with_retries(self, file_path.as_ref(), bytes, 0o644)
  }
  fn rename(&self, path_from: impl AsRef<Path>, path_to: impl AsRef<Path>) -> io::Result<()>;
  fn remove_file(&self, file_path: impl AsRef<Path>) -> io::Result<()>;
  fn remove_dir_all(&self, dir_path: impl AsRef<Path>) -> io::Result<()>;
  /// Removes a directory and all of its contents as best-effort cleanup,
  /// logging any failure at debug level rather than returning it. Use this
  /// for cleanup that shouldn't abort the surrounding operation, while still
  /// surfacing the cause in `--log-level=debug` output.
  fn try_remove_dir_all(&self, dir_path: impl AsRef<Path>) {
    if let Err(err) = self.remove_dir_all(dir_path) {
      log_debug!(self, "{:#}", err);
    }
  }
  fn dir_info(&self, dir_path: impl AsRef<Path>) -> io::Result<Vec<DirEntry>>;
  /// Kills any running process whose executable lives under the given directory
  /// and returns how many were killed. Used when clearing the cache so a process
  /// plugin that's still running can't stop its executable from being deleted
  /// (e.g. on Windows a running executable can't be removed). This is best-effort
  /// and never fails.
  fn kill_processes_using_dir(&self, dir_path: impl AsRef<Path>) -> usize;
  /// Gets whether anything exists at the path (follows symlinks, so a broken
  /// symlink does not count as existing).
  fn path_exists(&self, path: impl AsRef<Path>) -> bool;
  /// Gets whether the path exists and is a file (follows symlinks).
  fn path_is_file(&self, path: impl AsRef<Path>) -> bool;
  /// Stats the path in a single call, saying whether it's a file, directory,
  /// or symlink (`None` when the path doesn't exist). Symlinks are not
  /// followed—canonicalize and stat again to see what a symlink points at.
  fn path_kind(&self, path: impl AsRef<Path>) -> Option<PathKind>;
  fn canonicalize(&self, path: impl AsRef<Path>) -> io::Result<CanonicalizedPathBuf>;
  /// Canonicalizes a path that might not exist (ex. an unsaved file in an editor)
  /// by canonicalizing its closest existing ancestor and adding back the rest.
  fn canonicalize_maybe_not_exists(&self, path: impl AsRef<Path>) -> io::Result<CanonicalizedPathBuf> {
    canonicalize_path_maybe_not_exists(path.as_ref(), |path| self.canonicalize(path))
  }
  fn is_absolute_path(&self, path: impl AsRef<Path>) -> bool;
  fn file_permissions(&self, path: impl AsRef<Path>) -> io::Result<FilePermissions>;
  fn set_file_permissions(&self, path: impl AsRef<Path>, permissions: FilePermissions) -> io::Result<()>;
  fn mk_dir_all(&self, path: impl AsRef<Path>) -> io::Result<()>;
  fn cwd(&self) -> CanonicalizedPathBuf;
  fn current_exe(&self) -> io::Result<PathBuf>;
  /// Don't ever call this directly in the code. That's why this has this weird name.
  fn __log__(&self, text: &str);
  /// Don't ever call this directly in the code. That's why this has this weird name.
  fn __log_stderr__(&self, text: &str) {
    self.log_stderr_with_context(text, "dprint");
  }
  /// Logs an error to the console providing the context name.
  /// This will cause the logger to output the context name when appropriate.
  /// Ex. Will log the dprint process plugin name.
  fn log_stderr_with_context(&self, text: &str, context_name: &str);
  /// Information to force output when the environment is in "machine readable mode".
  fn log_machine_readable(&self, bytes: &[u8]);
  fn log_action_with_progress<TResult: Send + Sync, TCreate: FnOnce(Box<dyn Fn(usize)>) -> TResult + Send + Sync>(
    &self,
    message: &str,
    action: TCreate,
    total_size: usize,
  ) -> TResult;
  fn get_cache_dir(&self) -> CanonicalizedPathBuf;
  fn get_config_dir(&self) -> Option<PathBuf>;
  fn get_home_dir(&self) -> Option<CanonicalizedPathBuf>;
  /// Gets the CPU architecture.
  fn cpu_arch(&self) -> String;
  /// Gets the operating system.
  fn os(&self) -> String;
  fn available_parallelism(&self) -> Option<NonZeroUsize>;
  fn max_threads(&self) -> usize {
    resolve_max_threads(
      self.env_var("DPRINT_MAX_THREADS").as_deref().and_then(|s| s.to_str()),
      self.available_parallelism(),
    )
  }
  /// Gets the CLI version
  fn cli_version(&self) -> String;
  fn get_time_secs(&self) -> u64;
  fn get_selection(&self, prompt_message: &str, item_indent_width: u16, items: &[String]) -> Result<usize>;
  /// Prompts for multiple items, returning the indexes of the selected ones.
  /// Items that aren't selectable are shown but never returned.
  fn get_multi_selection(&self, prompt_message: &str, item_indent_width: u16, items: Vec<MultiSelectItem>) -> Result<Vec<usize>>;
  fn confirm(&self, prompt_message: &str, default_value: bool) -> Result<bool> {
    self.confirm_with_strategy(&BasicShowConfirmStrategy {
      prompt: prompt_message,
      default_value,
    })
  }
  fn confirm_with_strategy(&self, strategy: &dyn ShowConfirmStrategy) -> Result<bool>;
  fn run_command_get_status(&self, args: Vec<OsString>) -> io::Result<Option<i32>>;
  fn is_ci(&self) -> bool;
  fn is_terminal_interactive(&self) -> bool;
  fn log_level(&self) -> LogLevel;
  fn compile_wasm(&self, wasm_bytes: &[u8]) -> Result<CompilationResult>;
  fn wasm_cache_key(&self) -> String;
  /// Returns the current CPU usage as a value from 0-100.
  async fn cpu_usage(&self) -> u8;
  fn stdout(&self) -> Box<dyn Write + Send>;
  fn stdin(&self) -> Box<dyn Read + Send>;
  fn progress_bars(&self) -> Option<&Arc<ProgressBars>> {
    None
  }
  #[cfg(windows)]
  fn ensure_system_path(&self, directory_path: &str) -> io::Result<()>;
  #[cfg(windows)]
  fn remove_system_path(&self, directory_path: &str) -> io::Result<()>;
}

fn resolve_max_threads(env_var: Option<&str>, available_parallelism: Option<NonZeroUsize>) -> usize {
  fn maybe_specified_threads(env_var: Option<&str>) -> Option<usize> {
    let value = env_var?.parse::<usize>().ok()?;
    if value > 0 { Some(value) } else { None }
  }

  let maybe_actual_count = available_parallelism.map(|p| p.get());
  match maybe_specified_threads(env_var) {
    Some(specified_count) => match maybe_actual_count {
      Some(actual_count) if specified_count > actual_count => actual_count,
      _ => specified_count,
    },
    _ => maybe_actual_count.unwrap_or(4),
  }
}

/// Canonicalizes a path that might not exist by going up its ancestors until one
/// canonicalizes, then adding back the remaining path components.
fn canonicalize_path_maybe_not_exists(mut path: &Path, canonicalize: impl Fn(&Path) -> io::Result<CanonicalizedPathBuf>) -> io::Result<CanonicalizedPathBuf> {
  let mut names = Vec::new();
  loop {
    match canonicalize(path) {
      Ok(canonicalized_path) => {
        let mut path = canonicalized_path.into_path_buf();
        for name in names.into_iter().rev() {
          path.push(name);
        }
        return Ok(CanonicalizedPathBuf::new(path));
      }
      Err(err) if err.kind() == io::ErrorKind::NotFound => {
        let Some(name) = path.file_name() else {
          return Err(err);
        };
        names.push(name);
        path = match path.parent() {
          // a relative path's last parent is empty, which is the cwd
          Some(parent) if parent.as_os_str().is_empty() => Path::new("."),
          Some(parent) => parent,
          None => return Err(err),
        };
      }
      Err(err) => return Err(err),
    }
  }
}

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

  fn real_canonicalize(path: &Path) -> io::Result<CanonicalizedPathBuf> {
    dunce::canonicalize(path).map(CanonicalizedPathBuf::new)
  }

  #[test]
  #[allow(clippy::disallowed_methods)]
  fn should_canonicalize_path_maybe_not_exists() {
    let temp_dir = tempfile::tempdir().unwrap();
    let real_dir = real_canonicalize(temp_dir.path()).unwrap();
    std::fs::create_dir(real_dir.join("sub")).unwrap();
    std::fs::write(real_dir.join("sub").join("file.txt"), "").unwrap();

    // existing path
    let path = temp_dir.path().join("sub").join("file.txt");
    assert_eq!(
      canonicalize_path_maybe_not_exists(&path, real_canonicalize).unwrap().into_path_buf(),
      real_dir.join("sub").join("file.txt")
    );
    // file that doesn't exist in an existing directory
    let path = temp_dir.path().join("sub").join("Untitled.json");
    assert_eq!(
      canonicalize_path_maybe_not_exists(&path, real_canonicalize).unwrap().into_path_buf(),
      real_dir.join("sub").join("Untitled.json")
    );
    // multiple components that don't exist
    let path = temp_dir.path().join("new").join("dir").join("file.txt");
    assert_eq!(
      canonicalize_path_maybe_not_exists(&path, real_canonicalize).unwrap().into_path_buf(),
      real_dir.join("new").join("dir").join("file.txt")
    );
  }

  #[cfg(windows)]
  #[test]
  fn should_canonicalize_path_maybe_not_exists_with_different_casing() {
    let temp_dir = tempfile::tempdir().unwrap();
    let real_dir = real_canonicalize(temp_dir.path()).unwrap();
    // ex. vscode provides paths with a lowercase drive letter
    let lowercase_dir = PathBuf::from(real_dir.to_string_lossy().to_lowercase());
    let path = lowercase_dir.join("Untitled.json");
    assert_eq!(
      canonicalize_path_maybe_not_exists(&path, real_canonicalize).unwrap().into_path_buf(),
      real_dir.join("Untitled.json")
    );
  }

  #[test]
  fn should_error_canonicalize_path_maybe_not_exists_on_other_errors() {
    let result = canonicalize_path_maybe_not_exists(Path::new("/a/b.txt"), |_| Err(io::Error::other("failed")));
    assert_eq!(result.unwrap_err().to_string(), "failed");
  }

  #[test]
  fn should_resolve_num_threads() {
    assert_eq!(resolve_max_threads(None, None), 4);
    assert_eq!(resolve_max_threads(None, NonZeroUsize::new(1)), 1);
    assert_eq!(resolve_max_threads(None, NonZeroUsize::new(4)), 4);
    assert_eq!(resolve_max_threads(Some("2"), NonZeroUsize::new(4)), 2);
    assert_eq!(resolve_max_threads(Some("0"), NonZeroUsize::new(4)), 4);
    assert_eq!(resolve_max_threads(Some("5"), NonZeroUsize::new(4)), 4);
    assert_eq!(resolve_max_threads(Some("4"), NonZeroUsize::new(4)), 4);
  }
}