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