composer_primitives/types/
source_files.rs

1use anyhow::Error;
2use std::{env::current_dir, ffi::OsStr, fs, path::PathBuf};
3
4use itertools::Either;
5use std::collections::HashSet;
6use walkdir::WalkDir;
7
8use crate::constant::FILE_EXTENSION;
9
10#[derive(Clone, Debug)]
11pub struct SourceFiles {
12    base: PathBuf,
13    files: HashSet<PathBuf>,
14}
15
16impl SourceFiles {
17    pub fn new(path: Option<PathBuf>) -> Result<SourceFiles, Error> {
18        let base = match path {
19            Some(path) => {
20                if path.is_file() {
21                    path.parent().unwrap().to_path_buf()
22                } else if path.is_dir() {
23                    path
24                } else {
25                    return Err(Error::msg("PathNotFound"));
26                }
27            }
28            None => current_dir().unwrap(),
29        };
30
31        let file_paths = fs::read_dir(&base)
32            .unwrap()
33            .into_iter()
34            .flat_map(|item| {
35                let item = item.unwrap();
36
37                if item.path().is_dir() {
38                    Either::Left(
39                        WalkDir::new(item.path())
40                            .into_iter()
41                            .filter_map(|e| e.ok())
42                            .filter(move |e| {
43                                e.path().extension() == Some(OsStr::new(FILE_EXTENSION))
44                            })
45                            .map(|e| e.into_path()),
46                    )
47                } else {
48                    Either::Right(Box::new(
49                        vec![item.path()]
50                            .into_iter()
51                            .filter(|e| e.extension() == Some(OsStr::new(FILE_EXTENSION))),
52                    ))
53                }
54            })
55            .collect::<HashSet<PathBuf>>();
56
57        Ok(SourceFiles {
58            base,
59            files: file_paths,
60        })
61    }
62
63    pub fn files(&self) -> &HashSet<PathBuf> {
64        &self.files
65    }
66
67    pub fn base(&self) -> &PathBuf {
68        &self.base
69    }
70}