forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspace.rs
More file actions
793 lines (705 loc) · 27.8 KB
/
Copy pathworkspace.rs
File metadata and controls
793 lines (705 loc) · 27.8 KB
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
use camino::Utf8PathBuf;
use common::config::{Config, WorkspaceMemberSelection, WorkspaceSettings};
use common::ingot::Version;
use common::paths::{canonicalize_utf8, file_url_to_utf8_path, glob_pattern, normalize_slashes};
use common::urlext::UrlExt;
use glob::glob;
use smol_str::SmolStr;
use std::path::{Path, PathBuf};
use url::Url;
use crate::{
ResolutionHandler, Resolver,
files::{FilesResolutionDiagnostic, FilesResolutionError, FilesResolver, FilesResource},
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExpandedWorkspaceMember {
pub url: Url,
pub path: Utf8PathBuf,
pub name: Option<SmolStr>,
pub version: Option<Version>,
}
#[derive(Debug, Default)]
pub struct ContextDiscovery {
pub workspace_root: Option<Url>,
pub ingot_roots: Vec<Url>,
pub standalone_files: Vec<Url>,
pub diagnostics: Vec<FilesResolutionDiagnostic>,
}
enum DiscoveredConfig {
Workspace(Box<common::config::WorkspaceConfig>),
Ingot,
Invalid,
}
struct ContextProbe;
impl ResolutionHandler<FilesResolver> for ContextProbe {
type Item = Option<DiscoveredConfig>;
fn handle_resolution(&mut self, _description: &Url, resource: FilesResource) -> Self::Item {
let config = resource
.files
.iter()
.find(|file| file.path.as_str().ends_with("fe.toml"))
.map(|file| file.content.as_str())?;
match Config::parse(config) {
Ok(Config::Workspace(config)) => Some(DiscoveredConfig::Workspace(config)),
Ok(Config::Ingot(_)) => Some(DiscoveredConfig::Ingot),
Err(_) => Some(DiscoveredConfig::Invalid),
}
}
}
pub fn expand_workspace_members(
workspace: &WorkspaceSettings,
base_url: &Url,
selection: WorkspaceMemberSelection,
) -> Result<Vec<ExpandedWorkspaceMember>, String> {
let base_path = file_url_to_utf8_path(base_url)
.ok_or_else(|| "workspace URL is not a file URL or not UTF-8".to_string())?;
let base_canonical = canonicalize_utf8(base_path.as_std_path())
.map_err(|err| format!("failed to canonicalize workspace root {base_path}: {err}"))?;
let mut excluded = std::collections::HashSet::new();
for pattern in &workspace.exclude {
let pattern_path = base_path.join(pattern.as_str());
let entries = glob(&glob_pattern(pattern_path.as_std_path()))
.map_err(|err| format!("Invalid exclude pattern \"{pattern}\": {err}"))?;
for entry in entries {
let path = entry
.map_err(|err| format!("Glob error for exclude pattern \"{pattern}\": {err}"))?;
let canonical = canonicalize_utf8(&path)
.map_err(|err| format!("Glob error for exclude pattern \"{pattern}\": {err}"))?;
if !canonical.starts_with(&base_canonical) {
return Err(format!(
"Exclude pattern \"{pattern}\" escapes workspace root {base_path}"
));
}
excluded.insert(canonical);
}
}
let mut members = Vec::new();
let mut seen = std::collections::HashSet::new();
let spec_selection = match selection {
WorkspaceMemberSelection::DefaultOnly if workspace.default_members.is_some() => {
WorkspaceMemberSelection::All
}
WorkspaceMemberSelection::DefaultOnly => WorkspaceMemberSelection::PrimaryOnly,
selection => selection,
};
for spec in workspace.members_for_selection(spec_selection) {
let pattern = spec.path.as_str();
let has_glob = pattern.contains(['*', '?', '[']);
if !has_glob {
let path = base_path.join(pattern);
if !path.is_dir() {
continue;
}
let canonical = canonicalize_utf8(path.as_std_path()).map_err(|err| {
format!("failed to canonicalize member path \"{pattern}\": {err}")
})?;
if !canonical.starts_with(&base_canonical) {
return Err(format!(
"Member path \"{pattern}\" escapes workspace root {base_path}"
));
}
if excluded.contains(&canonical) {
continue;
}
if seen.insert(canonical.clone()) {
let relative = canonical
.strip_prefix(&base_canonical)
.map_err(|_| "member path escaped workspace root".to_string())?
.to_owned();
let url = base_url
.join_directory(&relative)
.map_err(|_| "failed to convert member path to URL".to_string())?;
members.push(ExpandedWorkspaceMember {
url,
path: relative,
name: spec.name.clone(),
version: spec.version.clone(),
});
}
continue;
}
if spec.name.is_some() || spec.version.is_some() {
return Err(format!(
"Member path \"{pattern}\" with name/version cannot contain glob patterns"
));
}
let pattern_path = base_path.join(pattern);
let entries = glob(&glob_pattern(pattern_path.as_std_path()))
.map_err(|err| format!("Invalid member pattern \"{pattern}\": {err}"))?;
for entry in entries {
let path = entry
.map_err(|err| format!("Glob error for member pattern \"{pattern}\": {err}"))?;
let canonical = canonicalize_utf8(&path)
.map_err(|err| format!("Glob error for member pattern \"{pattern}\": {err}"))?;
if !canonical.starts_with(&base_canonical) {
return Err(format!(
"Member pattern \"{pattern}\" escapes workspace root {base_path}"
));
}
if !canonical.is_dir() {
continue;
}
if excluded.contains(&canonical) {
continue;
}
if seen.insert(canonical.clone()) {
let relative = canonical
.strip_prefix(&base_canonical)
.map_err(|_| "member path escaped workspace root".to_string())?;
let url = base_url
.join_directory(&relative.to_owned())
.map_err(|_| "failed to convert member path to URL".to_string())?;
members.push(ExpandedWorkspaceMember {
url,
path: relative.to_owned(),
name: None,
version: None,
});
}
}
}
if matches!(selection, WorkspaceMemberSelection::DefaultOnly)
&& let Some(default_members) = &workspace.default_members
{
let defaults: std::collections::HashSet<String> = default_members
.iter()
.map(|member| normalize_slashes(member))
.collect();
members.retain(|member| defaults.contains(&normalize_slashes(member.path.as_str())));
}
Ok(members)
}
pub fn discover_context(
url: &Url,
scan_down: bool,
) -> Result<ContextDiscovery, FilesResolutionError> {
let path = url
.to_file_path()
.map_err(|_| FilesResolutionError::DirectoryDoesNotExist(url.clone()))?;
let mut discovery = ContextDiscovery::default();
let mut first_ingot_root: Option<Url> = None;
let is_file = path.is_file();
let start_dir = if is_file {
path.parent().map(PathBuf::from).unwrap_or(path.clone())
} else {
path.clone()
};
if !start_dir.exists() {
return Err(FilesResolutionError::DirectoryDoesNotExist(url.clone()));
}
let mut current = Some(start_dir.as_path());
let mut resolver = FilesResolver::new().with_required_file("fe.toml");
while let Some(dir) = current {
let dir_url = Url::from_directory_path(dir)
.map_err(|_| FilesResolutionError::DirectoryDoesNotExist(url.clone()))?;
let mut handler = ContextProbe;
let probe = resolver.resolve(&mut handler, &dir_url)?;
match probe {
Some(DiscoveredConfig::Workspace(config)) => {
discovery.workspace_root = Some(dir_url.clone());
if let Ok(members) = expand_workspace_members(
&config.workspace,
&dir_url,
WorkspaceMemberSelection::All,
) {
for member in members {
if !discovery.ingot_roots.contains(&member.url) {
discovery.ingot_roots.push(member.url);
}
}
}
if let Some(ingot_root) = first_ingot_root
&& ingot_root != dir_url
&& !discovery.ingot_roots.contains(&ingot_root)
{
discovery.ingot_roots.push(ingot_root);
}
return Ok(discovery);
}
Some(DiscoveredConfig::Ingot) | Some(DiscoveredConfig::Invalid)
if first_ingot_root.is_none() =>
{
first_ingot_root = Some(dir_url);
}
Some(DiscoveredConfig::Ingot) | Some(DiscoveredConfig::Invalid) => {}
None => {}
}
current = dir.parent();
}
if let Some(ingot_root) = first_ingot_root {
discovery.ingot_roots.push(ingot_root);
return Ok(discovery);
}
if is_file {
if let Some(root) = ancestor_root_for_src(&path) {
let ingot_url = Url::from_directory_path(&root)
.map_err(|_| FilesResolutionError::DirectoryDoesNotExist(url.clone()))?;
discovery
.diagnostics
.push(FilesResolutionDiagnostic::RequiredFileMissing(
ingot_url.clone(),
"fe.toml".to_string(),
));
discovery.ingot_roots.push(ingot_url);
return Ok(discovery);
}
if path.extension().and_then(|ext| ext.to_str()) == Some("fe")
&& let Ok(file_url) = Url::from_file_path(&path)
{
discovery.standalone_files.push(file_url);
}
return Ok(discovery);
}
// Upward walk found nothing and this is a directory without fe.toml.
// Scan downward for fe.toml files to discover nested workspaces/ingots
// (e.g. editor opened at a parent directory like a monorepo or workbook).
if scan_down {
discover_nested_configs(&start_dir, &mut resolver, &mut discovery)?;
}
Ok(discovery)
}
/// Recursively scan subdirectories for `fe.toml` files to discover nested
/// workspaces and ingots. Used when the editor root is a parent directory
/// that doesn't itself contain a Fe project (e.g. a monorepo or workbook).
fn discover_nested_configs(
root: &Path,
resolver: &mut FilesResolver,
discovery: &mut ContextDiscovery,
) -> Result<(), FilesResolutionError> {
const MAX_DEPTH: usize = 8;
const SKIP_DIRS: &[&str] = &[
".git",
".hg",
"node_modules",
"target",
"out",
".claude",
"__pycache__",
];
fn walk(
dir: &Path,
depth: usize,
resolver: &mut FilesResolver,
discovery: &mut ContextDiscovery,
) -> Result<(), FilesResolutionError> {
if depth > MAX_DEPTH {
return Ok(());
}
let dir_url = match Url::from_directory_path(dir) {
Ok(u) => u,
Err(_) => return Ok(()),
};
let mut handler = ContextProbe;
let probe = resolver.resolve(&mut handler, &dir_url)?;
match probe {
Some(DiscoveredConfig::Workspace(config)) => {
// Use the first discovered workspace as the primary root;
// additional workspaces are still loaded via ingot_roots.
if discovery.workspace_root.is_none() {
discovery.workspace_root = Some(dir_url.clone());
}
// Always add the workspace root itself so init_ingot processes it
if !discovery.ingot_roots.contains(&dir_url) {
discovery.ingot_roots.push(dir_url.clone());
}
if let Ok(members) = expand_workspace_members(
&config.workspace,
&dir_url,
WorkspaceMemberSelection::All,
) {
for member in members {
if !discovery.ingot_roots.contains(&member.url) {
discovery.ingot_roots.push(member.url);
}
}
}
// Don't recurse into a workspace — its members are already expanded
return Ok(());
}
Some(DiscoveredConfig::Ingot) => {
if !discovery.ingot_roots.contains(&dir_url) {
discovery.ingot_roots.push(dir_url);
}
// Don't recurse into an ingot
return Ok(());
}
Some(DiscoveredConfig::Invalid) | None => {}
}
// Recurse into subdirectories (sorted for deterministic discovery order)
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(_) => return Ok(()),
};
let mut subdirs: Vec<PathBuf> = entries
.filter_map(|e| e.ok())
.filter(|e| e.path().is_dir())
.filter(|e| {
let name = e.file_name();
let name_str = name.to_string_lossy();
!SKIP_DIRS.contains(&name_str.as_ref()) && !name_str.starts_with('.')
})
.map(|e| e.path())
.collect();
subdirs.sort();
for subdir in subdirs {
walk(&subdir, depth + 1, resolver, discovery)?;
}
Ok(())
}
walk(root, 0, resolver, discovery)
}
fn ancestor_root_for_src(path: &Path) -> Option<PathBuf> {
let mut current = path.parent();
while let Some(dir) = current {
if dir.file_name() == Some(std::ffi::OsStr::new("src")) {
return dir.parent().map(PathBuf::from);
}
current = dir.parent();
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn parse_workspace_settings(toml: &str) -> WorkspaceSettings {
let config = Config::parse(toml).expect("workspace config parses");
let Config::Workspace(workspace_config) = config else {
panic!("expected workspace config");
};
workspace_config.workspace.clone()
}
fn write_file(path: &Path, contents: &str) {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("create parent dirs");
}
fs::write(path, contents).expect("write file");
}
#[test]
fn discovers_workspace_root_above_member_ingot() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
write_file(
&root.join("fe.toml"),
r#"
[workspace]
members = ["ingots/*"]
"#,
);
write_file(
&root.join("ingots/app/fe.toml"),
r#"
[ingot]
name = "app"
version = "0.1.0"
"#,
);
fs::create_dir_all(root.join("ingots/app/src")).expect("create src dir");
let member_url = Url::from_directory_path(root.join("ingots/app")).expect("member url");
let discovery = discover_context(&member_url, false).expect("discover context");
let root_url = Url::from_directory_path(root).expect("root url");
assert_eq!(discovery.workspace_root, Some(root_url));
assert!(discovery.ingot_roots.contains(&member_url));
}
#[test]
fn discovers_workspace_root_even_if_nearest_config_is_invalid() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
write_file(
&root.join("fe.toml"),
r#"
[workspace]
members = ["ingots/*"]
"#,
);
write_file(&root.join("ingots/bad/fe.toml"), "not toml at all");
fs::create_dir_all(root.join("ingots/bad/src")).expect("create src dir");
let bad_url = Url::from_directory_path(root.join("ingots/bad")).expect("bad url");
let discovery = discover_context(&bad_url, false).expect("discover context");
let root_url = Url::from_directory_path(root).expect("root url");
assert_eq!(discovery.workspace_root, Some(root_url));
}
#[test]
fn expand_members_applies_exclude_patterns() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
fs::create_dir_all(root.join("ingots/app")).expect("create app dir");
fs::create_dir_all(root.join("ingots/bad")).expect("create bad dir");
let workspace = parse_workspace_settings(
r#"
[workspace]
members = ["ingots/*"]
exclude = ["ingots/bad"]
"#,
);
let root_url = Url::from_directory_path(root).expect("root url");
let members =
expand_workspace_members(&workspace, &root_url, WorkspaceMemberSelection::All)
.expect("expand members");
assert_eq!(members.len(), 1);
assert!(members[0].url.as_str().ends_with("/ingots/app/"));
}
#[test]
fn expand_members_deduplicates_overlapping_specs() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
fs::create_dir_all(root.join("ingots/app")).expect("create app dir");
let workspace = parse_workspace_settings(
r#"
[workspace]
members = ["ingots/*", "ingots/app"]
"#,
);
let root_url = Url::from_directory_path(root).expect("root url");
let members =
expand_workspace_members(&workspace, &root_url, WorkspaceMemberSelection::All)
.expect("expand members");
assert_eq!(members.len(), 1);
assert!(members[0].url.as_str().ends_with("/ingots/app/"));
}
#[test]
fn expand_members_default_only_filters_after_glob_expansion() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
fs::create_dir_all(root.join("ingots/app")).expect("create app dir");
fs::create_dir_all(root.join("ingots/lib")).expect("create lib dir");
let workspace = parse_workspace_settings(
r#"
[workspace]
members = ["ingots/*"]
default-members = ["ingots/app"]
"#,
);
let root_url = Url::from_directory_path(root).expect("root url");
let members =
expand_workspace_members(&workspace, &root_url, WorkspaceMemberSelection::DefaultOnly)
.expect("expand members");
assert_eq!(members.len(), 1);
assert_eq!(members[0].path, Utf8PathBuf::from("ingots").join("app"));
}
#[test]
fn expand_members_rejects_glob_when_name_is_specified() {
let tmp = tempfile::tempdir().expect("tempdir");
let root_url = Url::from_directory_path(tmp.path()).expect("root url");
let workspace = parse_workspace_settings(
r#"
[workspace]
members = [{ path = "ingots/*", name = "app" }]
"#,
);
let err = expand_workspace_members(&workspace, &root_url, WorkspaceMemberSelection::All)
.expect_err("expected error");
assert!(err.contains("cannot contain glob patterns"));
}
#[test]
fn expand_members_rejects_member_pattern_escaping_root() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
let outside = tempfile::tempdir_in(root.parent().expect("temp root has parent"))
.expect("outside tempdir");
let outside_name = outside
.path()
.file_name()
.expect("outside name")
.to_string_lossy()
.to_string();
let workspace = parse_workspace_settings(&format!(
r#"
[workspace]
members = ["../{outside_name}"]
"#
));
let root_url = Url::from_directory_path(root).expect("root url");
let err = expand_workspace_members(&workspace, &root_url, WorkspaceMemberSelection::All)
.expect_err("expected error");
assert!(err.contains("escapes workspace root"));
}
#[test]
fn expand_members_rejects_exclude_pattern_escaping_root() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
let outside = tempfile::tempdir_in(root.parent().expect("temp root has parent"))
.expect("outside tempdir");
let outside_name = outside
.path()
.file_name()
.expect("outside name")
.to_string_lossy()
.to_string();
let workspace = parse_workspace_settings(&format!(
r#"
[workspace]
members = ["ingots/*"]
exclude = ["../{outside_name}"]
"#
));
let root_url = Url::from_directory_path(root).expect("root url");
let err = expand_workspace_members(&workspace, &root_url, WorkspaceMemberSelection::All)
.expect_err("expected error");
assert!(err.contains("escapes workspace root"));
}
#[test]
fn discovers_nested_workspace_from_parent_directory() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
// Create a nested workspace: root/lessons/lesson1/fe.toml
write_file(
&root.join("lessons/lesson1/fe.toml"),
r#"
[workspace]
members = ["counter", "counter_user"]
"#,
);
fs::create_dir_all(root.join("lessons/lesson1/counter/src")).expect("create counter");
write_file(
&root.join("lessons/lesson1/counter/fe.toml"),
r#"
[ingot]
name = "counter"
version = "0.1.0"
"#,
);
fs::create_dir_all(root.join("lessons/lesson1/counter_user/src"))
.expect("create counter_user");
write_file(
&root.join("lessons/lesson1/counter_user/fe.toml"),
r#"
[ingot]
name = "counter_user"
version = "0.1.0"
"#,
);
// Discover from the parent root (no fe.toml here)
let root_url = Url::from_directory_path(root).expect("root url");
let discovery = discover_context(&root_url, true).expect("discover context");
let ws_url = Url::from_directory_path(root.join("lessons/lesson1")).expect("workspace url");
assert_eq!(discovery.workspace_root, Some(ws_url.clone()));
let counter_url =
Url::from_directory_path(root.join("lessons/lesson1/counter")).expect("counter url");
let counter_user_url = Url::from_directory_path(root.join("lessons/lesson1/counter_user"))
.expect("counter_user url");
assert!(
discovery.ingot_roots.contains(&ws_url),
"workspace root should be in ingot_roots"
);
assert!(
discovery.ingot_roots.contains(&counter_url),
"counter should be in ingot_roots"
);
assert!(
discovery.ingot_roots.contains(&counter_user_url),
"counter_user should be in ingot_roots"
);
}
#[test]
fn discovers_standalone_ingot_from_parent_directory() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
// Create a nested ingot without a workspace
fs::create_dir_all(root.join("projects/mylib/src")).expect("create mylib");
write_file(
&root.join("projects/mylib/fe.toml"),
r#"
[ingot]
name = "mylib"
version = "0.1.0"
"#,
);
let root_url = Url::from_directory_path(root).expect("root url");
let discovery = discover_context(&root_url, true).expect("discover context");
let mylib_url = Url::from_directory_path(root.join("projects/mylib")).expect("mylib url");
assert!(
discovery.ingot_roots.contains(&mylib_url),
"standalone ingot should be discovered"
);
assert!(
discovery.workspace_root.is_none(),
"no workspace root expected"
);
}
#[test]
fn discover_context_skips_noise_directories() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
// Put fe.toml in target/ and node_modules/ — should be skipped
write_file(
&root.join("target/fe.toml"),
"[ingot]\nname = \"bad\"\nversion = \"0.1.0\"",
);
write_file(
&root.join("node_modules/fe.toml"),
"[ingot]\nname = \"bad2\"\nversion = \"0.1.0\"",
);
write_file(
&root.join(".hidden/fe.toml"),
"[ingot]\nname = \"bad3\"\nversion = \"0.1.0\"",
);
// Real project
fs::create_dir_all(root.join("mylib/src")).expect("create mylib");
write_file(
&root.join("mylib/fe.toml"),
"[ingot]\nname = \"mylib\"\nversion = \"0.1.0\"",
);
let root_url = Url::from_directory_path(root).expect("root url");
let discovery = discover_context(&root_url, true).expect("discover context");
assert_eq!(discovery.ingot_roots.len(), 1, "only mylib should be found");
let mylib_url = Url::from_directory_path(root.join("mylib")).expect("mylib url");
assert!(discovery.ingot_roots.contains(&mylib_url));
}
#[test]
fn discover_context_multiple_workspaces_under_parent() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
// Two sibling workspaces under the root
write_file(
&root.join("ws_a/fe.toml"),
"[workspace]\nmembers = [\"app\"]",
);
fs::create_dir_all(root.join("ws_a/app")).expect("create ws_a/app");
write_file(
&root.join("ws_b/fe.toml"),
"[workspace]\nmembers = [\"lib\"]",
);
fs::create_dir_all(root.join("ws_b/lib")).expect("create ws_b/lib");
let root_url = Url::from_directory_path(root).expect("root url");
let discovery = discover_context(&root_url, true).expect("discover context");
// First workspace alphabetically should be primary
let ws_a_url = Url::from_directory_path(root.join("ws_a")).expect("ws_a url");
assert_eq!(
discovery.workspace_root,
Some(ws_a_url.clone()),
"first workspace alphabetically should be primary"
);
// Both workspaces and their members should be in ingot_roots
let ws_b_url = Url::from_directory_path(root.join("ws_b")).expect("ws_b url");
let app_url = Url::from_directory_path(root.join("ws_a/app")).expect("app url");
let lib_url = Url::from_directory_path(root.join("ws_b/lib")).expect("lib url");
assert!(discovery.ingot_roots.contains(&ws_a_url));
assert!(discovery.ingot_roots.contains(&app_url));
assert!(discovery.ingot_roots.contains(&ws_b_url));
assert!(discovery.ingot_roots.contains(&lib_url));
}
#[test]
fn discover_context_upward_takes_precedence_over_downward() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
// Workspace at root level
write_file(&root.join("fe.toml"), "[workspace]\nmembers = [\"app\"]");
fs::create_dir_all(root.join("app")).expect("create app");
// Nested workspace that should NOT be discovered (upward walk finds root first)
write_file(
&root.join("nested/fe.toml"),
"[workspace]\nmembers = [\"other\"]",
);
fs::create_dir_all(root.join("nested/other")).expect("create nested/other");
let root_url = Url::from_directory_path(root).expect("root url");
let discovery = discover_context(&root_url, true).expect("discover context");
// Upward walk finds workspace at root — downward scan should NOT run
assert_eq!(discovery.workspace_root, Some(root_url));
let nested_url = Url::from_directory_path(root.join("nested")).expect("nested url");
assert!(
!discovery.ingot_roots.contains(&nested_url),
"nested workspace should not be discovered when upward walk succeeds"
);
}
}