~zethra/stargazer

ref: 72f642cc156231c4f16e0df63587eb256a788627 stargazer/src/config/template.rs -rw-r--r-- 6.5 KiB
72f642ccSashanoraa fixup! fixup! Add basic Jinja templating a month ago
                                                                                
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::ffi::OsStr;
use std::fmt::Display;
use std::path::Path;

use minijinja::value::{Object, Value};
use minijinja::{Environment, Error, ErrorKind, State};
use os_str_bytes::OsStrBytes;
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};

pub fn get_env() -> Environment<'static> {
    let mut env = Environment::new();
    env.add_function("load_text", load_text);
    env.add_function("file_list", file_list);

    env.add_filter("dirs_first", dirs_first);
    env.add_filter("sort_files", sort_files);
    env.add_filter("lines", lines);
    env.add_filter("split", split);
    env
}

#[derive(Debug, Clone)]
struct FileEntry {
    name: String,
    stem: String,
    path: String,
    is_dir: bool,
}

impl Display for FileEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl Object for FileEntry {
    fn get_attr(&self, name: &str) -> Option<Value> {
        match name {
            "name" => Some(self.name.to_owned().into()),
            "stem" => Some(self.stem.to_owned().into()),
            "path" => Some(self.path.to_owned().into()),
            "is_dir" => Some(self.is_dir.into()),
            _ => None,
        }
    }

    fn attributes(&self) -> &[&str] {
        &["name", "stem", "path", "is_dir"]
    }
}

fn file_list(state: &State) -> Result<Vec<Value>, Error> {
    let file_path = state.lookup("path").ok_or_else(|| {
        Error::new(
            ErrorKind::NonKey,
            "Variable `path` not in template, this is a bug in stargazer",
        )
    })?;
    let file_path = String::try_from(file_path).map_err(|_| {
        Error::new(
            ErrorKind::BadSerialization,
            "Variable `path` is not a string, this is a bug in stargazer",
        )
    })?;
    let dir_path = Path::new(&file_path).parent().ok_or_else(|| {
        Error::new(
            ErrorKind::UndefinedError,
            format!(
                "This script's path `{}` does not have a parent directory",
                file_path
            ),
        )
    })?;
    let dir_iter = dir_path.read_dir().map_err(|_| {
        Error::new(
            ErrorKind::UndefinedError,
            format!("Error reading dir `{}`", dir_path.display()),
        )
    })?;
    let mut file_list = vec![];
    for entry in dir_iter {
        let entry = entry.map_err(|_| {
            Error::new(
                ErrorKind::UndefinedError,
                format!("Error reading entry for dir `{}`", dir_path.display()),
            )
        })?;
        if entry.path().extension() == Some(OsStr::new("tmpl")) {
            continue;
        }
        let mut file_name = entry.file_name().to_string_lossy().into_owned();
        let mut file_stem = entry
            .path()
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or("".to_owned());
        let is_dir = entry
            .file_type()
            .map_err(|_| {
                Error::new(
                    ErrorKind::UndefinedError,
                    format!(
                        "Can't get file type of `{}`",
                        entry.path().display()
                    ),
                )
            })?
            .is_dir();
        if is_dir {
            file_name.push('/');
            file_stem.push('/');
        }
        let file_path = format!(
            "./{}",
            percent_encode(
                entry.file_name().to_raw_bytes().as_ref(),
                NON_ALPHANUMERIC
            )
        );
        let file_entry = FileEntry {
            name: file_name,
            path: file_path,
            stem: file_stem,
            is_dir,
        };
        file_list.push(Value::from_object(file_entry));
    }
    Ok(file_list)
}

fn dirs_first(
    _state: &State,
    file_entries: Vec<Value>,
) -> Result<Vec<Value>, Error> {
    let mut entries: Vec<FileEntry> = vec![];
    for entry in file_entries {
        entries.push(
            entry
                .downcast_object_ref::<FileEntry>()
                .ok_or_else(|| {
                    Error::new(
                        ErrorKind::UndefinedError,
                        "Items not file entries",
                    )
                })?
                .clone(),
        );
    }
    entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
        (true, true) | (false, false) => Ordering::Equal,
        (true, false) => Ordering::Less,
        (false, true) => Ordering::Greater,
    });
    Ok(entries
        .into_iter()
        .map(|entry| Value::from_object(entry))
        .collect())
}

fn sort_files(
    _state: &State,
    file_entries: Vec<Value>,
) -> Result<Vec<Value>, Error> {
    let mut entries: Vec<FileEntry> = vec![];
    for entry in file_entries {
        entries.push(
            entry
                .downcast_object_ref::<FileEntry>()
                .ok_or_else(|| {
                    Error::new(
                        ErrorKind::UndefinedError,
                        "Items not file entries",
                    )
                })?
                .clone(),
        );
    }
    entries.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(entries
        .into_iter()
        .map(|entry| Value::from_object(entry))
        .collect())
}

fn load_text(state: &State, path: String) -> Result<String, Error> {
    let file_path = state.lookup("path").ok_or_else(|| {
        Error::new(
            ErrorKind::NonKey,
            "Variable `path` not in template, this is a bug in stargazer",
        )
    })?;
    let file_path = String::try_from(file_path).map_err(|_| {
        Error::new(
            ErrorKind::BadSerialization,
            "Variable `path` is not a string, this is a bug in stargazer",
        )
    })?;
    let dir_path = Path::new(&file_path).parent().ok_or_else(|| {
        Error::new(
            ErrorKind::UndefinedError,
            format!(
                "This script's path `{}` does not have a parent directory",
                file_path
            ),
        )
    })?;
    let file_path = dir_path.join(path);
    match std::fs::read_to_string(&file_path) {
        Ok(content) => Ok(content),
        Err(e) => Err(Error::new(
            ErrorKind::UndefinedError,
            format!("Error loading file content: {:#}", e),
        )),
    }
}

fn lines(_state: &State, text: String) -> Result<Vec<String>, Error> {
    Ok(text.lines().map(|s| s.to_owned()).collect())
}

fn split(_state: &State, text: String, pattern: String) -> Result<Vec<String>, Error> {
    Ok(text.split(&pattern).map(|s| s.to_owned()).collect())
}