|
@@ -1,6 +1,9 @@
|
1
|
1
|
use chrono::NaiveDateTime;
|
2
|
2
|
use diesel::pg::PgConnection as PGC;
|
3
|
3
|
use diesel::prelude::*;
|
|
4
|
+use syntect::highlighting::ThemeSet;
|
|
5
|
+use syntect::html::highlighted_html_for_string;
|
|
6
|
+use syntect::parsing::SyntaxSet;
|
4
|
7
|
|
5
|
8
|
use crate::schema::gists;
|
6
|
9
|
|
|
@@ -11,6 +14,7 @@ pub struct Gist {
|
11
|
14
|
pub body: String,
|
12
|
15
|
pub created_at: Option<NaiveDateTime>,
|
13
|
16
|
pub filetype: Option<String>,
|
|
17
|
+ pub formatted_body: String,
|
14
|
18
|
}
|
15
|
19
|
|
16
|
20
|
#[derive(Insertable, AsChangeset, Serialize, Deserialize)]
|
|
@@ -19,6 +23,23 @@ pub struct InsertableGist {
|
19
|
23
|
pub title: String,
|
20
|
24
|
pub body: String,
|
21
|
25
|
pub filetype: Option<String>,
|
|
26
|
+ pub formatted_body: String,
|
|
27
|
+}
|
|
28
|
+
|
|
29
|
+fn format_gist(filetype: Option<String>, body: String) -> String {
|
|
30
|
+ filetype.map_or(
|
|
31
|
+ format!("<pre class='plaintext'>{}</pre>", body),
|
|
32
|
+ |filetype| {
|
|
33
|
+ let ps = SyntaxSet::load_defaults_newlines();
|
|
34
|
+ let ts = ThemeSet::load_defaults();
|
|
35
|
+ ps.find_syntax_by_extension(&filetype).map_or(
|
|
36
|
+ format!("<pre class='plaintext'>{}</pre>", body),
|
|
37
|
+ |syntax| {
|
|
38
|
+ highlighted_html_for_string(&body, &ps, syntax, &ts.themes["Solarized (light)"])
|
|
39
|
+ },
|
|
40
|
+ )
|
|
41
|
+ },
|
|
42
|
+ )
|
22
|
43
|
}
|
23
|
44
|
|
24
|
45
|
pub fn all(connection: &PGC) -> QueryResult<Vec<Gist>> {
|
|
@@ -30,7 +51,13 @@ pub fn get(connection: &PGC, id: i32) -> QueryResult<Gist> {
|
30
|
51
|
}
|
31
|
52
|
|
32
|
53
|
pub fn insert(gist: InsertableGist, connection: &PGC) -> QueryResult<Gist> {
|
|
54
|
+ let formatted_gist = InsertableGist {
|
|
55
|
+ filetype: gist.filetype.clone(),
|
|
56
|
+ title: gist.title,
|
|
57
|
+ body: gist.body.clone(),
|
|
58
|
+ formatted_body: format_gist(gist.filetype, gist.body),
|
|
59
|
+ };
|
33
|
60
|
diesel::insert_into(gists::table)
|
34
|
|
- .values(gist)
|
|
61
|
+ .values(formatted_gist)
|
35
|
62
|
.get_result(connection)
|
36
|
63
|
}
|