-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdependency_downloader.rs
755 lines (669 loc) · 27 KB
/
dependency_downloader.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
use crate::{
config::{Dependency, GitDependency, HttpDependency},
errors::DownloadError,
remote::get_dependency_url_remote,
utils::{hash_folder, read_file, sanitize_dependency_name, zipfile_hash},
DEPENDENCY_DIR,
};
use reqwest::IntoUrl;
use std::{
fs,
io::Cursor,
path::{Path, PathBuf},
process::{Command, Stdio},
str,
};
use tokio::{fs as tokio_fs, io::AsyncWriteExt, task::JoinSet};
use yansi::Paint as _;
pub type Result<T> = std::result::Result<T, DownloadError>;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct IntegrityChecksum(pub String);
impl<T> From<T> for IntegrityChecksum
where
T: Into<String>,
{
fn from(value: T) -> Self {
let v: String = value.into();
IntegrityChecksum(v)
}
}
impl core::fmt::Display for IntegrityChecksum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// Download the dependencies from the list in parallel
///
/// Note: the dependencies list should be sorted by name and version
pub async fn download_dependencies(
dependencies: &[Dependency],
clean: bool,
) -> Result<Vec<DownloadResult>> {
// clean dependencies folder if flag is true
if clean {
// creates the directory
clean_dependency_directory();
}
// create the dependency directory if it doesn't exist
let dir = DEPENDENCY_DIR.clone();
if tokio_fs::metadata(&dir).await.is_err() {
tokio_fs::create_dir(&dir)
.await
.map_err(|e| DownloadError::IOError { path: dir, source: e })?;
}
let mut set = JoinSet::new();
for dep in dependencies {
set.spawn({
let d = dep.clone();
async move { download_dependency(&d, true).await }
});
}
let mut results = Vec::new();
while let Some(res) = set.join_next().await {
results.push(res??);
}
// sort to make the order consistent with the input dependencies list (which should be sorted)
results.sort_unstable_by(|a, b| a.name.cmp(&b.name).then_with(|| a.version.cmp(&b.version)));
Ok(results)
}
// un-zip-ing dependencies to dependencies folder
pub fn unzip_dependencies(dependencies: &[Dependency]) -> Result<Vec<Option<IntegrityChecksum>>> {
let res: Vec<_> = dependencies
.iter()
.map(|d| match d {
Dependency::Http(dep) => unzip_dependency(dep).map(Some),
_ => Ok(None),
})
.collect::<Result<Vec<_>>>()?;
Ok(res)
}
#[derive(Debug, Clone)]
pub struct DownloadResult {
pub name: String,
pub version: String,
pub hash: String,
pub url: String,
}
pub async fn download_dependency(
dependency: &Dependency,
skip_folder_check: bool,
) -> Result<DownloadResult> {
let dependency_directory: PathBuf = DEPENDENCY_DIR.clone();
// if we called this method from `download_dependencies` we don't need to check if the folder
// exists, as it was created by the caller
if !skip_folder_check && tokio_fs::metadata(&dependency_directory).await.is_err() {
if let Err(e) = tokio_fs::create_dir(&dependency_directory).await {
// temp fix for race condition until we use tokio fs everywhere
if tokio_fs::metadata(&dependency_directory).await.is_err() {
return Err(DownloadError::IOError { path: dependency_directory, source: e });
}
}
}
let res = match dependency {
Dependency::Http(dep) => {
let url = match &dep.url {
Some(url) => url.clone(),
None => get_dependency_url_remote(dependency).await?,
};
download_via_http(&url, dep, &dependency_directory).await?;
DownloadResult {
name: dep.name.clone(),
version: dep.version.clone(),
hash: zipfile_hash(dep)?.to_string(),
url,
}
}
Dependency::Git(dep) => {
let hash = download_via_git(dep, &dependency_directory).await?;
DownloadResult {
name: dep.name.clone(),
version: dep.version.clone(),
hash,
url: dep.git.clone(),
}
}
};
println!("{}", format!("Dependency {dependency} downloaded!").green());
Ok(res)
}
pub fn unzip_dependency(dependency: &HttpDependency) -> Result<IntegrityChecksum> {
let file_name =
sanitize_dependency_name(&format!("{}-{}", dependency.name, dependency.version));
let target_name = format!("{}/", file_name);
let zip_path = DEPENDENCY_DIR.join(format!("{file_name}.zip"));
let target_dir = DEPENDENCY_DIR.join(target_name);
let zip_contents = read_file(&zip_path).unwrap();
zip_extract::extract(Cursor::new(zip_contents), &target_dir, true)?;
println!("{}", format!("The dependency {dependency} was unzipped!").green());
hash_folder(&target_dir, Some(zip_path))
.map_err(|e| DownloadError::IOError { path: target_dir, source: e })
}
pub fn clean_dependency_directory() {
if fs::metadata(DEPENDENCY_DIR.clone()).is_ok() {
fs::remove_dir_all(DEPENDENCY_DIR.clone()).unwrap();
fs::create_dir(DEPENDENCY_DIR.clone()).unwrap();
}
}
async fn download_via_git(
dependency: &GitDependency,
dependency_directory: &Path,
) -> Result<String> {
println!("{}", format!("Started GIT download of {dependency}").green());
let target_dir =
sanitize_dependency_name(&format!("{}-{}", dependency.name, dependency.version));
let path = dependency_directory.join(target_dir);
let path_str = path.to_string_lossy().to_string();
if path.exists() {
let _ = fs::remove_dir_all(&path);
}
let mut git_clone = Command::new("git");
let result = git_clone
.args(["clone", &dependency.git, &path_str])
.env("GIT_TERMINAL_PROMPT", "0")
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let status = result.status().expect("Getting clone status failed");
let out = result.output().expect("Getting clone output failed");
if !status.success() {
let _ = fs::remove_dir_all(&path);
return Err(DownloadError::GitError(
str::from_utf8(&out.stderr).unwrap().trim().to_string(),
));
}
let rev = match dependency.rev.clone() {
Some(rev) => {
let mut git_get_commit = Command::new("git");
let result = git_get_commit
.args(["checkout".to_string(), rev.to_string()])
.env("GIT_TERMINAL_PROMPT", "0")
.current_dir(&path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let out = result.output().expect("Checkout to revision status failed");
let status = result.status().expect("Checkout to revision getting output failed");
if !status.success() {
let _ = fs::remove_dir_all(&path);
return Err(DownloadError::GitError(
str::from_utf8(&out.stderr).unwrap().trim().to_string(),
));
}
rev
}
None => {
let mut git_checkout = Command::new("git");
let result = git_checkout
.args(["rev-parse".to_string(), "--verify".to_string(), "HEAD".to_string()])
.env("GIT_TERMINAL_PROMPT", "0")
.current_dir(&path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let out = result.output().expect("Getting revision status failed");
let status = result.status().expect("Getting revision output failed");
if !status.success() {
let _ = fs::remove_dir_all(&path);
return Err(DownloadError::GitError(
str::from_utf8(&out.stderr).unwrap().trim().to_string(),
));
}
let hash = str::from_utf8(&out.stdout).unwrap().trim().to_string();
// check the commit hash
if !hash.is_empty() && hash.len() != 40 {
let _ = fs::remove_dir_all(&path);
return Err(DownloadError::GitError(format!("invalid revision hash: {hash}")));
}
hash
}
};
println!(
"{}",
format!("Successfully downloaded {} the dependency via git", dependency,).green()
);
Ok(rev)
}
async fn download_via_http(
url: impl IntoUrl,
dependency: &HttpDependency,
dependency_directory: &Path,
) -> Result<()> {
println!("{}", format!("Started HTTP download of {dependency}").green());
let zip_to_download =
sanitize_dependency_name(&format!("{}-{}.zip", dependency.name, dependency.version));
let resp = reqwest::get(url).await?;
let mut resp = resp.error_for_status()?;
let file_path = dependency_directory.join(&zip_to_download);
let mut file = tokio_fs::File::create(&file_path)
.await
.map_err(|e| DownloadError::IOError { path: file_path.clone(), source: e })?;
while let Some(mut chunk) = resp.chunk().await? {
file.write_all_buf(&mut chunk)
.await
.map_err(|e| DownloadError::IOError { path: file_path.clone(), source: e })?;
}
// make sure we finished writing the file
file.flush().await.map_err(|e| DownloadError::IOError { path: file_path, source: e })?;
Ok(())
}
pub fn delete_dependency_files(dependency: &Dependency) -> Result<()> {
let path = DEPENDENCY_DIR.join(sanitize_dependency_name(&format!(
"{}-{}",
dependency.name(),
dependency.version()
)));
fs::remove_dir_all(&path).map_err(|e| DownloadError::IOError { path, source: e })?;
Ok(())
}
pub fn install_subdependencies(dependency: &Dependency) -> Result<()> {
let dep_name =
sanitize_dependency_name(&format!("{}-{}", dependency.name(), dependency.version()));
let dep_dir = DEPENDENCY_DIR.join(dep_name);
if !dep_dir.exists() {
return Err(DownloadError::SubdependencyError(
"Dependency directory does not exists".to_string(),
));
}
let mut git = Command::new("git");
let result = git
.args(["submodule", "update", "--init", "--recursive"])
.env("GIT_TERMINAL_PROMPT", "0")
.current_dir(&dep_dir)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let status = result.status().expect("Subdependency via GIT failed");
if !status.success() {
println!("{}", "Dependency has no submodule dependency.".yellow());
}
let mut soldeer = Command::new("forge");
let result = soldeer
.args(["soldeer", "install"])
.current_dir(&dep_dir)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let status = result.status().expect("Subdependency via Soldeer failed");
if !status.success() {
println!("{}", "Dependency has no Soldeer dependency.".yellow());
}
Ok(())
}
#[cfg(test)]
#[allow(clippy::vec_init_then_push)]
mod tests {
use super::*;
use crate::{
janitor::healthcheck_dependency,
utils::{get_url_type, UrlType},
};
use serial_test::serial;
use std::{fs::metadata, path::Path};
#[tokio::test]
#[serial]
async fn download_dependencies_http_one_success() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~2.3.0.zip".to_string()),
checksum: None
});
dependencies.push(dependency.clone());
let results = download_dependencies(&dependencies, false).await.unwrap();
let path_zip =
DEPENDENCY_DIR.join(format!("{}-{}.zip", &dependency.name(), &dependency.version()));
assert!(path_zip.exists());
assert!(results.len() == 1);
assert!(!results[0].hash.is_empty());
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependency_gitlab_httpurl_with_a_specific_revision() {
clean_dependency_directory();
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Git(GitDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
git: "https://gitlab.com/mario4582928/Mario.git".to_string(),
rev: Some("7a0663eaf7488732f39550be655bad6694974cb3".to_string()),
});
dependencies.push(dependency.clone());
let results = download_dependencies(&dependencies, false).await.unwrap();
let path_dir =
DEPENDENCY_DIR.join(format!("{}-{}", &dependency.name(), &dependency.version()));
assert!(path_dir.exists());
assert!(path_dir.join("README.md").exists());
assert!(results.len() == 1);
assert_eq!(results[0].hash, "7a0663eaf7488732f39550be655bad6694974cb3"); // this is the last commit, hash == commit
// at this revision, this file should exists
let test_right_revision = DEPENDENCY_DIR
.join(format!("{}-{}", &dependency.name(), &dependency.version()))
.join("JustATest2.md");
assert!(test_right_revision.exists());
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependencies_gitlab_httpurl_one_success() {
clean_dependency_directory();
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Git(GitDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
git: "https://gitlab.com/mario4582928/Mario.git".to_string(),
rev: None,
});
dependencies.push(dependency.clone());
let results = download_dependencies(&dependencies, false).await.unwrap();
let path_dir =
DEPENDENCY_DIR.join(format!("{}-{}", &dependency.name(), &dependency.version()));
assert!(path_dir.exists());
assert!(path_dir.join("README.md").exists());
assert!(results.len() == 1);
assert_eq!(results[0].hash, "22868f426bd4dd0e682b5ec5f9bd55507664240c"); // this is the last commit, hash == commit
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependencies_http_two_success() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency_one = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~2.3.0.zip".to_string()),
checksum: None
});
dependencies.push(dependency_one.clone());
let dependency_two = Dependency::Http(HttpDependency {
name: "@uniswap-v2-core".to_string(),
version: "1.0.0-beta.4".to_string(),
url: Some("https://soldeer-revisions.s3.amazonaws.com/@uniswap-v2-core/1_0_0-beta_4_22-01-2024_13:18:27_v2-core.zip".to_string()),
checksum: None
});
dependencies.push(dependency_two.clone());
let results = download_dependencies(&dependencies, false).await.unwrap();
let mut path_zip = DEPENDENCY_DIR.join(format!(
"{}-{}.zip",
&dependency_one.name(),
&dependency_one.version()
));
assert!(path_zip.exists());
path_zip = DEPENDENCY_DIR.join(format!(
"{}-{}.zip",
&dependency_two.name(),
&dependency_two.version()
));
assert!(path_zip.exists());
assert!(results.len() == 2);
assert!(!results[0].hash.is_empty());
assert!(!results[1].hash.is_empty());
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependencies_git_http_two_success() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency_one = Dependency::Git(GitDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
git: "https://github.com/transmissions11/solmate.git".to_string(),
rev: None,
});
dependencies.push(dependency_one.clone());
let dependency_two = Dependency::Git(GitDependency {
name: "@uniswap-v2-core".to_string(),
version: "1.0.0-beta.4".to_string(),
git: "https://gitlab.com/mario4582928/Mario.git".to_string(),
rev: None,
});
dependencies.push(dependency_two.clone());
let results = download_dependencies(&dependencies, false).await.unwrap();
let mut path_dir = DEPENDENCY_DIR.join(format!(
"{}-{}",
&dependency_one.name(),
&dependency_one.version()
));
let mut path_dir_two = DEPENDENCY_DIR.join(format!(
"{}-{}",
&dependency_two.name(),
&dependency_two.version()
));
assert!(path_dir.exists());
assert!(path_dir_two.exists());
path_dir = DEPENDENCY_DIR.join(format!(
"{}-{}",
&dependency_one.name(),
&dependency_one.version()
));
path_dir_two = DEPENDENCY_DIR.join(format!(
"{}-{}",
&dependency_two.name(),
&dependency_two.version()
));
assert!(path_dir.exists());
assert!(path_dir_two.exists());
assert!(results.len() == 2);
assert!(!results[0].hash.is_empty());
assert!(!results[1].hash.is_empty());
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependency_should_replace_existing_zip() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency_one = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "download-dep-v1".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~2.3.0.zip".to_string()),
checksum: None
});
dependencies.push(dependency_one.clone());
download_dependencies(&dependencies, false).await.unwrap();
let path_zip = DEPENDENCY_DIR.join(format!(
"{}-{}.zip",
&dependency_one.name(),
&dependency_one.version()
));
let size_of_one = fs::metadata(Path::new(&path_zip)).unwrap().len();
let dependency_two = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "download-dep-v1".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~2.4.0.zip".to_string()),
checksum: None
});
dependencies = Vec::new();
dependencies.push(dependency_two.clone());
let results = download_dependencies(&dependencies, false).await.unwrap();
let size_of_two = fs::metadata(Path::new(&path_zip)).unwrap().len();
assert!(size_of_two > size_of_one);
assert!(results.len() == 1);
assert!(!results[0].hash.is_empty());
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependencies_one_with_clean_success() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency_old = Dependency::Http(HttpDependency {
name: "@uniswap-v2-core".to_string(),
version: "1.0.0-beta.4".to_string(),
url: Some("https://soldeer-revisions.s3.amazonaws.com/@uniswap-v2-core/1_0_0-beta_4_22-01-2024_13:18:27_v2-core.zip".to_string()),
checksum: None
});
dependencies.push(dependency_old.clone());
download_dependencies(&dependencies, false).await.unwrap();
// making sure the dependency exists so we can check the deletion
let path_zip_old = DEPENDENCY_DIR.join(format!(
"{}-{}.zip",
&dependency_old.name(),
&dependency_old.version()
));
assert!(path_zip_old.exists());
let dependency = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~2.3.0.zip".to_string()),
checksum: None
});
dependencies = Vec::new();
dependencies.push(dependency.clone());
let results = download_dependencies(&dependencies, true).await.unwrap();
let path_zip =
DEPENDENCY_DIR.join(format!("{}-{}.zip", &dependency.name(), &dependency.version()));
assert!(!path_zip_old.exists());
assert!(path_zip.exists());
assert!(results.len() == 1);
assert!(!results[0].hash.is_empty());
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependencies_http_one_fail() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~.zip".to_string()),
checksum: None
});
dependencies.push(dependency.clone());
match download_dependencies(&dependencies, false).await {
Ok(_) => {
assert_eq!("Invalid state", "");
}
Err(err) => {
assert_eq!(err.to_string(), "error downloading dependency: HTTP status client error (404 Not Found) for url (https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~.zip)");
}
}
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_dependencies_git_one_fail() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Git(GitDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
git: "git@github.com:transmissions11/solmate-wrong.git".to_string(),
rev: None,
});
dependencies.push(dependency.clone());
match download_dependencies(&dependencies, false).await {
Ok(_) => {
assert_eq!("Invalid state", "");
}
Err(err) => {
// we assert this as the message contains various absolute paths that can not be
// hardcoded here
assert!(err.to_string().contains("Cloning into"));
}
}
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn unzip_dependency_success() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
url: Some("https://github.com/mario-eth/soldeer-versions/raw/main/all_versions/@openzeppelin-contracts~2.3.0.zip".to_string()),
checksum: None
});
dependencies.push(dependency.clone());
download_dependencies(&dependencies, false).await.unwrap();
let path = DEPENDENCY_DIR.join(format!("{}-{}", &dependency.name(), &dependency.version()));
match unzip_dependencies(&dependencies) {
Ok(_) => {
assert!(path.exists());
assert!(metadata(&path).unwrap().len() > 0);
}
Err(_) => {
clean_dependency_directory();
assert_eq!("Error", "");
}
}
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn unzip_non_zip_file_error() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
url: Some(
"https://freetestdata.com/wp-content/uploads/2022/02/Free_Test_Data_117KB_JPG.jpg"
.to_string(),
),
checksum: None,
});
dependencies.push(dependency.clone());
download_dependencies(&dependencies, false).await.unwrap();
match unzip_dependencies(&dependencies) {
Ok(_) => {
clean_dependency_directory();
assert_eq!("Wrong State", "");
}
Err(err) => {
assert!(matches!(err, DownloadError::UnzipError(_)));
}
}
clean_dependency_directory();
}
#[tokio::test]
#[serial]
async fn download_unzip_check_integrity() {
let mut dependencies: Vec<Dependency> = Vec::new();
dependencies.push(Dependency::Http(HttpDependency {
name: "@openzeppelin-contracts".to_string(),
version: "3.3.0-custom-test".to_string(),
url: Some("https://soldeer-revisions.s3.amazonaws.com/@openzeppelin-contracts/3_3_0-rc_2_22-01-2024_13:12:57_contracts.zip".to_string()),
checksum: None,
}));
download_dependencies(&dependencies, false).await.unwrap();
unzip_dependency(dependencies[0].as_http().unwrap()).unwrap();
healthcheck_dependency(&dependencies[0]).unwrap();
assert!(DEPENDENCY_DIR
.join("@openzeppelin-contracts-3.3.0-custom-test")
.join("token")
.join("ERC20")
.join("ERC20.sol")
.exists());
clean_dependency_directory();
}
#[test]
fn get_download_tunnel_http() {
assert_eq!(
get_url_type("https://github.com/foundry-rs/forge-std/archive/refs/tags/v1.9.1.zip"),
UrlType::Http
);
}
#[test]
fn get_download_tunnel_git_giturl() {
assert_eq!(get_url_type("git@github.com:foundry-rs/forge-std.git"), UrlType::Git);
}
#[test]
fn get_download_tunnel_git_githttp() {
assert_eq!(get_url_type("https://github.com/foundry-rs/forge-std.git"), UrlType::Git);
}
#[tokio::test]
#[serial]
async fn remove_one_dependency() {
let mut dependencies: Vec<Dependency> = Vec::new();
let dependency = Dependency::Git(GitDependency {
name: "@openzeppelin-contracts".to_string(),
version: "2.3.0".to_string(),
git: "https://github.com/transmissions11/solmate.git".to_string(),
rev: None,
});
dependencies.push(dependency.clone());
match download_dependencies(&dependencies, false).await {
Ok(_) => {}
Err(_) => {
assert_eq!("Invalid state", "");
}
}
let _ = delete_dependency_files(&dependency);
assert!(!DEPENDENCY_DIR
.join(format!("{}~{}", dependency.name(), dependency.version()))
.exists());
}
}