dprint 0.59.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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::hash::Hasher;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use anyhow::Result;
use anyhow::bail;
use dprint_core::async_runtime::FutureExt;
use dprint_core::async_runtime::LocalBoxFuture;
use dprint_core::configuration::ConfigKeyMap;
use dprint_core::plugins::CancellationToken;
use dprint_core::plugins::CheckConfigUpdatesMessage;
use dprint_core::plugins::ConfigChange;
use dprint_core::plugins::CriticalFormatError;
use dprint_core::plugins::FileMatchingInfo;
use dprint_core::plugins::FormatConfigId;
use dprint_core::plugins::FormatError;
use dprint_core::plugins::FormatRange;
use dprint_core::plugins::FormatResult;
use dprint_core::plugins::HostFormatRequest;
use dprint_core::plugins::PluginInfo;
use dprint_core::plugins::process::HostFormatCallback;
use indexmap::IndexMap;
use thiserror::Error;

use crate::arg_parser::CliArgs;
use crate::arg_parser::ConfigDiscovery;
use crate::arg_parser::FilePatternArgs;
use crate::configuration::GlobalConfigDiagnostic;
use crate::configuration::RawPluginConfigOverride;
use crate::configuration::ResolveConfigError;
use crate::configuration::ResolvedConfig;
use crate::configuration::ResolvedConfigPathWithText;
use crate::configuration::get_default_config_file_in_ancestor_directories;
use crate::configuration::get_global_config;
use crate::configuration::get_plugin_config_map;
use crate::configuration::inherit_config;
use crate::configuration::resolve_config_from_args;
use crate::configuration::resolve_config_from_path_with_bytes;
use crate::configuration::resolve_global_config_path_and_text;
use crate::environment::CanonicalizedPathBuf;
use crate::environment::Environment;
use crate::format::EnsureStableFormat;
use crate::format::stabilize_format_text;
use crate::paths::FilesPathsByPlugins;
use crate::paths::IncludeScope;
use crate::paths::NoFilesFoundError;
use crate::paths::get_and_resolve_file_paths;
use crate::paths::get_file_paths_by_plugins;
use crate::paths::get_plugin_names_for_file_on_disk;
use crate::patterns::FileMatcher;
use crate::patterns::FileMatcherOptions;
use crate::patterns::OrderedPatternsMatcher;
use crate::plugins::FormatConfig;
use crate::plugins::InitializedPlugin;
use crate::plugins::InitializedPluginFormatRequest;
use crate::plugins::OutputPluginConfigDiagnosticsError;
use crate::plugins::PluginNameResolutionMaps;
use crate::plugins::PluginResolver;
use crate::plugins::PluginWrapper;
use crate::plugins::output_plugin_config_diagnostics;
use crate::utils::FastInsecureHasher;
use crate::utils::GlobOutput;
use crate::utils::OutsideBasePath;
use crate::utils::PathSource;
use crate::utils::escape_glob_text_for_cli;
use crate::utils::is_negated_glob;

pub enum GetPluginResult {
  /// The text of each of the plugin's configuration diagnostics in the form
  /// it was logged.
  HadDiagnostics(Vec<String>),
  Success(InitializedPluginWithConfig),
}

/// The error for formatting with a plugin that has configuration diagnostics.
///
/// The diagnostics are only logged the first time the plugin is used, so this
/// has their text for a consumer that reports each failure (ex. the lsp).
#[derive(Debug, Error)]
#[error("Had {} configuration errors.", .diagnostics.len())]
pub struct PluginConfigDiagnosticsError {
  pub diagnostics: Vec<String>,
}

pub struct PluginConfigOverride {
  files: Vec<String>,
  properties: ConfigKeyMap,
  config_id: FormatConfigId,
  matcher: OrderedPatternsMatcher,
}

pub struct PluginWithConfig {
  pub plugin: Rc<PluginWrapper>,
  pub associations: Option<Vec<String>>,
  pub overrides: Vec<PluginConfigOverride>,
  pub format_config: Arc<FormatConfig>,
  pub file_matching: FileMatchingInfo,
  /// The plugin's resolved configuration serialized as JSON. This is used by
  /// the incremental hash so that values the plugin derives at resolution time
  /// (ex. the exec plugin's `cacheKeyFiles` hash) invalidate the cache.
  serialized_resolved_config: String,
  /// The configuration diagnostics once checked, which is empty for none.
  config_diagnostics: tokio::sync::Mutex<Option<Vec<String>>>,
}

pub struct PluginWithConfigOptions {
  pub associations: Option<Vec<String>>,
  pub format_config: Arc<FormatConfig>,
  pub file_matching: FileMatchingInfo,
  pub overrides: Vec<PluginConfigOverride>,
  /// The plugin's resolved configuration serialized as JSON.
  pub serialized_resolved_config: String,
}

impl PluginWithConfig {
  pub fn new(plugin: Rc<PluginWrapper>, options: PluginWithConfigOptions) -> Self {
    Self {
      plugin,
      associations: options.associations,
      overrides: options.overrides,
      format_config: options.format_config,
      config_diagnostics: Default::default(),
      file_matching: options.file_matching,
      serialized_resolved_config: options.serialized_resolved_config,
    }
  }

  /// Gets a hash that represents the current state of the plugin.
  /// This is used for the "incremental" feature to tell if a plugin has changed state.
  pub fn incremental_hash(&self, hasher: &mut impl Hasher) {
    use std::hash::Hash;
    // list everything in here that would affect formatting
    hasher.write(self.info().name.as_bytes());
    hasher.write(self.info().version.as_bytes());

    // serialize the config keys in order to prevent the hash from changing
    let sorted_config = self.format_config.plugin.iter().collect::<BTreeMap<_, _>>();
    for (key, value) in sorted_config {
      hasher.write(key.as_bytes());
      value.hash(hasher);
    }

    // include the plugin's resolved config so that anything it derives at
    // resolution time but isn't present in the raw config map (ex. the exec
    // plugin folding `cacheKeyFiles` contents into its `cacheKey`) busts the cache
    hasher.write(self.serialized_resolved_config.as_bytes());

    if let Some(associations) = &self.associations {
      associations.len().hash(hasher);
      for association in associations {
        association.hash(hasher);
      }
    }
    self.overrides.len().hash(hasher);
    for override_config in &self.overrides {
      override_config.files.len().hash(hasher);
      for file in &override_config.files {
        file.hash(hasher);
      }
      let sorted_config = override_config.properties.iter().collect::<BTreeMap<_, _>>();
      sorted_config.len().hash(hasher);
      for (key, value) in sorted_config {
        key.hash(hasher);
        value.hash(hasher);
      }
    }
    self.format_config.global.hash(hasher);
  }

