-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathconfig.rs
1458 lines (1315 loc) · 49 KB
/
config.rs
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::is_hidden;
use anchor_client::Cluster;
use anchor_lang_idl::types::Idl;
use anyhow::{anyhow, bail, Context, Error, Result};
use clap::{Parser, ValueEnum};
use dirs::home_dir;
use heck::ToSnakeCase;
use reqwest::Url;
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use solana_cli_config::{Config as SolanaConfig, CONFIG_FILE};
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, Signer};
use solang_parser::pt::{ContractTy, SourceUnitPart};
use std::collections::{BTreeMap, HashMap};
use std::convert::TryFrom;
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::prelude::*;
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use std::{fmt, io};
use walkdir::WalkDir;
pub trait Merge: Sized {
fn merge(&mut self, _other: Self) {}
}
#[derive(Default, Debug, Parser)]
pub struct ConfigOverride {
/// Cluster override.
#[clap(global = true, long = "provider.cluster")]
pub cluster: Option<Cluster>,
/// Wallet override.
#[clap(global = true, long = "provider.wallet")]
pub wallet: Option<WalletPath>,
}
#[derive(Debug)]
pub struct WithPath<T> {
inner: T,
path: PathBuf,
}
impl<T> WithPath<T> {
pub fn new(inner: T, path: PathBuf) -> Self {
Self { inner, path }
}
pub fn path(&self) -> &PathBuf {
&self.path
}
pub fn into_inner(self) -> T {
self.inner
}
}
impl<T> std::convert::AsRef<T> for WithPath<T> {
fn as_ref(&self) -> &T {
&self.inner
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest(cargo_toml::Manifest);
impl Manifest {
pub fn from_path(p: impl AsRef<Path>) -> Result<Self> {
cargo_toml::Manifest::from_path(&p)
.map(Manifest)
.map_err(anyhow::Error::from)
.with_context(|| format!("Error reading manifest from path: {}", p.as_ref().display()))
}
pub fn lib_name(&self) -> Result<String> {
if self.lib.is_some() && self.lib.as_ref().unwrap().name.is_some() {
Ok(self
.lib
.as_ref()
.unwrap()
.name
.as_ref()
.unwrap()
.to_string()
.to_snake_case())
} else {
Ok(self
.package
.as_ref()
.ok_or_else(|| anyhow!("package section not provided"))?
.name
.to_string()
.to_snake_case())
}
}
pub fn version(&self) -> String {
match &self.package {
Some(package) => package.version().to_string(),
_ => "0.0.0".to_string(),
}
}
// Climbs each parent directory from the current dir until we find a Cargo.toml
pub fn discover() -> Result<Option<WithPath<Manifest>>> {
Manifest::discover_from_path(std::env::current_dir()?)
}
// Climbs each parent directory from a given starting directory until we find a Cargo.toml.
pub fn discover_from_path(start_from: PathBuf) -> Result<Option<WithPath<Manifest>>> {
let mut cwd_opt = Some(start_from.as_path());
while let Some(cwd) = cwd_opt {
let mut anchor_toml = false;
for f in fs::read_dir(cwd).with_context(|| {
format!("Error reading the directory with path: {}", cwd.display())
})? {
let p = f
.with_context(|| {
format!("Error reading the directory with path: {}", cwd.display())
})?
.path();
if let Some(filename) = p.file_name().and_then(|name| name.to_str()) {
if filename == "Cargo.toml" {
return Ok(Some(WithPath::new(Manifest::from_path(&p)?, p)));
}
if filename == "Anchor.toml" {
anchor_toml = true;
}
}
}
// Not found. Go up a directory level, but don't go up from Anchor.toml
if anchor_toml {
break;
}
cwd_opt = cwd.parent();
}
Ok(None)
}
}
impl Deref for Manifest {
type Target = cargo_toml::Manifest;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl WithPath<Config> {
pub fn get_rust_program_list(&self) -> Result<Vec<PathBuf>> {
// Canonicalize the workspace filepaths to compare with relative paths.
let (members, exclude) = self.canonicalize_workspace()?;
// Get all candidate programs.
//
// If [workspace.members] exists, then use that.
// Otherwise, default to `programs/*`.
let program_paths: Vec<PathBuf> = {
if members.is_empty() {
let path = self.path().parent().unwrap().join("programs");
if let Ok(entries) = fs::read_dir(path) {
entries
.filter(|entry| entry.as_ref().map(|e| e.path().is_dir()).unwrap_or(false))
.map(|dir| dir.map(|d| d.path().canonicalize().unwrap()))
.collect::<Vec<Result<PathBuf, std::io::Error>>>()
.into_iter()
.collect::<Result<Vec<PathBuf>, std::io::Error>>()?
} else {
Vec::new()
}
} else {
members
}
};
// Filter out everything part of the exclude array.
Ok(program_paths
.into_iter()
.filter(|m| !exclude.contains(m))
.collect())
}
/// Parse all the files with the .sol extension, and get a list of the all
/// contracts defined in them along with their path. One Solidity file may
/// define multiple contracts.
pub fn get_solidity_program_list(&self) -> Result<Vec<(String, PathBuf)>> {
let path = self.path().parent().unwrap().join("solidity");
let mut res = Vec::new();
if let Ok(entries) = fs::read_dir(path) {
for entry in entries {
let path = entry?.path();
if !path.is_file() || path.extension() != Some(OsStr::new("sol")) {
continue;
}
let source = fs::read_to_string(&path)?;
let tree = match solang_parser::parse(&source, 0) {
Ok((tree, _)) => tree,
Err(diag) => {
// The parser can return multiple errors, however this is exceedingly rare.
// Just use the first one, else the formatting will be a mess.
bail!(
"{}: {}: {}",
path.display(),
diag[0].level.to_string(),
diag[0].message
);
}
};
tree.0.iter().for_each(|part| {
if let SourceUnitPart::ContractDefinition(contract) = part {
// Must be a contract, not library/interface/abstract contract
if matches!(&contract.ty, ContractTy::Contract(..)) {
if let Some(name) = &contract.name {
res.push((name.name.clone(), path.clone()));
}
}
}
});
}
}
Ok(res)
}
pub fn read_all_programs(&self) -> Result<Vec<Program>> {
let mut r = vec![];
for path in self.get_rust_program_list()? {
let cargo = Manifest::from_path(path.join("Cargo.toml"))?;
let lib_name = cargo.lib_name()?;
let idl_filepath = format!("target/idl/{lib_name}.json");
let idl = fs::read(idl_filepath)
.ok()
.map(|bytes| serde_json::from_reader(&*bytes))
.transpose()?;
r.push(Program {
lib_name,
solidity: false,
path,
idl,
});
}
for (lib_name, path) in self.get_solidity_program_list()? {
let idl_filepath = format!("target/idl/{lib_name}.json");
let idl = fs::read(idl_filepath)
.ok()
.map(|bytes| serde_json::from_reader(&*bytes))
.transpose()?;
r.push(Program {
lib_name,
solidity: true,
path,
idl,
});
}
Ok(r)
}
/// Read and get all the programs from the workspace.
///
/// This method will only return the given program if `name` exists.
pub fn get_programs(&self, name: Option<String>) -> Result<Vec<Program>> {
let programs = self.read_all_programs()?;
let programs = match name {
Some(name) => vec![programs
.into_iter()
.find(|program| {
name == program.lib_name
|| name == program.path.file_name().unwrap().to_str().unwrap()
})
.ok_or_else(|| anyhow!("Program {name} not found"))?],
None => programs,
};
Ok(programs)
}
/// Get the specified program from the workspace.
pub fn get_program(&self, name: &str) -> Result<Program> {
self.get_programs(Some(name.to_owned()))?
.into_iter()
.next()
.ok_or_else(|| anyhow!("Expected a program"))
}
pub fn canonicalize_workspace(&self) -> Result<(Vec<PathBuf>, Vec<PathBuf>)> {
let members = self.process_paths(&self.workspace.members)?;
let exclude = self.process_paths(&self.workspace.exclude)?;
Ok((members, exclude))
}
fn process_paths(&self, paths: &[String]) -> Result<Vec<PathBuf>, Error> {
let base_path = self.path().parent().unwrap();
paths
.iter()
.flat_map(|m| {
let path = base_path.join(m);
if m.ends_with("/*") {
let dir = path.parent().unwrap();
match fs::read_dir(dir) {
Ok(entries) => entries
.filter_map(|entry| entry.ok())
.map(|entry| self.process_single_path(&entry.path()))
.collect(),
Err(e) => vec![Err(Error::new(io::Error::new(
io::ErrorKind::Other,
format!("Error reading directory {:?}: {}", dir, e),
)))],
}
} else {
vec![self.process_single_path(&path)]
}
})
.collect()
}
fn process_single_path(&self, path: &PathBuf) -> Result<PathBuf, Error> {
path.canonicalize().map_err(|e| {
Error::new(io::Error::new(
io::ErrorKind::Other,
format!("Error canonicalizing path {:?}: {}", path, e),
))
})
}
}
impl<T> std::ops::Deref for WithPath<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> std::ops::DerefMut for WithPath<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
#[derive(Debug, Default)]
pub struct Config {
pub toolchain: ToolchainConfig,
pub features: FeaturesConfig,
pub registry: RegistryConfig,
pub provider: ProviderConfig,
pub programs: ProgramsConfig,
pub scripts: ScriptsConfig,
pub workspace: WorkspaceConfig,
// Separate entry next to test_config because
// "anchor localnet" only has access to the Anchor.toml,
// not the Test.toml files
pub test_validator: Option<TestValidator>,
pub test_config: Option<TestConfig>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ToolchainConfig {
pub anchor_version: Option<String>,
pub solana_version: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FeaturesConfig {
/// Enable account resolution.
///
/// Not able to specify default bool value: https://github.com/serde-rs/serde/issues/368
#[serde(default = "FeaturesConfig::get_default_resolution")]
pub resolution: bool,
/// Disable safety comment checks
#[serde(default, rename = "skip-lint")]
pub skip_lint: bool,
}
impl FeaturesConfig {
fn get_default_resolution() -> bool {
true
}
}
impl Default for FeaturesConfig {
fn default() -> Self {
Self {
resolution: Self::get_default_resolution(),
skip_lint: false,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RegistryConfig {
pub url: String,
}
impl Default for RegistryConfig {
fn default() -> Self {
Self {
url: "https://api.apr.dev".to_string(),
}
}
}
#[derive(Debug, Default)]
pub struct ProviderConfig {
pub cluster: Cluster,
pub wallet: WalletPath,
}
pub type ScriptsConfig = BTreeMap<String, String>;
pub type ProgramsConfig = BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>;
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WorkspaceConfig {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exclude: Vec<String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub types: String,
}
#[derive(ValueEnum, Parser, Clone, PartialEq, Eq, Debug)]
pub enum BootstrapMode {
None,
Debian,
}
#[derive(ValueEnum, Parser, Clone, PartialEq, Eq, Debug)]
pub enum ProgramArch {
Bpf,
Sbf,
}
impl ProgramArch {
pub fn build_subcommand(&self) -> &str {
match self {
Self::Bpf => "build-bpf",
Self::Sbf => "build-sbf",
}
}
}
#[derive(Debug, Clone)]
pub struct BuildConfig {
pub verifiable: bool,
pub solana_version: Option<String>,
pub docker_image: String,
pub bootstrap: BootstrapMode,
}
impl Config {
pub fn add_test_config(
&mut self,
root: impl AsRef<Path>,
test_paths: Vec<PathBuf>,
) -> Result<()> {
self.test_config = TestConfig::discover(root, test_paths)?;
Ok(())
}
pub fn docker(&self) -> String {
let version = self
.toolchain
.anchor_version
.as_deref()
.unwrap_or(crate::DOCKER_BUILDER_VERSION);
format!("backpackapp/build:v{version}")
}
pub fn discover(cfg_override: &ConfigOverride) -> Result<Option<WithPath<Config>>> {
Config::_discover().map(|opt| {
opt.map(|mut cfg| {
if let Some(cluster) = cfg_override.cluster.clone() {
cfg.provider.cluster = cluster;
}
if let Some(wallet) = cfg_override.wallet.clone() {
cfg.provider.wallet = wallet;
}
cfg
})
})
}
// Climbs each parent directory until we find an Anchor.toml.
fn _discover() -> Result<Option<WithPath<Config>>> {
let _cwd = std::env::current_dir()?;
let mut cwd_opt = Some(_cwd.as_path());
while let Some(cwd) = cwd_opt {
for f in fs::read_dir(cwd).with_context(|| {
format!("Error reading the directory with path: {}", cwd.display())
})? {
let p = f
.with_context(|| {
format!("Error reading the directory with path: {}", cwd.display())
})?
.path();
if let Some(filename) = p.file_name() {
if filename.to_str() == Some("Anchor.toml") {
let cfg = Config::from_path(&p)?;
return Ok(Some(WithPath::new(cfg, p)));
}
}
}
cwd_opt = cwd.parent();
}
Ok(None)
}
fn from_path(p: impl AsRef<Path>) -> Result<Self> {
fs::read_to_string(&p)
.with_context(|| format!("Error reading the file with path: {}", p.as_ref().display()))?
.parse::<Self>()
}
pub fn wallet_kp(&self) -> Result<Keypair> {
solana_sdk::signature::read_keypair_file(&self.provider.wallet.to_string())
.map_err(|_| anyhow!("Unable to read keypair file"))
}
}
#[derive(Debug, Serialize, Deserialize)]
struct _Config {
toolchain: Option<ToolchainConfig>,
features: Option<FeaturesConfig>,
programs: Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>,
registry: Option<RegistryConfig>,
provider: Provider,
workspace: Option<WorkspaceConfig>,
scripts: Option<ScriptsConfig>,
test: Option<_TestValidator>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Provider {
#[serde(deserialize_with = "des_cluster")]
cluster: Cluster,
wallet: String,
}
fn des_cluster<'de, D>(deserializer: D) -> Result<Cluster, D::Error>
where
D: Deserializer<'de>,
{
struct StringOrCustomCluster(PhantomData<fn() -> Cluster>);
impl<'de> Visitor<'de> for StringOrCustomCluster {
type Value = Cluster;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("string or map")
}
fn visit_str<E>(self, value: &str) -> Result<Cluster, E>
where
E: de::Error,
{
value.parse().map_err(de::Error::custom)
}
fn visit_map<M>(self, mut map: M) -> Result<Cluster, M::Error>
where
M: MapAccess<'de>,
{
// Gets keys
if let (Some((http_key, http_value)), Some((ws_key, ws_value))) = (
map.next_entry::<String, String>()?,
map.next_entry::<String, String>()?,
) {
// Checks keys
if http_key != "http" || ws_key != "ws" {
return Err(de::Error::custom("Invalid key"));
}
// Checks urls
Url::parse(&http_value).map_err(de::Error::custom)?;
Url::parse(&ws_value).map_err(de::Error::custom)?;
Ok(Cluster::Custom(http_value, ws_value))
} else {
Err(de::Error::custom("Invalid entry"))
}
}
}
deserializer.deserialize_any(StringOrCustomCluster(PhantomData))
}
impl ToString for Config {
fn to_string(&self) -> String {
let programs = {
let c = ser_programs(&self.programs);
if c.is_empty() {
None
} else {
Some(c)
}
};
let cfg = _Config {
toolchain: Some(self.toolchain.clone()),
features: Some(self.features.clone()),
registry: Some(self.registry.clone()),
provider: Provider {
cluster: self.provider.cluster.clone(),
wallet: self.provider.wallet.stringify_with_tilde(),
},
test: self.test_validator.clone().map(Into::into),
scripts: match self.scripts.is_empty() {
true => None,
false => Some(self.scripts.clone()),
},
programs,
workspace: (!self.workspace.members.is_empty() || !self.workspace.exclude.is_empty())
.then(|| self.workspace.clone()),
};
toml::to_string(&cfg).expect("Must be well formed")
}
}
impl FromStr for Config {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cfg: _Config =
toml::from_str(s).map_err(|e| anyhow!("Unable to deserialize config: {e}"))?;
Ok(Config {
toolchain: cfg.toolchain.unwrap_or_default(),
features: cfg.features.unwrap_or_default(),
registry: cfg.registry.unwrap_or_default(),
provider: ProviderConfig {
cluster: cfg.provider.cluster,
wallet: shellexpand::tilde(&cfg.provider.wallet).parse()?,
},
scripts: cfg.scripts.unwrap_or_default(),
test_validator: cfg.test.map(Into::into),
test_config: None,
programs: cfg.programs.map_or(Ok(BTreeMap::new()), deser_programs)?,
workspace: cfg.workspace.unwrap_or_default(),
})
}
}
pub fn get_solana_cfg_url() -> Result<String, io::Error> {
let config_file = CONFIG_FILE.as_ref().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Default Solana config was not found",
)
})?;
SolanaConfig::load(config_file).map(|config| config.json_rpc_url)
}
fn ser_programs(
programs: &BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>,
) -> BTreeMap<String, BTreeMap<String, serde_json::Value>> {
programs
.iter()
.map(|(cluster, programs)| {
let cluster = cluster.to_string();
let programs = programs
.iter()
.map(|(name, deployment)| {
(
name.clone(),
to_value(&_ProgramDeployment::from(deployment)),
)
})
.collect::<BTreeMap<String, serde_json::Value>>();
(cluster, programs)
})
.collect::<BTreeMap<String, BTreeMap<String, serde_json::Value>>>()
}
fn to_value(dep: &_ProgramDeployment) -> serde_json::Value {
if dep.path.is_none() && dep.idl.is_none() {
return serde_json::Value::String(dep.address.to_string());
}
serde_json::to_value(dep).unwrap()
}
fn deser_programs(
programs: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
) -> Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>> {
programs
.iter()
.map(|(cluster, programs)| {
let cluster: Cluster = cluster.parse()?;
let programs = programs
.iter()
.map(|(name, program_id)| {
Ok((
name.clone(),
ProgramDeployment::try_from(match &program_id {
serde_json::Value::String(address) => _ProgramDeployment {
address: address.parse()?,
path: None,
idl: None,
},
serde_json::Value::Object(_) => {
serde_json::from_value(program_id.clone())
.map_err(|_| anyhow!("Unable to read toml"))?
}
_ => return Err(anyhow!("Invalid toml type")),
})?,
))
})
.collect::<Result<BTreeMap<String, ProgramDeployment>>>()?;
Ok((cluster, programs))
})
.collect::<Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>>>()
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct TestValidator {
pub genesis: Option<Vec<GenesisEntry>>,
pub validator: Option<Validator>,
pub startup_wait: i32,
pub shutdown_wait: i32,
pub upgradeable: bool,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct _TestValidator {
#[serde(skip_serializing_if = "Option::is_none")]
pub genesis: Option<Vec<GenesisEntry>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub validator: Option<_Validator>,
#[serde(skip_serializing_if = "Option::is_none")]
pub startup_wait: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shutdown_wait: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub upgradeable: Option<bool>,
}
pub const STARTUP_WAIT: i32 = 5000;
pub const SHUTDOWN_WAIT: i32 = 2000;
impl From<_TestValidator> for TestValidator {
fn from(_test_validator: _TestValidator) -> Self {
Self {
shutdown_wait: _test_validator.shutdown_wait.unwrap_or(SHUTDOWN_WAIT),
startup_wait: _test_validator.startup_wait.unwrap_or(STARTUP_WAIT),
genesis: _test_validator.genesis,
validator: _test_validator.validator.map(Into::into),
upgradeable: _test_validator.upgradeable.unwrap_or(false),
}
}
}
impl From<TestValidator> for _TestValidator {
fn from(test_validator: TestValidator) -> Self {
Self {
shutdown_wait: Some(test_validator.shutdown_wait),
startup_wait: Some(test_validator.startup_wait),
genesis: test_validator.genesis,
validator: test_validator.validator.map(Into::into),
upgradeable: Some(test_validator.upgradeable),
}
}
}
#[derive(Debug, Clone)]
pub struct TestConfig {
pub test_suite_configs: HashMap<PathBuf, TestToml>,
}
impl Deref for TestConfig {
type Target = HashMap<PathBuf, TestToml>;
fn deref(&self) -> &Self::Target {
&self.test_suite_configs
}
}
impl TestConfig {
pub fn discover(root: impl AsRef<Path>, test_paths: Vec<PathBuf>) -> Result<Option<Self>> {
let walker = WalkDir::new(root).into_iter();
let mut test_suite_configs = HashMap::new();
for entry in walker.filter_entry(|e| !is_hidden(e)) {
let entry = entry?;
if entry.file_name() == "Test.toml" {
let entry_path = entry.path();
let test_toml = TestToml::from_path(entry_path)?;
if test_paths.is_empty() || test_paths.iter().any(|p| entry_path.starts_with(p)) {
test_suite_configs.insert(entry.path().into(), test_toml);
}
}
}
Ok(match test_suite_configs.is_empty() {
true => None,
false => Some(Self { test_suite_configs }),
})
}
}
// This file needs to have the same (sub)structure as Anchor.toml
// so it can be parsed as a base test file from an Anchor.toml
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct _TestToml {
pub extends: Option<Vec<String>>,
pub test: Option<_TestValidator>,
pub scripts: Option<ScriptsConfig>,
}
impl _TestToml {
fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
let s = fs::read_to_string(&path)?;
let parsed_toml: Self = toml::from_str(&s)?;
let mut current_toml = _TestToml {
extends: None,
test: None,
scripts: None,
};
if let Some(bases) = &parsed_toml.extends {
for base in bases {
let mut canonical_base = base.clone();
canonical_base = canonicalize_filepath_from_origin(&canonical_base, &path)?;
current_toml.merge(_TestToml::from_path(&canonical_base)?);
}
}
current_toml.merge(parsed_toml);
if let Some(test) = &mut current_toml.test {
if let Some(genesis_programs) = &mut test.genesis {
for entry in genesis_programs {
entry.program = canonicalize_filepath_from_origin(&entry.program, &path)?;
}
}
if let Some(validator) = &mut test.validator {
if let Some(ledger_dir) = &mut validator.ledger {
*ledger_dir = canonicalize_filepath_from_origin(&ledger_dir, &path)?;
}
if let Some(accounts) = &mut validator.account {
for entry in accounts {
entry.filename = canonicalize_filepath_from_origin(&entry.filename, &path)?;
}
}
}
}
Ok(current_toml)
}
}
/// canonicalizes the `file_path` arg.
/// uses the `path` arg as the current dir
/// from which to turn the relative path
/// into a canonical one
fn canonicalize_filepath_from_origin(
file_path: impl AsRef<Path>,
origin: impl AsRef<Path>,
) -> Result<String> {
let previous_dir = std::env::current_dir()?;
std::env::set_current_dir(origin.as_ref().parent().unwrap())?;
let result = fs::canonicalize(&file_path)
.with_context(|| {
format!(
"Error reading (possibly relative) path: {}. If relative, this is the path that was used as the current path: {}",
&file_path.as_ref().display(),
&origin.as_ref().display()
)
})?
.display()
.to_string();
std::env::set_current_dir(previous_dir)?;
Ok(result)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestToml {
#[serde(skip_serializing_if = "Option::is_none")]
pub test: Option<TestValidator>,
pub scripts: ScriptsConfig,
}
impl TestToml {
pub fn from_path(p: impl AsRef<Path>) -> Result<Self> {
WithPath::new(_TestToml::from_path(&p)?, p.as_ref().into()).try_into()
}
}
impl Merge for _TestToml {
fn merge(&mut self, other: Self) {
let mut my_scripts = self.scripts.take();
match &mut my_scripts {
None => my_scripts = other.scripts,
Some(my_scripts) => {
if let Some(other_scripts) = other.scripts {
for (name, script) in other_scripts {
my_scripts.insert(name, script);
}
}
}
}
let mut my_test = self.test.take();
match &mut my_test {
Some(my_test) => {
if let Some(other_test) = other.test {
if let Some(startup_wait) = other_test.startup_wait {
my_test.startup_wait = Some(startup_wait);
}
if let Some(other_genesis) = other_test.genesis {
match &mut my_test.genesis {
Some(my_genesis) => {
for other_entry in other_genesis {
match my_genesis
.iter()
.position(|g| *g.address == other_entry.address)
{
None => my_genesis.push(other_entry),
Some(i) => my_genesis[i] = other_entry,
}
}
}
None => my_test.genesis = Some(other_genesis),
}
}
let mut my_validator = my_test.validator.take();
match &mut my_validator {
None => my_validator = other_test.validator,
Some(my_validator) => {
if let Some(other_validator) = other_test.validator {
my_validator.merge(other_validator)
}
}
}
my_test.validator = my_validator;
}
}
None => my_test = other.test,
};
// Instantiating a new Self object here ensures that
// this function will fail to compile if new fields get added
// to Self. This is useful as a reminder if they also require merging
*self = Self {
test: my_test,
scripts: my_scripts,
extends: self.extends.take(),
};
}
}
impl TryFrom<WithPath<_TestToml>> for TestToml {
type Error = Error;
fn try_from(mut value: WithPath<_TestToml>) -> Result<Self, Self::Error> {
Ok(Self {
test: value.test.take().map(Into::into),
scripts: value
.scripts
.take()
.ok_or_else(|| anyhow!("Missing 'scripts' section in Test.toml file."))?,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenesisEntry {
// Base58 pubkey string.
pub address: String,
// Filepath to the compiled program to embed into the genesis.
pub program: String,
// Whether the genesis program is upgradeable.
pub upgradeable: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloneEntry {
// Base58 pubkey string.
pub address: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountEntry {
// Base58 pubkey string.
pub address: String,
// Name of JSON file containing the account data.
pub filename: String,