2f86ce642318ec0e89803d3f3de2982c010e7b2f
[software/wi.git] / wi / rest.py
1 """
2
3 reStructuredText management classes
4
5 """
6
7 from __future__ import (absolute_import, division,                                                      print_function, unicode_literals)
8
9 import os
10 import shutil
11 import sys
12
13 from docutils import nodes
14 from docutils.parsers.rst import roles
15 from docutils.core import publish_file
16
17 from wi import files
18
19 def wi_role(role, rawtext, text, lineno, inliner,options={}, content=[]):
20     """
21     Support for wiki-links in the form :wi:`Title|Dest`.
22
23     Title is the mandatory label for the link.
24     Dest is an optional alternative destination for it.
25     """
26
27     # Todo: check that there is one of Title or url, 
28     # otherwise return an error
29     wi = text.split('|')
30     if len(wi) == 1:
31         label = wi[0]
32         dest = files.title_to_url(wi[0])
33     else:
34         label = wi[0]
35         dest = files.title_to_url(wi[1])
36
37     destfile = "%s.html"%(dest)
38     # TODO: check that there is an index.something in the directory
39     if os.path.isdir(dest):
40         destfile = os.path.join(dest,'index.html')
41     try:
42         path = "%s%s"%(inliner.document.settings.path_to_root,destfile)
43     except AttributeError:
44         path = destfile
45     node = nodes.reference(rawtext,label,refuri=path)
46
47     return [node],[]
48
49 roles.register_canonical_role('wi', wi_role)
50
51 def publish_html(fname,dest_dir,wi_dir,wi_exts,options={}):
52     # Exclude files with names starting with '.' or '_'
53     for path_comp in os.path.normpath(fname).split(os.sep):
54         try:
55             if path_comp[0] in ['_','.']:
56                 return
57         except IndexError:
58             # TODO: i18l
59             sys.stderr.write('Warning: trying to work on a zero lenght filename (a directory?)\n')
60             sys.stderr.write('         Source filename was: %s\n'%fname)
61             return
62
63     # Prepare destination directory
64     dest_fname = os.path.join(dest_dir,os.path.relpath(fname,wi_dir))
65     try:
66         os.makedirs(os.path.dirname(dest_fname))
67     except OSError:
68         pass
69     # Convert wi files to html, copy anything else
70     (root,ext) = os.path.splitext(dest_fname)
71     if ext[1:] in wi_exts:
72         dest_fname = '.'.join([root,'html'])
73         options['path_to_root'] = os.path.join(os.path.dirname(os.path.relpath(wi_dir,fname)),'')
74         publish_file(source_path=fname,
75                 destination_path=dest_fname,
76                 writer_name='html',
77                 settings_overrides=options)
78     else:
79         try:
80             shutil.copy(fname,dest_fname)
81         except (IOError, shutil.Error):
82             # Ignore copy errors
83             pass
84