~rjpcasalino/odyssey

ref: 3728f167e9b1d7cf1007d7aa8eee1c822f48b293 odyssey/src/odyssey -rw-r--r-- 8.0 KiB View raw
3728f167rjpcasalino adds pdf to regex for cv stuff 3 months ago
                                                                                
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env python3
# General issues:
# 1) target dir (i.e., _site) is hard coded - needs to be replaced
# 2) templates should be stored elsewhere
# 3) use docstring module 

import argparse
import re
import mistune
import yaml
import http.server
import socketserver
import os
import time
import shutil
import datetime
import jinja2
from jinja2 import Environment, FileSystemLoader, select_autoescape


# consts
WORKDIR = os.getcwd()
DIRS = ["layouts", "pages", "_drafts"]
PORT = 8000

# jinja2 env
env = Environment(
    loader=FileSystemLoader(WORKDIR + "/layouts"),
    autoescape=select_autoescape(enabled_extensions=('html'))
)

BASIC_TEMPLATE = """
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{{title}}</title>
  <meta name="robots" content="all">
  <style>
 body {
    max-width: 500px;
    margin: 15px;
    word-wrap: break-word;
    font-family: 'Lusitana', serif;
 }

 </head>

  <body>
	{{ content }}
  </body>
</html>
"""

DEFAULT_INDEX_MD = """---
title: Odyssey
layout: basic
---

 Hello world
"""

DEFAULT_ABOUT_MD = """---
title: About
layout: basic
---

This is the about page
"""

parser = argparse.ArgumentParser()
parser.add_argument("start", help="builds pages dir")
parser.add_argument("--init", "-i", action="store_true",
                    help="creates project dir: pages, layout, _site")
parser.add_argument("--serve", "-s", action="store_true",
                    help="starts a web server with content of _site")
parser.add_argument("--dest", "-d", action="store", help="send _site to DEST")
args = parser.parse_args()


def init():
    print("bootstrapping new project in: {}".format(WORKDIR))
    for d in DIRS:
        if os.path.isdir(d):
            pass
        os.mkdir(d)
        print("mkdir: {}".format(d))
    with open("layouts/basic.html", "w") as f:
        f.write(BASIC_TEMPLATE)
    with open("pages/index.md", "w") as f:
        f.write(DEFAULT_INDEX_MD)
    with open("pages/about.md", "w") as f:
        f.write(DEFAULT_ABOUT_MD)

def posts_dir_tree_walk(path):
    collection = {}
    for root, dirs, files in os.walk(path):
        for file_name in files:
            title = file_name.replace(".md", " ")
            collection[title] = file_name.replace(".md", ".html")
        for dir_name in dirs:
            collection[dir_name] = dir_name
    return collection

## TODO: instead of purge, diff.
def build_site():
    if os.path.isdir("_site"):
        print("remove stale _site tree")
        shutil.rmtree("_site")
    print("Creating _site dir")
    os.mkdir("_site")

def do_build():
    ## TODO: see above
    build_site()
    for dirpath, dirnames, filenames in os.walk("pages"):
        for dir in dirnames:
            os.mkdir(os.path.join(os.path.relpath(dirpath), dir).replace("pages", "_site"))
        for file in filenames:
            try:
                f = re.match("(?:png|jpg|jpeg|gif|svg|md|pdf)", file.split(".")[1])
                if "md" in f.group():
                    filename = os.path.join(dirpath, file)
                    with open(filename, "r+") as f:
                        # returns a tuple containing a count (from start which defaults to 0) and
                        # the values obtained from iterating over iterable.
                        block = list(enumerate(read_file(f, "---")))
                    if "index.md" in filename:
                        build_index(filename, block[0][1], block[1][1], time.ctime())                           
                    else:
                        build_page(filename, block[0][1], block[1][1], time.ctime())
                elif "pdf" in f.group():
                    ## this is cv related
                    shutil.copy(os.path.join(dirpath, file), "_site/cv/")
                else:
                    if os.path.isdir("_site/static/"):
                        shutil.copy(os.path.join(dirpath, file), "_site/static/")
                    else:
                        os.mkdir("_site/static/")
                        shutil.copy(os.path.join(dirpath, file), "_site/static/")
            except Exception as e:
                print("error during build: {}".format(e))
                pass


