ronantakizawa/codereview-bench huggingface dataset:
Repository: denoland/deno
File: runtime/permissions/lib.rs (Rust)

Code before:
    name: &'static str,
    info: impl FnOnce() -> Option<String>,
  ) -> String {
    format!(
      "{} access{}",
      name,
      info().map(|info| format!(" to {info}")).unwrap_or_default(),
    )
  }

  fn permission_denied_error(
    name: &'static str,
    info: impl FnOnce() -> Option<String>,
  ) -> PermissionDeniedError {
    PermissionDeniedError {
      access: Self::fmt_access(name, info),
      name,
    }
  }

  #[inline]
  fn check(
    self,
    name: &'static str,
    api_name: Option<&str>,
    info: impl Fn() -> Option<String>,
    prompt: bool,
  ) -> (Result<(), PermissionDeniedError>, bool, bool) {
    match self {
      PermissionState::Granted => {
        Self::log_perm_access(name, info);
        (Ok(()), false, false)
      }
      PermissionState::Prompt if prompt => {
        let msg = {
          let info = info();
          StringBuilder::<String>::build(|builder| {
            builder.append(name);
            builder.append(" access");
            if let Some(info) = &info {
              builder.append(" to ");
              builder.append(info);
            }
          })
          .unwrap()
        };
        match permission_prompt(&msg, name, api_name, true) {
          PromptResponse::Allow => {
            Self::log_perm_access(name, info);
            (Ok(()), true, false)
          }

Review comment (security):
These refactorings are for the future when we add prompting for when requesting --allow-all permissions. I've just removed that code for now in order to get this merged. This errors like before.

Code after:
          PERMISSION_EMOJI,
          Self::fmt_access(name, info().as_deref())
        ))
      );
    }
  }

  fn fmt_access(name: &'static str, info: Option<&str>) -> String {
    format!(
      "{} access{}",
      name,
      info.map(|info| format!(" to {info}")).unwrap_or_default(),
    )
  }

  fn permission_denied_error(
    name: &'static str,
    info: Option<&str>,
  ) -> PermissionDeniedError {
    PermissionDeniedError {
      access: Self::fmt_access(name, info),
      name,
    }
  }

  fn prompt(
    options: PromptOptions<'_>,
  ) -> (Result<(), PermissionDeniedError>, bool) {
    let PromptOptions {
      name,
      msg,
      api_name,
      info,
      is_unary,
    } = options;
    match permission_prompt(msg, name, api_name, is_unary) {
      PromptResponse::Allow => {
        Self::log_perm_access(name, || info.map(|i| i.to_string()));
        (Ok(()), false)
      }
      PromptResponse::AllowAll => {
        Self::log_perm_access(name, || info.map(|i| i.to_string()));
        (Ok(()), true)
      }
      PromptResponse::Deny => {
        (Err(Self::permission_denied_error(name, info)), false)
      }
    }
  }

  #[inline]
Repository: denoland/deno
File: ext/webgpu/surface.rs (Rust)

Code before:

    let err =
      device
        .instance
        .surface_configure(self.surface_id, device.id, &conf);

    device.error_handler.push_error(err);

    self.config.borrow_mut().replace(Configuration {
      device: device.into(),
      usage: configuration.usage,
      format: configuration.format,
      surface_config: conf,
    });

    Ok(())
  }

  #[fast]
  fn unconfigure(&self) {
    *self.config.borrow_mut() = None;
  }

  fn get_current_texture<'s>(
    &self,
    scope: &'s mut v8::HandleScope,
  ) -> Result<v8::Local<'s, v8::Object>, SurfaceError> {
    let config = self.config.borrow();
    let Some(config) = config.as_ref() else {
      return Err(SurfaceError::UnconfiguredContext);
    };

    {
      if let Some(obj) = self.texture.borrow().get(scope) {
        return Ok(obj);
      }
    }

    let output = config
      .device
      .instance
      .surface_get_current_texture(self.surface_id, None)?;

    match output.status {
      SurfaceStatus::Good | SurfaceStatus::Suboptimal => {
        let id = output.texture_id.unwrap();

        let texture = GPUTexture {
          instance: config.device.instance.clone(),
          error_handler: config.device.error_handler.clone(),
          id,

Review comment (suggestion):
```suggestion
    scope: &mut v8::HandleScope<'s>,
```

Code after:
      alpha_mode: configuration.alpha_mode.into(),
      view_formats: configuration
        .view_formats
        .into_iter()
        .map(Into::into)
        .collect(),
      desired_maximum_frame_latency: 2,
    };

    let device = configuration.device;

    let err =
      device
        .instance
        .surface_configure(self.surface_id, device.id, &conf);

    device.error_handler.push_error(err);

    self.config.borrow_mut().replace(Configuration {
      device: device.into(),
      usage: configuration.usage,
      format: configuration.format,
      surface_config: conf,
    });

    Ok(())
  }

  #[fast]
  fn unconfigure(&self) {
    *self.config.borrow_mut() = None;
  }

  fn get_current_texture<'s>(
    &self,
    scope: &mut v8::HandleScope<'s>,
  ) -> Result<v8::Local<'s, v8::Object>, SurfaceError> {
    let config = self.config.borrow();
    let Some(config) = config.as_ref() else {
      return Err(SurfaceError::UnconfiguredContext);
    };

    {
      if let Some(obj) = self.texture.borrow().get(scope) {
        return Ok(obj);
      }
    }

    let output = config
      .device
      .instance
