summaryrefslogtreecommitdiff
path: root/panfry/main.py
blob: 5d05d202fecb2780811c3c40d6f77ebd9dc3c494 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import signal
import shutil
import shlex
import SimpleHTTPServer
import BaseHTTPServer
import httplib
import panfry.cli
from panfry.templater import Templater
from panfry.document import Document


class StoppableHttpRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """http request handler with QUIT stopping the server"""

    def do_QUIT(self):
        """send 200 OK response, and set server.stop to True"""
        self.send_response(200)
        self.end_headers()
        self.server.stop = True


class StoppableHttpServer(BaseHTTPServer.HTTPServer):
    """http server that reacts to self.stop flag"""

    def serve_forever(self):
        """Handle one request at a time until stopped."""
        self.stop = False
        while not self.stop:
            self.handle_request()


def get_INDEX(path, index):
    INDEX = os.path.join('src', path, 'INDEX')
    if os.path.isfile(INDEX):
        for line in open(INDEX, 'r').readlines():
            newpath = os.path.join(path, line.strip())
            index = get_INDEX(newpath, index)
            index.append(newpath)
    return index

def get_env():
    env = panfry.cli.init_argparser().parse_args()
    env.pub_path = os.path.abspath(env.pub_path)

    if env.cmd in ['gen']:
        if not os.path.isdir(env.doc_path):
            print("%s directory not found. Aborting..." % env.doc_path)
            exit(1)

        if not env.templates_path:
            env.templates_path = os.path.join(env.doc_path, 'templates')

        if not os.path.isdir(env.templates_path):
            print("No templates path found. Aborting...")
            exit(1)

        if env.pandoc_options:
            env.pandoc_options = list(shlex.split(env.pandoc_options))

        env.index = ['']
        env.index = get_INDEX('', env.index)

    return env


def gen(env):
    for item in env.index:
        item = item.strip()
        print("Processing: %s..." % item)
        docpubpath = os.path.join(env.pub_path, item)
        document = Document(env.doc_path, item)
        document.templater = Templater(env.templates_path)
        document.pandoc_options = env.pandoc_options
        if env.simple_toc:
            document.toc_type = 'simple'

        if env.json_toc:
            document.toc_type = 'json'

        if env.clean and os.path.exists(env.pub_path):
            print("Cleanup, removing %s..." % env.pub_path)
            shutil.rmtree(env.pub_path)
        if not os.path.exists(docpubpath):
            os.makedirs(docpubpath)

        if env.assets:
            print("Publishing assets only...", end=' ')
            document.publish_assets(env.pub_path)
            print("done.")
            exit(0)

        print("\nUsing pandoc options:")
        for opt in env.pandoc_options:
            print("  --%s" % opt)

        print()

        ###### Create PDF
        pdffile = document.publish_pdf(docpubpath)
        if pdffile:
            print("Wrote PDF: %s" % pdffile)

        ###### Create epub
        epubfile = document.publish_epub(docpubpath)
        if epubfile:
            print("Wrote epub: %s" % epubfile)

        ###### Create HTML
        document.publish_html(docpubpath)

    exit(0)


def serve(env):
    os.chdir(env.pub_path)

    def signal_handler(signal, frame):
        print('You pressed Ctrl+C!')

        def stop_server(port):
            """send QUIT request to http server running on localhost:<port>"""
            conn = httplib.HTTPConnection("localhost:%d" % env.port)
            conn.request("QUIT", "/")
            conn.getresponse()
        exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    Handler = StoppableHttpRequestHandler

    httpd = StoppableHttpServer(("", int(env.port)), Handler)
    print("serving at port: %s" % int(env.port))
    httpd.serve_forever()
    signal.pause()


def main():
    CMD = dict(gen=gen, serve=serve)
    env = get_env()
    CMD[env.cmd](env)

if __name__ == "__main__":
    main()