  pub fn get_config_file_overrides_for_path(&self, file_path: &Path) -> ConfigKeyMap {
    let mut result = ConfigKeyMap::new();
    for override_config in &self.overrides {
      if override_config.matcher.matches(file_path) {
        for (key, value) in override_config.properties.iter() {
          result.insert(key.clone(), value.clone());
        }
      }
    }
    result
  }

  pub fn get_merged_overrides_for_path(&self, file_path: &Path, request_override_config: &ConfigKeyMap) -> ConfigKeyMap {
    let mut result = self.get_config_file_overrides_for_path(file_path);
    for (key, value) in request_override_config.iter() {
      result.insert(key.clone(), value.clone());
    }
    result
  }

  pub fn name(&self) -> &str {
    &self.info().name
  }

  pub fn info(&self) -> &PluginInfo {
    self.plugin.info()
  }

  pub async fn initialize(self: &Rc<Self>) -> Result<InitializedPluginWithConfig> {
    let instance = self.plugin.initialize().await?;
    Ok(InitializedPluginWithConfig {
      instance,
      plugin: self.clone(),
    })
  }

  pub async fn get_or_create_checking_config_diagnostics<TEnvironment: Environment>(self: &Rc<Self>, environment: &TEnvironment) -> Result<GetPluginResult> {
    // only allow one thread to initialize and output the diagnostics (we don't want the messages being spammed)
    let instance = self.initialize().await?;
    let mut config_diagnostics = self.config_diagnostics.lock().await;
    match &*config_diagnostics {
      Some(diagnostics) => {
        if !diagnostics.is_empty() {
          return Ok(GetPluginResult::HadDiagnostics(diagnostics.clone()));
        }
        Ok(GetPluginResult::Success(instance))
      }
      None => {
        let result = instance.output_config_diagnostics(environment).await?;
        if let Err(err) = result {
          log_error!(environment, &err.to_string());
          *config_diagnostics = Some(err.diagnostics.clone());
          Ok(GetPluginResult::HadDiagnostics(err.diagnostics))
        } else {
          let result = instance.output_override_config_diagnostics(environment).await?;
          if let Err(err) = result {
            log_error!(environment, &err.to_string());
            *config_diagnostics = Some(err.diagnostics.clone());
            Ok(GetPluginResult::HadDiagnostics(err.diagnostics))
          } else {
            *config_diagnostics = Some(Vec::new());
            Ok(GetPluginResult::Success(instance))
          }
        }
      }
    }
  }
}

pub struct InitializedPluginWithConfigFormatRequest {
  pub file_path: PathBuf,
  pub file_bytes: Vec<u8>,
  pub range: FormatRange,
  pub override_config: ConfigKeyMap,
  pub on_host_format: HostFormatCallback,
  pub token: Arc<dyn CancellationToken>,
}

#[derive(Clone)]
pub struct InitializedPluginWithConfig {
  plugin: Rc<PluginWithConfig>,
  instance: Rc<dyn InitializedPlugin>,
}

impl InitializedPluginWithConfig {
  pub fn info(&self) -> &PluginInfo {
    self.plugin.info()
  }

  pub async fn resolved_config(&self) -> Result<String> {
    self.instance.resolved_config(self.plugin.format_config.clone()).await
  }

  pub async fn file_matching_info(&self) -> Result<FileMatchingInfo> {
    self.instance.file_matching_info(self.plugin.format_config.clone()).await
  }

  pub async fn license_text(&self) -> Result<String> {
    self.instance.license_text().await
  }

  pub async fn output_config_diagnostics<TEnvironment: Environment>(
    &self,
    environment: &TEnvironment,
  ) -> Result<Result<(), OutputPluginConfigDiagnosticsError>> {
    output_plugin_config_diagnostics(&self.info().name, &*self.instance, self.plugin.format_config.clone(), environment).await
  }

  pub async fn output_override_config_diagnostics<TEnvironment: Environment>(
    &self,
    environment: &TEnvironment,
  ) -> Result<Result<(), OutputPluginConfigDiagnosticsError>> {
    let mut diagnostics = Vec::new();
    for override_config in &self.plugin.overrides {
      let mut plugin_config = self.plugin.format_config.plugin.clone();
      for (key, value) in override_config.properties.iter() {
        plugin_config.insert(key.clone(), value.clone());
      }
      let format_config = Arc::new(FormatConfig {
        id: override_config.config_id,
        plugin: plugin_config,
        global: self.plugin.format_config.global.clone(),
      });
      for diagnostic in self.instance.config_diagnostics(format_config).await? {
        let message = format!("[{}]: {}", self.info().name, diagnostic);
        log_warn!(environment, "{}", message);
        diagnostics.push(message);
      }
    }

    if !diagnostics.is_empty() {
      Ok(Err(OutputPluginConfigDiagnosticsError {
        plugin_name: self.info().name.to_string(),
        diagnostic_count: diagnostics.len(),
        diagnostics,
      }))
    } else {
      Ok(Ok(()))
    }
  }

  pub async fn check_config_updates(&self, message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>> {
    self.instance.check_config_updates(message).await
  }

  pub async fn format_text(&self, request: InitializedPluginWithConfigFormatRequest) -> FormatResult {
    self
      .instance
      .format_text(InitializedPluginFormatRequest {
        file_path: request.file_path,
        file_text: request.file_bytes,
        range: request.range,
        config: self.plugin.format_config.clone(),
        override_config: request.override_config,
        on_host_format: request.on_host_format,
        token: request.token,
      })
      .await
  }
}

pub struct PluginsScope<TEnvironment: Environment> {
  environment: TEnvironment,
  pub config: Option<Rc<ResolvedConfig>>,
  pub plugins: IndexMap<String, Rc<PluginWithConfig>>,
  pub plugin_name_maps: PluginNameResolutionMaps,
  global_config_diagnostics: Vec<GlobalConfigDiagnostic>,
  cached_editor_file_matcher: RefCell<Option<FileMatcher<TEnvironment>>>,
}

impl<TEnvironment: Environment> PluginsScope<TEnvironment> {
  pub fn new(
    environment: TEnvironment,
    plugins: Vec<Rc<PluginWithConfig>>,
    config: Rc<ResolvedConfig>,
    global_config_diagnostics: Vec<GlobalConfigDiagnostic>,
  ) -> Result<Self> {
    let plugin_name_maps = PluginNameResolutionMaps::from_plugins(plugins.iter().map(|p| p.as_ref()), &config.base_path, config.shebangs.as_ref())?;

    Ok(PluginsScope {
      environment,
      config: Some(config),
      plugin_name_maps,
      plugins: plugins.into_iter().map(|p| (p.name().to_string(), p)).collect(),
      global_config_diagnostics,
      cached_editor_file_matcher: Default::default(),
    })
  }

