Compare commits

...

3 Commits

Author SHA1 Message Date
qvalentin 87f5017920 add dockerfile 2021-08-29 19:14:37 +02:00
qvalentin 9163c865a7 add readme 2021-08-29 19:14:30 +02:00
qvalentin 7de446fd7f fix js rendering 2021-08-29 19:14:17 +02:00
5 changed files with 148 additions and 5 deletions

11
Dockerfile Normal file
View File

@ -0,0 +1,11 @@
FROM python:3.9
WORKDIR /app
COPY src/requirements.txt ./
RUN pip install -r requirements.txt
COPY src /app
EXPOSE 4876
CMD [ "python", "server.py" ]

42
README.md Normal file
View File

@ -0,0 +1,42 @@
# Gist-it Reborn
Embed any code from GitHub in your website just like a gist.
Based on this original [Repo](https://github.com/robertkrimen/gist-it), but quickly and dirtily rewritten in Python 3 using [Pygments](https://pygments.org/).
# Usage
Add the following snippet to your html or markdown to have the code be placed at that position.
```html
<script src="https://example.com/https://github.com/qvalentin/gist-it-reborn/blob/main/server.py"></script>
```
### Config
#### style
With the style query parameter you can select a highlighting style. A preview of possible values can be found [here](https://help.farbox.com/pygments.html).
Just append the query parameter `style` to the url.
```html
https://example.com/https://github.com/qvalentin/gist-it-reborn/blob/main/server.py?style=monokai
```
#### Selecting lines
You can choose to only show certain lines of the code. The parameter `slice` can be given in the format `from:to`.
```html
https://example.com/https://github.com/qvalentin/gist-it-reborn/blob/main/server.py?slice=5:20
```

View File

@ -19,9 +19,9 @@ from pygments.lexers import guess_lexer_for_filename
def render_gist_js(code, path):
template = Template("""script = document.querySelector('script[src$="{{ path }}"]')
script.insertAdjacentHTML( 'afterend','{{ code|tojson }}' );""")
script.insertAdjacentHTML( 'afterend',{{ code|tojson }} );""")
return template.render(code=code,path=path)
return template.render(code=str(code), path=path)
class HTTPRequestHandler(BaseHTTPRequestHandler):
@ -79,7 +79,7 @@ def main():
args = parser.parse_args()
server = HTTPServer(("localhost", 4876), HTTPRequestHandler)
print('HTTP Server Running...........')
print('HTTP Server Running on localhost:4876')
server.serve_forever()

3
src/requirements.txt Normal file
View File

@ -0,0 +1,3 @@
requests~=2.26.0
Jinja2~=3.0.1
Pygments~=2.10.0

87
src/server.py Normal file
View File

@ -0,0 +1,87 @@
#!/usr/bin/env python
"""A meaningful docstring
"""
import argparse
import re
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import requests
from jinja2 import Template
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import guess_lexer_for_filename
def render_gist_js(code, path):
template = Template("""script = document.querySelector('script[src$="{{ path }}"]')
script.insertAdjacentHTML( 'afterend','{{ code|tojson }}' );""")
return template.render(code=code, path=path)
class HTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
self.send_response(200, "running")
elif re.search("https://github.com/.*/.*", self.path):
github_raw_url = self.path[1:].replace("https://github.com/", "https://raw.githubusercontent.com/").replace("/blob/", "/")
response = requests.get(url=github_raw_url)
code = response.content.decode('UTF-8')
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
style = "default"
if 'style' in params:
style = params['style'][0]
if 'slice' in params:
slice_value = params['slice'][0].split(":")
from_ = int(slice_value[0])
to_ = int(slice_value[1])
lines = str(code).splitlines()
selected_lines = lines[from_:to_]
code = "\n".join(selected_lines)
filename = parsed_url.path.split('/')[-1:][0]
lexer = guess_lexer_for_filename(filename, response.content)
formatter = HtmlFormatter(linenos=False, cssclass="gist-it-highlight", style=style)
highlighted_code = highlight(code, lexer, formatter)
css = formatter.get_style_defs('.gist-it-highlight')
result = highlighted_code + f"<style> {css}</style>"
js_rendered = render_gist_js(result, self.path)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(js_rendered.encode('utf8'))
else:
self.send_response(404)
self.end_headers()
def main():
parser = argparse.ArgumentParser(description='HTTP Server')
args = parser.parse_args()
server = HTTPServer(("localhost", 4876), HTTPRequestHandler)
print('HTTP Server Running...........')
server.serve_forever()
if __name__ == '__main__':
main()