-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
1585 lines (1426 loc) · 55.7 KB
/
lib.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 flate2::read::GzDecoder;
use git2::{FetchOptions, ObjectType, RemoteCallbacks, Repository, SubmoduleUpdateOptions};
use log::{error, info, trace, warn};
use reqwest::Client;
#[cfg(feature = "userustpython")]
use rustpython_vm::literal::char;
use sha2::{Digest, Sha256};
use tar::Archive;
use tera::{Context, Tera};
use thiserror::Error;
use utils::{find_directories_by_name, make_long_path_compatible};
use xz2::read::XzDecoder;
use zip::ZipArchive;
pub mod command_executor;
pub mod idf_config;
pub mod idf_tools;
pub mod idf_versions;
pub mod python_utils;
pub mod settings;
pub mod system_dependencies;
pub mod utils;
pub mod version_manager;
use std::fs::{set_permissions, File};
use std::{
env,
fs::{self},
io::{self, Read, Write},
path::{Path, PathBuf},
sync::mpsc::Sender,
};
/// Creates an executable shell script with the given content and file path.
///
/// # Parameters
///
/// * `file_path`: A string representing the path where the shell script should be created.
/// * `content`: A string representing the content of the shell script.
///
/// # Return
///
/// * `Result<(), String>`: On success, returns `Ok(())`. On error, returns `Err(String)` containing the error message.
fn create_executable_shell_script(file_path: &str, content: &str) -> Result<(), String> {
if std::env::consts::OS == "windows" {
unimplemented!("create_executable_shell_script not implemented for Windows")
} else {
// Create and write to the file
let mut file = File::create(file_path).map_err(|e| e.to_string())?;
file.write_all(content.as_bytes())
.map_err(|e| e.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
// Set the file as executable (mode 0o755)
let permissions = PermissionsExt::from_mode(0o755);
set_permissions(Path::new(file_path), permissions).map_err(|e| e.to_string())?;
}
}
Ok(())
}
/// Formats a vector of key-value pairs into a bash-compatible format for environment variables.
///
/// # Parameters
///
/// * `pairs` - A reference to a vector of tuples, where each tuple contains a key (String) and a value (String).
///
/// # Return
///
/// * A String representing the formatted environment variable pairs in bash-compatible format.
/// Each pair is enclosed in double quotes and separated by a newline.
///
fn format_bash_env_pairs(pairs: &Vec<(String, String)>) -> String {
let formatted_pairs: Vec<String> = pairs
.iter()
.map(|(key, value)| format!(" \"{}:{}\"", key, value))
.collect();
format!("env_var_pairs=(\n{}\n)", formatted_pairs.join("\n"))
}
/// Formats a vector of key-value pairs into a PowerShell-compatible format for environment variables.
///
/// # Parameters
///
/// * `pairs`: A reference to a vector of tuples, where each tuple contains a key-value pair.
///
/// # Return
///
/// * A string representing the formatted environment variables in PowerShell-compatible format.
///
fn format_powershell_env_pairs(pairs: &Vec<(String, String)>) -> String {
let formatted_pairs: Vec<String> = pairs
.iter()
.map(|(key, value)| format!(" \"{}\" = \"{}\"", key, value))
.collect();
format!("$env_var_pairs = @{{\n{}\n}}", formatted_pairs.join("\n"))
}
/// Creates an activation shell script for the ESP-IDF toolchain.
///
/// # Parameters
///
/// * `file_path`: A string representing the path where the activation script should be created.
/// * `idf_path`: A string representing the path to the ESP-IDF installation.
/// * `idf_tools_path`: A string representing the path to the ESP-IDF tools installation.
/// * `idf_version`: A string representing the version of the ESP-IDF toolchain.
/// * `export_paths`: A vector of strings representing additional paths to be added to the shell's PATH environment variable.
///
/// # Return
///
/// * `Result<(), String>`: On success, returns `Ok(())`. On error, returns `Err(String)` containing the error message.
pub fn create_activation_shell_script(
file_path: &str,
idf_path: &str,
idf_tools_path: &str,
idf_python_env_path: Option<&str>,
idf_version: &str,
export_paths: Vec<String>,
env_var_pairs: Vec<(String, String)>,
) -> Result<(), String> {
ensure_path(file_path).map_err(|e| e.to_string())?;
let mut filename = PathBuf::from(file_path);
filename.push(format!("activate_idf_{}.sh", idf_version));
let template = include_str!("./../bash_scripts/activate_idf_template.sh");
let mut tera = Tera::default();
if let Err(e) = tera.add_raw_template("activate_idf_template", template) {
error!("Failed to add template: {}", e);
return Err(e.to_string());
}
let mut context = Context::new();
let env_var_pairs_str = format_bash_env_pairs(&env_var_pairs);
context.insert("env_var_pairs", &env_var_pairs_str);
context.insert("idf_path", &idf_path);
context.insert(
"idf_path_escaped",
&replace_unescaped_spaces_posix(idf_path),
);
context.insert("idf_tools_path", &idf_tools_path);
context.insert(
"idf_tools_path_escaped",
&replace_unescaped_spaces_posix(idf_tools_path),
);
context.insert("idf_version", &idf_version);
context.insert("addition_to_path", &export_paths.join(":"));
if let Some(idf_python_env_path) = idf_python_env_path {
context.insert("idf_python_env_path", &idf_python_env_path);
context.insert(
"idf_python_env_path_escaped",
&replace_unescaped_spaces_posix(idf_python_env_path),
);
} else {
context.insert("idf_python_env_path", &format!("{}/python", idf_tools_path));
context.insert(
"idf_python_env_path_escaped",
&replace_unescaped_spaces_posix(&format!("{}/python", idf_tools_path)),
);
}
let rendered = match tera.render("activate_idf_template", &context) {
Err(e) => {
error!("Failed to render template: {}", e);
return Err(e.to_string());
}
Ok(text) => text,
};
create_executable_shell_script(filename.to_str().unwrap(), &rendered)?;
Ok(())
}
// TODO: unify the replace_unescaped_spaces functions
pub fn replace_unescaped_spaces_posix(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\\' && chars.peek() == Some(&' ') {
// If we see a backslash followed by a space, keep them as-is
result.push(ch);
result.push(chars.next().unwrap());
} else if ch == ' ' {
// If we see a space not preceded by a backslash, replace it
result.push_str(r"\ ");
} else {
// For all other characters, just add them to the result
result.push(ch);
}
}
result
}
pub fn replace_unescaped_spaces_win(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '`' && chars.peek() == Some(&' ') {
result.push(ch);
result.push(chars.next().unwrap());
} else if ch == ' ' {
result.push_str(r"` ");
} else {
result.push(ch);
}
}
result
}
/// Runs a PowerShell script and captures its output.
/// TODO: fix documentation
///
/// # Parameters
///
/// * `script`: A string containing the PowerShell script to be executed.
///
/// # Returns
///
/// * `Ok(String)`: If the PowerShell script executes successfully, the function returns a `Result` containing the script's output as a string.
/// * `Err(Box<dyn std::error::Error>)`: If an error occurs during the execution of the PowerShell script, the function returns a `Result` containing the error.
pub fn run_powershell_script(script: &str) -> Result<String, std::io::Error> {
match std::env::consts::OS {
"windows" => match command_executor::get_executor().run_script_from_string(script) {
Ok(output) => {
trace!("stdout: {}", String::from_utf8_lossy(&output.stdout));
trace!("stderr: {}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))
}
Err(err) => Err(err),
},
_ => {
let error_message = "run_powershell_script is only supported on Windows.";
error!("{}", error_message);
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
error_message,
))
}
}
}
/// Creates a PowerShell profile script for the ESP-IDF tools.
///
/// # Parameters
///
/// * `profile_path` - A string representing the path where the PowerShell profile script should be created.
/// * `idf_path` - A string representing the path to the ESP-IDF repository.
/// * `idf_tools_path` - A string representing the path to the ESP-IDF tools directory.
///
/// # Returns
///
/// * `Result<String, std::io::Error>` - On success, returns the path to the created PowerShell profile script.
/// On error, returns an `std::io::Error` indicating the cause of the error.
fn create_powershell_profile(
profile_path: &str,
idf_path: &str,
idf_tools_path: &str,
idf_python_env_path: Option<&str>,
idf_version: &str,
export_paths: Vec<String>,
env_var_pairs: Vec<(String, String)>,
) -> Result<String, std::io::Error> {
let profile_template = include_str!("./../powershell_scripts/idf_tools_profile_template.ps1");
let mut tera = Tera::default();
if let Err(e) = tera.add_raw_template("powershell_profile", profile_template) {
error!("Failed to add template: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to add template",
));
}
ensure_path(profile_path).expect("Unable to create directory");
let mut context = Context::new();
println!("idf_path: {}", replace_unescaped_spaces_win(idf_path));
context.insert("idf_path", &replace_unescaped_spaces_win(idf_path));
context.insert("idf_version", &idf_version);
context.insert(
"env_var_pairs",
&format_powershell_env_pairs(&env_var_pairs),
);
context.insert(
"idf_tools_path",
&replace_unescaped_spaces_win(idf_tools_path),
);
if let Some(idf_python_env_path) = idf_python_env_path {
context.insert(
"idf_python_env_path",
&replace_unescaped_spaces_win(idf_python_env_path),
);
} else {
context.insert(
"idf_python_env_path",
&replace_unescaped_spaces_win(&format!("{}\\python", idf_tools_path)),
);
}
context.insert("add_paths_extras", &export_paths.join(";"));
let rendered = match tera.render("powershell_profile", &context) {
Err(e) => {
error!("Failed to render template: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to render template",
));
}
Ok(text) => text,
};
let mut filename = PathBuf::from(profile_path);
filename.push("Microsoft.PowerShell_profile.ps1");
fs::write(&filename, rendered).expect("Unable to write file");
Ok(filename.display().to_string())
}
/// Creates a desktop shortcut for the IDF tools using PowerShell on Windows.
///
/// # Parameters
///
/// * `idf_path` - A string representing the path to the ESP-IDF repository.
/// * `idf_tools_path` - A string representing the path to the IDF tools directory.
///
/// # Return Value
///
/// * `Result<String, std::io::Error>` - On success, returns a string indicating the output of the PowerShell script.
/// On error, returns an `std::io::Error` indicating the cause of the error.
pub fn create_desktop_shortcut(
profile_path: &str,
idf_path: &str,
idf_version: &str,
idf_tools_path: &str,
idf_python_env_path: Option<&str>,
export_paths: Vec<String>,
env_var_pairs: Vec<(String, String)>,
) -> Result<String, std::io::Error> {
match std::env::consts::OS {
"windows" => {
let filename = match create_powershell_profile(
profile_path,
idf_path,
idf_tools_path,
idf_python_env_path,
idf_version,
export_paths,
env_var_pairs,
) {
Ok(filename) => filename,
Err(err) => {
error!("Failed to create PowerShell profile: {}", err);
return Err(err);
}
};
let icon = include_bytes!("../assets/eim.ico");
let mut home = dirs::home_dir().unwrap();
home.push("Icons");
let _ = ensure_path(home.to_str().unwrap());
home.push("eim.ico");
fs::write(&home, icon).expect("Unable to write file");
let powershell_script_template =
include_str!("./../powershell_scripts/create_desktop_shortcut_template.ps1");
// Create a new Tera instance
let mut tera = Tera::default();
if let Err(e) = tera.add_raw_template("powershell_script", powershell_script_template) {
error!("Failed to add template: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to add template",
));
}
let mut context = Context::new();
context.insert("custom_profile_filename", &filename);
context.insert("name", &idf_version);
let rendered = match tera.render("powershell_script", &context) {
Err(e) => {
error!("Failed to render template: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to render template",
));
}
Ok(text) => text,
};
let output = match run_powershell_script(&rendered) {
Ok(o) => o,
Err(err) => {
error!("Failed to execute PowerShell script: {}", err);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to execute PowerShell script",
));
}
};
Ok(output)
}
_ => {
warn!("Creating desktop shortcut is only supported on Windows.");
Ok("Unimplemented on this platform.".to_string())
}
}
}
/// Retrieves the path to the local data directory for storing logs.
///
/// This function uses the `dirs` crate to find the appropriate directory for storing logs.
/// If the local data directory is found, it creates a subdirectory named "logs" within it.
/// If the directory creation fails, it returns an error.
///
/// # Returns
///
/// * `Some(PathBuf)` if the local data directory and log directory are successfully created.
/// * `None` if the local data directory cannot be determined.
///
pub fn get_log_directory() -> Option<PathBuf> {
// Use the dirs crate to find the local data directory
dirs::data_local_dir().map(|data_dir| {
// Create a subdirectory named "logs" within the local data directory
let log_dir = data_dir.join("eim").join("logs");
// Attempt to create the log directory
std::fs::create_dir_all(&log_dir).expect("Failed to create log directory");
// Return the path to the log directory
log_dir
})
}
/// Verifies the SHA256 checksum of a file against an expected checksum.
///
/// # Arguments
///
/// * `expected_checksum` - A string representing the expected SHA256 checksum.
/// * `file_path` - A string representing the path to the file to be verified.
///
/// # Returns
///
/// * `Ok(true)` if the file's checksum matches the expected checksum.
/// * `Ok(false)` if the file does not exist or its checksum does not match the expected checksum.
/// * `Err(io::Error)` if an error occurs while opening or reading the file.
pub fn verify_file_checksum(expected_checksum: &str, file_path: &str) -> Result<bool, io::Error> {
if !Path::new(file_path).exists() {
return Ok(false);
}
let mut file = File::open(file_path)?;
let mut hasher = Sha256::new();
let mut buffer = [0; 1024];
loop {
let bytes_read = file.read(&mut buffer)?;
if bytes_read == 0 {
break;
}
hasher.update(&buffer[..bytes_read]);
}
// Get the final hash
let result = hasher.finalize();
// Convert the hash to a hexadecimal string
let computed_checksum = format!("{:x}", result);
// Compare the computed checksum with the expected checksum
Ok(computed_checksum == expected_checksum)
}
/// Sets up the environment variables required for the ESP-IDF build system.
///
/// # Parameters
///
/// * `tool_install_directory`: A reference to a `PathBuf` representing the directory where the ESP-IDF tools are installed.
/// * `idf_path`: A reference to a `PathBuf` representing the path to the ESP-IDF framework directory.
///
/// # Return
///
/// * `Result<Vec<(String, String)>, String>`:
/// - On success, returns a `Vec` of tuples containing the environment variable names and their corresponding values.
/// - On error, returns a `String` describing the error.
///
pub fn setup_environment_variables(
tool_install_directory: &PathBuf,
idf_path: &PathBuf,
) -> Result<Vec<(String, String)>, String> {
let mut env_vars = vec![];
// env::set_var("IDF_TOOLS_PATH", tool_install_directory);
let instal_dir_string = tool_install_directory.to_str().unwrap().to_string();
env_vars.push(("IDF_TOOLS_PATH".to_string(), instal_dir_string));
let idf_path_string = idf_path.to_str().unwrap().to_string();
env_vars.push(("IDF_PATH".to_string(), idf_path_string));
env_vars.push((
"ESP_ROM_ELF_DIR".to_string(),
get_elf_rom_dir(tool_install_directory)
.unwrap()
.to_str()
.unwrap()
.to_string(),
));
env_vars.push((
"OPENOCD_SCRIPTS".to_string(),
get_openocd_scripts_folder(tool_install_directory).unwrap(),
));
let python_env_path_string = tool_install_directory
.join("python")
.to_str()
.unwrap()
.to_string();
env_vars.push(("IDF_PYTHON_ENV_PATH".to_string(), python_env_path_string));
Ok(env_vars)
}
/// Retrieves the path to the ELF (Executable and Linkable Format) ROM directory.
///
/// # Parameters
///
/// * `idf_tools_path` - A reference to a `PathBuf` representing the path to the IDF tools directory.
///
/// # Return
///
/// * `Result<PathBuf, std::io::Error>` - On success, returns a `PathBuf` representing the path to the ELF ROM directory.
/// On error, returns a `std::io::Error` indicating the cause of the error.
fn get_elf_rom_dir(idf_tools_path: &PathBuf) -> Result<PathBuf, std::io::Error> {
let elf_rom_dir = idf_tools_path.join("tools").join("esp-rom-elfs");
if elf_rom_dir.exists() {
let mut subdirs = vec![];
// Read the entries in the elf_rom_dir
for entry in fs::read_dir(&elf_rom_dir)? {
let entry = entry?;
let path = entry.path();
// Check if the entry is a directory and add it to the vector
if path.is_dir() {
subdirs.push(path);
}
}
// Sort the subdirectories
subdirs.sort();
if let Some(last_subdir) = subdirs.last() {
log::info!("ELF ROM directory found: {}", last_subdir.display());
return Ok(last_subdir.clone());
} else {
log::warn!("No ELF ROM directories found in {}", elf_rom_dir.display());
}
} else {
log::warn!("No ELF ROM directories found in {}", elf_rom_dir.display());
}
Ok(elf_rom_dir)
}
/// Retrieves the path to the OpenOCD scripts folder within the IDF tools directory.
///
/// # Parameters
///
/// * `idf_tools_path` - A reference to a `PathBuf` representing the path to the IDF tools directory.
///
/// # Return
///
/// * `Result<PathBuf, std::io::Error>` - On success, returns a `PathBuf` representing the path to the OpenOCD scripts folder.
/// On error, returns a `std::io::Error` indicating the cause of the error.
fn get_openocd_scripts_folder(idf_tools_path: &PathBuf) -> Result<String, std::io::Error> {
let search_path = idf_tools_path.join("tools").join("openocd-esp32");
let result = find_directories_by_name(&search_path, "scripts");
if result.is_empty() {
log::warn!("No OpenOCD scripts found in {}", search_path.display());
return Ok(String::new());
} else if result.len() > 1 {
log::warn!(
"Multiple OpenOCD scripts found in {}, using the first one",
search_path.display()
);
}
Ok(result[0].clone())
}
pub enum DownloadProgress {
Progress(u64, u64), // (downloaded, total)
Complete,
Error(String),
}
pub async fn download_file(
url: &str,
destination_path: &str,
progress_sender: Sender<DownloadProgress>,
) -> Result<(), std::io::Error> {
// Create a new HTTP client
let client = Client::new();
// Send a GET request to the specified URL
let mut response = client
.get(url)
.send()
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
// Get the total size of the file being downloaded
let total_size = response.content_length().ok_or_else(|| {
let _ = progress_sender.send(DownloadProgress::Error(
"Failed to get content length".into(),
));
std::io::Error::new(std::io::ErrorKind::Other, "Failed to get content length")
})?;
log::debug!("Downloading {} to {}", url, destination_path);
// Extract the filename from the URL
let filename = Path::new(&url).file_name().unwrap().to_str().unwrap();
log::debug!(
"Filename: {} and destination: {}",
filename,
destination_path
);
// Create a new file at the specified destination path
let mut file = File::create(Path::new(&destination_path).join(Path::new(filename)))?;
log::debug!("Created file at {}", destination_path);
// Initialize the amount downloaded
let mut downloaded: u64 = 0;
// Download the file in chunks
while let Some(chunk) = response
.chunk()
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?
{
// Update the amount downloaded
downloaded += chunk.len() as u64;
// Write the chunk to the file
file.write_all(&chunk)?;
// Call the progress callback function
if let Err(e) = progress_sender.send(DownloadProgress::Progress(downloaded, total_size)) {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to send progress: {}", e),
));
}
}
let _ = progress_sender.send(DownloadProgress::Complete);
// Return Ok(()) if the download was successful
Ok(())
}
#[derive(Error, Debug)]
pub enum DecompressionError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Zip error: {0}")]
Zip(#[from] zip::result::ZipError),
#[error("Unsupported archive format")]
UnsupportedFormat,
}
/// Decompresses an archive file into the specified destination directory.
///
/// # Parameters
///
/// * `archive_path`: A string representing the path to the archive file to be decompressed.
/// * `destination_path`: A string representing the path to the directory where the archive should be decompressed.
///
/// # Returns
///
/// * `Ok(())` if the decompression is successful.
/// * `Err(DecompressionError)` if an error occurs during the decompression process.
///
/// # Errors
///
/// This function can return the following errors:
///
/// * `DecompressionError::Io`: An error occurred while performing I/O operations.
/// * `DecompressionError::Zip`: An error occurred while decompressing a ZIP archive.
/// * `DecompressionError::UnsupportedFormat`: The specified archive format is not supported.
pub fn decompress_archive(
archive_path: &str,
destination_path: &str,
) -> Result<(), DecompressionError> {
let archive_path_long = make_long_path_compatible(archive_path);
let archive_path = Path::new(&archive_path_long);
let destination_path_long = make_long_path_compatible(destination_path);
let destination_path = Path::new(&destination_path_long);
if !destination_path.exists() {
std::fs::create_dir_all(destination_path)?;
}
match archive_path.extension().and_then(|ext| ext.to_str()) {
Some("zip") => decompress_zip(archive_path, destination_path),
Some("tar") => decompress_tar(archive_path, destination_path),
Some("gz") | Some("tgz") => {
if archive_path.to_str().unwrap_or("").ends_with(".tar.gz")
|| archive_path.extension().unwrap() == "tgz"
{
decompress_tar_gz(archive_path, destination_path)
} else {
Err(DecompressionError::UnsupportedFormat)
}
}
Some("xz") => {
if archive_path.to_str().unwrap_or("").ends_with(".tar.xz") {
decompress_tar_xz(archive_path, destination_path)
} else {
Err(DecompressionError::UnsupportedFormat)
}
}
_ => Err(DecompressionError::UnsupportedFormat),
}
}
/// Decompresses a ZIP archive into the specified destination directory.
///
/// # Parameters
///
/// * `archive_path`: A reference to a `Path` representing the path to the ZIP archive.
/// * `destination_path`: A reference to a `Path` representing the destination directory where the archive should be decompressed.
///
/// # Return Value
///
/// * `Result<(), DecompressionError>`: On success, returns `Ok(())`. On error, returns a `DecompressionError` indicating the cause of the error.
fn decompress_zip(archive_path: &Path, destination_path: &Path) -> Result<(), DecompressionError> {
log::info!(
"Decompressing {} to {}",
archive_path.display(),
destination_path.display()
);
if !Path::new(archive_path).exists() {
log::error!("File does not exist.");
return Err(DecompressionError::Io(io::Error::new(
io::ErrorKind::NotFound,
"Archive file not found",
)));
}
match std::env::consts::OS {
"windows" => {
let executor = crate::command_executor::get_executor();
let archive_path_str = archive_path.to_string_lossy();
let destination_path_str = destination_path.to_string_lossy();
let script = format!(
"Expand-Archive -Path '{}' -DestinationPath '{}' -Force",
archive_path_str, destination_path_str
);
match executor.run_script_from_string(&script) {
Ok(output) => {
if !output.status.success() {
let error_message = String::from_utf8_lossy(&output.stderr);
log::error!("Decompression failed: {}", error_message);
return Err(DecompressionError::Io(io::Error::new(
io::ErrorKind::Other,
format!("PowerShell decompression failed: {}", error_message),
)));
}
Ok(())
}
Err(e) => {
log::error!("Failed to execute PowerShell command: {}", e);
Err(DecompressionError::Io(e))
}
}
}
_ => {
let file = File::open(archive_path)?;
let mut archive = ZipArchive::new(file)?;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
let outpath = match file.enclosed_name() {
Some(path) => destination_path.join(path),
None => continue,
};
if file.name().ends_with('/') {
std::fs::create_dir_all(&outpath)?;
} else {
if let Some(p) = outpath.parent() {
if !p.exists() {
std::fs::create_dir_all(p)?;
}
}
let mut outfile = File::create(&outpath)?;
io::copy(&mut file, &mut outfile)?;
}
}
Ok(())
}
}
}
/// Decompresses a TAR archive into the specified destination directory.
///
/// # Parameters
///
/// * `archive_path`: A reference to a `Path` representing the path to the TAR archive.
/// * `destination_path`: A reference to a `Path` representing the destination directory where the archive should be decompressed.
///
/// # Return Value
///
/// * `Result<(), DecompressionError>`: On success, returns `Ok(())`. On error, returns a `DecompressionError` indicating the cause of the error.
fn decompress_tar(archive_path: &Path, destination_path: &Path) -> Result<(), DecompressionError> {
let file = File::open(archive_path)?;
let mut archive = Archive::new(file);
archive.unpack(destination_path)?;
Ok(())
}
/// Decompresses a TAR.GZ archive into the specified destination directory.
///
/// # Parameters
///
/// * `archive_path`: A reference to a `Path` representing the path to the TAR.GZ archive.
/// * `destination_path`: A reference to a `Path` representing the destination directory where the archive should be decompressed.
///
/// # Return Value
///
/// * `Result<(), DecompressionError>`: On success, returns `Ok(())`. On error, returns a `DecompressionError` indicating the cause of the error.
fn decompress_tar_gz(
archive_path: &Path,
destination_path: &Path,
) -> Result<(), DecompressionError> {
let file = File::open(archive_path)?;
let gz = GzDecoder::new(file);
let mut archive = Archive::new(gz);
archive.unpack(destination_path)?;
Ok(())
}
/// Decompresses a TAR.XZ archive into the specified destination directory.
///
/// # Parameters
///
/// * `archive_path`: A reference to a `Path` representing the path to the TAR.XZ archive.
/// * `destination_path`: A reference to a `Path` representing the destination directory where the archive should be decompressed.
///
/// # Returns
///
/// * `Result<(), DecompressionError>`: On success, returns `Ok(())`. On error, returns a `DecompressionError` indicating the cause of the error.
fn decompress_tar_xz(
archive_path: &Path,
destination_path: &Path,
) -> Result<(), DecompressionError> {
let file = File::open(archive_path)?;
let xz = XzDecoder::new(file);
let mut archive = Archive::new(xz);
archive.unpack(destination_path)?;
Ok(())
}
/// Ensures that a directory exists at the specified path.
/// If the directory does not exist, it will be created.
///
/// # Arguments
///
/// * `directory_path` - A string representing the path to the directory to be ensured.
///
/// # Returns
///
/// * `Ok(())` if the directory was successfully created or already exists.
/// * `Err(std::io::Error)` if an error occurred while creating the directory.
pub fn ensure_path(directory_path: &str) -> std::io::Result<()> {
let path = Path::new(directory_path);
if !path.exists() {
// If the directory does not exist, create it
fs::create_dir_all(directory_path)?;
}
Ok(())
}
/// Adds a directory to the system's PATH environment variable.
/// If the directory is already present in the PATH, it will not be added again.
///
/// # Arguments
///
/// * `directory_path` - A string representing the path of the directory to be added to the PATH.
///
/// # Example
///
/// ```rust
/// use idf_im_lib::add_path_to_path;
///
/// add_path_to_path("/usr/local/bin");
/// ```
pub fn add_path_to_path(directory_path: &str) {
// Retrieve the current PATH environment variable.
// If it does not exist, use an empty string as the default value.
let current_path = env::var("PATH").unwrap_or_default();
// Check if the directory path is already present in the PATH.
// If it is not present, construct a new PATH string with the directory path added.
if !current_path.contains(directory_path) {
let new_path = if current_path.is_empty() {
directory_path.to_owned()
} else {
format!("{};{}", current_path, directory_path)
};
// Set the new PATH environment variable.
env::set_var("PATH", new_path);
}
}
/// Messages that can be sent to update the progress bar.
pub enum ProgressMessage {
/// Update the progress bar with the given value.
Update(u64),
/// Finish the progress bar.
Finish,
}
/// Performs a shallow clone of a Git repository.
///
/// # Arguments
///
/// * `url` - A string representing the URL of the Git repository to clone.
/// * `path` - A string representing the local path where the repository should be cloned.
/// * `branch` - An optional string representing the branch to checkout after cloning. If `None`, the default branch will be checked out.
/// * `tag` - An optional string representing the tag to checkout after cloning. If `None`, the repository will be cloned at the specified branch.
/// * `tx` - A channel sender for progress reporting.
///
/// # Returns
///
/// * `Ok(Repository)` if the cloning process is successful and the repository is opened.
/// * `Err(git2::Error)` if an error occurs during the cloning process.
///
fn shallow_clone(
url: &str,
path: &str,
branch: Option<&str>,
tag: Option<&str>,
tx: std::sync::mpsc::Sender<ProgressMessage>,
recurse_submodules: bool,
) -> Result<Repository, git2::Error> {
// Initialize fetch options with depth 1 for shallow cloning
let mut fo = FetchOptions::new();
if tag.is_none() {
fo.depth(1);
}
// Set up remote callbacks for progress reporting
let mut callbacks = RemoteCallbacks::new();
callbacks.transfer_progress(|stats| {
let val =
((stats.received_objects() as f64) / (stats.total_objects() as f64) * 100.0) as u64;
tx.send(ProgressMessage::Update(val)).unwrap();
true
});
fo.remote_callbacks(callbacks);
// Create a new repository builder with the fetch options
let mut builder = git2::build::RepoBuilder::new();
builder.fetch_options(fo);
// Set the branch to checkout if specified
if let Some(branch) = branch {
builder.branch(branch);
};
// Clone the repository
let repo = builder.clone(url, Path::new(path))?;
// If a tag is specified, checkout the corresponding commit
if let Some(tag) = tag {
// Look up the tag reference
let tag_ref = repo.find_reference(&format!("refs/tags/{}", tag))?;
// Peel the tag reference to get the commit object
let tag_obj = tag_ref.peel(ObjectType::Commit)?;
// Checkout the commit that the tag points to
repo.checkout_tree(&tag_obj, None)?;
repo.set_head_detached(tag_obj.id())?;
};
// If a branch is specified, checkout the corresponding branch
if let Some(branch) = branch {
// Rev-parse the branch reference to get the commit object
let obj = repo.revparse_single(&format!("origin/{}", branch))?;
// Checkout the commit that the branch points to
repo.checkout_tree(&obj, None)?;
repo.set_head(&format!("refs/heads/{}", branch))?;
};
if recurse_submodules {
let mut sfo = FetchOptions::new();
let mut callbacks = RemoteCallbacks::new();
info!("Fetching submodules");
callbacks.transfer_progress(|stats| {