11 from amara import bindery
12 from amara.xslt import transform
13 from Cheetah.Template import Template
15 parser = argparse.ArgumentParser(description='Process docbook article tree.')
16 parser.add_argument('--style', nargs='?',
17 default=os.path.dirname(os.getcwd())+'/style/default/')
18 parser.add_argument('--output', nargs='?',
19 default=os.path.dirname(os.getcwd())+'/htdocs/')
20 args = parser.parse_args()
22 style_xslt = args.style+"docbook.xsl"
23 style_tmpl = args.style+"index.en.html.tmpl"
24 outputdir = args.output
26 valid_scripts = ['.py','.pl']
32 except OSError as exc: # Python >2.5
33 if exc.errno == errno.EEXIST:
37 def publish(src,target):
38 cmd = ["rsync","-a",src,target]
39 retcode = subprocess.call(cmd)
41 print 'Error: '+' '.join(cmd)+' Returncode ['+str(retcode)+']'
43 def generateSitemap():
46 sfile = open('sitemap.txt')
47 flist = sfile.read().split()
50 sitemap.append(dict(link=f))
51 except IOError, what_error:
52 print 'Sitemap missing - generating one.'
53 for dirname, dirnames, filenames in os.walk('.'):
54 for filename in filenames:
55 if fnmatch.fnmatch(filename, '*.xml'):
56 xfile = os.path.join(dirname,filename)
57 doc = bindery.parse(xfile,
58 prefixes={u'db': u'http://docbook.org/ns/docbook',
59 u'xi': u'http://www.w3.org/2001/XInclude'})
60 title = doc.xml_select(u'/db:article/db:info/db:title')
61 menu = doc.xml_select(u'/db:article/db:info/db:titleabbrev')
62 code = doc.xml_select(u"//xi:include[@parse='text']")
65 (p, ext) = os.path.splitext(c.href)
66 if ext in valid_scripts:
71 base = xfile.split('.')[1]
72 link = base.replace('index','')
73 level = len(filter(None,re.split(r'(/\w*/)',link)))
74 page = dict(title=unicode(doc.article.info.title),
75 menu=unicode(doc.article.info.titleabbrev),
76 output=os.path.join(dirname,
77 filename.replace('xml','html')),
86 print "adding "+link+" to sitemap"
90 sfile = open('sitemap.txt','w')
92 sfile.write(l['link']+'\n')
96 def expandXincludeTxt(page):
97 doc = bindery.parse(page['file'],
98 prefixes={u'db': u'http://docbook.org/ns/docbook',
99 u'xi': u'http://www.w3.org/2001/XInclude'})
101 code = doc.xml_select(u"//xi:include[@parse='text']")
103 (p, ext) = os.path.splitext(c.href)
104 if ext in valid_scripts:
105 exe = os.path.join(os.path.abspath(c.href))
106 xml = subprocess.Popen([exe],stdout=subprocess.PIPE)
107 xstr = bindery.parse(str(xml.stdout.read()))
108 id = c.xml_index_on_parent
109 for x in xstr.xml_children:
110 c.xml_parent.xml_insert(id,x)
111 c.xml_parent.xml_remove(c)
114 def xsltConvert(doc):
115 # amara can not handle the docbook stylesheets
116 # xmlarticle = transform(doc,style_xslt)
118 rundir = os.path.dirname(page['file'])
120 infile = os.path.basename(tempfile.mktemp())
121 outfile = tempfile.mktemp()
122 tfi = open(infile,'w')
123 tfi.write(doc.xml_encode())
125 # cmd = ["saxon-xslt-xinclude","-o",outfile,infile,style_xslt]
126 cmd = ["xsltproc","--xinclude","--output",outfile,style_xslt,infile]
127 retcode = subprocess.call(cmd)
129 print 'Error: '+' '.join(cmd)+' Returncode ['+str(retcode)+']'
130 tfo = open(outfile,'r')
138 def genMenu(page,sitemap,slevel,elevel):
141 if elevel == MAXLEVEL or elevel == 1:
144 idx = sitemap.index(page)
145 while (sitemap[idx]['level'] == page['level']):
147 title = sitemap[idx]['menu']
149 while (idx < len(sitemap) and sitemap[idx]['level'] == page['level']):
150 sm.append(sitemap[idx])
155 if slevel > p['level'] or elevel < p['level']:
157 if not title and p['link'] == '/':
160 if oldlevel < p['level']:
162 elif oldlevel > p['level']:
163 if p['link'][-1] == '/':
165 html+='</ul>\n</li>\n'
167 html+='<li><a href="%s">[%s]</a>' % (p['link'],p['menu'])
169 html+='<li><a href="%s">%s</a>' % (p['link'],p['menu'])
170 if p['link'][-1] != '/' or p['link'] == '/':
172 oldlevel = p['level']
176 def writeToTemplate(page,doc,sitemap):
177 (menu,menuname) = genMenu(page,sitemap,1,MAXLEVEL)
178 (levelmenu,levelname) = genMenu(page,sitemap,page['level'],page['level'])
179 template = Template(file=style_tmpl,
180 searchList=[{'title':page['title']},
183 {'levelmenu':levelmenu},
184 {'levelname':levelname}])
185 outfile = tmptarget+page['output']
186 mkdir_p(os.path.dirname(outfile))
187 out = open(outfile, 'w')
188 out.write(str(template))
191 sitemap = generateSitemap()
192 tmptarget = tempfile.mkdtemp()+'/'
195 print "Page : %-30s %30s" % (page['link'],
196 time.ctime(os.stat(page['file']).st_mtime)),
197 doc = expandXincludeTxt(page)
198 pubdoc = xsltConvert(doc)
199 writeToTemplate(page,pubdoc,sitemap)
201 print "[%5.2f s]" % (round(t2-t1,2))
202 publish(tmptarget, args.output)
203 publish(args.style+"css", args.output)
204 publish(args.style+"images",args.output)