blackjack/
file.rs

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
// Copyright 2024 Ole Kliemann
// SPDX-License-Identifier: Apache-2.0

use crate::error::Result;
use std::path::{Path, PathBuf};
use tokio::fs;

pub async fn read_yaml_files(dirname: PathBuf) -> Result<String> {
    log::debug!("read_yaml_files: {dirname:?}");
    let mut combined = String::new();
    let mut entries: Vec<_> = list_files(&dirname)
        .await?
        .into_iter()
        .filter(|path| {
            path.extension()
                .map(|ext| ext.to_string_lossy().eq_ignore_ascii_case("yaml"))
                .unwrap_or(false)
        })
        .collect();

    entries.sort();

    log::debug!("entries: {entries:?}");

    let mut first = true;

    for path in entries {
        let content = fs::read_to_string(&path).await?;

        if !first {
            combined.push_str("---\n");
        } else {
            first = false;
        }

        combined.push_str(&content);
        combined.push('\n');
    }

    log::debug!("returning: ...");
    Ok(combined)
}

pub async fn list_directories(dirname: &PathBuf) -> Result<Vec<PathBuf>> {
    let root = Path::new(dirname);
    let mut dir = fs::read_dir(root).await?;
    let mut result: Vec<PathBuf> = vec![];
    while let Some(entry) = dir.next_entry().await? {
        let path = entry.path();
        if path.is_dir() {
            result.push(path);
        }
    }
    Ok(result)
}

pub async fn list_files(dirname: &PathBuf) -> Result<Vec<PathBuf>> {
    log::debug!("list_files: {dirname:?}");
    let root = Path::new(dirname);
    let mut dir = fs::read_dir(root).await?;
    let mut result: Vec<PathBuf> = vec![];
    while let Some(entry) = dir.next_entry().await? {
        log::debug!("found: {dirname:?}");
        let path = entry.path();
        if path.is_file() {
            result.push(path);
        }
    }
    log::debug!("returning: {result:?}");
    Ok(result)
}