Skip to content

Commit a125cff

Browse files
committed
verify and download rootfs command
1 parent fc1575a commit a125cff

File tree

1 file changed

+75
-45
lines changed

1 file changed

+75
-45
lines changed

src/utils.rs

Lines changed: 75 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ use std::{env, fs, io};
99
use walkdir_minimal::WalkDir;
1010
use which::which;
1111

12-
pub const DOWNLOAD_TEMPLATE: &str =
13-
"{msg} {spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})";
12+
pub const DOWNLOAD_TEMPLATE: &str = "{msg} {spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})";
1413

1514
#[macro_export]
1615
macro_rules! parse_key_value {
@@ -40,9 +39,22 @@ macro_rules! parse_key_value {
4039
/// let val = _parse_key_value("install", "PATH", "cache", "--cache=/tmp".to_string(), None)?;
4140
/// assert_eq!(val, Some("/tmp".to_string()));
4241
/// ```
43-
pub fn _parse_key_value(sub: &str, val: &str, arg: String, next_args: Option<String>) -> Result<Option<String>, Box<dyn Error>> {
44-
let prefix = arg.clone().split("=").collect::<Vec<&str>>()[0].to_string().add("=");
45-
let cmd = env::current_exe().unwrap().file_name().unwrap().to_str().unwrap().to_string();
42+
pub fn _parse_key_value(
43+
sub: &str,
44+
val: &str,
45+
arg: String,
46+
next_args: Option<String>,
47+
) -> Result<Option<String>, Box<dyn Error>> {
48+
let prefix = arg.clone().split("=").collect::<Vec<&str>>()[0]
49+
.to_string()
50+
.add("=");
51+
let cmd = env::current_exe()
52+
.unwrap()
53+
.file_name()
54+
.unwrap()
55+
.to_str()
56+
.unwrap()
57+
.to_string();
4658
let mut value = arg.strip_prefix(&prefix).unwrap_or_default().to_string();
4759
let mut sp = "".to_string();
4860

@@ -68,11 +80,8 @@ pub fn _parse_key_value(sub: &str, val: &str, arg: String, next_args: Option<Str
6880
/// println!("Detected architecture: {}", arch);
6981
/// ```
7082
pub fn get_arch() -> String {
71-
env::var("ALPACK_ARCH").unwrap_or_else(
72-
|_| env::var("ARCH").unwrap_or_else(
73-
|_| env::consts::ARCH.to_string()
74-
)
75-
)
83+
env::var("ALPACK_ARCH")
84+
.unwrap_or_else(|_| env::var("ARCH").unwrap_or_else(|_| env::consts::ARCH.to_string()))
7685
}
7786

7887
/// Displays a final setup message with styled formatting.
@@ -86,9 +95,11 @@ pub fn get_arch() -> String {
8695
/// ```
8796
pub fn finish_msg_setup(cmd: String) {
8897
println!(
89-
"{s}\n Installation completed successfully!\n
98+
"{s}\n Installation completed successfully!\n
9099
To start the environment, run:\n{b}\n{s}",
91-
b = get_cmd_box(format!("$ {} run", cmd), Some(2), None).unwrap(), s = separator_line());
100+
b = get_cmd_box(format!("$ {} run", cmd), Some(2), None).unwrap(),
101+
s = separator_line()
102+
);
92103
}
93104

94105
/// Verifies that the specified rootfs directory exists.
@@ -106,13 +117,16 @@ b = get_cmd_box(format!("$ {} run", cmd), Some(2), None).unwrap(), s = separator
106117
/// ```
107118
pub fn check_rootfs_exists(cmd: String, path: String) -> Result<(), Box<dyn Error>> {
108119
let dir = Path::new(path.as_str());
109-
if ! dir.is_dir() {
120+
if !dir.is_dir() {
110121
return Err(format!(
111-
"{s}\n Error: rootfs directory not found.\n
122+
"{s}\n Error: rootfs directory not found.\n
112123
Expected location:
113124
-> {path}\n
114125
Please run the following command to set it up:\n{b}\n{s}",
115-
b = get_cmd_box(format!("$ {} setup", cmd), Some(2), None)?, s = separator_line()).into())
126+
b = get_cmd_box(format!("$ {} setup", cmd), Some(2), None)?,
127+
s = separator_line()
128+
)
129+
.into());
116130
}
117131
Ok(())
118132
}
@@ -130,24 +144,31 @@ b = get_cmd_box(format!("$ {} setup", cmd), Some(2), None)?, s = separator_line(
130144
/// let box_str = get_cmd_box("$ ALPack setup");
131145
/// println!("{}", box_str);
132146
/// ```
133-
pub fn get_cmd_box(name: String, repeat: Option<usize>, size: Option<usize>) -> Result<String, Box<dyn Error>> {
147+
pub fn get_cmd_box(
148+
name: String,
149+
repeat: Option<usize>,
150+
size: Option<usize>,
151+
) -> Result<String, Box<dyn Error>> {
134152
let command = name;
135153
let width: usize = size.unwrap_or_else(|| 50);
136154
let rep: usize = repeat.unwrap_or_else(|| 0);
137155

138-
let top = "╔".to_string() + &"═".repeat(width - 2) + "╗";
139-
let bottom ="╚".to_string() + &"═".repeat(width - 2) + "╝";
156+
let top = "╔".to_string() + &"═".repeat(width - 2) + "╗";
157+
let bottom = "╚".to_string() + &"═".repeat(width - 2) + "╝";
140158

141159
let mut middle = String::from("║ ");
142160
middle += command.as_str();
143161
middle += &" ".repeat(width - 3 - command.len());
144162
middle += "║";
145163

146164
if rep == 0 {
147-
return Ok(format!("{top}\n{middle}\n{bottom}"))
165+
return Ok(format!("{top}\n{middle}\n{bottom}"));
148166
}
149167

150-
Ok(format!("{r}{top}\n{r}{middle}\n{r}{bottom}", r = " ".repeat(rep)))
168+
Ok(format!(
169+
"{r}{top}\n{r}{middle}\n{r}{bottom}",
170+
r = " ".repeat(rep)
171+
))
151172
}
152173

153174
/// Generates a line composed of a repeated character.
@@ -180,7 +201,9 @@ pub fn separator_line() -> String {
180201
/// ```
181202
pub fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
182203
println!("copy {} to {}", src.display(), dst.display());
183-
let dir_name = src.file_name().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, "invalid directory") })?;
204+
let dir_name = src
205+
.file_name()
206+
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "invalid directory"))?;
184207
let dest_root = dst.join(dir_name);
185208

186209
for entry in WalkDir::new(src)? {
@@ -220,9 +243,12 @@ pub fn create_dir_with_fallback(target: String) -> io::Result<PathBuf> {
220243
match fs::create_dir_all(target_path) {
221244
Ok(_) => return Ok(target_path.to_path_buf()),
222245
Err(ref e) if e.kind() == io::ErrorKind::PermissionDenied => {
223-
eprintln!("\x1b[1;33mWarning\x1b[0m: Permission denied to create '{}', using default directory instead...", target);
246+
eprintln!(
247+
"\x1b[1;33mWarning\x1b[0m: Permission denied to create '{}', using default directory instead...",
248+
target
249+
);
224250
}
225-
Err(e) => return Err(e)
251+
Err(e) => return Err(e),
226252
}
227253

228254
let home = Settings::load_or_create().set_rootfs();
@@ -259,14 +285,30 @@ pub fn download_file(url: String, dest: String, filename: String) -> io::Result<
259285
}
260286

261287
println!("Saving file to: {save_file}");
262-
let resp = ureq::get(url).call().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
263-
let length = resp.headers().get("Content-Length").unwrap().to_str().unwrap().parse().unwrap();
288+
let resp = ureq::get(url)
289+
.call()
290+
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
291+
let length = resp
292+
.headers()
293+
.get("Content-Length")
294+
.unwrap()
295+
.to_str()
296+
.unwrap()
297+
.parse()
298+
.unwrap();
264299

265300
let bar = ProgressBar::new(length);
266301
bar.set_message("Downloading...");
267-
bar.set_style(ProgressStyle::with_template(DOWNLOAD_TEMPLATE).unwrap().progress_chars("##-"));
268-
269-
io::copy(&mut bar.wrap_read(resp.into_body().into_reader()), &mut File::create(save_file)?)?;
302+
bar.set_style(
303+
ProgressStyle::with_template(DOWNLOAD_TEMPLATE)
304+
.unwrap()
305+
.progress_chars("##-"),
306+
);
307+
308+
io::copy(
309+
&mut bar.wrap_read(resp.into_body().into_reader()),
310+
&mut File::create(save_file)?,
311+
)?;
270312
bar.finish_with_message("Downloaded!");
271313
Ok(save_dest)
272314
}
@@ -281,7 +323,6 @@ fn local_bin_dir() -> PathBuf {
281323
PathBuf::from(home).join(".local").join("bin")
282324
}
283325

284-
285326
/// Sets executable permissions on a file (Unix-only).
286327
///
287328
/// # Arguments
@@ -308,17 +349,12 @@ fn make_executable(path: &Path) -> io::Result<()> {
308349
/// * `None` if the command is unknown or unsupported.
309350
fn binary_url(cmd: &str) -> Option<&'static str> {
310351
match cmd {
311-
"proot" => Some(
312-
"https://github.com/LinuxDicasPro/StaticHub/releases/download/proot/proot",
313-
),
314-
"bwrap" => Some(
315-
"https://github.com/LinuxDicasPro/StaticHub/releases/download/bwrap/bwrap",
316-
),
352+
"proot" => Some("https://github.com/LinuxDicasPro/StaticHub/releases/download/proot/proot"),
353+
"bwrap" => Some("https://github.com/LinuxDicasPro/StaticHub/releases/download/bwrap/bwrap"),
317354
_ => None,
318355
}
319356
}
320357

321-
322358
/// Checks whether the current system architecture is x86_64.
323359
///
324360
/// # Returns
@@ -347,9 +383,7 @@ fn is_x86_64() -> bool {
347383
/// # Errors
348384
/// Returns `io::ErrorKind::Unsupported` if the command is not found and
349385
/// no binary is available for the current architecture.
350-
pub fn verify_and_download_rootfs_command(
351-
cmd_rootfs: &str,
352-
) -> io::Result<PathBuf> {
386+
pub fn verify_and_download_rootfs_command(cmd_rootfs: &str) -> io::Result<PathBuf> {
353387
if let Some(path) = which(cmd_rootfs).ok() {
354388
return Ok(path);
355389
}
@@ -371,12 +405,8 @@ pub fn verify_and_download_rootfs_command(
371405
));
372406
}
373407

374-
let url = binary_url(cmd_rootfs).ok_or_else(|| {
375-
io::Error::new(
376-
io::ErrorKind::InvalidInput,
377-
"invalid cmd_rootfs",
378-
)
379-
})?;
408+
let url = binary_url(cmd_rootfs)
409+
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid cmd_rootfs"))?;
380410

381411
fs::create_dir_all(&local_dir)?;
382412

0 commit comments

Comments
 (0)