-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy pathpackages.rs
More file actions
1167 lines (1060 loc) · 44.5 KB
/
Copy pathpackages.rs
File metadata and controls
1167 lines (1060 loc) · 44.5 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
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
use super::build_types::*;
use super::namespaces;
use super::packages;
use crate::config;
use crate::config::Config;
use crate::helpers;
use crate::helpers::StrippedVerbatimPath;
use crate::helpers::emojis::*;
use crate::project_context::{MonoRepoContext, ProjectContext};
use ahash::{AHashMap, AHashSet};
use anyhow::{Result, anyhow};
use console::style;
use log::debug;
use rayon::prelude::*;
use std::collections::hash_map::Entry;
use std::error;
use std::fs::{self};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
#[derive(Debug, Clone)]
pub struct SourceFileMeta {
pub modified: SystemTime,
pub is_type_dev: bool,
}
#[derive(Debug, Clone)]
pub enum Namespace {
Namespace(String),
NamespaceWithEntry { namespace: String, entry: String },
NoNamespace,
}
impl Namespace {
pub fn to_suffix(&self) -> Option<String> {
match self {
Namespace::Namespace(namespace) => Some(namespace.to_string()),
Namespace::NamespaceWithEntry { namespace, entry: _ } => Some("@".to_string() + namespace),
Namespace::NoNamespace => None,
}
}
}
#[derive(Debug, Clone)]
struct Dependency {
name: String,
config: config::Config,
path: PathBuf,
dependencies: Vec<Dependency>,
is_local_dep: bool,
}
#[derive(Debug, Clone)]
pub struct Package {
pub name: String,
pub config: config::Config,
pub source_folders: AHashSet<config::PackageSource>,
// these are the relative file paths (relative to the package root)
pub source_files: Option<AHashMap<PathBuf, SourceFileMeta>>,
pub namespace: Namespace,
pub modules: Option<AHashSet<String>>,
// canonicalized dir of the package
pub path: PathBuf,
pub dirs: Option<AHashSet<PathBuf>>,
pub is_local_dep: bool,
pub is_root: bool,
}
pub fn get_build_path(canonical_path: &Path) -> PathBuf {
canonical_path.join("lib").join("bs")
}
pub fn get_js_path(canonical_path: &Path) -> PathBuf {
canonical_path.join("lib").join("js")
}
pub fn get_esmodule_path(canonical_path: &Path) -> PathBuf {
canonical_path.join("lib").join("es6")
}
pub fn get_ocaml_build_path(canonical_path: &Path) -> PathBuf {
canonical_path.join("lib").join("ocaml")
}
impl Package {
pub fn get_ocaml_build_path(&self) -> PathBuf {
get_ocaml_build_path(&self.path)
}
pub fn get_build_path(&self) -> PathBuf {
get_build_path(&self.path)
}
pub fn get_compiler_info_path(&self) -> PathBuf {
self.get_build_path().join("compiler-info.json")
}
pub fn get_js_path(&self) -> PathBuf {
get_js_path(&self.path)
}
pub fn get_esmodule_path(&self) -> PathBuf {
get_esmodule_path(&self.path)
}
pub fn get_mlmap_path(&self) -> PathBuf {
let suffix = self
.namespace
.to_suffix()
.expect("namespace should be set for mlmap module");
self.get_build_path().join(format!("{suffix}.mlmap"))
}
pub fn get_mlmap_compile_path(&self) -> PathBuf {
let suffix = self
.namespace
.to_suffix()
.expect("namespace should be set for mlmap module");
self.get_build_path().join(format!("{suffix}.cmi"))
}
pub fn is_source_file_type_dev(&self, path: &Path) -> bool {
self.source_files
.as_ref()
.and_then(|sf| sf.get(path).map(|sfm| sfm.is_type_dev))
.unwrap_or(false)
}
}
impl PartialEq for Package {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Eq for Package {}
impl Hash for Package {
fn hash<H: Hasher>(&self, _state: &mut H) {
blake3::hash(self.name.as_bytes());
}
}
fn matches_filter(filter: &Option<regex::Regex>, path: &str) -> bool {
match filter {
Some(filter) => filter.is_match(path),
None => true,
}
}
pub fn read_folders(
filter: &Option<regex::Regex>,
package_dir: &Path,
path: &Path,
recurse: bool,
is_type_dev: bool,
) -> Result<AHashMap<PathBuf, SourceFileMeta>, Box<dyn error::Error>> {
let mut map: AHashMap<PathBuf, SourceFileMeta> = AHashMap::new();
let path_buf = PathBuf::from(path);
let meta = fs::metadata(package_dir.join(path));
let path_with_meta = meta.map(|meta| {
(
path.to_owned(),
SourceFileMeta {
modified: meta.modified().unwrap(),
is_type_dev,
},
)
});
for entry in fs::read_dir(package_dir.join(&path_buf))? {
let entry_path_buf = entry.map(|entry| entry.path())?;
let metadata = fs::metadata(&entry_path_buf)?;
let name = entry_path_buf.file_name().unwrap().to_str().unwrap().to_string();
let path_ext = entry_path_buf.extension().and_then(|x| x.to_str());
let new_path = path_buf.join(&name);
if metadata.file_type().is_dir() && recurse {
match read_folders(filter, package_dir, &new_path, recurse, is_type_dev) {
Ok(s) => map.extend(s),
Err(e) => log::error!("Could not read directory: {e}"),
}
}
match path_ext {
Some(extension) if helpers::is_source_file(extension) => match path_with_meta {
Ok((ref path, _)) if matches_filter(filter, &name) => {
let mut path = path.to_owned();
path.push(&name);
map.insert(
path,
SourceFileMeta {
modified: metadata.modified().unwrap(),
is_type_dev,
},
);
}
Ok(_) => log::info!("Filtered: {name:?}"),
Err(ref e) => log::error!("Could not read directory: {e}"),
},
_ => (),
}
}
Ok(map)
}
/// Given a projects' root folder and a `config::Source`, this recursively creates all the
/// sources in a flat list. In the process, it removes the children, as they are being resolved
/// because of the recursiveness. So you get a flat list of files back, retaining the type_ and
/// whether it needs to recurse into all structures
fn get_source_dirs(source: config::Source, sub_path: Option<PathBuf>) -> AHashSet<config::PackageSource> {
let mut source_folders: AHashSet<config::PackageSource> = AHashSet::new();
let source_folder = source.to_qualified_without_children(sub_path.to_owned());
source_folders.insert(source_folder.to_owned());
let (subdirs, full_recursive) = match source.to_owned() {
config::Source::Shorthand(_)
| config::Source::Qualified(config::PackageSource { subdirs: None, .. }) => (None, false),
config::Source::Qualified(config::PackageSource {
subdirs: Some(config::Subdirs::Recurse(recurse)),
..
}) => (None, recurse),
config::Source::Qualified(config::PackageSource {
subdirs: Some(config::Subdirs::Qualified(subdirs)),
..
}) => (Some(subdirs), false),
};
if !full_recursive {
let sub_path = Path::new(&source_folder.dir).to_path_buf();
subdirs
.unwrap_or(vec![])
.par_iter()
.map(|subsource| {
get_source_dirs(subsource.set_type(source.get_type()), Some(sub_path.to_owned()))
})
.collect::<Vec<AHashSet<config::PackageSource>>>()
.into_iter()
.for_each(|subdir| source_folders.extend(subdir))
}
source_folders
}
pub fn read_config(package_dir: &Path) -> Result<Config> {
let rescript_json_path = package_dir.join("rescript.json");
Config::new(&rescript_json_path)
}
pub fn read_dependency(
package_name: &str,
package_config: &Config,
project_context: &ProjectContext,
) -> Result<PathBuf> {
let path = helpers::try_package_path(package_config, project_context, package_name)?;
let canonical_path = match path
.canonicalize()
.map(StrippedVerbatimPath::to_stripped_verbatim_path)
{
Ok(canonical_path) => Ok(canonical_path),
Err(e) => Err(anyhow!(
"Failed canonicalizing the package \"{}\" path \"{}\" (are node_modules up-to-date?)...\nMore details: {}",
package_name,
path.to_string_lossy(),
e
)),
}?;
Ok(canonical_path)
}
/// Given a config, recursively finds all dependencies.
/// 1. It starts with registering dependencies and
/// prevents the operation for the ones which are already
/// registered for the parent packages. Especially relevant for peerDependencies.
/// 2. In parallel performs IO to read the dependencies config and
/// recursively continues operation for their dependencies as well.
/// 3. Detects and warns about duplicate packages (same name, different paths).
fn read_dependencies(
registered_dependencies_set: &mut AHashSet<String>,
project_context: &ProjectContext,
package_config: &Config,
show_progress: bool,
is_local_dep: bool,
) -> Vec<Dependency> {
let mut dependencies = package_config.dependencies.to_owned().unwrap_or_default();
// Concatenate dev dependencies if is_local_dep is true
if is_local_dep && let Some(dev_deps) = package_config.dev_dependencies.to_owned() {
dependencies.extend(dev_deps);
}
dependencies
.iter()
.filter_map(|package_name| {
if registered_dependencies_set.contains(package_name) {
// Package already registered - check for duplicate (different path)
// Re-resolve from current package and from root to compare paths
if let Ok(current_path) = read_dependency(package_name, package_config, project_context)
&& let Ok(chosen_path) = read_dependency(package_name, &project_context.current_config, project_context)
&& current_path != chosen_path
{
// Different paths - this is a duplicate
let root_path = project_context.get_root_path();
let chosen_relative = chosen_path
.strip_prefix(root_path)
.unwrap_or(&chosen_path);
let duplicate_relative = current_path
.strip_prefix(root_path)
.unwrap_or(¤t_path);
let current_package_path = package_config
.path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let parent_relative = current_package_path
.strip_prefix(root_path)
.unwrap_or(¤t_package_path);
eprintln!(
"Duplicated package: {} ./{} (chosen) vs ./{} in ./{}",
package_name,
chosen_relative.to_string_lossy(),
duplicate_relative.to_string_lossy(),
parent_relative.to_string_lossy()
);
}
None
} else {
registered_dependencies_set.insert(package_name.to_owned());
Some(package_name.to_owned())
}
})
.collect::<Vec<String>>()
// Read all config files in parallel instead of blocking
.par_iter()
.map(|package_name| {
let (config, canonical_path) =
match read_dependency(package_name, package_config, project_context) {
Err(error) => {
if show_progress {
println!(
"{} {} Error building package tree. {}",
style("[1/2]").bold().dim(),
CROSS,
error
);
}
let parent_path_str = project_context.get_root_path().to_string_lossy();
log::error!(
"We could not build package tree reading dependency '{package_name}', at path '{parent_path_str}'. Error: {error}",
);
std::process::exit(2)
}
Ok(canonical_path) => {
match read_config(&canonical_path) {
Ok(config) => (config, canonical_path),
Err(error) => {
let parent_path_str = project_context.get_root_path().to_string_lossy();
log::error!(
"We could not build package tree '{package_name}', at path '{parent_path_str}'. Error: {error}",
);
std::process::exit(2)
}
}
}
};
let is_local_dep = {
match &project_context.monorepo_context {
None => project_context.current_config.name.as_str() == package_name
,
Some(MonoRepoContext::MonorepoRoot {
local_dependencies,
local_dev_dependencies,
}) => {
local_dependencies.contains(package_name) || local_dev_dependencies.contains(package_name)
},
Some(MonoRepoContext::MonorepoPackage {
parent_config,
}) => {
helpers::is_local_package(&parent_config.path, &canonical_path)
}
}
};
let dependencies = read_dependencies(
&mut registered_dependencies_set.to_owned(),
project_context,
&config,
show_progress,
is_local_dep,
);
Dependency {
name: package_name.to_owned(),
config,
path: canonical_path,
dependencies,
is_local_dep,
}
})
.collect()
}
fn flatten_dependencies(dependencies: Vec<Dependency>) -> Vec<Dependency> {
let mut flattened: Vec<Dependency> = Vec::new();
for dep in dependencies {
flattened.push(dep.clone());
let nested_flattened = flatten_dependencies(dep.dependencies);
flattened.extend(nested_flattened);
}
flattened
}
pub fn read_package_name(package_dir: &Path) -> Result<String> {
let read_name = |file_name: &str| -> Result<Option<String>> {
let path = package_dir.join(file_name);
if !Path::exists(&path) {
return Ok(None);
}
let contents =
fs::read_to_string(&path).map_err(|e| anyhow!("Could not read {}: {}", file_name, e))?;
let json: serde_json::Value =
serde_json::from_str(&contents).map_err(|e| anyhow!("Could not parse {}: {}", file_name, e))?;
Ok(json["name"].as_str().map(|name| name.to_string()))
};
if let Some(name) = read_name("package.json")? {
return Ok(name);
}
if let Some(name) = read_name("rescript.json")? {
return Ok(name);
}
Err(anyhow!(
"No name field found in package.json or rescript.json in {}",
package_dir.to_string_lossy()
))
}
fn make_package(
config: config::Config,
package_path: &Path,
is_root: bool,
is_local_dep: bool,
) -> Result<Package> {
let source_folders = match config.sources.to_owned() {
Some(config::OneOrMore::Single(source)) => get_source_dirs(source, None),
Some(config::OneOrMore::Multiple(sources)) => {
let mut source_folders: AHashSet<config::PackageSource> = AHashSet::new();
sources
.iter()
.map(|source| get_source_dirs(source.to_owned(), None))
.collect::<Vec<AHashSet<config::PackageSource>>>()
.into_iter()
.for_each(|source| source_folders.extend(source));
source_folders
}
None => {
if !is_root {
let package_path_str = package_path.to_string_lossy();
log::warn!(
"Package '{}' has not defined any sources, but is not the root package. This is likely a mistake. It is located: {}",
config.name,
package_path_str
);
}
AHashSet::new()
}
};
let package_name = read_package_name(package_path)?;
if package_name != config.name {
log::warn!(
"\nPackage name mismatch for {}:\n\
The package.json name is \"{}\", while the rescript.json name is \"{}\"\n\
This inconsistency will cause issues with package resolution.\n",
package_path.to_string_lossy(),
package_name,
config.name,
);
}
Ok(Package {
name: package_name,
config: config.to_owned(),
source_folders,
source_files: None,
namespace: config.get_namespace(),
modules: None,
// we canonicalize the path name so it's always the same
path: package_path
.canonicalize()
.map(StrippedVerbatimPath::to_stripped_verbatim_path)
.expect("Could not canonicalize"),
dirs: None,
is_local_dep,
is_root,
})
}
fn read_packages(project_context: &ProjectContext, show_progress: bool) -> Result<AHashMap<String, Package>> {
// Store all packages and completely deduplicate them
let mut map: AHashMap<String, Package> = AHashMap::new();
let current_package = {
let config = &project_context.current_config;
let folder = config
.path
.parent()
.ok_or_else(|| anyhow!("Could not the read parent folder or a rescript.json file"))?;
make_package(config.to_owned(), folder, true, true)?
};
map.insert(current_package.name.to_string(), current_package);
let mut registered_dependencies_set: AHashSet<String> = AHashSet::new();
let dependencies = flatten_dependencies(read_dependencies(
&mut registered_dependencies_set,
project_context,
&project_context.current_config,
show_progress,
/* is local dep */ true,
));
for d in dependencies.iter() {
if !map.contains_key(&d.name) {
let package = make_package(d.config.to_owned(), &d.path, false, d.is_local_dep)?;
map.insert(d.name.to_string(), package);
}
}
Ok(map)
}
/// `get_source_files` is essentially a wrapper around `read_structure`, which read a
/// list of files in a folder to a hashmap of `string` / `fs::Metadata` (file metadata). Reason for
/// this wrapper is the recursiveness of the `config.json` subfolders. Some sources in config
/// can be specified as being fully recursive (`{ subdirs: true }`). This wrapper pulls out that
/// data from the config and pushes it forwards. Another thing is the 'type_', some files / folders
/// can be marked with the type 'dev'. Which means that they may not be around in the distributed
/// NPM package. The file reader allows for this, just warns when this happens.
/// TODO -> Check whether we actually need the `fs::Metadata`
pub fn get_source_files(
package_name: &String,
package_dir: &Path,
filter: &Option<regex::Regex>,
source: &config::PackageSource,
build_dev_deps: bool,
) -> AHashMap<PathBuf, SourceFileMeta> {
let mut map: AHashMap<PathBuf, SourceFileMeta> = AHashMap::new();
let recurse = match source {
config::PackageSource {
subdirs: Some(config::Subdirs::Recurse(subdirs)),
..
} => *subdirs,
_ => false,
};
let path_dir = Path::new(&source.dir);
let is_type_dev = source.is_type_dev();
if !build_dev_deps && is_type_dev {
return map;
}
match read_folders(filter, package_dir, path_dir, recurse, is_type_dev) {
Ok(files) => map.extend(files),
Err(_e) => log::error!(
"Could not read folder: {:?}. Specified in dependency: {}, located {:?}...",
path_dir.to_path_buf().into_os_string(),
package_name,
package_dir
),
};
map
}
/// This takes the tree of packages, and finds all the source files for each, adding them to the
/// respective packages.
fn extend_with_children(
filter: &Option<regex::Regex>,
mut build: AHashMap<String, Package>,
) -> AHashMap<String, Package> {
for (_key, package) in build.iter_mut() {
let mut map: AHashMap<PathBuf, SourceFileMeta> = AHashMap::new();
package
.source_folders
.par_iter()
.map(|source| {
get_source_files(
&package.name,
Path::new(&package.path),
filter,
source,
package.is_local_dep,
)
})
.collect::<Vec<AHashMap<PathBuf, SourceFileMeta>>>()
.into_iter()
.for_each(|source| map.extend(source));
let mut modules = AHashSet::from_iter(
map.keys()
.map(|key| helpers::file_path_to_module_name(key, &package.namespace)),
);
match package.namespace.to_owned() {
Namespace::Namespace(namespace) => {
let _ = modules.insert(namespace);
}
Namespace::NamespaceWithEntry { namespace, entry: _ } => {
let _ = modules.insert("@".to_string() + &namespace);
}
Namespace::NoNamespace => (),
}
package.modules = Some(modules);
let mut dirs = AHashSet::new();
map.keys().for_each(|path| {
let dir = std::path::Path::new(&path).parent().unwrap();
dirs.insert(dir.to_owned());
});
package.dirs = Some(dirs);
package.source_files = Some(map);
}
build
}
/// Make turns a folder, that should contain a config, into a tree of Packages.
/// It does so in two steps:
/// 1. Get all the packages parsed, and take all the source folders from the config
/// 2. Take the (by then deduplicated) packages, and find all the '.res' and
/// interface files.
///
/// The two step process is there to reduce IO overhead.
pub fn make(
filter: &Option<regex::Regex>,
project_context: &ProjectContext,
show_progress: bool,
) -> Result<AHashMap<String, Package>> {
let map = read_packages(project_context, show_progress)?;
/* Once we have the deduplicated packages, we can add the source files for each - to minimize
* the IO */
let result = extend_with_children(filter, map);
Ok(result)
}
pub fn parse_packages(build_state: &mut BuildState) -> Result<()> {
let packages = build_state.packages.clone();
for (package_name, package) in packages.iter() {
debug!("Parsing package: {package_name}");
if let Some(package_modules) = package.modules.to_owned() {
build_state.module_names.extend(package_modules)
}
let build_path_abs = package.get_build_path();
let bs_build_path = package.get_ocaml_build_path();
helpers::create_path(&build_path_abs);
helpers::create_path(&bs_build_path);
let root_config = build_state.get_root_config();
root_config.get_package_specs().iter().for_each(|spec| {
if !spec.in_source {
// we don't want to calculate this if we don't have out of source specs
// we do this twice, but we almost never have multiple package specs
// so this optimization is less important
let relative_dirs: AHashSet<PathBuf> = match &package.source_files {
Some(source_files) => source_files
.keys()
.map(|source_file| {
Path::new(source_file)
.parent()
.expect("parent dir not found")
.to_owned()
})
.collect(),
_ => AHashSet::new(),
};
if spec.is_common_js() {
helpers::create_path(&package.get_js_path());
relative_dirs.iter().for_each(|path_buf| {
helpers::create_path_for_path(&Path::join(&package.get_js_path(), path_buf))
})
} else {
helpers::create_path(&package.get_esmodule_path());
relative_dirs.iter().for_each(|path_buf| {
helpers::create_path_for_path(&Path::join(&package.get_esmodule_path(), path_buf))
})
}
}
});
package.namespace.to_suffix().iter().for_each(|namespace| {
// generate the mlmap "AST" file for modules that have a namespace configured
let source_files = match package.source_files.to_owned() {
Some(source_files) => source_files
.keys()
.map(|key| key.to_owned())
.collect::<Vec<PathBuf>>(),
None => unreachable!(),
};
let entry = match &package.namespace {
packages::Namespace::NamespaceWithEntry { entry, namespace: _ } => Some(entry),
_ => None,
};
let depending_modules = source_files
.iter()
.map(|path| helpers::file_path_to_module_name(path, &packages::Namespace::NoNamespace))
.filter(|module_name| {
if let Some(entry) = entry {
module_name != entry
} else {
true
}
})
.filter(|module_name| helpers::is_non_exotic_module_name(module_name))
.collect::<AHashSet<String>>();
let mlmap = namespaces::gen_mlmap(package, namespace, &depending_modules);
// mlmap will be compiled in the AST generation step
// compile_mlmap(&package, namespace, &project_root);
let deps = source_files
.iter()
.filter(|path| {
helpers::is_non_exotic_module_name(&helpers::file_path_to_module_name(
path,
&packages::Namespace::NoNamespace,
))
})
.map(|path| helpers::file_path_to_module_name(path, &package.namespace))
.filter(|module_name| {
if let Some(entry) = entry {
module_name != entry
} else {
true
}
})
.collect::<AHashSet<String>>();
build_state.insert_module(
&helpers::file_path_to_module_name(&mlmap.to_owned(), &packages::Namespace::NoNamespace),
Module {
deps_dirty: false,
source_type: SourceType::MlMap(MlMap { parse_dirty: false }),
deps,
dependents: AHashSet::new(),
package_name: package.name.to_owned(),
compile_dirty: false,
last_compiled_cmt: None,
last_compiled_cmi: None,
// Not sure if this is correct
is_type_dev: false,
},
);
});
debug!("Building source file-tree for package: {}", package.name);
if let Some(source_files) = &package.source_files {
for (file, metadata) in source_files.iter() {
let namespace = package.namespace.to_owned();
let extension = file.extension().unwrap().to_str().unwrap();
let module_name = helpers::file_path_to_module_name(file, &namespace);
if helpers::is_implementation_file(extension) {
// Store duplicate paths in an Option so we can build the error after the entry borrow ends.
let mut duplicate_paths: Option<(PathBuf, PathBuf)> = None;
match build_state.modules.entry(module_name.to_string()) {
Entry::Occupied(mut entry) => {
let module = entry.get_mut();
if let SourceType::SourceFile(ref mut source_file) = module.source_type {
if &source_file.implementation.path != file {
duplicate_paths = Some((
Path::new(&package.path).join(&source_file.implementation.path),
Path::new(&package.path).join(file),
));
}
source_file.implementation.path = file.to_owned();
source_file.implementation.last_modified = metadata.modified;
source_file.implementation.parse_dirty = true;
}
}
Entry::Vacant(entry) => {
entry.insert(Module {
deps_dirty: true,
source_type: SourceType::SourceFile(SourceFile {
implementation: Implementation {
path: file.to_owned(),
parse_state: ParseState::Pending,
compile_state: CompileState::Pending,
last_modified: metadata.modified,
parse_dirty: true,
compile_warnings: None,
},
interface: None,
}),
deps: AHashSet::new(),
dependents: AHashSet::new(),
package_name: package.name.to_owned(),
compile_dirty: true,
last_compiled_cmt: None,
last_compiled_cmi: None,
is_type_dev: metadata.is_type_dev,
});
}
}
if let Some((existing_path, duplicate_path)) = duplicate_paths {
let root_path = build_state.get_root_config().path.clone();
let root = root_path.parent().map(PathBuf::from).unwrap_or(root_path);
let existing_display = existing_path.strip_prefix(&root).unwrap_or(&existing_path);
let duplicate_display = duplicate_path.strip_prefix(&root).unwrap_or(&duplicate_path);
let mut first = existing_display.to_string_lossy().to_string();
let mut second = duplicate_display.to_string_lossy().to_string();
if second < first {
std::mem::swap(&mut first, &mut second);
}
return Err(anyhow!(
"Duplicate module name: {module_name}. Found in {} and {}. Rename one of these files.",
first,
second
));
}
} else {
// remove last character of string: resi -> res
let mut implementation_filename = file.to_owned();
let extension = implementation_filename.extension().unwrap().to_str().unwrap();
implementation_filename = match extension {
"resi" => implementation_filename.with_extension("res"),
_ => implementation_filename,
};
match source_files.get(&implementation_filename) {
None => {
if let Some(implementation_path) = source_files.keys().find(|path| {
let extension = path.extension().and_then(|ext| ext.to_str());
matches!(extension, Some(ext) if helpers::is_implementation_file(ext))
&& helpers::file_path_to_module_name(path, &namespace) == module_name
}) {
let implementation_display =
implementation_path.to_string_lossy().to_string();
let interface_display = file.to_string_lossy().to_string();
return Err(anyhow!(
"Implementation and interface have different path names or different cases: `{}` vs `{}`",
implementation_display,
interface_display
));
}
println!(
"{} No implementation file found for interface file (skipping): {}",
LINE_CLEAR,
file.to_string_lossy()
)
}
Some(_) => {
build_state
.modules
.entry(module_name.to_string())
.and_modify(|module| {
if let SourceType::SourceFile(ref mut source_file) = module.source_type {
source_file.interface = Some(Interface {
path: file.to_owned(),
parse_state: ParseState::Pending,
compile_state: CompileState::Pending,
last_modified: metadata.modified,
parse_dirty: true,
compile_warnings: None,
});
}
})
.or_insert(Module {
deps_dirty: true,
source_type: SourceType::SourceFile(SourceFile {
// this will be overwritten later
implementation: Implementation {
path: implementation_filename,
parse_state: ParseState::Pending,
compile_state: CompileState::Pending,
last_modified: metadata.modified,
parse_dirty: true,
compile_warnings: None,
},
interface: Some(Interface {
path: file.to_owned(),
parse_state: ParseState::Pending,
compile_state: CompileState::Pending,
last_modified: metadata.modified,
parse_dirty: true,
compile_warnings: None,
}),
}),
deps: AHashSet::new(),
dependents: AHashSet::new(),
package_name: package.name.to_owned(),
compile_dirty: true,
last_compiled_cmt: None,
last_compiled_cmi: None,
is_type_dev: metadata.is_type_dev,
});
}
}
}
}
}
}
Ok(())
}
impl Package {
pub fn get_jsx_args(&self) -> Vec<String> {
self.config.get_jsx_args()
}
pub fn get_jsx_mode_args(&self) -> Vec<String> {
self.config.get_jsx_mode_args()
}
pub fn get_jsx_module_args(&self) -> Vec<String> {
self.config.get_jsx_module_args()
}
pub fn get_jsx_preserve_args(&self) -> Vec<String> {
self.config.get_jsx_preserve_args()
}
}
fn get_unallowed_dependents(
packages: &AHashMap<String, Package>,
package_name: &String,
dependencies: &Vec<String>,
) -> Option<String> {
for deps_package_name in dependencies {
if let Some(deps_package) = packages.get(deps_package_name) {
let deps_allowed_dependents = deps_package.config.allowed_dependents.to_owned();
if let Some(allowed_dependents) = deps_allowed_dependents
&& !allowed_dependents.contains(package_name)
{
return Some(deps_package_name.to_string());
}
}
}
None
}
#[derive(Debug, Clone)]
struct UnallowedDependency {
deps: Vec<String>,
dev_deps: Vec<String>,
}
pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> bool {
let mut detected_unallowed_dependencies: AHashMap<String, UnallowedDependency> = AHashMap::new();
for (package_name, package) in packages {
let dependencies = &package.config.dependencies.to_owned().unwrap_or(vec![]);
let dev_dependencies = &package.config.dev_dependencies.to_owned().unwrap_or(vec![]);
[
("dependencies", dependencies),
("dev-dependencies", dev_dependencies),
]
.iter()
.for_each(|(dependency_type, dependencies)| {
if let Some(unallowed_dependency_name) =
get_unallowed_dependents(packages, package_name, dependencies)
{
let empty_unallowed_deps = UnallowedDependency {
deps: vec![],
dev_deps: vec![],
};
let unallowed_dependency = detected_unallowed_dependencies.entry(String::from(package_name));
let value = unallowed_dependency.or_insert_with(|| empty_unallowed_deps);
match *dependency_type {
"dependencies" => value.deps.push(unallowed_dependency_name),
"dev-dependencies" => value.dev_deps.push(unallowed_dependency_name),
_ => (),
}
}
});
}
for (package_name, unallowed_deps) in detected_unallowed_dependencies.iter() {
log::error!(
"\n{}: {} has the following unallowed dependencies:",
console::style("Error").red(),
console::style(package_name).bold()
);