summaryrefslogtreecommitdiff
path: root/src/utils/file_input_solve.rs
blob: 30d5765091ad4a17273e13b64f6c685cf2030a87 (plain)
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
use std::{
    env::current_dir,
    path::{Path, PathBuf},
};

use just_fmt::fmt_path::fmt_path;

pub fn parse_path_input(
    files: Vec<String>,
    recursive: bool,
    exclude_dir: Vec<&str>,
) -> Vec<PathBuf> {
    let current_dir = current_dir().unwrap();
    let files = if recursive {
        let mut result: Vec<PathBuf> = Vec::new();
        for arg in files.iter().skip(1) {
            if exclude_dir.contains(&arg.as_str()) {
                continue;
            }
            let path = current_dir.join(arg);
            if path.is_dir() {
                if let Err(e) = collect_files_recursively(&path, &mut result) {
                    eprintln!("Error collecting files recursively: {}", e);
                    continue;
                }
            } else {
                result.push(path);
            }
        }
        result
    } else {
        let mut result = Vec::new();
        for arg in files.iter().skip(1) {
            if exclude_dir.contains(&arg.as_str()) {
                continue;
            }
            let path = current_dir.join(arg);
            if path.is_dir() {
                if files.len() == 2 {
                    for entry in std::fs::read_dir(&path)
                        .unwrap_or_else(|e| {
                            eprintln!("Error reading directory: {}", e);
                            std::fs::read_dir(".").unwrap()
                        })
                        .flatten()
                    {
                        let entry_path = entry.path();
                        if !entry_path.is_dir() {
                            result.push(entry_path);
                        }
                    }
                }
            } else {
                result.push(path);
            }
        }
        result
    };
    files
        .into_iter()
        .filter_map(|path| match fmt_path(path) {
            Ok(formatted_path) => Some(formatted_path),
            Err(e) => {
                eprintln!("Error formatting path: {}", e);
                None
            }
        })
        .collect()
}

fn collect_files_recursively(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_files_recursively(&path, files)?;
        } else {
            files.push(path);
        }
    }
    Ok(())
}