forked from rescript-lang/rescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
1473 lines (1338 loc) · 47 KB
/
config.rs
File metadata and controls
1473 lines (1338 loc) · 47 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 crate::build::packages;
use crate::helpers;
use crate::helpers::deserialize::*;
use crate::project_context::ProjectContext;
use anyhow::{Result, anyhow, bail};
use convert_case::{Case, Casing};
use serde::de::{Error as DeError, Visitor};
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::fs;
use std::path::{MAIN_SEPARATOR, Path, PathBuf};
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum OneOrMore<T> {
Multiple(Vec<T>),
Single(T),
}
#[derive(Deserialize, Debug, Clone, PartialEq, Hash)]
#[serde(untagged)]
pub enum Subdirs {
Qualified(Vec<Source>),
Recurse(bool),
}
impl Eq for Subdirs {}
#[derive(Deserialize, Debug, Clone, PartialEq, Hash)]
pub struct PackageSource {
pub dir: String,
pub subdirs: Option<Subdirs>,
#[serde(rename = "type")]
pub type_: Option<String>,
}
impl PackageSource {
pub fn is_type_dev(&self) -> bool {
match &self.type_ {
Some(type_) => type_ == "dev",
None => false,
}
}
}
impl Eq for PackageSource {}
#[derive(Deserialize, Debug, Clone, PartialEq, Hash)]
#[serde(untagged)]
pub enum Source {
Shorthand(String),
Qualified(PackageSource),
}
impl Source {
/// When reading, we should propagate the sources all the way through the tree
pub fn get_type(&self) -> Option<String> {
match self {
Source::Shorthand(_) => None,
Source::Qualified(PackageSource { type_, .. }) => type_.clone(),
}
}
pub fn set_type(&self, type_: Option<String>) -> Source {
match (self, type_) {
(Source::Shorthand(dir), Some(type_)) => Source::Qualified(PackageSource {
dir: dir.to_string(),
subdirs: None,
type_: Some(type_),
}),
(Source::Qualified(package_source), type_) => Source::Qualified(PackageSource {
type_,
..package_source.clone()
}),
(source, _) => source.clone(),
}
}
/// `to_qualified_without_children` takes a tree like structure of dependencies, coming in from
/// `bsconfig`, and turns it into a flat list. The main thing we extract here are the source
/// folders, and optional subdirs, where potentially, the subdirs recurse or not.
pub fn to_qualified_without_children(&self, sub_path: Option<PathBuf>) -> PackageSource {
match self {
Source::Shorthand(dir) => PackageSource {
dir: sub_path
.map(|p| p.join(Path::new(dir)))
.unwrap_or(Path::new(dir).to_path_buf())
.to_string_lossy()
.to_string(),
subdirs: None,
type_: self.get_type(),
},
Source::Qualified(PackageSource {
dir,
type_,
subdirs: Some(Subdirs::Recurse(should_recurse)),
}) => PackageSource {
dir: sub_path
.map(|p| p.join(Path::new(dir)))
.unwrap_or(Path::new(dir).to_path_buf())
.to_string_lossy()
.to_string(),
subdirs: Some(Subdirs::Recurse(*should_recurse)),
type_: type_.to_owned(),
},
Source::Qualified(PackageSource { dir, type_, .. }) => PackageSource {
dir: sub_path
.map(|p| p.join(Path::new(dir)))
.unwrap_or(Path::new(dir).to_path_buf())
.to_string_lossy()
.to_string(),
subdirs: None,
type_: type_.to_owned(),
},
}
}
fn find_is_type_dev_for_sub_folder(
&self,
relative_parent_path: &Path,
target_source_folder: &Path,
) -> bool {
match &self {
Source::Shorthand(sub_folder) => {
relative_parent_path.join(Path::new(sub_folder)) == *target_source_folder
}
Source::Qualified(package_source) => {
// Note that we no longer check if type_ is dev of the nested subfolder.
// A parent was type:dev, so we assume all subfolders are as well.
let next_parent_path = relative_parent_path.join(Path::new(&package_source.dir));
if next_parent_path == *target_source_folder {
return true;
};
match &package_source.subdirs {
None => false,
Some(Subdirs::Recurse(false)) => false,
Some(Subdirs::Recurse(true)) => target_source_folder.starts_with(&next_parent_path),
Some(Subdirs::Qualified(nested_sources)) => nested_sources.iter().any(|nested_source| {
nested_source.find_is_type_dev_for_sub_folder(&next_parent_path, target_source_folder)
}),
}
}
}
}
}
impl Eq for Source {}
#[derive(Deserialize, Debug, Clone)]
pub struct PackageSpec {
pub module: String,
#[serde(rename = "in-source", default = "default_true")]
pub in_source: bool,
pub suffix: Option<String>,
}
impl PackageSpec {
pub fn get_out_of_source_dir(&self) -> String {
match self.module.as_str() {
"commonjs" => "js",
_ => "es6",
}
.to_string()
}
pub fn is_common_js(&self) -> bool {
self.module.as_str() == "commonjs"
}
pub fn get_suffix(&self) -> Option<String> {
self.suffix.to_owned()
}
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Error {
Catchall(bool),
Qualified(String),
}
#[derive(Deserialize, Debug, Clone)]
pub struct Warnings {
pub number: Option<String>,
pub error: Option<Error>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum NamespaceConfig {
Bool(bool),
String(String),
}
#[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum JsxMode {
Classic,
Automatic,
}
#[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum JsxModule {
React,
Other(String),
}
#[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct JsxSpecs {
pub version: Option<i32>,
pub module: Option<JsxModule>,
pub mode: Option<JsxMode>,
#[serde(rename = "v3-dependencies")]
pub v3_dependencies: Option<Vec<String>>,
pub preserve: Option<bool>,
}
/// We do not care about the internal structure because the gentype config is loaded by bsc.
pub type GenTypeConfig = serde_json::Value;
/// Configuration for running a command after each JavaScript file is compiled.
/// Note: Unlike bsb, rewatch passes absolute paths to the command for clarity.
#[derive(Deserialize, Debug, Clone)]
pub struct JsPostBuild {
pub cmd: String,
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum DeprecationWarning {
BsDependencies,
BsDevDependencies,
BscFlags,
PackageSpecsEs6,
PackageSpecsEs6Global,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum ExperimentalFeature {
LetUnwrap,
}
impl<'de> serde::Deserialize<'de> for ExperimentalFeature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EFVisitor;
impl<'de> Visitor<'de> for EFVisitor {
type Value = ExperimentalFeature;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a valid experimental feature id (e.g. LetUnwrap)")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: DeError,
{
match v {
"LetUnwrap" => Ok(ExperimentalFeature::LetUnwrap),
other => {
let available = ["LetUnwrap"].join(", ");
Err(DeError::custom(format!(
"Unknown experimental feature '{other}'. Available features: {available}",
)))
}
}
}
}
deserializer.deserialize_any(EFVisitor)
}
}
/// # rescript.json representation
/// This is tricky, there is a lot of ambiguity. This is probably incomplete.
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Config {
pub name: String,
// In the case of monorepos, the root source won't necessarily have to have sources. It can
// just be sources in packages
pub sources: Option<OneOrMore<Source>>,
#[serde(rename = "package-specs")]
pub package_specs: Option<OneOrMore<PackageSpec>>,
pub warnings: Option<Warnings>,
pub suffix: Option<String>,
pub dependencies: Option<Vec<String>>,
#[serde(rename = "dev-dependencies")]
pub dev_dependencies: Option<Vec<String>>,
// Deprecated field: overwrites dependencies
#[serde(rename = "bs-dependencies")]
bs_dependencies: Option<Vec<String>>,
// Deprecated field: overwrites dev_dependencies
#[serde(rename = "bs-dev-dependencies")]
bs_dev_dependencies: Option<Vec<String>>,
#[serde(rename = "ppx-flags")]
pub ppx_flags: Option<Vec<OneOrMore<String>>>,
#[serde(rename = "compiler-flags")]
pub compiler_flags: Option<Vec<OneOrMore<String>>>,
// Deprecated field: overwrites compiler_flags
#[serde(rename = "bsc-flags")]
bsc_flags: Option<Vec<OneOrMore<String>>>,
pub namespace: Option<NamespaceConfig>,
pub jsx: Option<JsxSpecs>,
#[serde(rename = "experimental-features")]
pub experimental_features: Option<HashMap<ExperimentalFeature, bool>>,
#[serde(rename = "gentypeconfig")]
pub gentype_config: Option<GenTypeConfig>,
#[serde(rename = "js-post-build")]
pub js_post_build: Option<JsPostBuild>,
// Used by the VS Code extension; ignored by rewatch but should not emit warnings.
// Payload is not validated here, only in the VS Code extension.
pub editor: Option<serde_json::Value>,
// this is a new feature of rewatch, and it's not part of the rescript.json spec
#[serde(rename = "namespace-entry")]
pub namespace_entry: Option<String>,
// this is a new feature of rewatch, and it's not part of the rescript.json spec
#[serde(rename = "allowed-dependents")]
pub allowed_dependents: Option<Vec<String>>,
// Holds all deprecation warnings for the config struct
#[serde(skip)]
deprecation_warnings: Vec<DeprecationWarning>,
// Holds unknown fields we encountered while parsing
#[serde(skip, default)]
unknown_fields: Vec<String>,
#[serde(default = "default_path")]
pub path: PathBuf,
}
fn default_path() -> PathBuf {
PathBuf::from("./rescript.json")
}
/// This flattens string flags
pub fn flatten_flags(flags: &Option<Vec<OneOrMore<String>>>) -> Vec<String> {
match flags {
None => vec![],
Some(xs) => xs
.iter()
.flat_map(|x| match x {
OneOrMore::Single(y) => vec![y.to_owned()],
OneOrMore::Multiple(ys) => ys.to_owned(),
})
.collect::<Vec<String>>()
.iter()
.flat_map(|str| str.split(' '))
.map(|str| str.to_string())
.collect::<Vec<String>>(),
}
}
/// Since ppx-flags could be one or more, and could potentially be nested, this function takes the
/// flags and flattens them.
pub fn flatten_ppx_flags(
project_context: &ProjectContext,
package_config: &Config,
flags: &Option<Vec<OneOrMore<String>>>,
) -> Result<Vec<String>> {
match flags {
None => Ok(vec![]),
Some(flags) => flags.iter().try_fold(Vec::new(), |mut acc, x| {
match x {
OneOrMore::Single(y) => {
let first_character = y.chars().next();
match first_character {
Some('.') => {
let path = helpers::try_package_path(
package_config,
project_context,
&format!("{}{}{}", &package_config.name, MAIN_SEPARATOR, y),
)
.map(|p| p.to_string_lossy().to_string())?;
acc.push(String::from("-ppx"));
acc.push(path);
}
_ => {
acc.push(String::from("-ppx"));
let path = helpers::try_package_path(package_config, project_context, y)
.map(|p| p.to_string_lossy().to_string())?;
acc.push(path);
}
}
}
OneOrMore::Multiple(ys) if ys.is_empty() => (),
OneOrMore::Multiple(ys) => {
let first_character = ys[0].chars().next();
let ppx = match first_character {
Some('.') => helpers::try_package_path(
package_config,
project_context,
&format!("{}{}{}", package_config.name, MAIN_SEPARATOR, &ys[0]),
)
.map(|p| p.to_string_lossy().to_string())?,
_ => helpers::try_package_path(package_config, project_context, &ys[0])
.map(|p| p.to_string_lossy().to_string())?,
};
acc.push(String::from("-ppx"));
acc.push(
vec![ppx]
.into_iter()
.chain(ys[1..].to_owned())
.collect::<Vec<String>>()
.join(" "),
);
}
};
Ok(acc)
}),
}
}
fn namespace_from_package_name(package_name: &str) -> String {
let len = package_name.len();
let mut buf = String::with_capacity(len);
fn aux(s: &str, capital: bool, buf: &mut String, off: usize) {
if off >= s.len() {
return;
}
let ch = s.as_bytes()[off] as char;
match ch {
'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => {
let new_capital = false;
buf.push(if capital { ch.to_ascii_uppercase() } else { ch });
aux(s, new_capital, buf, off + 1);
}
'/' | '-' => {
aux(s, true, buf, off + 1);
}
_ => {
aux(s, capital, buf, off + 1);
}
}
}
aux(package_name, true, &mut buf, 0);
buf
}
impl Config {
/// Try to convert a bsconfig from a certain path to a bsconfig struct
pub fn new(path: &Path) -> Result<Self> {
let read = fs::read_to_string(path)?;
let mut config = Config::new_from_json_string(&read)?;
config.set_path(path.to_path_buf())?;
Ok(config)
}
/// Try to convert a bsconfig from a string to a bsconfig struct
pub fn new_from_json_string(config_str: &str) -> Result<Self> {
let mut deserializer = serde_json::Deserializer::from_str(config_str);
let mut tracker = serde_path_to_error::Track::new();
let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
let mut unknown_fields = Vec::new();
let mut config: Config =
serde_ignored::deserialize(path_deserializer, |path| unknown_fields.push(path.to_string()))
.map_err(|err: serde_json::Error| {
let path = tracker.path().to_string();
if path.is_empty() {
anyhow!("Failed to parse rescript.json: {err}")
} else {
anyhow!("Failed to parse rescript.json at {path}: {err}")
}
})?;
config.handle_deprecations()?;
config.unknown_fields = unknown_fields;
Ok(config)
}
fn set_path(&mut self, path: PathBuf) -> Result<()> {
self.path = path;
Ok(())
}
pub fn get_namespace(&self) -> packages::Namespace {
let namespace_from_package = namespace_from_package_name(&self.name);
match (self.namespace.as_ref(), self.namespace_entry.as_ref()) {
(Some(NamespaceConfig::Bool(false)), _) => packages::Namespace::NoNamespace,
(None, _) => packages::Namespace::NoNamespace,
(Some(NamespaceConfig::Bool(true)), None) => {
packages::Namespace::Namespace(namespace_from_package)
}
(Some(NamespaceConfig::Bool(true)), Some(entry)) => packages::Namespace::NamespaceWithEntry {
namespace: namespace_from_package,
entry: entry.to_string(),
},
(Some(NamespaceConfig::String(str)), None) => match str.as_str() {
"true" => packages::Namespace::Namespace(namespace_from_package),
namespace if namespace.is_case(Case::UpperFlat) => {
packages::Namespace::Namespace(namespace.to_string())
}
namespace => packages::Namespace::Namespace(namespace_from_package_name(namespace)),
},
(Some(self::NamespaceConfig::String(str)), Some(entry)) => match str.as_str() {
"true" => packages::Namespace::NamespaceWithEntry {
namespace: namespace_from_package,
entry: entry.to_string(),
},
namespace if namespace.is_case(Case::UpperFlat) => packages::Namespace::NamespaceWithEntry {
namespace: namespace.to_string(),
entry: entry.to_string(),
},
namespace => packages::Namespace::NamespaceWithEntry {
namespace: namespace.to_string().to_case(Case::Pascal),
entry: entry.to_string(),
},
},
}
}
pub fn get_jsx_args(&self) -> Vec<String> {
match self.jsx.to_owned() {
Some(jsx) => match jsx.version {
Some(version) if version == 4 => {
vec!["-bs-jsx".to_string(), version.to_string()]
}
Some(version) => panic!("JSX version {version} is unsupported"),
None => vec![],
},
None => vec![],
}
}
pub fn get_jsx_mode_args(&self) -> Vec<String> {
match self.jsx.to_owned() {
Some(jsx) => match jsx.mode {
Some(JsxMode::Classic) => {
vec!["-bs-jsx-mode".to_string(), "classic".to_string()]
}
Some(JsxMode::Automatic) => {
vec!["-bs-jsx-mode".to_string(), "automatic".to_string()]
}
None => vec![],
},
_ => vec![],
}
}
pub fn get_jsx_module_args(&self) -> Vec<String> {
match self.jsx.to_owned() {
Some(jsx) => match jsx.module {
Some(JsxModule::React) => {
vec!["-bs-jsx-module".to_string(), "react".to_string()]
}
Some(JsxModule::Other(module)) => {
vec!["-bs-jsx-module".to_string(), module]
}
None => vec![],
},
_ => vec![],
}
}
pub fn get_jsx_preserve_args(&self) -> Vec<String> {
match self.jsx.to_owned() {
Some(jsx) => match jsx.preserve {
Some(true) => vec!["-bs-jsx-preserve".to_string()],
_ => vec![],
},
_ => vec![],
}
}
pub fn get_experimental_features_args(&self) -> Vec<String> {
match &self.experimental_features {
None => vec![],
Some(map) => map
.iter()
.filter_map(|(k, v)| if *v { Some(k) } else { None })
.flat_map(|feature| {
vec![
"-enable-experimental".to_string(),
match feature {
ExperimentalFeature::LetUnwrap => "LetUnwrap",
}
.to_string(),
]
})
.collect(),
}
}
pub fn get_gentype_arg(&self) -> Vec<String> {
match &self.gentype_config {
Some(_) => vec!["-bs-gentype".to_string()],
None => vec![],
}
}
pub fn get_warning_args(&self, is_local_dep: bool, warn_error_override: Option<String>) -> Vec<String> {
// Ignore warning config for non local dependencies (node_module dependencies)
if !is_local_dep {
return vec![];
}
// Command-line --warn-error flag takes precedence over rescript.json configuration
// This follows the same precedence behavior as the legacy bsb build system
if let Some(warn_error_str) = warn_error_override {
return vec!["-warn-error".to_string(), warn_error_str];
}
match self.warnings {
None => vec![],
Some(ref warnings) => {
let warn_number = match warnings.number {
None => vec![],
Some(ref warnings) => {
vec!["-w".to_string(), warnings.to_string()]
}
};
let warn_error = match warnings.error {
Some(Error::Catchall(true)) => {
vec!["-warn-error".to_string(), "A".to_string()]
}
Some(Error::Qualified(ref errors)) => {
vec!["-warn-error".to_string(), errors.to_string()]
}
_ => vec![],
};
[warn_number, warn_error].concat()
}
}
}
pub fn get_package_specs(&self) -> Vec<PackageSpec> {
match self.package_specs.clone() {
None => vec![PackageSpec {
module: "commonjs".to_string(),
in_source: true,
suffix: Some(".js".to_string()),
}],
Some(OneOrMore::Single(spec)) => vec![spec],
Some(OneOrMore::Multiple(vec)) => vec,
}
}
pub fn get_suffix(&self, spec: &PackageSpec) -> String {
spec.get_suffix()
.or(self.suffix.clone())
.unwrap_or(".js".to_string())
}
pub fn find_is_type_dev_for_path(&self, relative_path: &Path) -> bool {
let relative_parent = match relative_path.parent() {
None => return false,
Some(parent) => Path::new(parent),
};
let package_sources = match self.sources.as_ref() {
None => vec![],
Some(OneOrMore::Single(Source::Shorthand(_))) => vec![],
Some(OneOrMore::Single(Source::Qualified(source))) => vec![source],
Some(OneOrMore::Multiple(multiple)) => multiple
.iter()
.filter_map(|source| match source {
Source::Shorthand(_) => None,
Source::Qualified(package_source) => Some(package_source),
})
.collect(),
};
package_sources.iter().any(|package_source| {
if !package_source.is_type_dev() {
false
} else {
let dir_path = Path::new(&package_source.dir);
if dir_path == relative_parent {
return true;
};
match &package_source.subdirs {
None => false,
Some(Subdirs::Recurse(false)) => false,
Some(Subdirs::Recurse(true)) => relative_path.starts_with(dir_path),
Some(Subdirs::Qualified(sub_dirs)) => sub_dirs
.iter()
.any(|sub_dir| sub_dir.find_is_type_dev_for_sub_folder(dir_path, relative_parent)),
}
}
})
}
pub fn get_deprecations(&self) -> &[DeprecationWarning] {
&self.deprecation_warnings
}
pub fn get_unknown_fields(&self) -> Vec<String> {
self.unknown_fields
.iter()
.filter(|field| !self.is_unsupported_field(field))
.cloned()
.collect()
}
pub fn get_unsupported_fields(&self) -> Vec<String> {
self.unknown_fields
.iter()
.filter(|field| self.is_unsupported_field(field))
.cloned()
.collect::<Vec<_>>()
}
fn is_unsupported_field(&self, field: &str) -> bool {
const UNSUPPORTED_TOP_LEVEL_FIELDS: &[&str] = &[
"ignored-dirs",
"generators",
"cut-generators",
"pp-flags",
"entries",
"use-stdlib",
"external-stdlib",
"bs-external-includes",
"reanalyze",
];
let top_level = field.split(|c| ['.', '['].contains(&c)).next().unwrap_or(field);
UNSUPPORTED_TOP_LEVEL_FIELDS.contains(&top_level)
}
fn handle_deprecations(&mut self) -> Result<()> {
if self.dependencies.is_some() && self.bs_dependencies.is_some() {
bail!("dependencies and bs-dependencies are mutually exclusive. Please use 'dependencies'.");
}
if self.dev_dependencies.is_some() && self.bs_dev_dependencies.is_some() {
bail!(
"dev-dependencies and bs-dev-dependencies are mutually exclusive. Please use 'dev-dependencies'"
);
}
if self.compiler_flags.is_some() && self.bsc_flags.is_some() {
bail!("compiler-flags and bsc-flags are mutually exclusive. Please use 'compiler-flags'");
}
if self.bs_dependencies.is_some() {
self.dependencies = self.bs_dependencies.take();
self.deprecation_warnings.push(DeprecationWarning::BsDependencies);
}
if self.bs_dev_dependencies.is_some() {
self.dev_dependencies = self.bs_dev_dependencies.take();
self.deprecation_warnings
.push(DeprecationWarning::BsDevDependencies);
}
if self.bsc_flags.is_some() {
self.compiler_flags = self.bsc_flags.take();
self.deprecation_warnings.push(DeprecationWarning::BscFlags);
}
let (has_es6, has_es6_global) = match &self.package_specs {
None => (false, false),
Some(OneOrMore::Single(spec)) => (spec.module == "es6", spec.module == "es6-global"),
Some(OneOrMore::Multiple(specs)) => (
specs.iter().any(|spec| spec.module == "es6"),
specs.iter().any(|spec| spec.module == "es6-global"),
),
};
if has_es6 {
self.deprecation_warnings
.push(DeprecationWarning::PackageSpecsEs6);
}
if has_es6_global {
self.deprecation_warnings
.push(DeprecationWarning::PackageSpecsEs6Global);
}
Ok(())
}
}
#[cfg(test)]
pub mod tests {
use super::*;
pub struct CreateConfigArgs {
pub name: String,
pub bs_deps: Vec<String>,
pub build_dev_deps: Vec<String>,
pub allowed_dependents: Option<Vec<String>>,
pub path: PathBuf,
}
pub fn create_config(args: CreateConfigArgs) -> Config {
Config {
name: args.name,
sources: Some(crate::config::OneOrMore::Single(Source::Shorthand(String::from(
"Source",
)))),
package_specs: None,
warnings: None,
suffix: None,
dependencies: Some(args.bs_deps),
dev_dependencies: Some(args.build_dev_deps),
bs_dependencies: None,
bs_dev_dependencies: None,
ppx_flags: None,
compiler_flags: None,
bsc_flags: None,
namespace: None,
jsx: None,
gentype_config: None,
js_post_build: None,
editor: None,
namespace_entry: None,
deprecation_warnings: vec![],
experimental_features: None,
allowed_dependents: args.allowed_dependents,
unknown_fields: vec![],
path: args.path,
}
}
#[test]
fn test_getters() {
let json = r#"
{
"name": "my-monorepo",
"sources": [ { "dir": "src/", "subdirs": true } ],
"package-specs": [ { "module": "es6", "in-source": true } ],
"suffix": ".mjs",
"dependencies": [ "@teamwalnut/app" ]
}
"#;
let config = serde_json::from_str::<Config>(json).unwrap();
let specs = config.get_package_specs();
assert_eq!(specs.len(), 1);
let spec = specs.first().unwrap();
assert_eq!(spec.module, "es6");
assert_eq!(config.get_suffix(spec), ".mjs");
}
#[test]
fn test_sources() {
let json = r#"
{
"name": "@rescript/core",
"version": "0.5.0",
"sources": {
"dir": "test",
"subdirs": ["intl"],
"type": "dev"
},
"suffix": ".mjs",
"package-specs": {
"module": "esmodule",
"in-source": true
},
"dev-dependencies": ["@rescript/tools"],
"warnings": {
"error": "+101"
}
}
"#;
let config = serde_json::from_str::<Config>(json).unwrap();
if let Some(OneOrMore::Single(source)) = config.sources {
let source = source.to_qualified_without_children(None);
assert_eq!(source.type_, Some(String::from("dev")));
} else {
dbg!(config.sources);
unreachable!()
}
}
#[test]
fn test_dev_sources_multiple() {
let json = r#"
{
"name": "@rescript/core",
"version": "0.5.0",
"sources": [
{ "dir": "src" },
{ "dir": "test", "type": "dev" }
],
"package-specs": {
"module": "esmodule",
"in-source": true
},
"dev-dependencies": ["@rescript/tools"],
"suffix": ".mjs",
"warnings": {
"error": "+101"
}
}
"#;
let config = serde_json::from_str::<Config>(json).unwrap();
if let Some(OneOrMore::Multiple(sources)) = config.sources {
assert_eq!(sources.len(), 2);
let test_dir = sources[1].to_qualified_without_children(None);
assert_eq!(test_dir.type_, Some(String::from("dev")));
} else {
dbg!(config.sources);
unreachable!()
}
}
#[test]
fn test_detect_gentypeconfig() {
let json = r#"
{
"name": "my-monorepo",
"sources": [ { "dir": "src/", "subdirs": true } ],
"package-specs": [ { "module": "es6", "in-source": true } ],
"suffix": ".mjs",
"dependencies": [ "@teamwalnut/app" ],
"gentypeconfig": {
"module": "esmodule",
"generatedFileExtension": ".gen.tsx"
}
}
"#;
let config = serde_json::from_str::<Config>(json).unwrap();
assert!(config.gentype_config.is_some());
assert_eq!(config.get_gentype_arg(), vec!["-bs-gentype".to_string()]);
}
#[test]
fn test_other_jsx_module() {
let json = r#"
{
"name": "my-monorepo",
"sources": [ { "dir": "src/", "subdirs": true } ],
"package-specs": [ { "module": "es6", "in-source": true } ],
"suffix": ".mjs",
"dependencies": [ "@teamwalnut/app" ],
"jsx": {
"module": "Voby.JSX"
}
}
"#;
let config = serde_json::from_str::<Config>(json).unwrap();
assert!(config.jsx.is_some());
assert_eq!(
config.jsx.unwrap(),
JsxSpecs {
version: None,
module: Some(JsxModule::Other(String::from("Voby.JSX"))),
mode: None,
v3_dependencies: None,
preserve: None,
},
);
}
#[test]
fn test_jsx_preserve() {
let json = r#"
{
"name": "my-monorepo",
"sources": [ { "dir": "src/", "subdirs": true } ],
"package-specs": [ { "module": "es6", "in-source": true } ],
"suffix": ".mjs",
"dependencies": [ "@teamwalnut/app" ],
"jsx": { "version": 4, "preserve": true }
}
"#;
let config = serde_json::from_str::<Config>(json).unwrap();
assert!(config.jsx.is_some());
assert_eq!(
config.jsx.unwrap(),
JsxSpecs {
version: Some(4),
module: None,
mode: None,
v3_dependencies: None,
preserve: Some(true),
},
);
}
#[test]
fn test_get_suffix() {
let json = r#"
{
"name": "testrepo",
"sources": {
"dir": "src",
"subdirs": true
},
"package-specs": [
{
"module": "es6",
"in-source": true
}
],