  pub fn ensure_valid_for_cli_args(&self, cli_args: &CliArgs) -> Result<()> {
    self.ensure_no_global_config_diagnostics()?;
    self.ensure_plugins_found()?;
    // Skip checking these diagnostics when the user provides
    // plugins from the CLI args. They may be doing this to filter
    // to only specific plugins.
    if cli_args.plugins.is_empty() {
      self.ensure_no_unknown_config_property_diagnostics()?;
    }
    Ok(())
  }

  pub fn ensure_plugins_found(&self) -> Result<(), NoPluginsFoundError> {
    if self.plugins.is_empty() { Err(NoPluginsFoundError) } else { Ok(()) }
  }

  pub fn ensure_no_global_config_diagnostics(&self) -> Result<(), ResolveConfigError> {
    if self.global_config_diagnostics.is_empty() {
      return Ok(());
    }
    let diagnostics = self
      .global_config_diagnostics
      .iter()
      .filter_map(|d| match d {
        GlobalConfigDiagnostic::UnknownProperty(_) => None,
        GlobalConfigDiagnostic::Other(d) => Some(d.to_string()),
      })
      .collect::<Vec<_>>();
    self.error_for_diagnostics(&diagnostics)
  }

  pub fn ensure_no_unknown_config_property_diagnostics(&self) -> Result<(), ResolveConfigError> {
    if self.global_config_diagnostics.is_empty() {
      return Ok(());
    }
    let diagnostics = self
      .global_config_diagnostics
      .iter()
      .filter_map(|d| match d {
        GlobalConfigDiagnostic::UnknownProperty(d) => Some(d.to_string()),
        GlobalConfigDiagnostic::Other(_) => None,
      })
      .collect::<Vec<_>>();
    self.error_for_diagnostics(&diagnostics)
  }

  fn error_for_diagnostics(&self, diagnostics: &[String]) -> Result<(), ResolveConfigError> {
    if diagnostics.is_empty() {
      return Ok(());
    }
    let diagnostics_len = diagnostics.len();
    let mut output_text = String::new();
    for diagnostic in diagnostics {
      output_text.push_str("* ");
      output_text.push_str(diagnostic);
      output_text.push('\n');
    }
    output_text.push_str(&format!("\nHad {} config diagnostic(s)", diagnostics_len));
    if let Some(config) = &self.config {
      output_text.push_str(&format!(" in {}", config.source));
    }
    Err(ResolveConfigError::Other(anyhow::anyhow!("{}", output_text)))
  }

  pub fn process_plugin_count(&self) -> usize {
    self.plugins.values().filter(|p| p.plugin.is_process_plugin()).count()
  }

  pub fn get_plugin(&self, name: &str) -> Rc<PluginWithConfig> {
    self
      .plugins
      .get(name)
      .cloned()
      .unwrap_or_else(|| panic!("Expected to find plugin in collection: {}", name))
  }

  pub fn plugins_hash(&self) -> u64 {
    use std::hash::Hash;
    let mut hasher = FastInsecureHasher::default();
    for plugin in self.plugins.values() {
      plugin.incremental_hash(&mut hasher);
    }
    // the shebang mappings affect which plugin formats a file
    if let Some(shebangs) = self.config.as_ref().and_then(|c| c.shebangs.as_ref()) {
      shebangs.len().hash(&mut hasher);
      for (shebang, extension) in shebangs {
        shebang.hash(&mut hasher);
        extension.hash(&mut hasher);
      }
    }
    hasher.finish()
  }

  pub fn create_host_format_callback(self: &Rc<Self>) -> HostFormatCallback {
    let scope = self.clone();
    Rc::new(move |host_request| scope.format(host_request))
  }

  /// Whether the editor should ask this scope to format the file.
  ///
  /// `file_bytes_start` is the start of the editor's in-memory text when it has
  /// it (ex. the LSP), which is what an extensionless file's shebang needs to be
  /// resolved from so an unsaved shebang still matches. When it's `None` (ex. the
  /// editor service, which only receives a path) the file on disk is used.
  pub fn can_format_for_editor(&self, file_path: &Path, file_bytes_start: Option<&[u8]>) -> bool {
    if !self.matches_editor_file_patterns(file_path) {
      return false;
    }

    // Extensionless files match the includes patterns whenever any shebangs are
    // configured because their shebang isn't known up front, so ensure one
    // actually resolves to a plugin rather than claiming every extensionless file.
    if self.plugin_name_maps.may_match_shebang(file_path) {
      return match file_bytes_start {
        Some(file_bytes_start) => !self
          .plugin_name_maps
          .get_plugin_names_from_file_path_and_bytes(file_path, file_bytes_start)
          .is_empty(),
        None => !get_plugin_names_for_file_on_disk(&self.plugin_name_maps, file_path, &self.environment).is_empty(),
      };
    }

    true
  }

  fn matches_editor_file_patterns(&self, file_path: &Path) -> bool {
    let mut file_matcher_borrow = self.cached_editor_file_matcher.borrow_mut();
    if file_matcher_borrow.is_none() {
      let Some(config) = &self.config else {
        return false;
      };
      let matcher = match FileMatcher::new(
        self.environment.clone(),
        FileMatcherOptions {
          config,
          args: &FilePatternArgs::default(),
          root_dir: &config.base_path,
          specified_file_path: None,
          // this matcher lives as long as the scope, which in an editor is until
          // the dprint config changes, and gitignores change more often than that
          detect_gitignore_changes: true,
        },
      ) {
        Ok(matcher) => matcher,
        Err(err) => {
          log_warn!(self.environment, "Error creating file matcher: {}", err);
          return false;
        }
      };
      file_matcher_borrow.replace(matcher);
    }
    match file_matcher_borrow.as_mut() {
      Some(file_matcher) => file_matcher.matches_and_dir_not_ignored(file_path),
      None => false, // should never happen
    }
  }