def read_file(seq, delim):
    line = seq.readline()
    # yaml and markdown blocks
    markdown_block = []
    yaml_block = []
    delim_count = 0
    if line.strip() != delim.strip():
        raise ValueError("invalid front matter")
    for line in seq:
        if line.startswith(delim.strip()):
            delim_count += 1
            if line.strip() != delim.strip() or delim_count >= 2:
                raise ValueError("invalid front matter")
            yield yaml_block
            # TODO: do we really need to recast these values?
            yaml_block = []
            markdown_block = []
        yaml_block.append(line)
        markdown_block.append(line)
    yield markdown_block

## TODO: CLEAN UP
## build an index and list provide a dict of all post names and links
def build_index(filename, yaml_block, markdown_block, time_stamp):
    print("BUILD_INDEX: {}".format(filename))
    posts = posts_dir_tree_walk("./pages/posts/")
    try:
        yaml_block = yaml.safe_load("".join(yaml_block))
    except:
        raise
    try:
        with open(filename.split(".")[0].replace("pages", "_site/") + ".html", "w") as f:
            try:
                print("yaml options:", yaml_block)
                template = env.get_template(yaml_block["layout"] + ".html")
            except jinja2.exceptions.TemplateNotFound as e:
                print("could not find {} in layout directory!".format(yaml_block["layout"]))
                raise
            except Exception:
                print("error building template")
                raise
            try:
                markdown_block = handle_markdown_block(markdown_block)
            except Exception:
                print("error during markdown parse")
                raise
            f.write(template.render({"title": yaml_block["title"], "content": markdown_block, "posts": posts, "time_stamp": time_stamp}))
    except FileNotFoundError as e:
        print("FILE NOT FOUND:{}".format(filename))

def build_page(filename, yaml_block, markdown_block, time_stamp):
    print("BUILD_PAGE: {}".format(filename))
    try:
        yaml_block = yaml.safe_load("".join(yaml_block))
    except:
        raise
    try:
        with open(filename.split(".")[0].replace("pages", "_site/") + ".html", "w") as f:
            try:
                print("yaml options:", yaml_block)
                template = env.get_template(yaml_block["layout"] + ".html")
            except jinja2.exceptions.TemplateNotFound as e:
                print("could not find {} in layout directory!".format(yaml_block["layout"]))
                raise
            except Exception:
                print("error building template")
                raise
            try:
                markdown_block = handle_markdown_block(markdown_block)
            except Exception:
                print("error during markdown parse")
                raise
            f.write(template.render({"title": yaml_block["title"], "content": markdown_block, "time_stamp": time_stamp}))
    except FileNotFoundError as e:
        print("FILE NOT FOUND:{}".format(filename))


def handle_markdown_block(md_block):
    # remove delim
    md_block.pop(0)
    try:
        m = mistune.markdown("".join(md_block), escape=False)
    except Exception:
        print("mistune error")
        raise
    return m

if args.init:
    init()
if args.start:
    print("Working in: {}".format(os.path.basename(WORKDIR)))
    try:
        do_build()
    except Exception:
        raise
    else:
        if args.dest:
            try:
                shutil.copytree("_site", args.dest)
            except Exception:
                raise
        if args.serve:
            web_dir = os.path.relpath(WORKDIR + "/_site", ".")
            os.chdir(web_dir)

            Handler = http.server.SimpleHTTPRequestHandler
            httpd = socketserver.TCPServer(("", PORT), Handler)
            print("serving at port: {}".format(PORT))
            httpd.serve_forever()
    print("Done")