forked from dfrommi/blog-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJekyllFilter.groovy
executable file
·52 lines (40 loc) · 1.56 KB
/
JekyllFilter.groovy
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
#!/usr/bin/env groovy
@GrabResolver('https://jitpack.io')
@Grab('com.github.dfrommi:groovy-pandoc')
@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')
import groovyx.net.http.RESTClient
import groovyx.net.http.ContentType
import static com.github.dfrommi.pandoc.Pandoc.*
import com.github.dfrommi.pandoc.types.*
toJSONFilter { def elem, def meta ->
if(elem in Header && elem.level == 1) {
meta.metadata['title'] = toText(elem.text)
return []
}
if(elem in Image && !(elem.url.contains("://") || elem.url.startsWith("/"))) {
elem.url = "${meta.metadata.topic_url_raw}/${elem.url}"
}
if(elem in Link && !(elem.url.contains("://") || elem.url.startsWith("/"))) {
elem.url = "${meta.metadata.topic_url}/${elem.url}"
}
if(elem in CodeBlock) {
return highlight(elem)
}
elem
}
def toText(Inline[] inlines) {
inlines.inject("") { text, item -> text + ((item instanceof Space) ? " " : item.text) }
}
def highlight(CodeBlock cb) {
def githubToken = System.getenv("GITHUB_API_TOKEN")
def client = new RESTClient("https://api.github.com")
client.contentType = ContentType.TEXT
client.headers = [Accept : 'text/html', 'User-Agent': "curl/7.43.0"]
if(githubToken) {
client.headers << [Authorization: "token ${githubToken}"]
}
String language = cb.attr.classes ? cb.attr.classes.first() : ''
String content = "```${language}\n${cb.code}\n```"
def resp = client.post(path: "/markdown", requestContentType: ContentType.JSON, body: [text: content])
return new RawBlock(format: "html", content: "{% raw %}\n${resp.data.text}\n{% endraw %}")
}