Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download
Views: 18655
1
import frontmatter
2
from pbx_gs_python_utils.utils.Files import Files
3
4
class Hugo_Page():
5
def __init__(self, base_folder=None):
6
self.folder_oss = Files.path_combine(__file__, '../../../..')
7
self.base_folder = base_folder
8
self.file_template = Files.path_combine(self.folder_oss,"{0}/{1}".format(self.base_folder,'_template.md'))
9
10
11
def create(self, name):
12
name = name.replace('.md','')
13
template = self.load(self.file_template)
14
template['metadata']['title'] = name
15
template['path'] = template['path'].replace('_template', self.fix_name(name))
16
file_path = self.md_file_path(template['path'])
17
if Files.exists(file_path):
18
return { 'status': 'error', 'data':'target file already existed: {0}'.format(file_path)}
19
return self.save(template)
20
21
def delete(self, name):
22
if Files.exists(name):
23
full_path = name
24
else:
25
virtual_path = "{0}/{1}".format(self.base_folder, self.fix_name(name) + '.md')
26
full_path = self.md_file_path(virtual_path)
27
if Files.exists(full_path) is False:
28
return False
29
Files.delete(full_path)
30
31
return Files.exists(full_path) is False
32
33
def fix_name(self, name):
34
return name.replace(' ','-').lower()
35
36
def md_file_path(self, virtual_path:str):
37
if virtual_path.startswith('/'): virtual_path = virtual_path[1:]
38
return Files.path_combine(self.folder_oss,virtual_path)
39
40
def load(self, path):
41
if Files.exists(path):
42
file_data = frontmatter.load(path)
43
relative_path = path.replace(self.folder_oss,'')
44
data = { 'path': relative_path , 'content': file_data.content, 'metadata': file_data.metadata }
45
return data
46
47
def save(self, data):
48
try:
49
post = frontmatter.Post(data.get('content'))
50
post.metadata = data.get('metadata')
51
for key, value in post.metadata.items():
52
default_value = '' if key not in ['sessions'] else []
53
post.metadata[key] = value if value else default_value
54
55
file_path = self.md_file_path(data['path'] )
56
57
Files.write(file_path, frontmatter.dumps(post))
58
if Files.exists(file_path):
59
return { 'status': 'ok', 'data': data}
60
else:
61
return {'status': 'error', 'data': 'file not saved ok: {0}'.format(file_path) }
62
except Exception as error:
63
return { 'status': 'error', 'data': error }
64