Repository: denoland/deno
File: libs/config/workspace/mod.rs (Rust)

Code before:
  DenoWorker,
}

impl Default for TsTypeLib {
  fn default() -> Self {
    Self::DenoWindow
  }
}

#[derive(Debug, Clone)]
pub struct CompilerOptionsSource {
  pub specifier: UrlRc,
  pub compiler_options: Option<CompilerOptions>,
}

#[derive(Debug, Clone, Default)]
struct CachedDirectoryValues {
  bench: OnceLock<BenchConfig>,
  test: OnceLock<TestConfig>,
}

#[derive(Debug, Clone)]
pub struct WorkspaceDirectory {
  pub workspace: WorkspaceRc,
  /// The directory that this context is for. This is generally the cwd.
  pub dir_url: UrlRc,
  pkg_json: Option<WorkspaceDirConfig<PackageJson>>,
  deno_json: Option<WorkspaceDirConfig<ConfigFile>>,
  cached: CachedDirectoryValues,
}

impl WorkspaceDirectory {
  pub fn empty(opts: WorkspaceDirectoryEmptyOptions) -> WorkspaceDirectoryRc {
    let workspace = new_rc(Workspace {
      config_folders: IndexMap::from([(
        opts.root_dir.clone(),
        FolderConfigs::default(),
      )]),
      root_dir_url: opts.root_dir.clone(),
      links: BTreeMap::new(),
      vendor_dir: match opts.use_vendor_dir {
        VendorEnablement::Enable { cwd } => Some(cwd.join("vendor")),
        VendorEnablement::Disable => None,
      },
      cached: Default::default(),
    });
    workspace.resolve_member_dir(&opts.root_dir)
  }

