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
|
import base64
import filetype
import os
from .file import sanitize_file_name, tree_join
from .page import Page
from .tree import safe_join
def bytes_to_content(file_bytes):
if not file_bytes:
return (None, 'empty')
try:
text = file_bytes.decode('utf-8')
return (text, 'text')
except UnicodeError:
if filetype.is_image(file_bytes):
# TODO: Refer to the static file once that's implemented.
img = base64.b64encode(file_bytes)
return (img.decode('utf-8'), 'image')
return (None, None)
class FilePage(Page):
def __init__(self, out_dir, name, commit, file_name, file_path, content_subdir):
tree = safe_join(commit.tree, file_path)
super(FilePage, self).__init__('file.md', out_dir, os.path.join(tree_join(commit, file_path), sanitize_file_name(file_name, tree.blobs) + '.md'), name, content_subdir)
self.commit = commit
self.file_name = file_name
self.file_path = file_path
self.tree = tree
def read_file(self):
return self.tree.join(self.file_name).data_stream.read()
def context(self):
file_bytes = self.read_file()
content, file_type = bytes_to_content(file_bytes)
return {
'content': content,
'content_subdir': self.content_subdir,
'file_extension': os.path.splitext(self.file_name)[1].lstrip('.'),
'title': self.name + ': ' + self.file_name,
'type': file_type
}
|