1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5use std::sync::{Mutex, OnceLock};
6
7use rustc_hash::FxHashSet;
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
10
11use crate::config::UsedClassMemberRule;
12
13pub const PLUGIN_EXTENSIONS: &[&str] = &["toml", "json", "jsonc"];
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema, Default)]
19#[serde(rename_all = "camelCase")]
20pub enum EntryPointRole {
21 Runtime,
23 Test,
25 #[default]
27 Support,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum AutoImportKind {
34 Named,
36 Default,
38 DefaultComponent,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct AutoImportRule {
54 pub name: String,
58 pub source: PathBuf,
60 pub kind: AutoImportKind,
62 pub scope: Vec<PathBuf>,
67}
68
69impl AutoImportRule {
70 #[must_use]
72 pub const fn new(name: String, source: PathBuf, kind: AutoImportKind) -> Self {
73 Self {
74 name,
75 source,
76 kind,
77 scope: Vec::new(),
78 }
79 }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct JsxImportSourceRule {
92 pub source: String,
95 pub config_dir: PathBuf,
99 pub include: Vec<String>,
102 pub exclude: Vec<String>,
105}
106
107#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
112#[serde(tag = "type", rename_all = "camelCase")]
113pub enum PluginDetection {
114 Dependency {
116 package: String,
118 },
119 FileExists {
121 pattern: String,
126 },
127 All {
129 conditions: Vec<Self>,
131 },
132 Any {
134 conditions: Vec<Self>,
136 },
137}
138
139#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
166#[serde(rename_all = "camelCase")]
167pub struct ExternalPluginDef {
168 #[serde(rename = "$schema", default, skip_serializing)]
170 #[schemars(skip)]
171 pub schema: Option<String>,
172
173 pub name: String,
175
176 #[serde(default)]
179 pub detection: Option<PluginDetection>,
180
181 #[serde(default)]
186 pub enablers: Vec<String>,
187
188 #[serde(default)]
190 pub entry_points: Vec<String>,
191
192 #[serde(default, skip_serializing_if = "Option::is_none")]
199 #[schemars(with = "EntryPointRole", default = "schema_default_entry_point_role")]
200 pub entry_point_role: Option<EntryPointRole>,
201
202 #[serde(default)]
209 pub manifest_entries: Vec<ManifestEntryRule>,
210
211 #[serde(default)]
213 pub config_patterns: Vec<String>,
214
215 #[serde(default)]
221 pub config_default_export_opt_out: Vec<String>,
222
223 #[serde(default)]
225 pub always_used: Vec<String>,
226
227 #[serde(default)]
230 pub tooling_dependencies: Vec<String>,
231
232 #[serde(default)]
234 pub used_exports: Vec<ExternalUsedExport>,
235
236 #[serde(default)]
241 pub used_class_members: Vec<UsedClassMemberRule>,
242}
243
244#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
246pub struct ExternalUsedExport {
247 pub pattern: String,
250 pub exports: Vec<String>,
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema, Default)]
258#[serde(rename_all = "lowercase")]
259pub enum ManifestFormat {
260 #[default]
262 Jsonc,
263 Json,
265}
266
267#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
273pub struct ManifestFieldPath {
274 raw: String,
275 segments: Vec<ManifestFieldSegment>,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
280pub enum ManifestFieldSegment {
281 Key(String),
283 Each,
285}
286
287impl ManifestFieldPath {
288 #[must_use]
290 pub fn as_str(&self) -> &str {
291 &self.raw
292 }
293
294 #[must_use]
296 pub fn segments(&self) -> &[ManifestFieldSegment] {
297 &self.segments
298 }
299
300 fn parse(raw: String) -> Result<Self, String> {
301 if raw.is_empty() {
302 return Err("manifest field path must not be empty".to_string());
303 }
304
305 let mut segments = Vec::new();
306 for component in raw.split('.') {
307 if component.is_empty() {
308 return Err(format!(
309 "manifest field path '{raw}' contains an empty segment"
310 ));
311 }
312
313 let key_end = component.find('[').unwrap_or(component.len());
314 let key = &component[..key_end];
315 if key.is_empty() || key.contains(['{', '}', ']']) {
316 return Err(format!(
317 "manifest field path '{raw}' contains unsupported bracket syntax"
318 ));
319 }
320 segments.push(ManifestFieldSegment::Key(key.to_string()));
321
322 let mut suffix = &component[key_end..];
323 while !suffix.is_empty() {
324 let Some(rest) = suffix.strip_prefix("[*]") else {
325 return Err(format!(
326 "manifest field path '{raw}' only supports exact '[*]' array traversal"
327 ));
328 };
329 segments.push(ManifestFieldSegment::Each);
330 suffix = rest;
331 }
332 }
333
334 Ok(Self { raw, segments })
335 }
336}
337
338impl FromStr for ManifestFieldPath {
339 type Err = String;
340
341 fn from_str(raw: &str) -> Result<Self, Self::Err> {
342 Self::parse(raw.to_string())
343 }
344}
345
346impl fmt::Display for ManifestFieldPath {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 f.write_str(&self.raw)
349 }
350}
351
352impl Serialize for ManifestFieldPath {
353 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
354 where
355 S: Serializer,
356 {
357 serializer.serialize_str(&self.raw)
358 }
359}
360
361impl<'de> Deserialize<'de> for ManifestFieldPath {
362 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
363 where
364 D: Deserializer<'de>,
365 {
366 let raw = String::deserialize(deserializer)?;
367 Self::parse(raw).map_err(|e| D::Error::custom(crate::parse_error::own_message(e)))
368 }
369}
370
371#[derive(Debug, Clone, PartialEq, Eq)]
373pub enum ManifestPathPart {
374 Literal(String),
376 Field(ManifestFieldPath),
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct ManifestPathTemplate {
383 raw: String,
384 parts: Vec<ManifestPathPart>,
385}
386
387impl ManifestPathTemplate {
388 #[must_use]
390 pub fn as_str(&self) -> &str {
391 &self.raw
392 }
393
394 #[must_use]
396 pub fn parts(&self) -> &[ManifestPathPart] {
397 &self.parts
398 }
399
400 #[must_use]
402 pub fn validation_pattern(&self) -> String {
403 let mut pattern = String::with_capacity(self.raw.len());
404 for part in &self.parts {
405 match part {
406 ManifestPathPart::Literal(literal) => pattern.push_str(literal),
407 ManifestPathPart::Field(_) => pattern.push_str("fallowinterp"),
408 }
409 }
410 pattern
411 }
412
413 fn parse(raw: String) -> Result<Self, String> {
414 let mut parts = Vec::new();
415 let mut rest = raw.as_str();
416
417 while let Some(start) = rest.find("${") {
418 if start > 0 {
419 parts.push(ManifestPathPart::Literal(rest[..start].to_string()));
420 }
421
422 let after = &rest[start + 2..];
423 let Some(end) = after.find('}') else {
424 return Err(format!(
425 "manifest entry path '{raw}' contains an unterminated interpolation"
426 ));
427 };
428 let field = after[..end].parse::<ManifestFieldPath>()?;
429 parts.push(ManifestPathPart::Field(field));
430 rest = &after[end + 1..];
431 }
432
433 if !rest.is_empty() {
434 parts.push(ManifestPathPart::Literal(rest.to_string()));
435 }
436 if parts.is_empty() {
437 parts.push(ManifestPathPart::Literal(String::new()));
438 }
439
440 Ok(Self { raw, parts })
441 }
442}
443
444impl FromStr for ManifestPathTemplate {
445 type Err = String;
446
447 fn from_str(raw: &str) -> Result<Self, Self::Err> {
448 Self::parse(raw.to_string())
449 }
450}
451
452impl fmt::Display for ManifestPathTemplate {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 f.write_str(&self.raw)
455 }
456}
457
458impl Serialize for ManifestPathTemplate {
459 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
460 where
461 S: Serializer,
462 {
463 serializer.serialize_str(&self.raw)
464 }
465}
466
467impl<'de> Deserialize<'de> for ManifestPathTemplate {
468 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
469 where
470 D: Deserializer<'de>,
471 {
472 let raw = String::deserialize(deserializer)?;
473 Self::parse(raw).map_err(|e| D::Error::custom(crate::parse_error::own_message(e)))
474 }
475}
476
477#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
482#[serde(untagged)]
483pub enum ManifestCondition {
484 Exists(ManifestExistsPredicate),
486 Equals(serde_json::Value),
488}
489
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
492#[serde(deny_unknown_fields)]
493pub struct ManifestExistsPredicate {
494 pub exists: bool,
496}
497
498#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
517#[serde(rename_all = "camelCase")]
518pub struct ManifestEntryRule {
519 pub manifests: String,
522
523 #[serde(default)]
525 pub format: ManifestFormat,
526
527 #[serde(default)]
533 #[schemars(with = "BTreeMap<String, ManifestCondition>")]
534 pub when: BTreeMap<ManifestFieldPath, ManifestCondition>,
535
536 pub entries: Vec<ManifestSeedRule>,
538}
539
540#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
543#[serde(rename_all = "camelCase")]
544pub struct ManifestSeedRule {
545 #[schemars(with = "String")]
553 pub path: ManifestPathTemplate,
554
555 #[serde(default)]
558 #[schemars(with = "BTreeMap<String, ManifestCondition>")]
559 pub when: BTreeMap<ManifestFieldPath, ManifestCondition>,
560}
561
562fn default_external_entry_point_role() -> EntryPointRole {
563 EntryPointRole::Support
564}
565
566#[expect(
567 clippy::unnecessary_wraps,
568 reason = "the schema default must have the field type"
569)]
570fn schema_default_entry_point_role() -> Option<EntryPointRole> {
571 Some(default_external_entry_point_role())
572}
573
574impl ExternalPluginDef {
575 #[must_use]
577 pub fn effective_entry_point_role(&self) -> EntryPointRole {
578 self.entry_point_role
579 .unwrap_or_else(default_external_entry_point_role)
580 }
581
582 #[must_use]
585 pub fn has_explicit_support_role(&self) -> bool {
586 self.entry_point_role == Some(EntryPointRole::Support)
587 }
588
589 pub const NEVER_ACTIVATES_REASON: &str =
592 "no detection or enablers declared, so the plugin can never activate";
593
594 #[must_use]
597 pub fn has_activation_condition(&self) -> bool {
598 self.detection.is_some() || !self.enablers.is_empty()
599 }
600
601 #[must_use]
603 pub fn json_schema() -> serde_json::Value {
604 serde_json::to_value(schemars::schema_for!(ExternalPluginDef)).unwrap_or_default()
605 }
606
607 pub fn validate_user_globs(
621 &self,
622 ) -> Result<(), Vec<crate::config::glob_validation::GlobValidationError>> {
623 use crate::config::glob_validation::{compile_user_glob, validate_user_globs};
624
625 let mut errors = Vec::new();
626 validate_user_globs(&self.entry_points, "framework[].entryPoints", &mut errors);
627 validate_user_globs(&self.always_used, "framework[].alwaysUsed", &mut errors);
628 validate_user_globs(
629 &self.config_patterns,
630 "framework[].configPatterns",
631 &mut errors,
632 );
633 for used in &self.used_exports {
634 if let Err(e) = compile_user_glob(&used.pattern, "framework[].usedExports[].pattern") {
635 errors.push(e);
636 }
637 }
638 for rule in &self.manifest_entries {
639 if let Err(e) =
640 compile_user_glob(&rule.manifests, "framework[].manifestEntries[].manifests")
641 {
642 errors.push(e);
643 }
644 for seed in &rule.entries {
645 let probe = seed.path.validation_pattern();
648 if let Err(e) =
649 compile_user_glob(&probe, "framework[].manifestEntries[].entries[].path")
650 {
651 errors.push(e);
652 }
653 }
654 }
655 if let Some(detection) = &self.detection {
656 validate_detection_user_globs(detection, "framework[].detection", &mut errors);
657 }
658 if errors.is_empty() {
659 Ok(())
660 } else {
661 Err(errors)
662 }
663 }
664}
665
666fn validate_detection_user_globs(
669 detection: &PluginDetection,
670 field: &'static str,
671 errors: &mut Vec<crate::config::glob_validation::GlobValidationError>,
672) {
673 match detection {
674 PluginDetection::Dependency { .. } => {}
675 PluginDetection::FileExists { pattern } => {
676 if let Err(e) = crate::config::glob_validation::compile_user_glob(pattern, field) {
677 errors.push(e);
678 }
679 }
680 PluginDetection::All { conditions } | PluginDetection::Any { conditions } => {
681 for condition in conditions {
682 validate_detection_user_globs(condition, field, errors);
683 }
684 }
685 }
686}
687
688pub fn discover_and_validate_external_plugins(
703 root: &Path,
704 config_plugin_paths: &[String],
705) -> Result<Vec<ExternalPluginDef>, Vec<crate::config::glob_validation::GlobValidationError>> {
706 let plugins = discover_external_plugins(root, config_plugin_paths);
707 let mut errors = Vec::new();
708 for plugin in &plugins {
709 if let Err(mut plugin_errors) = plugin.validate_user_globs() {
710 errors.append(&mut plugin_errors);
711 }
712 }
713 if errors.is_empty() {
714 Ok(plugins)
715 } else {
716 Err(errors)
717 }
718}
719
720enum PluginFormat {
722 Toml,
723 Json,
724 Jsonc,
725}
726
727impl PluginFormat {
728 fn from_path(path: &Path) -> Option<Self> {
729 match path.extension().and_then(|e| e.to_str()) {
730 Some("toml") => Some(Self::Toml),
731 Some("json") => Some(Self::Json),
732 Some("jsonc") => Some(Self::Jsonc),
733 _ => None,
734 }
735 }
736}
737
738const DEFAULT_PLUGINS_DIR_NAME: &str = "plugins";
741
742pub const ROOT_PLUGIN_FILE_PREFIX: &str = "fallow-plugin-";
745
746fn is_plugin_file(path: &Path) -> bool {
747 path.extension()
748 .and_then(|e| e.to_str())
749 .is_some_and(|ext| PLUGIN_EXTENSIONS.contains(&ext))
750}
751
752fn parse_plugin(content: &str, format: &PluginFormat, path: &Path) -> Option<ExternalPluginDef> {
754 match plugin_parse_error(content, format) {
755 Ok(plugin) => Some(plugin),
756 Err(e) => {
757 tracing::warn!("failed to parse external plugin {}: {e}", path.display());
758 None
759 }
760 }
761}
762
763fn plugin_parse_error(content: &str, format: &PluginFormat) -> Result<ExternalPluginDef, String> {
765 match format {
766 PluginFormat::Toml => crate::toml_input::from_str::<ExternalPluginDef>(content)
767 .map_err(|e| crate::parse_error::describe_toml(&e, content)),
768 PluginFormat::Json => serde_json::from_str::<ExternalPluginDef>(content)
769 .map_err(|e| crate::parse_error::describe_json(&e)),
770 PluginFormat::Jsonc => crate::jsonc::parse_to_value::<ExternalPluginDef>(content)
771 .map_err(|e| crate::parse_error::describe_jsonc(&e)),
772 }
773}
774
775#[derive(Debug, Clone, Copy, PartialEq, Eq)]
777#[non_exhaustive]
778pub enum ConfiguredPluginDiagnosticKind {
779 Missing,
781 OutsideProjectRoot,
783 UnsupportedFormat,
785 Unreadable,
787 InvalidDefinition,
789 NoPluginFiles,
791}
792
793#[derive(Debug, Clone, PartialEq, Eq)]
795#[non_exhaustive]
796pub struct ConfiguredPluginDiagnostic {
797 pub kind: ConfiguredPluginDiagnosticKind,
799 pub path: PathBuf,
801}
802
803#[must_use]
810pub fn diagnose_configured_external_plugins(
811 root: &Path,
812 config_plugin_paths: &[String],
813) -> Vec<ConfiguredPluginDiagnostic> {
814 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
815 let mut diagnostics = Vec::new();
816
817 for path_str in config_plugin_paths {
818 let path = root.join(path_str);
819 if !plugin_path_text_allowed(root, &canonical_root, &path) {
820 diagnostics.push(ConfiguredPluginDiagnostic {
821 kind: ConfiguredPluginDiagnosticKind::OutsideProjectRoot,
822 path,
823 });
824 continue;
825 }
826 let metadata = match std::fs::metadata(&path) {
827 Ok(metadata) => metadata,
828 Err(error) => {
829 diagnostics.push(ConfiguredPluginDiagnostic {
830 kind: if error.kind() == std::io::ErrorKind::NotFound {
831 ConfiguredPluginDiagnosticKind::Missing
832 } else {
833 ConfiguredPluginDiagnosticKind::Unreadable
834 },
835 path,
836 });
837 continue;
838 }
839 };
840
841 if !is_within_root(&path, &canonical_root) {
842 diagnostics.push(ConfiguredPluginDiagnostic {
843 kind: ConfiguredPluginDiagnosticKind::OutsideProjectRoot,
844 path,
845 });
846 continue;
847 }
848
849 if metadata.is_dir() {
850 diagnose_configured_plugin_dir(&path, &canonical_root, &mut diagnostics);
851 } else if metadata.is_file() {
852 diagnose_configured_plugin_file(&path, &canonical_root, &mut diagnostics);
853 } else {
854 diagnostics.push(ConfiguredPluginDiagnostic {
855 kind: ConfiguredPluginDiagnosticKind::UnsupportedFormat,
856 path,
857 });
858 }
859 }
860
861 diagnostics
862}
863
864fn diagnose_configured_plugin_dir(
865 dir: &Path,
866 canonical_root: &Path,
867 diagnostics: &mut Vec<ConfiguredPluginDiagnostic>,
868) {
869 let Ok(entries) = std::fs::read_dir(dir) else {
870 diagnostics.push(ConfiguredPluginDiagnostic {
871 kind: ConfiguredPluginDiagnosticKind::Unreadable,
872 path: dir.to_path_buf(),
873 });
874 return;
875 };
876 let mut plugin_files = Vec::new();
877 let mut entry_failed = false;
878 for entry in entries {
879 match entry {
880 Ok(entry) => {
881 let path = entry.path();
882 if path.is_file() && is_plugin_file(&path) {
883 plugin_files.push(path);
884 }
885 }
886 Err(_) => {
887 entry_failed = true;
888 diagnostics.push(ConfiguredPluginDiagnostic {
889 kind: ConfiguredPluginDiagnosticKind::Unreadable,
890 path: dir.to_path_buf(),
891 });
892 }
893 }
894 }
895 if plugin_files.is_empty() && !entry_failed {
896 diagnostics.push(ConfiguredPluginDiagnostic {
897 kind: ConfiguredPluginDiagnosticKind::NoPluginFiles,
898 path: dir.to_path_buf(),
899 });
900 return;
901 }
902 plugin_files.sort();
903 for path in plugin_files {
904 diagnose_configured_plugin_file(&path, canonical_root, diagnostics);
905 }
906}
907
908fn diagnose_configured_plugin_file(
909 path: &Path,
910 canonical_root: &Path,
911 diagnostics: &mut Vec<ConfiguredPluginDiagnostic>,
912) {
913 let kind = if !is_within_root(path, canonical_root) {
914 Some(ConfiguredPluginDiagnosticKind::OutsideProjectRoot)
915 } else if let Some(format) = PluginFormat::from_path(path) {
916 match fallow_types::read_guard::read_to_string_inside(
917 canonical_root,
918 path,
919 fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
920 ) {
921 Ok(content) => match parse_plugin(&content, &format, path) {
922 Some(plugin) if !plugin.name.is_empty() => None,
923 Some(_) | None => Some(ConfiguredPluginDiagnosticKind::InvalidDefinition),
924 },
925 Err(_) => Some(ConfiguredPluginDiagnosticKind::Unreadable),
926 }
927 } else {
928 Some(ConfiguredPluginDiagnosticKind::UnsupportedFormat)
929 };
930 if let Some(kind) = kind {
931 diagnostics.push(ConfiguredPluginDiagnostic {
932 kind,
933 path: path.to_path_buf(),
934 });
935 }
936}
937
938pub fn resolve_external_plugins(
941 root: &Path,
942 config_plugin_paths: &[String],
943 framework: Vec<ExternalPluginDef>,
944) -> Vec<ExternalPluginDef> {
945 let mut plugins = discover_external_plugins(root, config_plugin_paths);
946 plugins.extend(framework);
947 plugins.retain(|plugin| match plugin.validate_user_globs() {
950 Ok(()) => true,
951 Err(errors) => {
952 for error in errors {
953 tracing::warn!("skipping external plugin '{}': {error}", plugin.name);
954 }
955 false
956 }
957 });
958 warn_on_plugins_that_never_activate(&plugins);
959 plugins
960}
961
962fn warn_on_plugins_that_never_activate(plugins: &[ExternalPluginDef]) {
965 static WARNED: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
966 let warned = WARNED.get_or_init(|| Mutex::new(FxHashSet::default()));
967
968 for plugin in plugins {
969 if plugin.has_activation_condition() {
970 continue;
971 }
972 if let Ok(mut set) = warned.lock()
973 && !set.insert(plugin.name.clone())
974 {
975 continue;
976 }
977 tracing::warn!(
978 "plugin '{}': {}. Add one of them, then run `fallow plugin-check`.",
979 plugin.name,
980 ExternalPluginDef::NEVER_ACTIVATES_REASON,
981 );
982 }
983}
984
985pub fn discover_external_plugins(
992 root: &Path,
993 config_plugin_paths: &[String],
994) -> Vec<ExternalPluginDef> {
995 let mut plugins = Vec::new();
996 let mut seen_names = rustc_hash::FxHashSet::default();
997
998 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
999
1000 load_configured_plugin_paths(
1001 root,
1002 config_plugin_paths,
1003 &canonical_root,
1004 &mut plugins,
1005 &mut seen_names,
1006 );
1007 load_default_plugins_dir(root, &canonical_root, &mut plugins, &mut seen_names);
1008 load_root_plugin_files(root, &canonical_root, &mut plugins, &mut seen_names);
1009
1010 plugins
1011}
1012
1013fn load_configured_plugin_paths(
1014 root: &Path,
1015 config_plugin_paths: &[String],
1016 canonical_root: &Path,
1017 plugins: &mut Vec<ExternalPluginDef>,
1018 seen_names: &mut rustc_hash::FxHashSet<String>,
1019) {
1020 for path_str in config_plugin_paths {
1021 let path = root.join(path_str);
1022 match crate::project_read::project_entry(canonical_root, Path::new(path_str)) {
1023 crate::project_read::ProjectEntry::Missing => continue,
1024 crate::project_read::ProjectEntry::Outside => {
1025 tracing::warn!("plugin path '{path_str}' resolves outside project root, skipping");
1026 continue;
1027 }
1028 crate::project_read::ProjectEntry::Inside => {}
1029 }
1030 if path.is_dir() {
1031 load_plugins_from_dir(&path, canonical_root, plugins, seen_names);
1032 } else if path.is_file() {
1033 load_plugin_file(&path, canonical_root, plugins, seen_names);
1034 }
1035 }
1036}
1037
1038fn load_default_plugins_dir(
1039 root: &Path,
1040 canonical_root: &Path,
1041 plugins: &mut Vec<ExternalPluginDef>,
1042 seen_names: &mut rustc_hash::FxHashSet<String>,
1043) {
1044 let plugins_dir = root.join(".fallow").join(DEFAULT_PLUGINS_DIR_NAME);
1045 if plugins_dir.is_dir() && is_within_root(&plugins_dir, canonical_root) {
1046 load_plugins_from_dir(&plugins_dir, canonical_root, plugins, seen_names);
1047 }
1048}
1049
1050fn load_root_plugin_files(
1051 root: &Path,
1052 canonical_root: &Path,
1053 plugins: &mut Vec<ExternalPluginDef>,
1054 seen_names: &mut rustc_hash::FxHashSet<String>,
1055) {
1056 for path in root_plugin_files(root) {
1057 load_plugin_file(&path, canonical_root, plugins, seen_names);
1058 }
1059}
1060
1061fn root_plugin_files(root: &Path) -> Vec<PathBuf> {
1063 let Ok(entries) = std::fs::read_dir(root) else {
1064 return Vec::new();
1065 };
1066 let mut plugin_files: Vec<PathBuf> = entries
1067 .filter_map(Result::ok)
1068 .map(|e| e.path())
1069 .filter(|p| {
1070 is_file_or_link(p)
1071 && p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
1072 n.starts_with(ROOT_PLUGIN_FILE_PREFIX) && is_plugin_file(Path::new(n))
1073 })
1074 })
1075 .collect();
1076 plugin_files.sort();
1077 plugin_files
1078}
1079
1080fn plugin_files_in_dir(dir: &Path) -> Vec<PathBuf> {
1082 let Ok(entries) = std::fs::read_dir(dir) else {
1083 return Vec::new();
1084 };
1085 let mut plugin_files: Vec<PathBuf> = entries
1086 .filter_map(Result::ok)
1087 .map(|e| e.path())
1088 .filter(|p| is_file_or_link(p) && is_plugin_file(p))
1089 .collect();
1090 plugin_files.sort();
1091 plugin_files
1092}
1093
1094#[must_use]
1098pub fn is_default_external_plugin_file(path: &Path) -> bool {
1099 if !is_plugin_file(path) {
1100 return false;
1101 }
1102 let name_matches = path
1103 .file_name()
1104 .and_then(|name| name.to_str())
1105 .is_some_and(|name| name.starts_with(ROOT_PLUGIN_FILE_PREFIX));
1106 let parent = path.parent();
1107 let in_plugins_dir = parent
1108 .and_then(Path::file_name)
1109 .is_some_and(|name| name == DEFAULT_PLUGINS_DIR_NAME)
1110 && parent
1111 .and_then(Path::parent)
1112 .and_then(Path::file_name)
1113 .is_some_and(|name| name == ".fallow");
1114 name_matches || in_plugins_dir
1115}
1116
1117#[must_use]
1123pub fn external_plugin_source_files(root: &Path, config_plugin_paths: &[String]) -> Vec<PathBuf> {
1124 let mut files = Vec::new();
1125 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
1126 for path_str in config_plugin_paths {
1127 let path = root.join(path_str);
1128 if !plugin_path_text_allowed(root, &canonical_root, &path) {
1129 continue;
1130 }
1131 if path.is_dir() {
1132 files.extend(plugin_files_in_dir(&path));
1133 } else {
1134 files.push(path);
1135 }
1136 }
1137 files.extend(plugin_files_in_dir(
1138 &root.join(".fallow").join(DEFAULT_PLUGINS_DIR_NAME),
1139 ));
1140 files.extend(root_plugin_files(root));
1141 files
1142}
1143
1144fn plugin_path_text_allowed(root: &Path, canonical_root: &Path, path: &Path) -> bool {
1148 let has_prefix = matches!(
1151 path.components().next(),
1152 Some(std::path::Component::Prefix(_))
1153 );
1154 if has_prefix && !path.is_absolute() {
1155 return false;
1156 }
1157 !path.is_absolute()
1158 || crate::project_read::absolute_path_text_inside(path, canonical_root, root)
1159}
1160
1161fn is_file_or_link(path: &Path) -> bool {
1167 path.symlink_metadata().is_ok_and(|meta| {
1168 meta.is_file()
1169 || (meta.file_type().is_symlink()
1170 && std::fs::metadata(path).map_or(true, |target| target.is_file()))
1171 })
1172}
1173
1174fn is_within_root(path: &Path, canonical_root: &Path) -> bool {
1177 dunce::canonicalize(path).is_ok_and(|canonical| canonical.starts_with(canonical_root))
1178}
1179
1180fn load_plugins_from_dir(
1181 dir: &Path,
1182 canonical_root: &Path,
1183 plugins: &mut Vec<ExternalPluginDef>,
1184 seen: &mut rustc_hash::FxHashSet<String>,
1185) {
1186 for path in plugin_files_in_dir(dir) {
1187 load_plugin_file(&path, canonical_root, plugins, seen);
1188 }
1189}
1190
1191fn load_plugin_file(
1192 path: &Path,
1193 canonical_root: &Path,
1194 plugins: &mut Vec<ExternalPluginDef>,
1195 seen: &mut rustc_hash::FxHashSet<String>,
1196) {
1197 if !is_within_root(path, canonical_root) {
1198 tracing::warn!(
1199 "plugin file '{}' resolves outside project root (symlink?), skipping",
1200 path.display()
1201 );
1202 return;
1203 }
1204
1205 let Some(format) = PluginFormat::from_path(path) else {
1206 tracing::warn!(
1207 "unsupported plugin file extension for {}, expected .toml, .json, or .jsonc",
1208 path.display()
1209 );
1210 return;
1211 };
1212
1213 let Some(content) = read_plugin_file(path, canonical_root) else {
1214 return;
1215 };
1216
1217 if let Some(plugin) = parse_plugin(&content, &format, path) {
1218 push_plugin_if_unique(plugin, path, plugins, seen);
1219 }
1220}
1221
1222fn read_plugin_file(path: &Path, canonical_root: &Path) -> Option<String> {
1223 match fallow_types::read_guard::read_to_string_inside(
1224 canonical_root,
1225 path,
1226 fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
1227 ) {
1228 Ok(content) => Some(content),
1229 Err(e) => {
1230 tracing::warn!("failed to read external plugin file: {e}");
1231 None
1232 }
1233 }
1234}
1235
1236fn push_plugin_if_unique(
1237 plugin: ExternalPluginDef,
1238 path: &Path,
1239 plugins: &mut Vec<ExternalPluginDef>,
1240 seen: &mut rustc_hash::FxHashSet<String>,
1241) {
1242 if plugin.name.is_empty() {
1243 tracing::warn!(
1244 "external plugin in {} has an empty name, skipping",
1245 path.display()
1246 );
1247 return;
1248 }
1249
1250 if seen.insert(plugin.name.clone()) {
1251 plugins.push(plugin);
1252 } else {
1253 tracing::warn!(
1254 "duplicate external plugin '{}' in {}, skipping",
1255 plugin.name,
1256 path.display()
1257 );
1258 }
1259}
1260
1261#[cfg(test)]
1262mod tests;