svn-gvsig-desktop / tags / v1_9_Build_1238 / docs / scripts / mkbook.py @ 47840
History | View | Annotate | Download (12.2 KB)
1 |
#!/usr/bin/python
|
---|---|
2 |
import os |
3 |
import sys |
4 |
import shutil |
5 |
import re |
6 |
|
7 |
|
8 |
class RootDir(object): |
9 |
def __init__(self,path): |
10 |
self._path = os.path.abspath(path)
|
11 |
|
12 |
def __str__(self): |
13 |
return self._path |
14 |
|
15 |
def data(self,*dirs): |
16 |
return os.path.join(self._path,"datos",*dirs) |
17 |
|
18 |
def docbook(self,*dirs): |
19 |
return os.path.join(self._path,"docbook",*dirs) |
20 |
|
21 |
def __call__(self,*dirs): |
22 |
return os.path.join(self._path,*dirs) |
23 |
|
24 |
def getExtension(fname): |
25 |
"""
|
26 |
Retorna la extension del fichero con punto,
|
27 |
"fff.xxx" -> ".xxx"
|
28 |
"""
|
29 |
return os.path.splitext(fname)[1] |
30 |
|
31 |
def removeExtension(fname): |
32 |
"""
|
33 |
Retorna el nombre del fichero sin la extension.
|
34 |
Quita tambien el punto.
|
35 |
"fff.xxx" -> "fff"
|
36 |
"""
|
37 |
return os.path.splitext(fname)[0] |
38 |
|
39 |
def shell(cmd,head=None): |
40 |
status = 0
|
41 |
childstdin, childstdout, childstderr = os.popen3(cmd) |
42 |
while True: |
43 |
line = childstdout.readline() |
44 |
if line in (None,""): |
45 |
break
|
46 |
print line
|
47 |
if head == None: |
48 |
head = "Error ejecutando '%s'" % (cmd)
|
49 |
while True: |
50 |
line = childstderr.readline() |
51 |
if line in (None,""): |
52 |
break
|
53 |
if head != None: |
54 |
print head
|
55 |
head = None
|
56 |
status=1
|
57 |
print ">>> "+line |
58 |
return status
|
59 |
|
60 |
class ProcessDocBook(object): |
61 |
def __init__(self, sourceDir, tempDir, distDir): |
62 |
self.sourceDir = RootDir(sourceDir)
|
63 |
self.tempDir = RootDir(tempDir)
|
64 |
self.distDir = RootDir(distDir)
|
65 |
self.imageCounter = 1 |
66 |
self.status=0 |
67 |
|
68 |
def __str__(self): |
69 |
return "ProcessDocBook( sourceDir =%s, tempDir=%s, distDir=%s, imageCounter=%s, status=%s)"%( |
70 |
self.sourceDir,
|
71 |
self.tempDir,
|
72 |
self.distDir,
|
73 |
self.imageCounter,
|
74 |
self.status
|
75 |
) |
76 |
|
77 |
def nextImageCounter(self): |
78 |
self.imageCounter += 1 |
79 |
return self.imageCounter |
80 |
|
81 |
def toTempPath(self,*path): |
82 |
path = os.path.join(*path) |
83 |
return os.path.join(
|
84 |
str(self.tempDir), |
85 |
path[ len(str(self.sourceDir))+1: ] |
86 |
) |
87 |
|
88 |
def copyFromTo(self,source,dest): |
89 |
|
90 |
try:
|
91 |
shutil.copy(source,dest) |
92 |
except OSError, e: |
93 |
if e.errno!=1: |
94 |
print "copyFromTo: Error copiando la fuente %s a destino %s. Error %s, %s"%( |
95 |
sourceImage, |
96 |
targetImage, |
97 |
str(e.__class__),
|
98 |
str(e)
|
99 |
) |
100 |
raise
|
101 |
|
102 |
return
|
103 |
|
104 |
def makedirs(self,*dirs): |
105 |
path = os.path.join(*dirs) |
106 |
try:
|
107 |
os.makedirs(path) |
108 |
except OSError, e: |
109 |
if e.errno!=17: |
110 |
print "makedirs: Se ha producido un error creando el directorio '%s', error %s, %s" % ( |
111 |
path, |
112 |
str(e.__class__),
|
113 |
str(e)
|
114 |
) |
115 |
raise
|
116 |
return
|
117 |
|
118 |
def sxw2docbook(self, pathnameSXW): |
119 |
"""
|
120 |
Copia el fichero SXW al temp, y lo transforma en un
|
121 |
docbook.
|
122 |
"""
|
123 |
pathnameSXWInTemp = self.toTempPath(pathnameSXW)
|
124 |
#print "Procesando %s --> %s" % (pathnameSXW,pathnameSXWInTemp)
|
125 |
#shutil.copyfile(pathnameSXW,pathnameSXWInTemp)
|
126 |
self.copyFromTo(pathnameSXW,pathnameSXWInTemp)
|
127 |
os.chdir(os.path.dirname(pathnameSXWInTemp)) |
128 |
shell("ooo2dbk -a -c/etc/ooo2dbk.xml '%s'" % pathnameSXWInTemp)
|
129 |
os.unlink(pathnameSXWInTemp) |
130 |
pathnameSXWInTempWhitoutExt = removeExtension(pathnameSXWInTemp).replace(" ","_") |
131 |
os.rename(pathnameSXWInTempWhitoutExt+".docb.xml",pathnameSXWInTempWhitoutExt+".docbook") |
132 |
|
133 |
def getImageListOfSXW(self, pathnameSXW): |
134 |
"""
|
135 |
Retorna una lista con las imagenes extraidas
|
136 |
del fichero SXW, y una propuesta de nombre para
|
137 |
renombrarla.
|
138 |
"""
|
139 |
#print "obteniendo la lista de imagenes de %s" % (pathnameSXW)
|
140 |
imagesPath = os.path.join( |
141 |
os.path.dirname(self.toTempPath(pathnameSXW)),
|
142 |
"images"
|
143 |
) |
144 |
images=list()
|
145 |
files= os.listdir(imagesPath) |
146 |
for fname in files: |
147 |
if fname[:-4]!="_dbk": |
148 |
image = ( |
149 |
fname, |
150 |
"_dbk%03d_%s"%(self.nextImageCounter(),fname) |
151 |
) |
152 |
images.append(image) |
153 |
return images
|
154 |
|
155 |
def moveImagesOfSXW(self, pathnameSXW, images): |
156 |
"""
|
157 |
Recibe una lista de imagenes del fichero SXW con
|
158 |
las propuestas para renombrarlas, y las renombra,
|
159 |
las mueve a directorio data/images del temp.
|
160 |
"""
|
161 |
#print "Moviendo las imagenes de %s" % (pathnameSXW)
|
162 |
sourcePath = os.path.join( |
163 |
os.path.dirname(self.toTempPath(pathnameSXW)),
|
164 |
"images"
|
165 |
) |
166 |
targetPath = self.tempDir.data("images") |
167 |
self.makedirs(targetPath)
|
168 |
for image in images: |
169 |
shutil.move( |
170 |
os.path.join(sourcePath,image[0]),
|
171 |
os.path.join(targetPath,image[1])
|
172 |
) |
173 |
return True |
174 |
|
175 |
|
176 |
def fixImagesInDocBookOfSXW(self, pathnameSXW, images): |
177 |
"""
|
178 |
Actualiza los nombres de las imagenes del fichero
|
179 |
docbook generado a partir del SXW.
|
180 |
"""
|
181 |
pathname = removeExtension(self.toTempPath(pathnameSXW))+".docbook" |
182 |
f=file(pathname,"r") |
183 |
todo=f.readlines() |
184 |
f.close() |
185 |
f=file(pathname,"w") |
186 |
for line in todo: |
187 |
for oldName,newName in images: |
188 |
oldStr="<imagedata fileref=\"images/%s\""%oldName
|
189 |
newStr="<imagedata fileref=\"images/%s\""%newName
|
190 |
line=line.replace(oldStr,newStr) |
191 |
f.write(line) |
192 |
f.close() |
193 |
|
194 |
def fixTagsHeaderFromSXW(self, pathnameSXW): |
195 |
"""
|
196 |
"""
|
197 |
pathname = removeExtension(self.toTempPath(pathnameSXW))+".docbook" |
198 |
f=file(pathname,"r") |
199 |
todo=f.readlines() |
200 |
f.close() |
201 |
|
202 |
del todo[0] # Eliminamos <? xml ... |
203 |
del todo[0] # Eliminanos <ENTITY .... |
204 |
|
205 |
if re.match("\s*[<]article[> ]",todo[0] )!= None and re.match("\s*[<]/articleinfo[>]\s*",todo[5] )!= None : |
206 |
#print "Eliminando tag <article> de %s" % (pathname)
|
207 |
|
208 |
del todo[0] # Eliminamos <article lang="es-ES"> |
209 |
del todo[0] # Eliminamos <?ooogenerator Ope |
210 |
del todo[0] # Eliminamos <?oooversion ?> |
211 |
del todo[0] # Eliminamos <articleinfo> |
212 |
del todo[0] # Eliminamos <authorgroup/> |
213 |
del todo[0] # Eliminamos </articleinfo> |
214 |
del todo[-1] # Eliminamos </article> |
215 |
|
216 |
f=file(pathname,"w") |
217 |
for line in todo: |
218 |
f.write(line) |
219 |
f.close() |
220 |
|
221 |
def SXWsToDocbookInTemp(self): |
222 |
"""
|
223 |
Se recorre el directorio datos de los fuentes y convierte
|
224 |
los ficheros sxw en docbook dejandolos en el directorio datos
|
225 |
de temp.
|
226 |
"""
|
227 |
|
228 |
for root, dirs, files in os.walk(self.sourceDir.data()): |
229 |
#print "root %s\, dirs %s\n, files%s\n"%(root, dirs, files)
|
230 |
if os.path.split(root)[1] !="CVS": |
231 |
self.makedirs( self.toTempPath(root) ) |
232 |
for fname in files: |
233 |
sys.stdout.write(".")
|
234 |
sys.stdout.flush() |
235 |
#print fname
|
236 |
extension = getExtension(fname).lower() |
237 |
if extension ==".sxw": |
238 |
pathname = os.path.join(root,fname) |
239 |
self.sxw2docbook(pathname)
|
240 |
self.fixTagsHeaderFromSXW(pathname)
|
241 |
images = self.getImageListOfSXW(pathname)
|
242 |
self.moveImagesOfSXW(pathname, images)
|
243 |
self.fixImagesInDocBookOfSXW(pathname, images)
|
244 |
print
|
245 |
return True |
246 |
|
247 |
def copyDocbookFromSourceToTemp(self): |
248 |
"""
|
249 |
Copia los ficheros docbook del directorio source al
|
250 |
directorio temp, procesandolos a taves del CPP.
|
251 |
"""
|
252 |
for root, dirs, files in os.walk(self.sourceDir.docbook()): |
253 |
if os.path.split(root)[1] !="CVS": |
254 |
self.makedirs( self.toTempPath(root) ) |
255 |
for fname in files: |
256 |
extension = getExtension(fname).lower() |
257 |
if extension ==".docbook": |
258 |
cmd = """cpp -I%s -CC %s""" %(
|
259 |
str(self.tempDir), |
260 |
os.path.join(root,fname) |
261 |
) |
262 |
childstdin, childstdout, childstderr = os.popen3(cmd) |
263 |
fout = file(self.toTempPath(root,fname),"w") |
264 |
while True: |
265 |
line = childstdout.readline() |
266 |
if line in (None,""): |
267 |
break
|
268 |
if re.match("^#\s[0-9][0-9]*\s",line) == None: |
269 |
fout.write(line) |
270 |
head = "Error preprocesando el fichero '%s' (%s)" % (fname, cmd)
|
271 |
while True: |
272 |
line = childstderr.readline() |
273 |
if line in (None,""): |
274 |
break
|
275 |
if head != None: |
276 |
print head
|
277 |
head = None
|
278 |
self.status=1 |
279 |
print " "+line |
280 |
return True |
281 |
|
282 |
def copyImagesToDocBookDirInTemp(self): |
283 |
"""
|
284 |
Copia las imagenes referenciadas en el los ficheros
|
285 |
docbook a un directorio "images" junto a cada docbook.
|
286 |
"""
|
287 |
|
288 |
for root, dirs, files in os.walk(self.tempDir.docbook()): |
289 |
for fname in files: |
290 |
try:
|
291 |
#print "Moviendo imagenes de %s al directorio %s " %( fname,root)
|
292 |
extension = getExtension(fname).lower() |
293 |
if extension ==".docbook": |
294 |
f=file(os.path.join(root,fname),"r") |
295 |
todo=f.read() |
296 |
f.close() |
297 |
matchs=re.finditer('[<]imagedata fileref="([^"]*)"',todo)
|
298 |
for match in matchs: |
299 |
imageName=match.group(1)
|
300 |
sourceImage = self.tempDir.data(
|
301 |
"images",
|
302 |
os.path.basename(imageName) |
303 |
) |
304 |
targetImage = os.path.join( root, imageName) |
305 |
self.makedirs(os.path.dirname(targetImage))
|
306 |
#shutil.copyfile(sourceImage, targetImage)
|
307 |
#shutil.copy(sourceImage,self.distDir("images"))
|
308 |
self.copyFromTo(sourceImage, targetImage)
|
309 |
self.copyFromTo(sourceImage,self.distDir("images")) |
310 |
except Exception,e: |
311 |
print "Error: copyImagesToDocBookDirInTemp(procesisng file %s/%s imageName=%s), error %s, %s" % ( |
312 |
root, |
313 |
fname, |
314 |
imageName, |
315 |
str(e.__class__),
|
316 |
str(e)
|
317 |
) |
318 |
|
319 |
return True |
320 |
|
321 |
def buildHtmlFromDocbookOfTemp(self,mainfname): |
322 |
xsltFile="/usr/share/xml/docbook/stylesheet/nwalsh/xhtml/chunk.xsl"
|
323 |
|
324 |
if not os.path.isabs(mainfname): |
325 |
mainfname = self.tempDir.docbook(mainfname)
|
326 |
|
327 |
os.chdir( self.tempDir.docbook() )
|
328 |
cmd = "xsltproc -o %s/ %s %s 2>&1"% (
|
329 |
self.distDir(),
|
330 |
xsltFile, |
331 |
mainfname |
332 |
) |
333 |
print os.path.abspath(os.curdir)
|
334 |
print cmd
|
335 |
shell(cmd) |
336 |
|
337 |
def process(self,mainfname="principal.docbook"): |
338 |
self.makedirs(self.distDir("images")) |
339 |
print "Procesando ficheros SXW" |
340 |
self.SXWsToDocbookInTemp()
|
341 |
|
342 |
print "Preprocesando ficheros docbook" |
343 |
self.copyDocbookFromSourceToTemp()
|
344 |
|
345 |
print "Moviendo las imagenes" |
346 |
self.copyImagesToDocBookDirInTemp()
|
347 |
|
348 |
print "Construyendo el html" |
349 |
self.buildHtmlFromDocbookOfTemp(mainfname)
|
350 |
|
351 |
return True |
352 |
|
353 |
def __call__(self,mainfname="principal.docbook"): |
354 |
return self.process(mainfname) |
355 |
|
356 |
|
357 |
def main(): |
358 |
process = ProcessDocBook( |
359 |
sourceDir=sys.argv[1],
|
360 |
tempDir=sys.argv[2],
|
361 |
distDir=sys.argv[3]
|
362 |
) |
363 |
process() |
364 |
if process.status !=0: |
365 |
sys.exit(process.status) |
366 |
|
367 |
if __name__ == "__main__": |
368 |
main() |