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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use crate::progress::Progress;
use anyhow::bail;
use std::{
    future::Future,
    path::{Path, PathBuf},
    pin::Pin,
};
use tracing::instrument;

/// A tool to build a [`Scooper`].
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub struct ScooperBuilder {
    pub sources: Vec<PathBuf>,
    pub delete: bool,
    pub processed: Option<PathBuf>,
    pub failed: Option<PathBuf>,
}

impl ScooperBuilder {
    pub fn build(self) -> anyhow::Result<Scooper> {
        let files = self.discover()?;
        Ok(Scooper {
            builder: self,
            files,
        })
    }

    /// Discover files to upload
    fn discover(&self) -> anyhow::Result<Vec<PathBuf>> {
        Ok(self
            .sources
            .iter()
            .map(|path| Self::discover_one(path))
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .flatten()
            .collect())
    }

    fn discover_one(path: &Path) -> anyhow::Result<Vec<PathBuf>> {
        log::debug!("Discovering: {}", path.display());

        if !path.exists() {
            bail!("{} does not exist", path.display());
        } else if path.is_file() {
            log::debug!("Is a file");
            Ok(vec![path.to_path_buf()])
        } else if path.is_dir() {
            log::debug!("Is a directory");
            let mut result = Vec::new();

            for path in walkdir::WalkDir::new(path).into_iter() {
                let path = path?;
                if path.file_type().is_file() {
                    result.push(path.path().to_path_buf());
                }
            }

            Ok(result)
        } else {
            log::warn!("Is something unknown: {}", path.display());
            Ok(vec![])
        }
    }
}

/// A tool to scoop up files
pub struct Scooper {
    builder: ScooperBuilder,
    files: Vec<PathBuf>,
}

impl Scooper {
    #[instrument(skip_all, err)]
    pub async fn process<F>(self, progress: impl Into<Progress>, processor: F) -> anyhow::Result<()>
    where
        F: for<'a> Fn(&'a Path) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + 'a>>,
    {
        if let Some(processed) = &self.builder.processed {
            tokio::fs::create_dir_all(processed).await?;
        }
        if let Some(failed) = &self.builder.failed {
            tokio::fs::create_dir_all(failed).await?;
        }

        let total = self.files.len();
        let mut errors = 0usize;

        let progress = progress.into();
        let p = progress.start(total);
        for file in self.files {
            p.set_message(
                file.file_name()
                    .map(|s| s.to_string_lossy())
                    .unwrap_or_else(|| file.to_string_lossy())
                    .to_string()
                    .into(),
            );
            match processor(&file).await {
                Ok(()) => {
                    if self.builder.delete {
                        tokio::fs::remove_file(&file).await?;
                    } else if let Some(processed) = &self.builder.processed {
                        tokio::fs::copy(&file, processed.join(&file)).await?;
                        tokio::fs::remove_file(&file).await?;
                    }
                }
                Err(err) => {
                    errors += 1;
                    log::error!("Failed to upload file: {err}");
                    if let Some(failed) = &self.builder.failed {
                        tokio::fs::copy(&file, failed.join(&file)).await?;
                        tokio::fs::remove_file(&file).await?;
                    }
                }
            }
            p.tick();
        }
        drop(p);

        match errors {
            0 => {
                log::info!("Uploaded {total} files");
                Ok(())
            }
            n => bail!("Failed to upload {n} (of {total}) files"),
        }
    }
}