]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy.py
f9fba5315ad76442eb91d4c16abe8cb9921a91fe
[u/mrichter/AliRoot.git] / doxygen / thtml2doxy.py
1 #!/usr/bin/env python
2
3 ## @package thtml2doxy_clang
4 #  Translates THtml C++ comments to Doxygen using libclang as parser.
5 #
6 #  This code relies on Python bindings for libclang: libclang's interface is pretty unstable, and
7 #  its Python bindings are unstable as well.
8 #
9 #  AST (Abstract Source Tree) traversal is performed entirely using libclang used as a C++ parser,
10 #  instead of attempting to write a parser ourselves.
11 #
12 #  This code (expecially AST traversal) was inspired by:
13 #
14 #   - [Implementing a code generator with libclang](http://szelei.me/code-generator/)
15 #     (this refers to API calls used here)
16 #   - [Parsing C++ in Python with Clang](http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang)
17 #     (outdated, API calls described there do not work anymore, but useful to understand some basic
18 #     concepts)
19 #
20 #  Usage:
21 #
22 #    `thtml2doxy_clang [--stdout|-o] [-d] [--debug=DEBUG_LEVEL] file1 [file2 [file3...]]`
23 #
24 #  Parameters:
25 #
26 #   - `--stdout|-o`: output all on standard output instead of writing files in place
27 #   - `-d`: enable debug mode (very verbose output)
28 #   - `--debug=DEBUG_LEVEL`: set debug level to one of `DEBUG`, `INFO`, `WARNING`, `ERROR`,
29 #     `CRITICAL`
30 #
31 #  @author Dario Berzano, CERN
32 #  @date 2014-12-05
33
34
35 import sys
36 import os
37 import re
38 import logging
39 import getopt
40 import clang.cindex
41
42
43 ## Brain-dead color output for terminal.
44 class Colt(str):
45
46   def red(self):
47     return self.color('\033[31m')
48
49   def green(self):
50     return self.color('\033[32m')
51
52   def yellow(self):
53     return self.color('\033[33m')
54
55   def blue(self):
56     return self.color('\033[34m')
57
58   def magenta(self):
59     return self.color('\033[35m')
60
61   def cyan(self):
62     return self.color('\033[36m')
63
64   def color(self, c):
65     return c + self + '\033[m'
66
67
68 ## Comment.
69 class Comment:
70
71   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
72     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
73     self.lines = lines
74     self.first_line = first_line
75     self.first_col = first_col
76     self.last_line = last_line
77     self.last_col = last_col
78     self.indent = indent
79     self.func = func
80
81   def has_comment(self, line):
82     return line >= self.first_line and line <= self.last_line
83
84   def __str__(self):
85     return "<Comment for %s: [%d,%d:%d,%d] %s>" % (self.func, self.first_line, self.first_col, self.last_line, self.last_col, self.lines)
86
87
88 ## A data member comment.
89 class MemberComment:
90
91   def __init__(self, text, is_transient, array_size, first_line, first_col, func):
92     assert first_line > 0, 'Wrong line number'
93     self.lines = [ text ]
94     self.is_transient = is_transient
95     self.array_size = array_size
96     self.first_line = first_line
97     self.first_col = first_col
98     self.func = func
99
100   def has_comment(self, line):
101     return line == self.first_line
102
103   def __str__(self):
104
105     if self.is_transient:
106       tt = '!transient! '
107     else:
108       tt = ''
109
110     if self.array_size is not None:
111       ars = '[%s] ' % self.array_size
112     else:
113       ars = ''
114
115     return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
116
117
118 ## A dummy comment that removes comment lines.
119 class RemoveComment(Comment):
120
121   def __init__(self, first_line, last_line):
122     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
123     self.first_line = first_line
124     self.last_line = last_line
125     self.func = '<remove>'
126
127   def __str__(self):
128     return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
129
130
131 ## Parses method comments.
132 #
133 #  @param cursor   Current libclang parser cursor
134 #  @param comments Array of comments: new ones will be appended there
135 def comment_method(cursor, comments):
136
137   # we are looking for the following structure: method -> compound statement -> comment, i.e. we
138   # need to extract the first comment in the compound statement composing the method
139
140   in_compound_stmt = False
141   expect_comment = False
142   emit_comment = False
143
144   comment = []
145   comment_function = cursor.spelling or cursor.displayname
146   comment_line_start = -1
147   comment_line_end = -1
148   comment_col_start = -1
149   comment_col_end = -1
150   comment_indent = -1
151
152   for token in cursor.get_tokens():
153
154     if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
155       if not in_compound_stmt:
156         in_compound_stmt = True
157         expect_comment = True
158         comment_line_end = -1
159     else:
160       if in_compound_stmt:
161         in_compound_stmt = False
162         emit_comment = True
163
164     # tkind = str(token.kind)[str(token.kind).index('.')+1:]
165     # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
166
167     if in_compound_stmt:
168
169       if expect_comment:
170
171         extent = token.extent
172         line_start = extent.start.line
173         line_end = extent.end.line
174
175         if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
176           pass
177
178         elif token.kind == clang.cindex.TokenKind.COMMENT and (comment_line_end == -1 or (line_start == comment_line_end+1 and line_end-line_start == 0)):
179           comment_line_end = line_end
180           comment_col_end = extent.end.column
181
182           if comment_indent == -1 or (extent.start.column-1) < comment_indent:
183             comment_indent = extent.start.column-1
184
185           if comment_line_start == -1:
186             comment_line_start = line_start
187             comment_col_start = extent.start.column
188           comment.extend( token.spelling.split('\n') )
189
190           # multiline comments are parsed in one go, therefore don't expect subsequent comments
191           if line_end - line_start > 0:
192             emit_comment = True
193             expect_comment = False
194
195         else:
196           emit_comment = True
197           expect_comment = False
198
199     if emit_comment:
200
201       if comment_line_start > 0:
202
203         comment = refactor_comment( comment )
204
205         if len(comment) > 0:
206           logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
207           comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
208         else:
209           logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
210           comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
211           #comments.append(RemoveComment(comment_line_start, comment_line_end))
212
213       else:
214         logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
215
216       comment = []
217       comment_line_start = -1
218       comment_line_end = -1
219       comment_col_start = -1
220       comment_col_end = -1
221       comment_indent = -1
222
223       emit_comment = False
224       break
225
226
227 ## Parses comments to class data members.
228 #
229 #  @param cursor   Current libclang parser cursor
230 #  @param comments Array of comments: new ones will be appended there
231 def comment_datamember(cursor, comments):
232
233   # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
234   # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
235   # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
236   # definition is fully on one line, and we take the line number from cursor.location.
237
238   line_num = cursor.location.line
239   raw = None
240   prev = None
241   found = False
242
243   # Huge overkill
244   with open(str(cursor.location.file)) as fp:
245     cur_line = 0
246     for raw in fp:
247       cur_line = cur_line + 1
248       if cur_line == line_num:
249         found = True
250         break
251       prev = raw
252
253   assert found, 'A line that should exist was not found in file' % cursor.location.file
254
255   recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
256   recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
257
258   mcomm = re.search(recomm, raw)
259   if mcomm:
260     # If it does not match, we do not have a comment
261     member_name = cursor.spelling;
262     is_transient = mcomm.group(2) is not None
263     array_size = mcomm.group(4)
264     text = mcomm.group(5)
265
266     col_num = mcomm.start()+1;
267
268     if array_size is not None and prev is not None:
269       # ROOT arrays with comments already converted to Doxygen have the member description on the
270       # previous line
271       mcomm_doxyary = re.search(recomm_doxyary, prev)
272       if mcomm_doxyary:
273         text = mcomm_doxyary.group(1)
274         comments.append(RemoveComment(line_num-1, line_num-1))
275
276     logging.debug('Comment found for member %s' % Colt(member_name).magenta())
277
278     comments.append( MemberComment(
279       text,
280       is_transient,
281       array_size,
282       line_num,
283       col_num,
284       member_name ))
285
286
287 ## Parses class description (beginning of file).
288 #
289 #  The clang parser does not work in this case so we do it manually, but it is very simple: we keep
290 #  the first consecutive sequence of single-line comments (//) we find - provided that it occurs
291 #  before any other comment found so far in the file (the comments array is inspected to ensure
292 #  this).
293 #
294 #  Multi-line comments (/* ... */) are not considered as they are commonly used to display
295 #  copyright notice.
296 #
297 #  @param filename Name of the current file
298 #  @param comments Array of comments: new ones will be appended there
299 def comment_classdesc(filename, comments):
300
301   recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
302
303   reclass_doxy = r'(?i)^\s*\\class:?\s*(.*?)\s*$'
304   class_name_doxy = None
305
306   reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
307   redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
308   author = None
309   date = None
310
311   comment_lines = []
312
313   start_line = -1
314   end_line = -1
315
316   line_num = 0
317
318   with open(filename, 'r') as fp:
319
320     for raw in fp:
321
322       line_num = line_num + 1
323
324       if raw.strip() == '' and start_line > 0:
325         # Skip empty lines
326         continue
327
328       stripped = strip_html(raw)
329       mcomm = re.search(recomm, stripped)
330       if mcomm:
331
332         if start_line == -1:
333
334           # First line. Check that we do not overlap with other comments
335           comment_overlaps = False
336           for c in comments:
337             if c.has_comment(line_num):
338               comment_overlaps = True
339               break
340
341           if comment_overlaps:
342             # No need to look for other comments
343             break
344
345           start_line = line_num
346
347         end_line = line_num
348         append = True
349
350         mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
351         if mclass_doxy:
352           class_name_doxy = mclass_doxy.group(1)
353           append = False
354         else:
355           mauthor = re.search(reauthor, mcomm.group(1))
356           if mauthor:
357             author = mauthor.group(1)
358             if date is None:
359               # Date specified in the standalone \date field has priority
360               date = mauthor.group(2)
361             append = False
362           else:
363             mdate = re.search(redate, mcomm.group(1))
364             if mdate:
365               date = mdate.group(1)
366               append = False
367
368         if append:
369           comment_lines.append( mcomm.group(1) )
370
371       else:
372         if start_line > 0:
373           break
374
375   if class_name_doxy is None:
376
377     # No \class specified: guess it from file name
378     reclass = r'^(.*/)?(.*?)(\..*)?$'
379     mclass = re.search( reclass, filename )
380     if mclass:
381       class_name_doxy = mclass.group(2)
382     else:
383       assert False, 'Regexp unable to extract classname from file'
384
385   if start_line > 0:
386
387     # Prepend \class specifier (and an empty line)
388     comment_lines[:0] = [ '\\class ' + class_name_doxy ]
389
390     # Append author and date if they exist
391     comment_lines.append('')
392
393     if author is not None:
394       comment_lines.append( '\\author ' + author )
395
396     if date is not None:
397       comment_lines.append( '\\date ' + date )
398
399     comment_lines = refactor_comment(comment_lines, do_strip_html=False)
400     logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
401     comments.append(Comment(
402       comment_lines,
403       start_line, 1, end_line, 1,
404       0, class_name_doxy
405     ))
406
407   else:
408
409     logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
410
411
412 ## Traverse the AST recursively starting from the current cursor.
413 #
414 #  @param cursor    A Clang parser cursor
415 #  @param filename  Name of the current file
416 #  @param comments  Array of comments: new ones will be appended there
417 #  @param recursion Current recursion depth
418 def traverse_ast(cursor, filename, comments, recursion=0):
419
420   # libclang traverses included files as well: we do not want this behavior
421   if cursor.location.file is not None and str(cursor.location.file) != filename:
422     logging.debug("Skipping processing of included %s" % cursor.location.file)
423     return
424
425   text = cursor.spelling or cursor.displayname
426   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
427
428   indent = ''
429   for i in range(0, recursion):
430     indent = indent + '  '
431
432   if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
433
434     # cursor ran into a C++ method
435     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
436     comment_method(cursor, comments)
437
438   elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
439
440     # cursor ran into a data member declaration
441     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
442     comment_datamember(cursor, comments)
443
444   else:
445
446     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
447
448   for child_cursor in cursor.get_children():
449     traverse_ast(child_cursor, filename, comments, recursion+1)
450
451   if recursion == 0:
452     comment_classdesc(filename, comments)
453
454
455 ## Strip some HTML tags from the given string. Returns clean string.
456 #
457 #  @param s Input string
458 def strip_html(s):
459   rehtml = r'(?i)</?(P|H[0-9]|BR)/?>'
460   return re.sub(rehtml, '', s)
461
462
463 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
464 #
465 #  @param comment An array containing the lines of the original comment
466 def refactor_comment(comment, do_strip_html=True):
467
468   recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
469   regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
470
471   # Support for LaTeX blocks spanning on multiple lines
472   relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
473   in_latex = False
474   latex_block = False
475
476   # Support for LaTeX blocks on a single line
477   reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
478
479   new_comment = []
480   insert_blank = False
481   wait_first_non_blank = True
482   for line_comment in comment:
483
484     # Strip some HTML tags
485     if do_strip_html:
486       line_comment = strip_html(line_comment)
487
488     mcomm = re.search( recomm, line_comment )
489     if mcomm:
490       new_line_comment = mcomm.group(2)
491       mgarbage = re.search( regarbage, new_line_comment )
492
493       if new_line_comment == '' or mgarbage is not None:
494         insert_blank = True
495       else:
496         if insert_blank and not wait_first_non_blank:
497           new_comment.append('')
498         insert_blank = False
499         wait_first_non_blank = False
500
501         # Postprocessing: LaTeX formulas in ROOT format
502         # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
503         # There can be several ROOT LaTeX forumlas per line
504         while True:
505           minline_latex = re.search( reinline_latex, new_line_comment )
506           if minline_latex:
507             new_line_comment = '%s\\f$%s\\f$%s' % \
508               ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
509                 minline_latex.group(3) )
510           else:
511             break
512
513         # ROOT LaTeX: do we have a Begin/End_LaTeX block?
514         # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
515         # block here left without a corresponding ending block
516         mlatex = re.search( relatex, new_line_comment )
517         if mlatex:
518
519           # before and after parts have been already stripped
520           l_before = mlatex.group(2)
521           l_after = mlatex.group(4)
522           is_begin = mlatex.group(3).upper() == 'BEGIN'  # if not, END
523
524           if l_before is None:
525             l_before = ''
526           if l_after is None:
527             l_after = ''
528
529           if is_begin:
530
531             # Begin of LaTeX part
532
533             in_latex = True
534             if l_before == '' and l_after == '':
535
536               # Opening tag alone: mark the beginning of a block: \f[ ... \f]
537               latex_block = True
538               new_comment.append( '\\f[' )
539
540             else:
541               # Mark the beginning of inline: \f$ ... \f$
542               latex_block = False
543               new_comment.append(
544                 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
545               )
546
547           else:
548
549             # End of LaTeX part
550             in_latex = False
551
552             if latex_block:
553
554               # Closing a LaTeX block
555               if l_before != '':
556                 new_comment.append( l_before.replace('#', '\\') )
557               new_comment.append( '\\f]' )
558               if l_after != '':
559                 new_comment.append( l_after )
560
561             else:
562
563               # Closing a LaTeX inline
564               new_comment.append(
565                 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
566               )
567
568           # Prevent appending lines (we have already done that)
569           new_line_comment = None
570
571         if new_line_comment is not None:
572           if in_latex:
573             new_line_comment = new_line_comment.replace('#', '\\')
574           new_comment.append( new_line_comment )
575
576     else:
577       assert False, 'Comment regexp does not match'
578
579   return new_comment
580
581
582 ## Rewrites all comments from the given file handler.
583 #
584 #  @param fhin     The file handler to read from
585 #  @param fhout    The file handler to write to
586 #  @param comments Array of comments
587 def rewrite_comments(fhin, fhout, comments):
588
589   line_num = 0
590   in_comment = False
591   skip_empty = False
592   comm = None
593   prev_comm = None
594
595   rindent = r'^(\s*)'
596
597   for line in fhin:
598
599     line_num = line_num + 1
600
601     # Find current comment
602     prev_comm = comm
603     comm = None
604     for c in comments:
605       if c.has_comment(line_num):
606         comm = c
607
608     if comm:
609
610       if isinstance(comm, MemberComment):
611         non_comment = line[ 0:comm.first_col-1 ]
612
613         if comm.array_size is not None:
614
615           mindent = re.search(rindent, line)
616           if comm.is_transient:
617             tt = '!'
618           else:
619             tt = ''
620
621           # Special case: we need multiple lines not to confuse ROOT's C++ parser
622           fhout.write('%s/// %s\n%s//%s[%s]\n' % (
623             mindent.group(1),
624             comm.lines[0],
625             non_comment,
626             tt,
627             comm.array_size
628           ))
629
630         else:
631
632           if comm.is_transient:
633             tt = '!'
634           else:
635             tt = '/'
636
637           fhout.write('%s//%s< %s\n' % (
638             non_comment,
639             tt,
640             comm.lines[0]
641           ))
642
643       elif isinstance(comm, RemoveComment):
644         # Do nothing: just skip line
645         pass
646
647       elif prev_comm is None:
648         # Beginning of a new comment block of type Comment
649         in_comment = True
650
651         # Extract the non-comment part and print it if it exists
652         non_comment = line[ 0:comm.first_col-1 ].rstrip()
653         if non_comment != '':
654           fhout.write( non_comment + '\n' )
655
656     else:
657
658       if in_comment:
659
660         # We have just exited a comment block of type Comment
661         in_comment = False
662
663         # Dump revamped comment, if applicable
664         text_indent = ''
665         for i in range(0,prev_comm.indent):
666           text_indent = text_indent + ' '
667
668         for lc in prev_comm.lines:
669           fhout.write( "%s/// %s\n" % (text_indent, lc) );
670         fhout.write('\n')
671         skip_empty = True
672
673       line_out = line.rstrip('\n')
674       if skip_empty:
675         skip_empty = False
676         if line_out.strip() != '':
677           fhout.write( line_out + '\n' )
678       else:
679         fhout.write( line_out + '\n' )
680
681
682 ## The main function.
683 #
684 #  Return value is the executable's return value.
685 def main(argv):
686
687   # Setup logging on stderr
688   log_level = logging.INFO
689   logging.basicConfig(
690     level=log_level,
691     format='%(levelname)-8s %(funcName)-20s %(message)s',
692     stream=sys.stderr
693   )
694
695   # Parse command-line options
696   output_on_stdout = False
697   include_flags = []
698   try:
699     opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
700     for o, a in opts:
701       if o == '--debug':
702         log_level = getattr( logging, a.upper(), None )
703         if not isinstance(log_level, int):
704           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
705       elif o == '-d':
706         log_level = logging.DEBUG
707       elif o == '-o' or o == '--stdout':
708         output_on_stdout = True
709       elif o == '-I':
710         if os.path.isdir(a):
711           include_flags.extend( [ '-I', a ] )
712         else:
713           logging.fatal('Include directory not found: %s' % Colt(a).magenta())
714           return 2
715       else:
716         assert False, 'Unhandled argument'
717   except getopt.GetoptError as e:
718     logging.fatal('Invalid arguments: %s' % e)
719     return 1
720
721   logging.getLogger('').setLevel(log_level)
722
723   # Attempt to load libclang from a list of known locations
724   libclang_locations = [
725     '/usr/lib/llvm-3.5/lib/libclang.so.1',
726     '/usr/lib/libclang.so',
727     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
728   ]
729   libclang_found = False
730
731   for lib in libclang_locations:
732     if os.path.isfile(lib):
733       clang.cindex.Config.set_library_file(lib)
734       libclang_found = True
735       break
736
737   if not libclang_found:
738     logging.fatal('Cannot find libclang')
739     return 1
740
741   # Loop over all files
742   for fn in args:
743
744     logging.info('Input file: %s' % Colt(fn).magenta())
745     index = clang.cindex.Index.create()
746     clang_args = [ '-x', 'c++' ]
747     clang_args.extend( include_flags )
748     translation_unit = index.parse(fn, args=clang_args)
749
750     comments = []
751     traverse_ast( translation_unit.cursor, fn, comments )
752     for c in comments:
753
754       logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
755
756       if isinstance(c, MemberComment):
757
758         if c.is_transient:
759           transient_text = Colt('transient ').yellow()
760         else:
761           transient_text = ''
762
763         if c.array_size is not None:
764           array_text = Colt('arraysize=%s ' % c.array_size).yellow()
765         else:
766           array_text = ''
767
768         logging.debug(
769           "%s %s%s{%s}" % ( \
770             Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
771             transient_text,
772             array_text,
773             Colt(c.lines[0]).cyan()
774         ))
775
776       elif isinstance(c, RemoveComment):
777
778         logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
779
780       else:
781         for l in c.lines:
782           logging.debug(
783             Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
784             "{%s}" % Colt(l).cyan()
785           )
786
787     try:
788
789       if output_on_stdout:
790         with open(fn, 'r') as fhin:
791           rewrite_comments( fhin, sys.stdout, comments )
792       else:
793         fn_back = fn + '.thtml2doxy_backup'
794         os.rename( fn, fn_back )
795
796         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
797           rewrite_comments( fhin, fhout, comments )
798
799         os.remove( fn_back )
800         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
801     except (IOError,OSError) as e:
802       logging.error('File operation failed: %s' % e)
803
804   return 0
805
806
807 if __name__ == '__main__':
808   sys.exit( main( sys.argv[1:] ) )