kget/
utils.rs

1/// Print a message to the console if not in quiet mode.
2/// 
3/// # Arguments
4/// 
5/// * `msg` - The message to print
6/// * `quiet_mode` - If true, suppress printing the message
7pub fn print(msg: &str, quiet_mode: bool) {
8    if !quiet_mode {
9        println!("{}", msg);
10    }
11}
12
13/// Tries to extract the filename from a URL.
14/// If the URL cannot be parsed or does not contain a filename in the path,
15/// it returns the provided default filename.
16///
17/// # Arguments
18///
19/// * `url_str` - A string slice of the URL to extract the filename from.
20/// * `default_filename` - The filename to return if none can be extracted from the URL.
21///
22/// # Returns
23///
24/// A `String` containing the extracted filename or the default filename.
25pub fn get_filename_from_url_or_default(url_str: &str, default_filename: &str) -> String {
26    // Tries to parse the URL
27    if let Ok(parsed_url) = url::Url::parse(url_str) {
28        // Tries to get the last segment of the path
29        if let Some(segments) = parsed_url.path_segments() {
30            if let Some(last_segment) = segments.last() {
31                if !last_segment.is_empty() {
32                    return last_segment.to_string();
33                }
34            }
35        }
36    }
37    // Returns the default filename if parsing fails or the path is empty/invalid
38    default_filename.to_string()
39}
40
41/// Resolves the final output path.
42/// If output_arg is None, extracts filename from URL.
43/// If output_arg is a directory, appends filename from URL.
44/// If output_arg is a file path, uses it as is.
45pub fn resolve_output_path(output_arg: Option<String>, url: &str, default_name: &str) -> String {
46    if let Some(path_str) = output_arg {
47        let path = std::path::Path::new(&path_str);
48        if path.is_dir() {
49            let filename = get_filename_from_url_or_default(url, default_name);
50            path.join(filename).to_string_lossy().to_string()
51        } else {
52            path_str
53        }
54    } else {
55        get_filename_from_url_or_default(url, default_name)
56    }
57}
58