  pub fn format(self: &Rc<Self>, request: HostFormatRequest) -> LocalBoxFuture<'static, FormatResult> {
    // owned because they outlive this scope by moving into the future below
    let plugin_names = self
      .plugin_name_maps
      .get_plugin_names_from_file_path_and_bytes(&request.file_path, &request.file_bytes)
      .into_iter()
      .map(ToOwned::to_owned)
      .collect::<Vec<String>>();
    log_debug!(
      self.environment,
      "Host formatting {} - File length: {} - Plugins: [{}] - Range: {:?}",
      request.file_path.display(),
      request.file_bytes.len(),
      plugin_names.join(", "),
      request.range,
    );
    let scope = self.clone();
    async move {
      let mut file_text = request.file_bytes;
      let mut had_change = false;
      for plugin_name in plugin_names {
        let plugin = scope.get_plugin(&plugin_name);
        match plugin.get_or_create_checking_config_diagnostics(&scope.environment).await {
          Ok(GetPluginResult::Success(initialized_plugin)) => {
            let result = initialized_plugin
              .format_text(InitializedPluginWithConfigFormatRequest {
                file_path: request.file_path.clone(),
                file_bytes: file_text.clone(),
                range: request.range.clone(),
                override_config: plugin.get_merged_overrides_for_path(&request.file_path, &request.override_config),
                on_host_format: scope.create_host_format_callback(),
                token: request.token.clone(),
              })
              .await;
            if let Some(new_text) = result? {
              file_text = new_text;
              had_change = true;
            }
          }
          Ok(GetPluginResult::HadDiagnostics(diagnostics)) => return Err(FormatError::new(PluginConfigDiagnosticsError { diagnostics })),
          Err(err) => return Err(CriticalFormatError(FormatError::new(err)).into()),
        }
      }

      Ok(if had_change { Some(file_text) } else { None })
    }
    .boxed_local()
  }

  /// Formats the text like `format`, then formats a changed result again until
  /// it's stable the same way `dprint fmt` does. This shouldn't be used for host
  /// formatting (ex. code blocks) because the outer text is already made stable.
  pub async fn format_stable(self: &Rc<Self>, request: HostFormatRequest, ensure_stable_format: EnsureStableFormat) -> FormatResult {
    // the range wouldn't apply to the formatted text, so only format a range once
    if !ensure_stable_format.0 || request.range.is_some() {
      return self.format(request).await;
    }
    let file_path = request.file_path.clone();
    let override_config = request.override_config.clone();
    let token = request.token.clone();
    let original_text = request.file_bytes.clone();
    let Some(formatted_text) = self.format(request).await? else {
      return Ok(None);
    };
    // a plugin may say it changed the text without changing it
    if formatted_text == original_text {
      return Ok(Some(formatted_text));
    }
    let stable_text = stabilize_format_text(&self.environment, &file_path, formatted_text, |text| {
      let scope = self.clone();
      let request = HostFormatRequest {
        file_path: file_path.clone(),
        file_bytes: text.clone(),
        range: None,
        override_config: override_config.clone(),
        token: token.clone(),
      };
      async move {
        // the result gets discarded, so stop by saying the text didn't change
        if request.token.is_cancelled() {
          return Ok(text);
        }
        match scope.format(request).await {
          Ok(new_text) => Ok(new_text.unwrap_or(text)),
          Err(err) => Err(anyhow::anyhow!(dprint_core::plugins::error_to_string(&err))),
        }
      }
    })
    .await
    .map_err(FormatError::new)?;
    Ok(Some(stable_text))
  }
}

pub struct PluginsScopeAndPathsCollection<TEnvironment: Environment> {
  environment: TEnvironment,
  inner: Vec<PluginsScopeAndPaths<TEnvironment>>,
}

impl<TEnvironment: Environment> PluginsScopeAndPathsCollection<TEnvironment> {
  pub fn ensure_valid_for_cli_args(&self, cli_args: &CliArgs) -> Result<()> {
    for scope in &self.inner {
      scope.scope.ensure_valid_for_cli_args(cli_args)?;
    }

    // ensure we found some files
    if !cli_args.sub_command.allow_no_files() {
      let cli_file_patterns = cli_args.sub_command.file_patterns().and_then(|p| p.include_patterns.as_ref());
      match cli_file_patterns {
        // the user explicitly specified no files to format (ex. `--stdin-files`
        // with no lines), so there's nothing to format and that's ok
        Some(patterns) if patterns.is_empty() => {}
        // when the user specifies a pattern on the command line, just ensure that one scope matched
        Some(_) => {
          let all_empty = self.iter().all(|s| s.file_paths_by_plugins.is_empty());
          if all_empty {
            return Err(
              NoFilesFoundError {
                base_path: self.environment.cwd(),
              }
              .into(),
            );
          }
        }
        // if no args specified then ensure all scopes have files
        None => {
          for scope in &self.inner {
            if let Some(config) = scope.scope.config.as_ref() {
              scope.file_paths_by_plugins.ensure_not_empty(&config.base_path)?;
            }
          }
        }
      }
    }

    Ok(())
  }

  pub fn len(&self) -> usize {
    self.inner.len()
  }

  pub fn iter(&self) -> impl Iterator<Item = &PluginsScopeAndPaths<TEnvironment>> {
    self.inner.iter()
  }

  pub fn into_iter(self) -> impl Iterator<Item = PluginsScopeAndPaths<TEnvironment>> {
    self.inner.into_iter()
  }
}

pub struct PluginsScopeAndPaths<TEnvironment: Environment> {
  pub scope: PluginsScope<TEnvironment>,
  pub file_paths_by_plugins: FilesPathsByPlugins,
}

pub struct ResolvePluginsScopeAndPathsOptions {
  pub skip_traversal: bool,
}

pub async fn resolve_plugins_scope_and_paths<TEnvironment: Environment>(
  args: &CliArgs,
  patterns: &FilePatternArgs,
  environment: &TEnvironment,
  plugin_resolver: &Rc<PluginResolver<TEnvironment>>,
  options: ResolvePluginsScopeAndPathsOptions,
) -> Result<PluginsScopeAndPathsCollection<TEnvironment>> {
  let resolver = PluginsAndPathsResolver {
    args,
    patterns,
    environment,
    plugin_resolver,
    skip_traversal: options.skip_traversal,
  };

  resolver.resolve_for_config().await
}

