1 # Copyright (C) 2009-2010 Gianluca Montecchi <gian@grys.it>
2 # W. Trevor King <wking@drexel.edu>
4 # This file is part of Bugs Everywhere.
6 # Bugs Everywhere is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the
8 # Free Software Foundation, either version 2 of the License, or (at your
9 # option) any later version.
11 # Bugs Everywhere is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with Bugs Everywhere. If not, see <http://www.gnu.org/licenses/>.
26 import xml.sax.saxutils
30 import libbe.command.util
32 import libbe.util.encoding
36 class HTML (libbe.command.Command):
37 """Generate a static HTML dump of the current repository status
40 >>> import libbe.bugdir
41 >>> bd = libbe.bugdir.SimpleBugDir(memory=False)
42 >>> io = libbe.command.StringInputOutput()
43 >>> io.stdout = sys.stdout
44 >>> ui = libbe.command.UserInterface(io=io)
45 >>> ui.storage_callbacks.set_storage(bd.storage)
48 >>> ret = ui.run(cmd, {'output':os.path.join(bd.storage.repo, 'html_export')})
49 >>> os.path.exists(os.path.join(bd.storage.repo, 'html_export'))
51 >>> os.path.exists(os.path.join(bd.storage.repo, 'html_export', 'index.html'))
53 >>> os.path.exists(os.path.join(bd.storage.repo, 'html_export', 'index_inactive.html'))
55 >>> os.path.exists(os.path.join(bd.storage.repo, 'html_export', 'bugs'))
57 >>> os.path.exists(os.path.join(bd.storage.repo, 'html_export', 'bugs', 'a', 'index.html'))
59 >>> os.path.exists(os.path.join(bd.storage.repo, 'html_export', 'bugs', 'b', 'index.html'))
66 def __init__(self, *args, **kwargs):
67 libbe.command.Command.__init__(self, *args, **kwargs)
69 libbe.command.Option(name='output', short_name='o',
70 help='Set the output path (%default)',
71 arg=libbe.command.Argument(
72 name='output', metavar='DIR', default='./html_export',
73 completion_callback=libbe.command.util.complete_path)),
74 libbe.command.Option(name='template-dir', short_name='t',
75 help='Use a different template. Defaults to internal templates',
76 arg=libbe.command.Argument(
77 name='template-dir', metavar='DIR',
78 completion_callback=libbe.command.util.complete_path)),
79 libbe.command.Option(name='title',
80 help='Set the bug repository title (%default)',
81 arg=libbe.command.Argument(
82 name='title', metavar='STRING',
83 default='BugsEverywhere Issue Tracker')),
84 libbe.command.Option(name='index-header',
85 help='Set the index page headers (%default)',
86 arg=libbe.command.Argument(
87 name='index-header', metavar='STRING',
88 default='BugsEverywhere Bug List')),
89 libbe.command.Option(name='export-template', short_name='e',
90 help='Export the default template and exit.'),
91 libbe.command.Option(name='export-template-dir', short_name='d',
92 help='Set the directory for the template export (%default)',
93 arg=libbe.command.Argument(
94 name='export-template-dir', metavar='DIR',
95 default='./default-templates/',
96 completion_callback=libbe.command.util.complete_path)),
97 libbe.command.Option(name='min-id-length', short_name='l',
98 help='Attempt to truncate bug and comment IDs to this length. Set to -1 for non-truncated IDs (%default)',
99 arg=libbe.command.Argument(
100 name='min-id-length', metavar='INT',
101 default=-1, type='int')),
102 libbe.command.Option(name='verbose', short_name='v',
103 help='Verbose output, default is %default'),
106 def _run(self, **params):
107 if params['export-template'] == True:
108 html_gen.write_default_template(params['export-template-dir'])
110 bugdir = self._get_bugdir()
111 bugdir.load_all_bugs()
112 html_gen = HTMLGen(bugdir,
113 template=params['template-dir'],
114 title=params['title'],
115 index_header=params['index-header'],
116 min_id_length=params['min-id-length'],
117 verbose=params['verbose'],
119 html_gen.run(params['output'])
122 def _long_help(self):
124 Generate a set of html pages representing the current state of the bug
128 Html = HTML # alias for libbe.command.base.get_command_class()
130 class HTMLGen (object):
131 def __init__(self, bd, template=None,
132 title="Site Title", index_header="Index Header",
134 verbose=False, encoding=None, stdout=None,
136 self.generation_time = time.ctime()
139 self.template = "default"
141 self.template = os.path.abspath(os.path.expanduser(template))
143 self.index_header = index_header
144 self.verbose = verbose
147 self.encoding = encoding
149 self.encoding = libbe.util.encoding.get_filesystem_encoding()
150 self._load_default_templates()
152 self._load_user_templates()
153 self.min_id_length = min_id_length
155 def run(self, out_dir):
156 if self.verbose == True:
157 print >> self.stdout, \
158 'Creating the html output in %s using templates in %s' \
159 % (out_dir, self.template)
163 bugs = [b for b in self.bd]
165 bugs_active = [b for b in bugs if b.active == True]
166 bugs_inactive = [b for b in bugs if b.active != True]
168 self._create_output_directories(out_dir)
169 self._write_css_file()
172 up_link = '../../index.html'
174 up_link = '../../index_inactive.html'
175 self._write_bug_file(b, up_link)
176 self._write_index_file(
177 bugs_active, title=self.title,
178 index_header=self.index_header, bug_type='active')
179 self._write_index_file(
180 bugs_inactive, title=self.title,
181 index_header=self.index_header, bug_type='inactive')
183 def _truncated_bug_id(self, bug):
184 return libbe.util.id._truncate(
185 bug.uuid, bug.sibling_uuids(),
186 min_length=self.min_id_length)
188 def _truncated_comment_id(self, comment):
189 return libbe.util.id._truncate(
190 comment.uuid, comment.sibling_uuids(),
191 min_length=self.min_id_length)
193 def _create_output_directories(self, out_dir):
195 print >> self.stdout, 'Creating output directories'
196 self.out_dir = self._make_dir(out_dir)
197 self.out_dir_bugs = self._make_dir(
198 os.path.join(self.out_dir, 'bugs'))
200 def _write_css_file(self):
202 print >> self.stdout, 'Writing css file'
203 assert hasattr(self, 'out_dir'), \
204 'Must run after ._create_output_directories()'
205 self._write_file(self.css_file,
206 [self.out_dir,'style.css'])
208 def _write_bug_file(self, bug, up_link):
210 print >> self.stdout, '\tCreating bug file for %s' % bug.id.user()
211 assert hasattr(self, 'out_dir_bugs'), \
212 'Must run after ._create_output_directories()'
214 bug.load_comments(load_full=True)
215 comment_entries = self._generate_bug_comment_entries(bug)
216 dirname = self._truncated_bug_id(bug)
217 fullpath = os.path.join(self.out_dir_bugs, dirname, 'index.html')
218 template_info = {'title':self.title,
219 'charset':self.encoding,
221 'shortname':bug.id.user(),
222 'comment_entries':comment_entries,
223 'generation_time':self.generation_time}
224 for attr in ['uuid', 'severity', 'status', 'assigned',
225 'reporter', 'creator', 'time_string', 'summary']:
226 template_info[attr] = self._escape(getattr(bug, attr))
227 fulldir = os.path.join(self.out_dir_bugs, dirname)
228 if not os.path.exists(fulldir):
230 self._write_file(self.bug_file % template_info, [fullpath])
232 def _generate_bug_comment_entries(self, bug):
233 assert hasattr(self, 'out_dir_bugs'), \
234 'Must run after ._create_output_directories()'
238 bug.comment_root.sort(cmp=libbe.comment.cmp_time, reverse=True)
239 for depth,comment in bug.comment_root.thread(flatten=False):
240 while len(stack) > depth:
241 # pop non-parents off the stack
243 # close non-parent <div class="comment...
244 comment_entries.append('</div>\n')
245 assert len(stack) == depth
246 stack.append(comment)
248 'shortname': comment.id.user(),
249 'truncated_id': self._truncated_comment_id(comment)}
251 comment_entries.append('<div class="comment root">')
253 comment_entries.append(
254 '<div class="comment" id="%s">'
255 % template_info['truncated_id'])
256 for attr in ['uuid', 'author', 'date', 'body']:
257 value = getattr(comment, attr)
259 link_long_ids = False
261 if comment.content_type == 'text/html':
263 elif comment.content_type.startswith('text/'):
264 value = '<pre>\n'+self._escape(value)+'\n</pre>'
266 elif comment.content_type.startswith('image/'):
268 value = '<img src="./%s/%s" />' \
269 % (self._truncated_bug_id(bug),
270 self._truncated_comment_id(comment))
273 value = '<a href="./%s/%s">Link to %s file</a>.' \
274 % (self._truncated_bug_id(bug),
275 self._truncated_comment_id(comment),
276 comment.content_type)
277 if link_long_ids == True:
278 value = self._long_to_linked_user(value)
279 if save_body == True:
280 per_bug_dir = os.path.join(self.out_dir_bugs, bug.uuid)
281 if not os.path.exists(per_bug_dir):
282 os.mkdir(per_bug_dir)
283 comment_path = os.path.join(per_bug_dir, comment.uuid)
285 '<Files %s>\n ForceType %s\n</Files>' \
286 % (comment.uuid, comment.content_type),
287 [per_bug_dir, '.htaccess'], mode='a')
288 self._write_file(comment.body,
289 [per_bug_dir, comment.uuid], mode='wb')
291 value = self._escape(value)
292 template_info[attr] = value
293 comment_entries.append(self.bug_comment_entry % template_info)
294 while len(stack) > 0:
296 comment_entries.append('</div>\n') # close every remaining <div class='comment...
297 return '\n'.join(comment_entries)
299 def _long_to_linked_user(self, text):
301 >>> import libbe.bugdir
302 >>> bd = libbe.bugdir.SimpleBugDir(memory=False)
304 >>> h._long_to_linked_user('A link #abc123/a#, and a non-link #x#y#.')
305 'A link <a href="./a/">abc/a</a>, and a non-link #x#y#.'
308 replacer = libbe.util.id.IDreplacer(
309 [self.bd], self._long_to_linked_user_replacer, wrap=False)
311 libbe.util.id.REGEXP, replacer, text)
313 def _long_to_linked_user_replacer(self, bugdirs, long_id):
315 >>> import libbe.bugdir
316 >>> import libbe.util.id
317 >>> bd = libbe.bugdir.SimpleBugDir(memory=False)
318 >>> a = bd.bug_from_uuid('a')
319 >>> uuid_gen = libbe.util.id.uuid_gen
320 >>> libbe.util.id.uuid_gen = lambda : '0123'
321 >>> c = a.new_comment('comment for link testing')
322 >>> libbe.util.id.uuid_gen = uuid_gen
326 >>> h._long_to_linked_user_replacer([bd], 'abc123')
328 >>> h._long_to_linked_user_replacer([bd], 'abc123/a')
329 '<a href="./a/">abc/a</a>'
330 >>> h._long_to_linked_user_replacer([bd], 'abc123/a/0123')
331 '<a href="./a/#0123">abc/a/012</a>'
332 >>> h._long_to_linked_user_replacer([bd], 'x')
334 >>> h._long_to_linked_user_replacer([bd], '')
339 p = libbe.util.id.parse_user(bugdirs[0], long_id)
340 except (libbe.util.id.MultipleIDMatches,
341 libbe.util.id.NoIDMatches,
342 libbe.util.id.InvalidIDStructure), e:
343 return '#%s#' % long_id # re-wrap failures
344 if p['type'] == 'bugdir':
345 return '#%s#' % long_id
346 elif p['type'] == 'bug':
347 bug,comment = libbe.command.util.bug_comment_from_user_id(
349 return '<a href="./%s/">%s</a>' \
350 % (self._truncated_bug_id(bug), bug.id.user())
351 elif p['type'] == 'comment':
352 bug,comment = libbe.command.util.bug_comment_from_user_id(
354 return '<a href="./%s/#%s">%s</a>' \
355 % (self._truncated_bug_id(bug),
356 self._truncated_comment_id(comment),
358 raise Exception('Invalid id type %s for "%s"'
359 % (p['type'], long_id))
361 def _write_index_file(self, bugs, title, index_header, bug_type='active'):
363 print >> self.stdout, 'Writing %s index file for %d bugs' % (bug_type, len(bugs))
364 assert hasattr(self, 'out_dir'), 'Must run after ._create_output_directories()'
367 bug_entries = self._generate_index_bug_entries(bugs)
369 if bug_type == 'active':
370 filename = 'index.html'
371 elif bug_type == 'inactive':
372 filename = 'index_inactive.html'
374 raise Exception, 'Unrecognized bug_type: "%s"' % bug_type
375 template_info = {'title':title,
376 'index_header':index_header,
377 'charset':self.encoding,
378 'active_class':'tab sel',
379 'inactive_class':'tab nsel',
380 'bug_entries':bug_entries,
381 'generation_time':self.generation_time}
382 if bug_type == 'inactive':
383 template_info['active_class'] = 'tab nsel'
384 template_info['inactive_class'] = 'tab sel'
386 self._write_file(self.index_file % template_info,
387 [self.out_dir, filename])
389 def _generate_index_bug_entries(self, bugs):
393 print >> self.stdout, '\tCreating bug entry for %s' % bug.id.user()
394 template_info = {'shortname':bug.id.user()}
395 for attr in ['uuid', 'severity', 'status', 'assigned',
396 'reporter', 'creator', 'time_string', 'summary']:
397 template_info[attr] = self._escape(getattr(bug, attr))
398 template_info['dir'] = self._truncated_bug_id(bug)
399 bug_entries.append(self.index_bug_entry % template_info)
400 return '\n'.join(bug_entries)
402 def _escape(self, string):
405 return xml.sax.saxutils.escape(string)
407 def _load_user_templates(self):
408 for filename,attr in [('style.css','css_file'),
409 ('index_file.tpl','index_file'),
410 ('index_bug_entry.tpl','index_bug_entry'),
411 ('bug_file.tpl','bug_file'),
412 ('bug_comment_entry.tpl','bug_comment_entry')]:
413 fullpath = os.path.join(self.template, filename)
414 if os.path.exists(fullpath):
415 setattr(self, attr, self._read_file([fullpath]))
417 def _make_dir(self, dir_path):
418 dir_path = os.path.abspath(os.path.expanduser(dir_path))
419 if not os.path.exists(dir_path):
421 os.makedirs(dir_path)
423 raise libbe.command.UserError(
424 'Cannot create output directory "%s".' % dir_path)
427 def _write_file(self, content, path_array, mode='w'):
428 return libbe.util.encoding.set_file_contents(
429 os.path.join(*path_array), content, mode, self.encoding)
431 def _read_file(self, path_array, mode='r'):
432 return libbe.util.encoding.get_file_contents(
433 os.path.join(*path_array), mode, self.encoding, decode=True)
435 def write_default_template(self, out_dir):
437 print >> self.stdout, 'Creating output directories'
438 self.out_dir = self._make_dir(out_dir)
440 print >> self.stdout, 'Creating css file'
441 self._write_css_file()
443 print >> self.stdout, 'Creating index_file.tpl file'
444 self._write_file(self.index_file,
445 [self.out_dir, 'index_file.tpl'])
447 print >> self.stdout, 'Creating index_bug_entry.tpl file'
448 self._write_file(self.index_bug_entry,
449 [self.out_dir, 'index_bug_entry.tpl'])
451 print >> self.stdout, 'Creating bug_file.tpl file'
452 self._write_file(self.bug_file,
453 [self.out_dir, 'bug_file.tpl'])
455 print >> self.stdout, 'Creating bug_comment_entry.tpl file'
456 self._write_file(self.bug_comment_entry,
457 [self.out_dir, 'bug_comment_entry.tpl'])
459 def _load_default_templates(self):
462 font-family: "lucida grande", "sans serif";
473 background-color: #fcfcfc;
489 border: 10px #313131;
504 padding-right: 0.5em;
509 img { border-style: none; }
513 background-color: #305275;
522 list-style-type: none;
530 text-decoration: none;
533 a { color: #003d41; }
534 a:visited { color: #553d41; }
535 .footer a { color: #508d91; }
537 /* bug index pages */
545 background-color: #afafaf;
546 border: 1px solid #afafaf;
550 td.nsel.tab { border: 0px; }
553 background-color: #afafaf;
554 border: 2px solid #afafaf;
557 .bug_list tr { width: auto; }
558 tr.wishlist { background-color: #B4FF9B; }
559 tr.minor { background-color: #FCFF98; }
560 tr.serious { background-color: #FFB648; }
561 tr.critical { background-color: #FF752A; }
562 tr.fatal { background-color: #FF3300; }
564 /* bug detail pages */
566 td.bug_detail_label { text-align: right; }
568 td.bug_comment_label { text-align: right; vertical-align: top; }
580 /* padding-top: 0px; */
581 padding-bottom: 20px;
585 self.index_file = """
586 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
587 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
588 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
590 <title>%(title)s</title>
591 <meta http-equiv="Content-Type" content="text/html; charset=%(charset)s" />
592 <link rel="stylesheet" href="style.css" type="text/css" />
597 <h1>%(index_header)s</h1>
602 <td class="%(active_class)s"><a href="index.html">Active Bugs</a></td>
603 <td class="%(inactive_class)s"><a href="index_inactive.html">Inactive Bugs</a></td>
607 <table class="bug_list">
617 <p>Generated by <a href="http://www.bugseverywhere.org/">
618 BugsEverywhere</a> on %(generation_time)s</p>
620 <a href="http://validator.w3.org/check?uri=referer">Validate XHTML</a> |
621 <a href="http://jigsaw.w3.org/css-validator/check?uri=referer">Validate CSS</a>
629 self.index_bug_entry ="""
630 <tr class="%(severity)s">
631 <td><a href="bugs/%(dir)s/">%(shortname)s</a></td>
632 <td><a href="bugs/%(dir)s/">%(status)s</a></td>
633 <td><a href="bugs/%(dir)s/">%(severity)s</a></td>
634 <td><a href="bugs/%(dir)s/">%(summary)s</a></td>
635 <td><a href="bugs/%(dir)s/">%(time_string)s</a></td>
640 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
641 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
642 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
644 <title>%(title)s</title>
645 <meta http-equiv="Content-Type" content="text/html; charset=%(charset)s" />
646 <link rel="stylesheet" href="../../style.css" type="text/css" />
651 <h1>BugsEverywhere Bug List</h1>
652 <h5><a href="%(up_link)s">Back to Index</a></h5>
653 <h2>Bug: %(shortname)s</h2>
657 <tr><td class="bug_detail_label">ID :</td>
658 <td class="bug_detail">%(uuid)s</td></tr>
659 <tr><td class="bug_detail_label">Short name :</td>
660 <td class="bug_detail">%(shortname)s</td></tr>
661 <tr><td class="bug_detail_label">Status :</td>
662 <td class="bug_detail">%(status)s</td></tr>
663 <tr><td class="bug_detail_label">Severity :</td>
664 <td class="bug_detail">%(severity)s</td></tr>
665 <tr><td class="bug_detail_label">Assigned :</td>
666 <td class="bug_detail">%(assigned)s</td></tr>
667 <tr><td class="bug_detail_label">Reporter :</td>
668 <td class="bug_detail">%(reporter)s</td></tr>
669 <tr><td class="bug_detail_label">Creator :</td>
670 <td class="bug_detail">%(creator)s</td></tr>
671 <tr><td class="bug_detail_label">Created :</td>
672 <td class="bug_detail">%(time_string)s</td></tr>
673 <tr><td class="bug_detail_label">Summary :</td>
674 <td class="bug_detail">%(summary)s</td></tr>
683 <h5><a href="%(up_link)s">Back to Index</a></h5>
686 <p>Generated by <a href="http://www.bugseverywhere.org/">
687 BugsEverywhere</a> on %(generation_time)s</p>
689 <a href="http://validator.w3.org/check?uri=referer">Validate XHTML</a> |
690 <a href="http://jigsaw.w3.org/css-validator/check?uri=referer">Validate CSS</a>
698 self.bug_comment_entry ="""
701 <td class="bug_comment_label">Comment:</td>
702 <td class="bug_comment">
703 --------- Comment ---------<br/>
705 Short name: %(shortname)s<br/>
706 From: %(author)s<br/>
715 # strip leading whitespace
716 for attr in ['css_file', 'index_file', 'index_bug_entry', 'bug_file',
717 'bug_comment_entry']:
718 value = getattr(self, attr)
719 value = value.replace('\n'+' '*12, '\n')
720 setattr(self, attr, value.strip()+'\n')