1use crate::*;
2use anyhow::Result;
3use std::{
4 fs,
5 io::{self, Read, Write},
6 path::Path,
7};
8use tracing_subscriber::{EnvFilter, fmt};
9
10
11pub fn initialize() {
13 let env_log = match EnvFilter::try_from_env("LOG") {
14 Ok(env_value_from_env) => env_value_from_env,
15 Err(_) => EnvFilter::from("info"),
16 };
17 fmt()
18 .compact()
19 .with_thread_names(false)
20 .with_thread_ids(false)
21 .with_ansi(true)
22 .with_env_filter(env_log)
23 .with_filter_reloading()
24 .init();
25}
26
27
28pub fn put_to_clipboard(text: &str) -> Result<()> {
29 let mut clipboard = clippers::Clipboard::get();
30 clipboard.write_text(text)?;
31 Ok(())
32}
33
34
35pub fn local_file_size<P: AsRef<Path>>(file_path: P) -> Result<u64> {
36 let metadata = fs::metadata(file_path)?;
37 Ok(metadata.len())
38}
39
40
41pub fn size_kib(size_in_bytes: u64) -> f64 {
42 (size_in_bytes as f64) / 1024.0
43}
44
45
46pub fn file_extension<P: AsRef<Path>>(path: P) -> String {
47 path.as_ref()
48 .extension()
49 .and_then(|e| e.to_str())
50 .map(|e| format!(".{e}"))
51 .unwrap_or_default()
52}
53
54
55pub fn stream_file_to_remote<R, W>(
56 reader: &mut R,
57 writer: &mut W,
58 buffer_size: usize,
59 total_size: u64,
60) -> Result<()>
61where
62 R: Read,
63 W: Write,
64{
65 let mut buffer = vec![0u8; buffer_size];
66 let chunks = if total_size > 0 {
68 (total_size / buffer_size as u64) + 1
69 } else {
70 1
71 };
72
73 info!(
74 "Streaming file of size: {:.2}KiB to remote server..",
75 size_kib(total_size)
76 );
77
78 let mut chunk_index = 0u64;
79 loop {
80 let bytes_read = reader.read(&mut buffer)?;
81 if bytes_read == 0 {
82 break;
83 }
84
85 writer.write_all(&buffer[..bytes_read])?;
86 chunk_index += 1;
87
88 let percent = if chunks > 0 {
89 (chunk_index as f64 * 100.0) / chunks as f64
90 } else {
91 100.0
92 };
93
94 eprint!("\rProgress: {percent:.2}% ");
95 io::stderr().flush()?;
96 }
97
98 eprintln!(); info!("Upload complete!");
100 Ok(())
101}