struct PluginsAndPathsResolver<'a, TEnvironment: Environment> {
  args: &'a CliArgs,
  patterns: &'a FilePatternArgs,
  environment: &'a TEnvironment,
  plugin_resolver: &'a Rc<PluginResolver<TEnvironment>>,
  skip_traversal: bool,
}

impl<'a, TEnvironment: Environment> PluginsAndPathsResolver<'a, TEnvironment> {
  pub async fn resolve_for_config(&'a self) -> Result<PluginsScopeAndPathsCollection<TEnvironment>> {
    let config = Rc::new(resolve_config_from_args(self.args, self.environment).await?);
    let scope = resolve_plugins_scope(config.clone(), self.environment, self.plugin_resolver).await?;
    let config_discovery = self.args.config_discovery(self.environment);
    let mut glob_output = if self.skip_traversal {
      GlobOutput::default()
    } else {
      get_and_resolve_file_paths(
        &config,
        self.patterns,
        config_discovery,
        IncludeScope::AllowAncestors,
        scope.plugins.values().map(|p| p.as_ref()),
        self.environment,
      )
      .await?
    };
    let root_config_path = config.source.maybe_local_path().cloned();

    // resolve specified paths that are outside the config's directory
    // against the config file found in their own directory tree or the
    // user's global config file
    let outside_scopes = self
      .resolve_outside_base_paths(&mut glob_output, &config, config_discovery, root_config_path.clone())
      .await?;

    let file_paths_by_plugins = get_file_paths_by_plugins(&scope.plugin_name_maps, glob_output.file_paths, glob_output.shebang_lines, self.environment)?;

    let mut result = vec![PluginsScopeAndPaths { scope, file_paths_by_plugins }];
    // todo: parallelize?
    let patterns = Rc::new(self.patterns.clone());
    for config_file_path in glob_output.config_files {
      result.extend(
        self
          .resolve_for_sub_config(config_file_path, config.clone(), config_discovery, root_config_path.clone(), patterns.clone())
          .await?,
      );
    }
    result.extend(outside_scopes);

    Ok(PluginsScopeAndPathsCollection {
      environment: self.environment.clone(),
      inner: result,
    })
  }

  /// Resolves the scopes for specified paths and patterns that are outside
  /// the config's directory. Each one uses the config file found in its own
  /// directory tree when one exists, otherwise the explicitly specified or
  /// global config file, and it's an error when there's no config file to use.
  async fn resolve_outside_base_paths(
    &'a self,
    glob_output: &mut GlobOutput,
    config: &Rc<ResolvedConfig>,
    config_discovery: ConfigDiscovery,
    root_config_path: Option<CanonicalizedPathBuf>,
  ) -> Result<Vec<PluginsScopeAndPaths<TEnvironment>>> {
    let outside_base_paths = std::mem::take(&mut glob_output.outside_base_paths);
    if outside_base_paths.is_empty() {
      return Ok(Vec::new());
    }

    // group the paths by the config that governs them
    let mut path_groups: IndexMap<OutsideScopeConfigKey, (OutsideScopeConfig, Vec<String>)> = IndexMap::new();
    for outside_path in outside_base_paths {
      let Some(scope_config) = self.resolve_outside_scope_config(&outside_path, config, config_discovery)? else {
        continue; // skipped with a warning
      };
      path_groups
        .entry(scope_config.group_key())
        .or_insert_with(|| (scope_config, Vec::new()))
        .1
        .push(outside_path.include_pattern);
    }

    let mut result = Vec::new();
    for (_, (scope_config, include_patterns)) in path_groups {
      result.extend(
        self
          .resolve_outside_scope(scope_config, include_patterns, config, config_discovery, root_config_path.clone())
          .await?,
      );
    }
    Ok(result)
  }

  /// Resolves the config that governs the provided outside path. Returns
  /// `None` when the path should be skipped (a warning was logged).
  fn resolve_outside_scope_config(
    &self,
    outside_path: &OutsideBasePath,
    config: &ResolvedConfig,
    config_discovery: ConfigDiscovery,
  ) -> Result<Option<OutsideScopeConfig>> {
    let discover_tree_configs = self.args.config.is_none() && config_discovery.traverse_ancestors();
    if discover_tree_configs && let Some(config_path) = get_default_config_file_in_ancestor_directories(self.environment, &outside_path.config_search_dir)? {
      return Ok(Some(OutsideScopeConfig::ConfigFile(config_path)));
    }

    if self.args.config.is_some() || config.is_global {
      // an explicitly specified config file or the global config file
      // governs explicitly specified paths anywhere
      let root_dir = self.canonical_path_root_dir(&outside_path.config_search_dir)?;
      return Ok(Some(OutsideScopeConfig::RebasedCurrentConfig(root_dir)));
    }

    // only fall back to the global config file when config discovery is in
    // its default mode to match main config file resolution
    if matches!(config_discovery, ConfigDiscovery::Default)
      && let Some(config_path) = self.global_config_path_based_at_path_root(&outside_path.config_search_dir)?
    {
      return Ok(Some(OutsideScopeConfig::ConfigFile(config_path)));
    }

    if self.args.sub_command.allow_skipping_paths() {
      log_warn!(
        self.environment,
        "WARNING: Skipping '{}' because no dprint config file was found for it.",
        outside_path.include_pattern,
      );
      Ok(None)
    } else {
      bail!(
        concat!(
          "No dprint config file found for '{}'. The path is outside the config file's directory ",
          "and no dprint config file was found in the path's ancestor directories. Create one there ",
          "or set up a global config file by running `dprint init --global`."
        ),
        outside_path.include_pattern,
      );
    }
  }