  pub fn discover<TSys: FsMetadata + FsRead + FsReadDir>(
    sys: &TSys,

Review comment (suggestion):
```suggestion
  dir_url: UrlRc,
```

There's a dir_url() function.

Code after:
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum TsTypeLib {
  DenoWindow,
  DenoWorker,
}

impl Default for TsTypeLib {
  fn default() -> Self {
    Self::DenoWindow
  }
}

#[derive(Debug, Clone)]
pub struct CompilerOptionsSource {
  pub specifier: UrlRc,
  pub compiler_options: Option<CompilerOptions>,
}

#[derive(Debug, Clone, Default)]
struct CachedDirectoryValues {
  permissions: OnceLock<PermissionsConfig>,
  bench: OnceLock<BenchConfig>,
  compile: OnceLock<CompileConfig>,
  test: OnceLock<TestConfig>,
}

#[derive(Debug, Clone)]
pub struct WorkspaceDirectory {
  pub workspace: WorkspaceRc,
  /// The directory that this context is for. This is generally the cwd.
  dir_url: UrlRc,
  pkg_json: Option<WorkspaceDirConfig<PackageJson>>,
  deno_json: Option<WorkspaceDirConfig<ConfigFile>>,
  cached: CachedDirectoryValues,
}

impl WorkspaceDirectory {
  pub fn empty(opts: WorkspaceDirectoryEmptyOptions) -> WorkspaceDirectoryRc {
    let workspace = new_rc(Workspace {
      config_folders: IndexMap::from([(
        opts.root_dir.clone(),
        FolderConfigs::default(),
      )]),
      root_dir_url: opts.root_dir.clone(),
      links: BTreeMap::new(),
      vendor_dir: match opts.use_vendor_dir {
        VendorEnablement::Enable { cwd } => Some(cwd.join("vendor")),
        VendorEnablement::Disable => None,
      },
      cached: Default::default(),
    });
Repository: denoland/deno
File: libs/resolver/workspace.rs (Rust)

Code before:
  PackageJsonImport {
    pkg_json: &'a PackageJsonRc,
  },
}

#[derive(Debug, Clone, Error, JsError)]
#[class(type)]
pub enum WorkspaceResolveError {
  #[error("Failed joining '{}' to '{}'. {:#}", .sub_path, .base, .error)]
  InvalidExportPath {
    base: Url,
    sub_path: String,
    error: url::ParseError,
  },
  #[error("Unknown export '{}' for '{}'.\n  Package exports:\n{}", export_name, package_name, .exports.iter().map(|e| format!(" * {}", e)).collect::<Vec<_>>().join("\n"))]
  UnknownExport {
    package_name: String,
    export_name: String,
    exports: Vec<String>,
  },
}

#[derive(Debug, Error, JsError)]
#[class(type)]
#[error(
  "Import \"{}\" via 'compilerOptions.paths[{:?}]' did not match an existing file", prior_resolution.as_ref().map(|s| s.as_str()).unwrap_or(specifier.as_str()), matched_key
)]
pub struct NotFoundInCompilerOptionsPathsError {
  specifier: String,
  referrer: Url,
  matched_key: String,
  prior_resolution: Option<Url>,
}

#[derive(Debug, Error, JsError)]
pub enum MappedResolutionError {
  #[class(inherit)]
  #[error(transparent)]
  Specifier(#[from] SpecifierError),
  #[class(inherit)]
  #[error(transparent)]
  ImportMap(#[from] ImportMapError),
  #[class(inherit)]
  #[error(transparent)]
  Workspace(#[from] WorkspaceResolveError),
  #[class(inherit)]
  #[error(transparent)]
  NotFoundInCompilerOptionsPaths(
    #[from] Box<NotFoundInCompilerOptionsPathsError>,
  ),
}

Review comment (bug):
Nitpick: Can you change this to not use `:?` and instead add explicit quotes? It's a bit more explicit and then won't ever do a debug format if the value ever changes to something other than a string.

Code after:
  PackageJsonImport {
    pkg_json: &'a PackageJsonRc,
  },
}

#[derive(Debug, Clone, Error, JsError)]
#[class(type)]
pub enum WorkspaceResolveError {
  #[error("Failed joining '{}' to '{}'. {:#}", .sub_path, .base, .error)]
  InvalidExportPath {
    base: Url,
    sub_path: String,
    error: url::ParseError,
  },
  #[error("Unknown export '{}' for '{}'.\n  Package exports:\n{}", export_name, package_name, .exports.iter().map(|e| format!(" * {}", e)).collect::<Vec<_>>().join("\n"))]
  UnknownExport {
    package_name: String,
    export_name: String,
    exports: Vec<String>,
  },
}

#[derive(Debug, Error, JsError)]
#[class(type)]
#[error(
  "Import \"{}\" via 'compilerOptions.paths[\"{}\"]' did not match an existing file", prior_resolution.as_ref().map(|s| s.as_str()).unwrap_or(specifier.as_str()), matched_key
)]
pub struct NotFoundInCompilerOptionsPathsError {
  specifier: String,
  referrer: Url,
  matched_key: String,
  prior_resolution: Option<Url>,
}

#[derive(Debug, Error, JsError)]
pub enum MappedResolutionError {
  #[class(inherit)]
  #[error(transparent)]
  Specifier(#[from] SpecifierError),
  #[class(inherit)]
  #[error(transparent)]
  ImportMap(#[from] ImportMapError),
  #[class(inherit)]
  #[error(transparent)]
  Workspace(#[from] WorkspaceResolveError),
  #[class(inherit)]
  #[error(transparent)]
  NotFoundInCompilerOptionsPaths(
    #[from] Box<NotFoundInCompilerOptionsPathsError>,
  ),
}
Repository: denoland/deno
File: libs/resolver/workspace.rs (Rust)

Code before:
  PackageJsonImport {
    pkg_json: &'a PackageJsonRc,
  },
}

#[derive(Debug, Clone, Error, JsError)]
#[class(type)]
pub enum WorkspaceResolveError {
  #[error("Failed joining '{}' to '{}'. {:#}", .sub_path, .base, .error)]
  InvalidExportPath {
    base: Url,
    sub_path: String,
    error: url::ParseError,
  },
  #[error("Unknown export '{}' for '{}'.\n  Package exports:\n{}", export_name, package_name, .exports.iter().map(|e| format!(" * {}", e)).collect::<Vec<_>>().join("\n"))]
  UnknownExport {
    package_name: String,
    export_name: String,
    exports: Vec<String>,
  },
}

#[derive(Debug, Error, JsError)]
#[class(type)]
#[error(
  "Import \"{}\" via 'compilerOptions.paths["{}"]' did not match an existing file", prior_resolution.as_ref().map(|s| s.as_str()).unwrap_or(specifier.as_str()), matched_key
)]
pub struct NotFoundInCompilerOptionsPathsError {
  specifier: String,
  referrer: Url,
  matched_key: String,
  prior_resolution: Option<Url>,
}

#[derive(Debug, Error, JsError)]
pub enum MappedResolutionError {
  #[class(inherit)]
  #[error(transparent)]
  Specifier(#[from] SpecifierError),
  #[class(inherit)]
  #[error(transparent)]
  ImportMap(#[from] ImportMapError),
  #[class(inherit)]
  #[error(transparent)]
  Workspace(#[from] WorkspaceResolveError),
  #[class(inherit)]
  #[error(transparent)]
  NotFoundInCompilerOptionsPaths(
    #[from] Box<NotFoundInCompilerOptionsPathsError>,
  ),
}

Review comment (suggestion):
```suggestion
  "Import \"{}\" via 'compilerOptions.paths[\"{}\"]' did not match an existing file", prior_resolution.as_ref().map(|s| s.as_str()).unwrap_or(specifier.as_str()), matched_key
```

Code after:
  PackageJsonImport {
    pkg_json: &'a PackageJsonRc,
  },
}

#[derive(Debug, Clone, Error, JsError)]
#[class(type)]
pub enum WorkspaceResolveError {
  #[error("Failed joining '{}' to '{}'. {:#}", .sub_path, .base, .error)]
  InvalidExportPath {
    base: Url,
    sub_path: String,
    error: url::ParseError,
  },
  #[error("Unknown export '{}' for '{}'.\n  Package exports:\n{}", export_name, package_name, .exports.iter().map(|e| format!(" * {}", e)).collect::<Vec<_>>().join("\n"))]
  UnknownExport {
    package_name: String,
    export_name: String,
    exports: Vec<String>,
  },
}

#[derive(Debug, Error, JsError)]
#[class(type)]
#[error(
  "Import \"{}\" via 'compilerOptions.paths[\"{}\"]' did not match an existing file", prior_resolution.as_ref().map(|s| s.as_str()).unwrap_or(specifier.as_str()), matched_key
)]
pub struct NotFoundInCompilerOptionsPathsError {
  specifier: String,
  referrer: Url,
  matched_key: String,
  prior_resolution: Option<Url>,
}

#[derive(Debug, Error, JsError)]
pub enum MappedResolutionError {
  #[class(inherit)]
  #[error(transparent)]
  Specifier(#[from] SpecifierError),
  #[class(inherit)]
  #[error(transparent)]
  ImportMap(#[from] ImportMapError),
  #[class(inherit)]
  #[error(transparent)]
  Workspace(#[from] WorkspaceResolveError),
  #[class(inherit)]
  #[error(transparent)]
  NotFoundInCompilerOptionsPaths(
    #[from] Box<NotFoundInCompilerOptionsPathsError>,
  ),
}
Repository: denoland/deno
File: runtime/permissions/broker.rs (Rust)

Code before:
static PERMISSION_BROKER: OnceLock<PermissionBroker> = OnceLock::new();

pub fn set_broker(broker: PermissionBroker) {
  assert!(PERMISSION_BROKER.set(broker).is_ok());
}

pub fn has_broker() -> bool {
  PERMISSION_BROKER.get().is_some()
}

#[derive(serde::Serialize)]
struct PermissionBrokerRequest<'a> {
  v: u32,
  id: u32,
  datetime: String,
  permission: &'a str,
  value: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
struct PermissionBrokerResponse {
  id: u32,
  result: String,
}

pub struct PermissionBroker {
  stream: Mutex<IpcPipe>,
  next_id: AtomicU32,
}

impl PermissionBroker {
  pub fn new(socket_path: impl Into<PathBuf>) -> Self {
    let socket_path = socket_path.into();
    let stream = match IpcPipe::connect(&socket_path) {
      Ok(s) => s,
      Err(err) => {
        log::error!("Failed to create permission broker: {:?}", err);
        std::process::exit(BROKER_EXIT_CODE);
      }
    };
    Self {
      stream: Mutex::new(stream),
      next_id: std::sync::atomic::AtomicU32::new(1),
    }
  }

  fn check(
    &self,
    permission: &str,
    stringified_value: Option<String>,
  ) -> std::io::Result<BrokerResponse> {

Review comment (security):
Is this name ok?

Example:

```json
{
  "id": 1,
  "result": "deny",
  "reason": "Make sure to enable env var permissions in your user settings."
}
```

Code after:
static PERMISSION_BROKER: OnceLock<PermissionBroker> = OnceLock::new();

pub fn set_broker(broker: PermissionBroker) {
  assert!(PERMISSION_BROKER.set(broker).is_ok());
}

pub fn has_broker() -> bool {
  PERMISSION_BROKER.get().is_some()
}

#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct PermissionBrokerRequest<'a> {
  v: u32,
  id: u32,
  datetime: String,
  permission: &'a str,
  value: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct PermissionBrokerResponse {
  id: u32,
  result: String,
  reason: Option<String>,
}

pub struct PermissionBroker {
  stream: Mutex<IpcPipe>,
  next_id: AtomicU32,
}

impl PermissionBroker {
  pub fn new(socket_path: impl Into<PathBuf>) -> Self {
    let socket_path = socket_path.into();
    let stream = match IpcPipe::connect(&socket_path) {
      Ok(s) => s,
      Err(err) => {
        log::error!("Failed to create permission broker: {:?}", err);
        std::process::exit(BROKER_EXIT_CODE);
      }
    };
    Self {
      stream: Mutex::new(stream),
      next_id: std::sync::atomic::AtomicU32::new(1),
    }
  }

  fn check(
    &self,
Repository: denoland/deno
File: cli/args/mod.rs (Rust)

Code before:

  pub fn otel_config(&self) -> OtelConfig {
    self.flags.otel_config()
  }

  pub fn no_legacy_abort(&self) -> bool {
    self.flags.no_legacy_abort()
  }

  pub fn env_file_name(&self) -> Option<&Vec<String>> {
    self.flags.env_file.as_ref()
  }

  /// Returns preload/import modules and require modules
  pub fn all_preload_modules(&self) -> Result<Vec<ModuleSpecifier>, AnyError> {
    if self.flags.preload.is_empty() && self.flags.require.is_empty() {
      return Ok(vec![]);
    }

    let mut modules = IndexSet::new();
    for preload_specifier in self.flags.preload.iter() {
      modules
        .insert(resolve_url_or_path(preload_specifier, self.initial_cwd())?);
    }

    for require_specifier in self.flags.require.iter() {
      modules
        .insert(resolve_url_or_path(require_specifier, self.initial_cwd())?);
    }

    Ok(modules.into_iter().collect())
  }

  pub fn preload_modules(&self) -> Result<Vec<ModuleSpecifier>, AnyError> {
    if self.flags.preload.is_empty() {
      return Ok(vec![]);
    }

    let mut modules = Vec::with_capacity(self.flags.preload.len());
    for preload_specifier in self.flags.preload.iter() {
      modules.push(resolve_url_or_path(preload_specifier, self.initial_cwd())?);
    }

    Ok(modules)
  }

  pub fn require_modules(&self) -> Result<Vec<ModuleSpecifier>, AnyError> {
    if self.flags.require.is_empty() {
      return Ok(vec![]);
    }


Review comment (suggestion):
Can you please explain this one? Why are you storing both `--preload` and `--require` modules in the same set? preload are ESM while require are CJS

Code after:
  pub fn otel_config(&self) -> OtelConfig {
    self.flags.otel_config()
  }

  pub fn no_legacy_abort(&self) -> bool {
    self.flags.no_legacy_abort()
  }

  pub fn env_file_name(&self) -> Option<&Vec<String>> {
    self.flags.env_file.as_ref()
  }

  pub fn preload_modules(&self) -> Result<Vec<ModuleSpecifier>, AnyError> {
    if self.flags.preload.is_empty() {
      return Ok(vec![]);
    }

    let mut modules = Vec::with_capacity(self.flags.preload.len());
    for preload_specifier in self.flags.preload.iter() {
      modules.push(resolve_url_or_path(preload_specifier, self.initial_cwd())?);
    }

    Ok(modules)
  }

  pub fn require_modules(&self) -> Result<Vec<ModuleSpecifier>, AnyError> {
    if self.flags.require.is_empty() {
      return Ok(vec![]);
    }

    let mut require = Vec::with_capacity(self.flags.require.len());
    for require_specifier in self.flags.require.iter() {
      require.push(resolve_url_or_path(require_specifier, self.initial_cwd())?);
    }

    Ok(require)
  }

  fn resolve_main_module_with_resolver_if_bare(
    &self,
    raw_specifier: &str,
    resolver: Option<&WorkspaceMainModuleResolver>,
    default_resolve: impl Fn() -> Result<ModuleSpecifier, AnyError>,
  ) -> Result<ModuleSpecifier, AnyError> {
    match resolver {
      Some(resolver)
        if !raw_specifier.starts_with('.')
          && !Path::new(raw_specifier).is_absolute() =>
      {
        let cwd = deno_path_util::url_from_directory_path(self.initial_cwd())?;
        resolver
Repository: denoland/deno
File: cli/tools/fmt.rs (Rust)

Code before:
  dprint_plugin_typescript::format_parsed_source(
    parsed_source,
    &get_resolved_typescript_config(fmt_options),
    Some(&create_external_formatter_for_typescript(unstable_options)),
  )
}

#[async_trait]
trait Formatter {
  async fn handle_files(
    &self,
    paths: Vec<PathBuf>,
    fmt_options: FmtOptionsConfig,
    unstable_options: UnstableFmtOptions,
    incremental_cache: Arc<IncrementalCache>,
    ext: Option<String>,
  ) -> Result<(), AnyError>;

  fn finish(&self) -> Result<(), AnyError>;
}

struct CheckFormatter {
  not_formatted_files_count: Arc<AtomicUsize>,
  checked_files_count: Arc<AtomicUsize>,
  fail_fast: bool,
  found_error: Arc<std::sync::atomic::AtomicBool>,
}

impl CheckFormatter {
  fn new(fail_fast: bool) -> Self {
    Self {
      not_formatted_files_count: Arc::new(AtomicUsize::new(0)),
      checked_files_count: Arc::new(AtomicUsize::new(0)),
      fail_fast,
      found_error: Arc::new(std::sync::atomic::AtomicBool::new(false)),
    }
  }
}

#[async_trait]
impl Formatter for CheckFormatter {
  async fn handle_files(
    &self,
    paths: Vec<PathBuf>,
    fmt_options: FmtOptionsConfig,
    unstable_options: UnstableFmtOptions,
    incremental_cache: Arc<IncrementalCache>,
    ext: Option<String>,
  ) -> Result<(), AnyError> {
    // prevent threads outputting at the same time
    let output_lock = Arc::new(Mutex::new(0));

Review comment (bug):
It seems this `found_error` is only relevant when `fail_fast` is `true`, so maybe do...

```rs
fail_fast_found_error: Option<Arc<std::sync::atomic::AtomicBool>>,
```

...to communicate that and to only do the work of setting it when `fail_fast` is true.

Code after:
) -> Result<Option<String>, AnyError> {
  dprint_plugin_typescript::format_parsed_source(
    parsed_source,
    &get_resolved_typescript_config(fmt_options),
    Some(&create_external_formatter_for_typescript(unstable_options)),
  )
}

#[async_trait]
trait Formatter {
  async fn handle_files(
    &self,
    paths: Vec<PathBuf>,
    fmt_options: FmtOptionsConfig,
    unstable_options: UnstableFmtOptions,
    incremental_cache: Arc<IncrementalCache>,
    ext: Option<String>,
  ) -> Result<(), AnyError>;

  fn finish(&self) -> Result<(), AnyError>;
}

struct CheckFormatter {
  not_formatted_files_count: Arc<AtomicUsize>,
  checked_files_count: Arc<AtomicUsize>,
  fail_fast_found_error: Option<Arc<std::sync::atomic::AtomicBool>>,
}

impl CheckFormatter {
  fn new(fail_fast: bool) -> Self {
    Self {
      not_formatted_files_count: Arc::new(AtomicUsize::new(0)),
      checked_files_count: Arc::new(AtomicUsize::new(0)),
      fail_fast_found_error: if fail_fast {
        Some(Arc::new(std::sync::atomic::AtomicBool::new(false)))
      } else {
        None
      },
    }
  }
}

#[async_trait]
impl Formatter for CheckFormatter {
  async fn handle_files(
    &self,
    paths: Vec<PathBuf>,
    fmt_options: FmtOptionsConfig,
    unstable_options: UnstableFmtOptions,
    incremental_cache: Arc<IncrementalCache>,
    ext: Option<String>,