aboutsummaryrefslogtreecommitdiff
path: root/src/file_handler/file_strategies/gemini.rs
blob: 45963784ffca23fa7003e46d4f97145e161113f2 (plain)
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
pub struct Strategy {}

use std::fs::{create_dir_all, read_to_string, File as IOFile};
use std::io::Write;
use std::path::Path;

use crate::file_handler::{File, FileType, Strategy as FileHandlerStrategy};
use gema_texto::{gemini_parser::parse, html_renderer::render_html};

impl Strategy {
    fn is_title(line: &str) -> bool {
        line.starts_with("--- title:")
    }

    fn is_description(line: &str) -> bool {
        line.starts_with("--- description:")
    }

    fn get_title(line: &str) -> &str {
        line.split_once("--- title:").unwrap().1
    }

    fn get_description(line: &str) -> &str {
        line.split_once("--- description:").unwrap().1
    }
}

impl FileHandlerStrategy for Strategy {
    fn is(&self, path: &Path) -> bool {
        if let Some(extension) = path.extension() {
            return !path.is_dir() && extension == "gmi";
        }
        false
    }

    fn identify(&self) -> FileType {
        FileType::Gemini
    }

    fn can_handle(&self, file_type: &FileType) -> bool {
        matches!(file_type, FileType::Gemini)
    }

    fn handle_html(&self, source: &Path, destination: &Path, file: &File, layout: &str) {
        let gemini_contents = read_to_string(&file.path).unwrap();

        // Front matter extraction
        let lines: Vec<&str> = gemini_contents.split('\n').collect();
        let mut lines_found = 0;
        let mut title = "";
        let mut description = "";
        if let Some(slice) = lines.get(..2) {
            for line in slice {
                if Strategy::is_title(line) {
                    title = Strategy::get_title(line).trim();
                    lines_found += 1;
                    continue;
                }
                if Strategy::is_description(line) {
                    description = Strategy::get_description(line).trim();
                    lines_found += 1;
                    continue;
                }
            }
        }

        let gemini_source = lines[lines_found..].join("\n");
        let content_html = render_html(&parse(&gemini_source[..]));

        let generated_html = layout
            .replace("{{ title }}", title)
            .replace("{{ description }}", description)
            .replace("{{ content }}", &content_html[..]);

        let relative_path = file.path.strip_prefix(source).unwrap();
        let mut complete_destination = destination.join(relative_path);
        complete_destination.set_extension("html");
        let destination_parent = complete_destination.parent().unwrap();
        create_dir_all(destination_parent).unwrap();

        let mut destination_file = IOFile::create(&complete_destination).unwrap();
        destination_file
            .write_all(generated_html.as_bytes())
            .unwrap();
    }

    fn handle_gemini(&self, source: &Path, destination: &Path, file: &File) {
        let gemini_contents = read_to_string(&file.path).unwrap();

        // Front matter extraction
        let lines: Vec<&str> = gemini_contents.split('\n').collect();
        let mut lines_found = 0;
        if let Some(slice) = lines.get(..2) {
            for line in slice {
                if Strategy::is_title(line) {
                    lines_found += 1;
                    continue;
                }
                if Strategy::is_description(line) {
                    lines_found += 1;
                    continue;
                }
            }
        }

        let gemini_source = lines[lines_found..].join("\n");

        let relative_path = file.path.strip_prefix(source).unwrap();
        let complete_destination = destination.join(relative_path);
        let destination_parent = complete_destination.parent().unwrap();
        create_dir_all(destination_parent).unwrap();

        let mut destination_file = IOFile::create(&complete_destination).unwrap();
        destination_file
            .write_all(gemini_source.as_bytes())
            .unwrap();
    }
}

#[cfg(test)]
mod tests {
    use std::fs::create_dir_all;

    use super::*;

    use test_utilities::*;

    #[test]
    fn detects_title() {
        assert!(Strategy::is_title("--- title: Hello!"));
    }

    #[test]
    fn does_not_detect_other_keys_as_title() {
        assert!(!Strategy::is_title("--- description: Hello!"));
    }

    #[test]
    fn detects_description() {
        assert!(Strategy::is_description("--- description: What is this?"));
    }

    #[test]
    fn does_not_detect_other_keys_as_description() {
        assert!(!Strategy::is_description("--- title: What is this?"));
    }

    #[test]
    fn extracts_title() {
        assert_eq!(Strategy::get_title("--- title: Hello!").trim(), "Hello!");
    }

    #[test]
    fn extracts_description() {
        assert_eq!(
            Strategy::get_description("--- description: What is this?").trim(),
            "What is this?"
        );
    }