  /// Resolves the scope and file paths for a group of outside paths that
  /// share a governing config.
  async fn resolve_outside_scope(
    &'a self,
    scope_config: OutsideScopeConfig,
    mut include_patterns: Vec<String>,
    config: &Rc<ResolvedConfig>,
    config_discovery: ConfigDiscovery,
    root_config_path: Option<CanonicalizedPathBuf>,
  ) -> Result<Vec<PluginsScopeAndPaths<TEnvironment>>> {
    // carry the negated patterns along so exclusions specified on the
    // command line keep applying in the new scope, but only resolve the
    // grouped paths so files matched by the other args don't get formatted
    // a second time
    include_patterns.extend(self.patterns.include_patterns.iter().flatten().filter(|p| is_negated_glob(p)).cloned());
    // the current scope already handles everything in the config's
    // directory (ex. a `dprint fmt ..` arg covers it with `**`), escaping
    // in case the directory path contains glob characters (ex. `[app]`)
    include_patterns.push(format!("!{}/**", escape_glob_text_for_cli(&config.base_path.to_string_lossy())));
    let patterns = Rc::new(FilePatternArgs {
      include_patterns: Some(include_patterns),
      only_staged: false,
      only_dirty: false,
      ..self.patterns.clone()
    });
    match scope_config {
      OutsideScopeConfig::ConfigFile(config_path) => {
        self
          .resolve_for_config_path(
            config_path,
            config.clone(),
            /* is descendant config */ false,
            config_discovery,
            root_config_path,
            patterns,
          )
          .await
      }
      OutsideScopeConfig::RebasedCurrentConfig(base_path) => {
        // with an explicitly specified config file, don't let other config
        // files take over parts of the scope
        let config_discovery = if self.args.config.is_some() {
          ConfigDiscovery::IgnoreDescendants
        } else {
          config_discovery
        };
        self
          .resolve_for_rebased_config(config, base_path, config_discovery, root_config_path, patterns)
          .await
      }
    }
  }

  /// Resolves the scope and file paths for the provided config with its base
  /// directory changed to the provided path (ex. resolving paths on another
  /// drive against the in-use config file).
  async fn resolve_for_rebased_config(
    &'a self,
    config: &Rc<ResolvedConfig>,
    base_path: CanonicalizedPathBuf,
    config_discovery: ConfigDiscovery,
    root_config_path: Option<CanonicalizedPathBuf>,
    patterns: Rc<FilePatternArgs>,
  ) -> Result<Vec<PluginsScopeAndPaths<TEnvironment>>> {
    let mut rebased_config = (**config).clone();
    rebased_config.base_path = base_path;
    self
      .resolve_scope_and_descendants(Rc::new(rebased_config), config_discovery, root_config_path, patterns)
      .await
  }

  /// Gets the global config file based at the root directory of the provided
  /// path so the path is within the resulting config's directory.
  fn global_config_path_based_at_path_root(&self, path: &Path) -> Result<Option<ResolvedConfigPathWithText>> {
    let Some(global_config_path) = resolve_global_config_path_and_text(self.environment)? else {
      return Ok(None);
    };
    Ok(Some(ResolvedConfigPathWithText {
      base_path: self.canonical_path_root_dir(path)?,
      ..global_config_path
    }))
  }

  /// Gets the canonicalized root directory of the provided path (ex. the
  /// drive root on Windows).
  fn canonical_path_root_dir(&self, path: &Path) -> Result<CanonicalizedPathBuf> {
    let root_dir = path.ancestors().last().unwrap();
    Ok(self.environment.canonicalize(root_dir)?)
  }

  async fn resolve_for_sub_config(
    &'a self,
    config_file_path: PathBuf,
    parent_config: Rc<ResolvedConfig>,
    config_discovery: ConfigDiscovery,
    root_config_path: Option<CanonicalizedPathBuf>,
    patterns: Rc<FilePatternArgs>,
  ) -> Result<Vec<PluginsScopeAndPaths<TEnvironment>>> {
    log_debug!(self.environment, "Analyzing config file {}", config_file_path.display());
    let config_file_path = self.environment.canonicalize(&config_file_path)?;
    if Some(&config_file_path) == root_config_path.as_ref() {
      // config file specified via `--config` so ignore it
      return Ok(Vec::new());
    }
    let config_path = ResolvedConfigPathWithText {
      content: self.environment.read_file(&config_file_path)?,
      base_path: config_file_path.parent().unwrap(),
      source: PathSource::new_local(config_file_path),
      is_global_config: false,
      is_first_download: false,
    };
    self
      .resolve_for_config_path(
        config_path,
        parent_config,
        /* is descendant config */ true,
        config_discovery,
        root_config_path,
        patterns,
      )
      .await
  }

  /// Resolves the scope and file paths for a config file, recursively
  /// resolving any descendant config files found within its directory.
  fn resolve_for_config_path(
    &'a self,
    config_path: ResolvedConfigPathWithText,
    parent_config: Rc<ResolvedConfig>,
    is_descendant_config: bool,
    config_discovery: ConfigDiscovery,
    root_config_path: Option<CanonicalizedPathBuf>,
    patterns: Rc<FilePatternArgs>,
  ) -> LocalBoxFuture<'a, Result<Vec<PluginsScopeAndPaths<TEnvironment>>>> {
    async move {
      let mut config = resolve_config_from_path_with_bytes(&config_path, self.environment).await?;
      // when a nested config opts into inheriting, merge in the ancestor config
      if is_descendant_config && config.inherit == Some(true) {
        config = inherit_config(config, &parent_config)?;
      }
      if !self.args.plugins.is_empty() {
        config.plugins.clone_from(&parent_config.plugins);
      }
      self
        .resolve_scope_and_descendants(Rc::new(config), config_discovery, root_config_path, patterns)
        .await
    }
    .boxed_local()
  }

  /// Resolves the plugins scope and file paths for the provided config,
  /// recursively resolving any descendant config files found within its
  /// directory.
  async fn resolve_scope_and_descendants(
    &'a self,
    config: Rc<ResolvedConfig>,
    config_discovery: ConfigDiscovery,
    root_config_path: Option<CanonicalizedPathBuf>,
    patterns: Rc<FilePatternArgs>,
  ) -> Result<Vec<PluginsScopeAndPaths<TEnvironment>>> {
    let scope = resolve_plugins_scope(config.clone(), self.environment, self.plugin_resolver).await?;
    let mut glob_output = get_and_resolve_file_paths(
      &config,
      &patterns,
      config_discovery,
      IncludeScope::ConfigDir,
      scope.plugins.values().map(|p| p.as_ref()),
      self.environment,
    )
    .await?;
    // paths outside this config's directory were already handled when
    // resolving the root scope
    glob_output.outside_base_paths.clear();
    let file_paths_by_plugins = get_file_paths_by_plugins(&scope.plugin_name_maps, glob_output.file_paths, glob_output.shebang_lines, self.environment)?;

    let mut result = vec![PluginsScopeAndPaths { scope, file_paths_by_plugins }];
    // todo: parallelize?
    for config_file_path in glob_output.config_files {
      result.extend(
        self
          .resolve_for_sub_config(config_file_path, config.clone(), config_discovery, root_config_path.clone(), patterns.clone())
          .await?,
      );
    }
    Ok(result)
  }
}

