Simple tool for automatic file management
1use color_eyre::eyre::Result;
2
3use std::path::{Path, PathBuf};
4
5use tokio::fs;
6use tokio_stream::wrappers::ReadDirStream;
7
8use serde::Deserialize;
9
10use crate::actions::Action;
11use crate::filters::Filter;
12
13/// Definition of the job files
14#[derive(Debug, Deserialize)]
15pub struct Job {
16 filter: Box<dyn Filter>,
17 location: PathBuf,
18 actions: Vec<Action>,
19}
20
21impl Job {
22 /// Returns stream of actions that should be executed
23 pub async fn actions(
24 &self,
25 ) -> Result<impl tokio_stream::Stream<Item = (Action, PathBuf)> + '_> {
26 let loc = normalise_path(&self.location);
27
28 let dir = ReadDirStream::new(fs::read_dir(&loc).await?);
29
30 Ok(async_stream::stream! {
31 for await entry in dir {
32 let entry = entry.unwrap();
33 if self.filter.matches(&entry.path()).await {
34 for action in &self.actions {
35 yield (action.clone(), entry.path())
36 }
37 }
38 }
39 })
40 }
41}
42
43pub(crate) fn normalise_path(path: &Path) -> PathBuf {
44 match path.strip_prefix("~") {
45 Ok(prefix) => std::env::home_dir().unwrap().join(prefix),
46 Err(_) => path.to_owned(),
47 }
48}