    #[test]
    fn identifies_gemini_file() {
        let test_dir = setup_test_dir();
        create_test_file(&test_dir.join("test.gmi"), "");
        let strategy = Strategy {};
        assert!(strategy.is(&test_dir.join("test.gmi")));
    }

    #[test]
    fn rejects_non_gemini_file() {
        let test_dir = setup_test_dir();
        create_test_file(&test_dir.join("_layout.html"), "");
        create_test_file(&test_dir.join("image.png"), "");
        let strategy = Strategy {};
        assert!(!strategy.is(&test_dir.join("_layout.html")));
        assert!(!strategy.is(&test_dir.join("image.png")));
        assert!(!strategy.is(&test_dir));
    }

    #[test]
    fn identifies_gemini_type() {
        let strategy = Strategy {};
        assert!(matches!(strategy.identify(), FileType::Gemini));
    }

    #[test]
    fn handles_gemini_type() {
        let strategy = Strategy {};
        assert!(strategy.can_handle(&FileType::Gemini));
    }

    #[test]
    fn rejects_non_gemini_types() {
        let strategy = Strategy {};
        assert!(!strategy.can_handle(&FileType::Layout));
        assert!(!strategy.can_handle(&FileType::File));
        assert!(!strategy.can_handle(&FileType::Unknown));
    }

    #[test]
    fn handles_html_generation() {
        let test_dir = setup_test_dir();
        let source_dir = test_dir.join("source");
        let output_dir = test_dir.join("output");
        create_dir_all(&source_dir).expect("Could not create source test directory");
        create_dir_all(&output_dir).expect("Could not create output test directory");
        let layout = "\
<html>
<head>
<title>{{ title }}</title>
<meta name=\"description\" content=\"{{ description }}\">
</head>
<body>{{ content }}</body>
</html>
";
        create_test_file(
            &source_dir.join("test.gmi"),
            "\
--- title: Page Is Cool!
--- description: My Description
# Test
Hello world
",
        );

        let strategy = Strategy {};
        let file = File {
            path: source_dir.join("test.gmi"),
            file_type: FileType::Gemini,
        };

        strategy.handle_html(&source_dir, &output_dir, &file, layout);

        let html_output = output_dir.join("test.html");
        assert!(html_output.exists());
        assert_file_contents(
            &html_output,
            "\
<html>
<head>
<title>Page Is Cool!</title>
<meta name=\"description\" content=\"My Description\">
</head>
<body><section class=\"h1\">
<h1> Test</h1>
<p>Hello world</p>
</section>
</body>
</html>
",
        );
    }

    #[test]
    fn handles_gemini_generation() {
        let test_dir = setup_test_dir();
        let source_dir = test_dir.join("source");
        let output_dir = test_dir.join("output");
        create_dir_all(&source_dir).expect("Could not create source test directory");
        create_dir_all(&output_dir).expect("Could not create output test directory");
        create_test_file(
            &source_dir.join("test.gmi"),
            "\
--- title: Page Is Cool!
--- description: My Description
# Test
Hello world
",
        );

        let strategy = Strategy {};
        let file = File {
            path: source_dir.join("test.gmi"),
            file_type: FileType::Gemini,
        };

        strategy.handle_gemini(&source_dir, &output_dir, &file);

        let gemini_output = output_dir.join("test.gmi");
        assert!(gemini_output.exists());
        assert_file_contents(
            &gemini_output,
            "\
# Test
Hello world
",
        );
    }

    #[test]
    fn handles_nested_structure() {
        let test_dir = setup_test_dir();
        let source_dir = test_dir.join("source");
        let output_dir = test_dir.join("output");
        create_dir_all(source_dir.join("nested")).expect("Could not create source test directory");
        create_dir_all(&output_dir).expect("Could not create output test directory");
        let layout = "\
<html>
<head>
<title>{{ title }}</title>
<meta name=\"description\" content=\"{{ description }}\">
</head>
<body>{{ content }}</body>
</html>
";
        create_test_file(
            &source_dir.join("nested/test.gmi"),
            "\
--- title: Page Is Cool!
--- description: My Description
# Test
Hello world
",
        );

        let strategy = Strategy {};
        let file = File {
            path: source_dir.join("nested/test.gmi"),
            file_type: FileType::Gemini,
        };

        strategy.handle_html(&source_dir, &output_dir, &file, layout);

        let html_output = output_dir.join("nested/test.html");
        assert!(html_output.exists());
        assert_file_contents(
            &html_output,
            "\
<html>
<head>
<title>Page Is Cool!</title>
<meta name=\"description\" content=\"My Description\">
</head>
<body><section class=\"h1\">
<h1> Test</h1>
<p>Hello world</p>
</section>
</body>
</html>
",
        );
    }
}