/// The config governing paths that are outside the main config's directory.
enum OutsideScopeConfig {
  /// A config file found for the outside path (in its directory tree or
  /// the user's global config file).
  ConfigFile(ResolvedConfigPathWithText),
  /// The config file already in use (an explicitly specified `--config`
  /// or the global config file), rebased at the outside path's root
  /// directory so the path is within the scope and the config's
  /// unanchored patterns still apply.
  RebasedCurrentConfig(CanonicalizedPathBuf),
}

impl OutsideScopeConfig {
  fn group_key(&self) -> OutsideScopeConfigKey {
    match self {
      Self::ConfigFile(config_path) => OutsideScopeConfigKey::ConfigFile(config_path.base_path.clone()),
      Self::RebasedCurrentConfig(base_path) => OutsideScopeConfigKey::RebasedCurrentConfig(base_path.clone()),
    }
  }
}

/// Identifies the config governing a group of outside paths.
///
/// The base directory alone isn't enough because a config file could live in
/// the same directory the current config gets rebased at (ex. a config file at
/// a drive root), which would otherwise silently resolve some paths against the
/// wrong config. The way the config is resolved rules that out today, but
/// keying on the variant makes it impossible to get wrong.
#[derive(PartialEq, Eq, Hash)]
enum OutsideScopeConfigKey {
  ConfigFile(CanonicalizedPathBuf),
  RebasedCurrentConfig(CanonicalizedPathBuf),
}

pub async fn get_plugins_scope_from_args<TEnvironment: Environment>(
  args: &CliArgs,
  environment: &TEnvironment,
  plugin_resolver: &Rc<PluginResolver<TEnvironment>>,
) -> Result<PluginsScope<TEnvironment>, ResolvePluginsError> {
  match resolve_config_from_args(args, environment).await {
    Ok(config) => resolve_plugins_scope(Rc::new(config), environment, plugin_resolver).await,
    // ignore
    Err(_) => Ok(PluginsScope {
      environment: environment.clone(),
      config: None,
      plugin_name_maps: Default::default(),
      plugins: Default::default(),
      global_config_diagnostics: Default::default(),
      cached_editor_file_matcher: Default::default(),
    }),
  }
}

#[derive(Debug, Error)]
#[error("No formatting plugins found. Ensure at least one is specified in the 'plugins' array of the configuration file.")]
pub struct NoPluginsFoundError;

