summaryrefslogtreecommitdiff
path: root/distixlib/plugins/html_plugin.py
blob: 379a83c117a0dc72e04f135b792d8d7fbe6508d1 (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
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
# Copyright 2016  Lars Wirzenius
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-3+ =*=


import locale
import markdown
import os
import time
import uuid

import cliapp

import distixlib


class HtmlPlugin(cliapp.Plugin):

    def enable(self):
        self.app.add_subcommand(
            'html', self.html, arg_synopsis='OUTPUT-DIR')

    def html(self, args):
        '''Generate static HTML web pages of the repository and its tickets.'''

        dirname = self.parse_args(args)
        self.create_output(dirname)

        repo = distixlib.Repository('.')

        site = StaticSite()
        site.set_output_dir(dirname)
        site.set_repository(repo)
        site.render()

    def parse_args(self, args):
        if len(args) != 1:
            raise UsageError()
        return args[0]

    def create_output(self, dirname):
        if os.path.isdir(dirname):
            if os.listdir(dirname):
                raise OutputNotEmptyError(dirname=dirname)
        elif os.path.exists(dirname):
            raise OutputExistsError(dirname=dirname)
        else:
            os.mkdir(dirname)


class StaticSite(object):

    def __init__(self):
        self._dirname = None
        self._repo = None
        self._ticket_store = None
        self._renderer = distixlib.HtmlRenderer()
        self._timestamp = None

    def set_repository(self, repo):
        self._repo = repo
        self._ticket_store = repo.open_ticket_store(distixlib.tickets_dir_name)

    def set_output_dir(self, dirname):
        self._dirname = dirname

    def render(self):
        self._timestamp = self._format_timestamp()

        self._render_ticket_list(
            'index.html.j2', 'index.html', self._ticket_is_open)
        self._render_ticket_list(
            'closed.html.j2', 'closed.html', self._ticket_is_closed)
        for ticket in self._ticket_store.get_tickets():
            self._render_ticket(ticket)
        self._copy_static_files()

    def _format_timestamp(self):
        return time.strftime('%Y-%d-%m %H:%M:%S')

    def _render_ticket_list(self, template, filename, condition):
        variables = {
            'description_html': self._make_html(self._repo.get_description()),
            'tickets': self._sort_tickets(self._get_tickets(condition)),
            'timestamp': self._timestamp,
        }
        html = self._renderer.render(template, variables)
        self._write_file(filename, html)

    def _sort_tickets(self, tickets):
        return sorted(tickets, key=lambda t: t.get_newest_message_timestamp())

    def _render_ticket(self, ticket):
        thread = distixlib.MessageThread()
        for msg in ticket.get_messages():
            thread.add_message(msg)

        msg_renderer = distixlib.MessageRenderer()

        metadata = ticket.get_ticket_metadata()

        variables = {
            'ticket': ticket,
            'metadata': metadata,
            'msgs': [
                msg_renderer.summary(msg)
                for msg in thread.get_messages_in_date_order()
            ],
            'timestamp': self._timestamp,
        }

        html = self._renderer.render('ticket.html.j2', variables)
        self._write_file('{}.html'.format(ticket.get_ticket_id()), html)

    def _make_html(self, text):
        return markdown.markdown(text)

    def _get_tickets(self, condition):
        return [
            ticket
            for ticket in self._ticket_store.get_tickets()
            if condition(ticket)
        ]

    def _ticket_is_open(self, ticket):
        return not self._ticket_is_closed(ticket)

    def _ticket_is_closed(self, ticket):
        return self._ticket_has_key_value(ticket, 'status', 'closed')

    def _ticket_has_key_value(self, ticket, key, value):
        metadata = ticket.get_ticket_metadata()
        return key in metadata and value in metadata.get_all_values(key)

    def _copy_static_files(self):
        filenames = ['distix.css']
        for filename in filenames:
            data = self._read_file(filename)
            self._write_file(filename, data)

    def _read_file(self, filename):
        pathname = os.path.join(
            os.path.dirname(distixlib.__file__),
            filename)
        with open(pathname) as f:
            return f.read()

    def _write_file(self, filename, text):
        with open(os.path.join(self._dirname, filename), 'w') as f:
            f.write(text.encode('UTF8'))


class UsageError(distixlib.StructuredError):

    msg = '"html" command must get exactly one argument: the output directory'


class OutputNotEmptyError(distixlib.StructuredError):

    msg = 'Output directory {dirname} is not empty'


class OutputExistsError(distixlib.StructuredError):

    msg = 'Output directory {dirname} exists, but is not an empty directory'