#[derive(Debug, Error)]
#[error(transparent)]
pub struct ResolvePluginsError(#[from] anyhow::Error);

pub async fn resolve_plugins_scope<TEnvironment: Environment>(
  config: Rc<ResolvedConfig>,
  environment: &TEnvironment,
  plugin_resolver: &Rc<PluginResolver<TEnvironment>>,
) -> Result<PluginsScope<TEnvironment>, ResolvePluginsError> {
  // resolve the plugins
  let plugins = filter_duplicate_plugin_names(plugin_resolver.resolve_plugins(config.plugins.clone()).await?);
  let mut config_map = config.config_map.clone();

  // resolve each plugin's configuration
  let mut plugins_with_config = Vec::new();
  for plugin in plugins.into_iter() {
    plugins_with_config.push((get_plugin_config_map(&plugin, &mut config_map)?, plugin));
  }

  // now get global config
  let global_config_result = get_global_config(config_map);
  let global_config = global_config_result.config;
  let config_base_path = config.base_path.clone();

  // create the scope
  let plugins = plugins_with_config
    .into_iter()
    .map(|(plugin_config, plugin)| {
      let global_config = global_config.clone();
      let overrides = resolve_plugin_config_overrides(plugin_config.overrides, &config_base_path, plugin_resolver)?;
      let next_config_id = plugin_resolver.next_config_id();
      Ok(
        async move {
          let instance = plugin.initialize().await?;
          let format_config = Arc::new(FormatConfig {
            id: next_config_id,
            global: global_config,
            plugin: plugin_config.properties,
          });
          let file_matching = instance.file_matching_info(format_config.clone()).await?;
          let serialized_resolved_config = instance.resolved_config(format_config.clone()).await?;
          Ok::<_, anyhow::Error>(Rc::new(PluginWithConfig::new(
            plugin,
            PluginWithConfigOptions {
              associations: plugin_config.associations,
              format_config,
              file_matching,
              overrides,
              serialized_resolved_config,
            },
          )))
        }
        .boxed_local(),
      )
    })
    .collect::<Result<Vec<_>>>()?;
  let plugin_results = dprint_core::async_runtime::future::join_all(plugins).await;
  let mut plugins = Vec::with_capacity(plugin_results.len());
  for result in plugin_results {
    plugins.push(result?);
  }

  Ok(PluginsScope::new(environment.clone(), plugins, config, global_config_result.diagnostics)?)
}

/// Keeps only the highest precedence plugin for each plugin name.
///
/// The same plugin may end up specified more than once with different sources
/// (ex. a config pinning a newer version of a plugin that the config it extends
/// also specifies). Plugins are ordered by descending precedence, so the first
/// entry for a name wins.
///
/// This can't be done when resolving the configuration because a plugin's name
/// is only known once it has been resolved.
fn filter_duplicate_plugin_names(plugins: Vec<Rc<PluginWrapper>>) -> Vec<Rc<PluginWrapper>> {
  let mut names = HashSet::with_capacity(plugins.len());

  plugins.into_iter().filter(|plugin| names.insert(plugin.info().name.clone())).collect()
}

fn resolve_plugin_config_overrides<TEnvironment: Environment>(
  overrides: Vec<RawPluginConfigOverride>,
  config_base_path: &CanonicalizedPathBuf,
  plugin_resolver: &Rc<PluginResolver<TEnvironment>>,
) -> Result<Vec<PluginConfigOverride>> {
  overrides
    .into_iter()
    .map(|override_config| {
      let matcher = OrderedPatternsMatcher::new(&override_config.files, config_base_path)?;
      Ok(PluginConfigOverride {
        files: override_config.files,
        properties: override_config.properties,
        config_id: plugin_resolver.next_config_id(),
        matcher,
      })
    })
    .collect()
}

#[cfg(test)]
mod test {
  use dprint_core::configuration::ConfigKeyValue;
  use dprint_core::configuration::GlobalConfiguration;

  use crate::plugins::TestPlugin;

  use super::*;

  // a plugin can derive values at resolution time that aren't present in the
  // raw config map (ex. the exec plugin folds the contents of `cacheKeyFiles`
  // into its `cacheKey`). these must participate in the incremental hash so that
  // changing one of those files invalidates the cache. see issue #1135.
  #[test]
  fn incremental_hash_includes_resolved_config() {
    fn hash_with_resolved_config(resolved_config: &str) -> u64 {
      let plugin = Rc::new(PluginWrapper::new(Box::new(TestPlugin::new("test-plugin", "test-plugin", vec!["txt"], vec![]))));
      let format_config = Arc::new(FormatConfig {
        id: FormatConfigId::from_raw(1),
        global: Default::default(),
        plugin: Default::default(),
      });
      let plugin_with_config = PluginWithConfig::new(
        plugin,
        PluginWithConfigOptions {
          associations: None,
          format_config,
          file_matching: FileMatchingInfo {
            file_extensions: vec!["txt".to_string()],
            file_names: vec![],
            additive: false,
          },
          overrides: Vec::new(),
          serialized_resolved_config: resolved_config.to_string(),
        },
      );
      let mut hasher = FastInsecureHasher::default();
      plugin_with_config.incremental_hash(&mut hasher);
      hasher.finish()
    }

    // the same raw config map but a different resolved config must produce a different hash
    assert_ne!(
      hash_with_resolved_config(r#"{"cacheKey":"a"}"#),
      hash_with_resolved_config(r#"{"cacheKey":"b"}"#)
    );
    // and the same resolved config must produce the same hash
    assert_eq!(
      hash_with_resolved_config(r#"{"cacheKey":"a"}"#),
      hash_with_resolved_config(r#"{"cacheKey":"a"}"#)
    );
  }

  #[test]
  fn should_include_shebangs_in_plugins_hash() {
    fn hash_with_shebangs(shebangs: Option<IndexMap<String, String>>) -> u64 {
      let environment = crate::environment::TestEnvironment::new();
      let base_path = CanonicalizedPathBuf::new_for_testing("/");
      let config = Rc::new(ResolvedConfig {
        config_map: Default::default(),
        base_path: base_path.clone(),
        source: PathSource::new_local(base_path.join_panic_relative("dprint.json")),
        is_global: false,
        excludes: None,
        includes: None,
        incremental: None,
        shebangs,
        inherit: None,
        plugins: Vec::new(),
      });
      let scope = PluginsScope::new(environment, vec![Rc::new(create_plugin_with_overrides(Vec::new()))], config, Vec::new()).unwrap();
      scope.plugins_hash()
    }
    fn shebangs(entries: &[(&str, &str)]) -> Option<IndexMap<String, String>> {
      Some(entries.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())
    }

    assert_eq!(hash_with_shebangs(None), hash_with_shebangs(None));
    assert_eq!(
      hash_with_shebangs(shebangs(&[("#!/bin/sh", "sh")])),
      hash_with_shebangs(shebangs(&[("#!/bin/sh", "sh")]))
    );
    assert_ne!(hash_with_shebangs(None), hash_with_shebangs(shebangs(&[("#!/bin/sh", "sh")])));
    // changing the mapped extension changes which plugin formats the file
    assert_ne!(
      hash_with_shebangs(shebangs(&[("#!/bin/sh", "sh")])),
      hash_with_shebangs(shebangs(&[("#!/bin/sh", "txt")]))
    );
  }

  #[test]
  fn should_hash_associations_with_boundaries() {
    fn hash_with_associations(associations: Vec<&str>) -> u64 {
      let mut plugin = create_plugin_with_overrides(Vec::new());
      plugin.associations = Some(associations.into_iter().map(ToOwned::to_owned).collect());
      get_plugin_hash(&plugin)
    }

    assert_ne!(hash_with_associations(vec!["ab", "c"]), hash_with_associations(vec!["a", "bc"]));
  }

  #[test]
  fn should_hash_override_file_patterns_and_property_keys_with_boundaries() {
    let plugin_ab_c = create_plugin_with_override(vec!["ab".to_string()], ConfigKeyMap::from([("c".to_string(), ConfigKeyValue::from_bool(true))]));
    let plugin_a_bc = create_plugin_with_override(vec!["a".to_string()], ConfigKeyMap::from([("bc".to_string(), ConfigKeyValue::from_bool(true))]));

    assert_ne!(get_plugin_hash(&plugin_ab_c), get_plugin_hash(&plugin_a_bc));
  }

  #[test]
  fn should_include_config_overrides_in_incremental_hash() {
    let config_base_path = CanonicalizedPathBuf::new_for_testing("/");
    let plugin_without_override = create_plugin_with_overrides(Vec::new());
    let plugin_with_override = create_plugin_with_overrides(vec![PluginConfigOverride {
      files: vec!["**/package.txt".to_string()],
      properties: ConfigKeyMap::from([("ending".to_string(), "package".into())]),
      config_id: FormatConfigId::from_raw(2),
      matcher: OrderedPatternsMatcher::new(&["**/package.txt".to_string()], &config_base_path).unwrap(),
    }]);

    assert_ne!(get_plugin_hash(&plugin_without_override), get_plugin_hash(&plugin_with_override));
  }

  fn get_plugin_hash(plugin: &PluginWithConfig) -> u64 {
    let mut hasher = FastInsecureHasher::default();
    plugin.incremental_hash(&mut hasher);
    hasher.finish()
  }

  fn create_plugin_with_override(files: Vec<String>, properties: ConfigKeyMap) -> PluginWithConfig {
    let config_base_path = CanonicalizedPathBuf::new_for_testing("/config");
    let matcher = OrderedPatternsMatcher::new(&files, &config_base_path).unwrap();
    create_plugin_with_overrides(vec![PluginConfigOverride {
      files,
      properties,
      config_id: FormatConfigId::from_raw(2),
      matcher,
    }])
  }

  fn create_plugin_with_overrides(overrides: Vec<PluginConfigOverride>) -> PluginWithConfig {
    PluginWithConfig::new(
      Rc::new(PluginWrapper::new(Box::new(TestPlugin::new("test-plugin", "test-plugin", vec!["txt"], vec![])))),
      PluginWithConfigOptions {
        associations: None,
        format_config: Arc::new(FormatConfig {
          id: FormatConfigId::from_raw(1),
          plugin: ConfigKeyMap::from([("ending".to_string(), "base".into())]),
          global: GlobalConfiguration::default(),
        }),
        file_matching: FileMatchingInfo {
          file_extensions: vec!["txt".to_string()],
          file_names: Vec::new(),
          additive: false,
        },
        overrides,
        serialized_resolved_config: String::new(),
      },
    )
  }
}