File: wrapcomments.py

package info (click to toggle)
deal.ii 9.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 236,560 kB
  • sloc: cpp: 334,965; ansic: 72,687; python: 2,374; sh: 841; perl: 761; xml: 437; makefile: 82; javascript: 14
file content (588 lines) | stat: -rwxr-xr-x 17,875 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
#!/usr/bin/env python3

## ---------------------------------------------------------------------
##
## Copyright (C) 2016 - 2019 by the deal.II authors
##
## This file is part of the deal.II library.
##
## The deal.II library is free software; you can use it, redistribute
## it, and/or modify it under the terms of the GNU Lesser General
## Public License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
## The full text of the license can be found in the file LICENSE.md at
## the top level directory of deal.II.
##
## ---------------------------------------------------------------------

#
# Written by timo.heister@gmail.com

# run this script on all headers of deal.II to fix comment line wrapping for
# doxygen comments.
# Example:
# cd include
# find . -name "*h" -print | while read file;do ../contrib/utilities/wrapcomments.py $file >temp;mv temp $file;done

from __future__ import print_function
import textwrap
import sys, re

# As of python 2.6 we can tell the text wrapper to not break on hyphens. This is
# usually what we want to do: we don't want to split URLs with hyphens and
# doxygen will format 'non-primitive' as 'non- primitive' if it is
# (inadvertently) split across two lines.
wrapper = textwrap.TextWrapper(break_on_hyphens=False)

# take an array of lines and wrap them to 78 columns and let each line start
# with @p startwith
def wrap_block(lines, startwith):
    longline = " ".join(lines)
    wrapper.initial_indent = startwith
    wrapper.subsequent_indent = startwith
    wrapper.break_long_words = False
    wrapper.width = 78
    return wrapper.wrap(longline)

# strips whitespace and leading "*" from each lines
def remove_junk(lines):
    out = []
    for line in lines:
        line = line.strip()
        if line.startswith("*"):
            line = line[1:].strip()
        out.append(line)
    return out

# returns True if at least one entry in @p list is contained in @p str
def one_in(list, str):
    for li in list:
        if li in str:
            return True
    return False

# returns True if @p str starts with one of the entries in @p list
def starts_with_one(list, str):
    for li in list:
        if str.startswith(li):
            return True
    return False

# take a doxygen comment block "/** bla ... */" given as a list of lines and
# format it in a pretty way rewrapping lines while taking care to keep certain
# structure.
def format_block(lines, infostr=""):
    if len(lines)==1 and "/*" in lines[0] and "*/" in lines[0]:
        return lines

    if (not "/**" in lines[0]
          or not "*/" in lines[-1]):
        print("%s not a code block"%infostr, file=sys.stderr)
        return lines

    for line in lines[1:-1]:
        assert(not "/*" in line)
        assert(not "*/" in line)

    lines[-1]=lines[-1].replace("**/","*/")

    if not lines[0].strip().startswith("/**"):
        print ("%s error, ignoring code block with junk in same line before"%infostr, file=sys.stderr)
        return lines
    if not lines[-1].strip().endswith("*/"):
        print ("%s error, ignoring code block not ending at end of line"%infostr, file=sys.stderr)
        return lines

    if lines[0].strip()!="/**":
        #print ("%s warning code block not starting in separate line"%infostr, file=sys.stderr)
        idx = lines[0].find("/**")
        temp = [lines[0][0:idx+3], lines[0][idx+3:]]
        temp.extend(lines[1:])
        lines = temp
    if lines[-1].strip()!="*/":
        #print ("%s warning code block not ending in separate line"%infostr, file=sys.stderr)
        idx = lines[-1].find("*/")
        temp = lines[0:-1]
        temp.append(lines[-1][0:idx])
        temp.append(lines[-1][idx:])
        lines = temp

    idx = lines[0].find("/**")
    start = lines[0][:idx]+" * "
    
    out = [lines[0].rstrip()]
    idx = 1
    endidx = len(lines)-1
    curlines = []

    ops_startline = ["<li>", "@param", "@returns", "@warning", "@ingroup", "@author", "@date", "@related", "@relates", "@relatesalso", "@deprecated", "@image", "@return", "@brief", "@attention", "@copydoc", "@addtogroup", "@todo", "@tparam", "@see", "@note", "@skip", "@skipline", "@until", "@line", "@dontinclude", "@include"]

    # subset of ops_startline that does not want stuff from the next line appended
    # to this.
    ops_also_end_paragraph = ["@image", "@skip", "@skipline", "@until", "@line", "@dontinclude", "@include"]

    # stuff handled in the while loop down: @code, @verbatim, @f @ref

    ops_separate_line = ["<ol>", "</ol>", "<ul>", "</ul>", "@{", "@}", "<br>"]

    # separate and do not break:
    ops_title_line = ["@page", "@name"]

    #todo:
    #  @arg @c @cond  @em @endcond @f{ @internal @name @post @pre  @sa 

    while idx<endidx:
        if one_in(ops_separate_line, lines[idx]):
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            thisline = remove_junk([lines[idx]])[0]
            for it in ops_separate_line:
                if it in thisline and thisline!=it:
                    print ("%s warning %s not in separate line"%(infostr, it), file=sys.stderr)
            out.append(start + thisline)
        elif re.match(r'\*\s+- ',lines[idx].strip()):
            # bullet ('-') list
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            thisline = lines[idx].strip()[2:]
            out.append(start + thisline)
        elif lines[idx].strip().startswith("* ") and re.match(r'\s*\d+.',lines[idx][3:]):
            # numbered list
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            thisline = lines[idx].strip()[2:]
            out.append(start + thisline)
            
        elif one_in(ops_title_line, lines[idx]):
            # do not break @page, etc.
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            thisline = remove_junk([lines[idx]])[0]
            
            if not thisline.split(" ")[0] in ops_title_line:
                print ("%s warning: @page/@name not at start of line"%(infostr), file=sys.stderr)
            out.append(start + thisline.strip())

        elif "@ref" in lines[idx]:
            # @ref link "some long description"
            # is special, and we mustn't break it
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            thisline = remove_junk([lines[idx]])[0]
            if not thisline.startswith("@ref") and not thisline.startswith("(@ref"):
                print ("%s warning %s not at start of line"%(infostr, "@ref"), file=sys.stderr)

            # format:
            # @ref name "some text" blub
            # or @ref name blurb
            withquotes = thisline.split('"')
            if len(withquotes)==3:
                thisline = withquotes[0]+'"'+withquotes[1]+'"'
                remain = withquotes[2]
                for st in [')', '.', ',', ':']:
                    if remain.startswith(st):
                        thisline = thisline + st
                        remain = remain[1:]

                # do not wrap the @ref line:
                out.append(start + thisline.strip())
                if len(withquotes[0].strip().split(' '))!=2:
                    print ("%s warning @ref line looks broken"%(infostr), file=sys.stderr)     
            elif len(withquotes)==1:
                words = thisline.strip().split(" ")
                if len(words)<2 or len(words[0])==0 or len(words[1])==0:
                    print ("%s warning @ref line looks broken"%(infostr), file=sys.stderr)     
                thisline = words[0] + ' ' + words[1]
                out.append(start + thisline.strip())
                remain = " ".join(words[2:])
            else:
                print ("%s warning @ref quotes are not in single line"%(infostr), file=sys.stderr)
                remain = ''

            if len(remain)>0:
                curlines.append(remain)
            
        elif one_in(ops_startline, lines[idx]):
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            thisline = remove_junk([lines[idx]])[0]
            if not starts_with_one(ops_startline, thisline):
                for it in ops_startline:
                    if it in thisline:
                        print ("%s warning %s not at start of line"%(infostr, it), file=sys.stderr)
            if one_in(ops_also_end_paragraph, lines[idx]):
                out.append(lines[idx].rstrip())
            else:
                curlines.append(lines[idx])
        elif one_in(["@code", "@verbatim", "@f[", "@f{"], lines[idx]):
            if "@f{" in lines[idx]:
                if not lines[idx].endswith("}{"):
                    print ("%s warning malformed @f{*}{"%(infostr), file=sys.stderr)
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            while True:
                thisline = lines[idx].rstrip()
                if thisline.strip()=="*":
                    thisline = start
                elif thisline.strip()=="@code" or thisline.strip()=="@endcode":
                    thisline = start + thisline.strip()
                elif thisline.strip()[0:2]!="* ":
                    if thisline[0:len(start)].strip()=="":
                        # just a missing *, so keep old indentation
                        thisline = start + thisline[len(start):]
                    else:
                        # no way to recover indentation:
                        print ("%s Error: wrong formatting inside @code block"%infostr, file=sys.stderr)
                        thisline = start + thisline.strip()
                else:
                    thisline = start + thisline.strip()[2:]
                out.append(thisline.rstrip())
                if one_in(["@endcode", "@endverbatim", "@f]", "@f}"], lines[idx]):
                    break
                idx += 1
        elif lines[idx].strip()=="*":
            if curlines!=[]:
                out.extend(wrap_block(remove_junk(curlines), start))
                curlines=[]
            out.append(start[:-1]) #skip whitespace at the end
        else:
            curlines.append(lines[idx])
        idx += 1

    if curlines!=[]:
        out.extend(wrap_block(remove_junk(curlines), start))        

    out.append(start[0:-2] + lines[-1].strip())

    return out


# test the routines:
lineI = ["   * blub", \
         "   * two three ", \
         "   * four"]
lineO = ["blub", \
         "two three", \
         "four"]
assert(remove_junk(lineI)==lineO)

lineI = ["blub", \
         "two three", \
         "four"]
lineO = ["   * blub two three four"]
assert(wrap_block(lineI,"   * ")==lineO)

lineI = [" * 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2",\
         " * A 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0"]
assert(wrap_block(remove_junk(lineI)," * ")==lineI)

lineI = [" * Structure which is passed to Triangulation::create_triangulation. It",\
         " * contains all data needed to construct a cell, namely the indices of the",\
         " * vertices and the material indicator."]
assert(wrap_block(remove_junk(lineI)," * ")==lineI)

lineI = ["  /**", \
         "   * blub", \
         "   * two three", \
         "   * four", \
         "   */"]
lineO = ["  /**", \
         "   * blub two three four", \
         "   */"]
assert(format_block(lineI)==lineO)

lineI = ["  /**", \
         "   * blub", \
         "   * two three", \
         "   * ", \
         "   * four", \
         "   */"]
lineO = ["  /**", \
         "   * blub two three", \
         "   *", \
         "   * four", \
         "   */"]
assert(format_block(lineI)==lineO)

lineI = ["  /**", \
         "   * blub", \
         "   * @code", \
         "   *   two three", \
         "   * @endcode", \
         "   * four", \
         "   */"]
assert(format_block(lineI)==lineI)

lineI = ["  /**", \
         "   * blub", \
         "   * @code ", \
         "   *   two three", \
         "   *   two three  ", \
         "   * ", \
         "   *   two three", \
         "   * @endcode ", \
         "   * four", \
         "   */"]
lineO = ["  /**", \
         "   * blub", \
         "   * @code", \
         "   *   two three", \
         "   *   two three", \
         "   *", \
         "   *   two three", \
         "   * @endcode", \
         "   * four", \
         "   */"]
assert(format_block(lineI)==lineO)
 
lineI = ["  /**", \
         "   * blub", \
         "       @code ", \
         "       two three", \
         "      @endcode ", \
         "   * four", \
         "   */"]
lineO = ["  /**", \
         "   * blub", \
         "   * @code", \
         "   *   two three", \
         "   * @endcode", \
         "   * four", \
         "   */"]
assert(format_block(lineI)==lineO)


lineI = ["  /**", \
         "   * blub", \
         "   * @code ", \
         "    *   two three", \
         "   *   two three  ", \
         " * ", \
         "       two three", \
         "    ", \
         "   * @endcode ", \
         "   * four", \
         "   */"]
lineO = ["  /**", \
         "   * blub", \
         "   * @code", \
         "   *   two three", \
         "   *   two three", \
         "   *", \
         "   *   two three", \
         "   *", \
         "   * @endcode", \
         "   * four", \
         "   */"]
assert(format_block(lineI)==lineO)



lineI = ["  /**", \
         "   * blub", \
         "   * <ul>", \
         "   * <li> bla", \
         "   * <li> blub", \
         "   * </ul>", \
         "   */"]
assert(format_block(lineI)==lineI)
 
lineI = ["    /** @addtogroup Exceptions", \
         "     * @{ */"]
lineO = ["    /**", \
         "     * @addtogroup Exceptions", \
         "     * @{", \
         "     */"]
assert(format_block(lineI)==lineO)

lineI = [" /** ", \
         "  *   bla", \
         "  * @image testing.png", \
         "  *  blub", \
         "  */"]
lineO = [" /**", \
         "  * bla", \
         "  * @image testing.png", \
         "  * blub", \
         "  */"]
assert(format_block(lineI)==lineO)

lineI = [" /** ", \
         "  * @ref a b c d e", \
         "  * @ref a \"b c\" d dd", \
         "  */"]
lineO = [" /**", \
         "  * @ref a", \
         "  * b c d e", \
         "  * @ref a \"b c\"", \
         "  * d dd", \
         "  */"]
assert(format_block(lineI)==lineO)

long = "long "*20
lineI = [" /** ", \
         "  * @ref a \""+long+"\" d", \
         "  */"]
lineO = [" /**", \
         "  * @ref a \""+long+"\"", \
         "  * d", \
         "  */"]
assert(format_block(lineI)==lineO)

lineI = [" /** ", \
         "  * @ref a. c", \
         "  * @ref a \"b c\". c2", \
         "  */"]
lineO = [" /**", \
         "  * @ref a.", \
         "  * c", \
         "  * @ref a \"b c\".", \
         "  * c2", \
         "  */"]
assert(format_block(lineI)==lineO)

# do not break @page:
longtext = "bla bla"*20
lineI = [" /**", \
         "  * @page " + longtext, \
         "  * hello", \
         "  */"]
assert(format_block(lineI)==lineI)

# do not break $very_long_formula_without_spacing$:
longtext = "blabla"*20
lineI = [" /**", \
         "  * a $" + longtext + "$", \
         "  */"]
lineO = [" /**", \
         "  * a", \
         "  * $" + longtext + "$", \
         "  */"]
assert(format_block(lineI)==lineO)

# nested lists
lineI = [" /**", \
         "  * Hello:", \
         "  * - A", \
         "  * - B", \
         "  *   - C", \
         "  *   - D", \
         "  * - E", \
         "  *         - very indented", \
         "  */"]
lineO = lineI
assert(format_block(lineI)==lineO)

# @f{}
lineI = [" /**", \
         "  * Hello:", \
         "  * @f{aligned*}{", \
         "  *   A\\\\", \
         "  *   B", \
         "  * @f}", \
         "  * bla", \
         "  */"]
lineO = lineI
assert(format_block(lineI)==lineO)

# @until 
lineI = [" /**", \
         "  * Hello:", \
         "  * @include a", \
         "  * bla", \
         "  * @dontinclude a", \
         "  * bla", \
         "  * @line a", \
         "  * bla", \
         "  * @skip a", \
         "  * bla", \
         "  * @until a", \
         "  * bla", \
         "  */"]
lineO = lineI
assert(format_block(lineI)==lineO)

# lists
lineI = [" /**", \
         "  * Hello:", \
         "  *  - a", \
         "  *  - b", \
         "  * the end.", \
         "  */"]
lineO = lineI
assert(format_block(lineI)==lineO)

# numbered lists
lineI = [" /**", \
         "  * Hello:", \
         "  * 1. a", \
         "  * 2. b", \
         "  * the end.", \
         "  */"]
lineO = lineI
assert(format_block(lineI)==lineO)

# do not break @name:
longtext = "bla bla"*20
lineI = [" /**", \
         "  * @name " + longtext, \
         "  * hello", \
         "  */"]
assert(format_block(lineI)==lineI)


#print (lineI)
#print (format_block(lineI))




# now open the file and do the work


args=sys.argv
args.pop(0)

if len(args)!=1:
    print("Usage: wrapcomments.py infile >outfile")
    exit(0)

f = open(args[0])
lines = f.readlines()
f.close()

out = []
cur = []
inblock = False
lineidx = 0
for line in lines:
    lineidx += 1
    line = line.replace("\n","")
    if not inblock and "/**" in line:
        inblock = True
        cur = []
    if inblock:
        cur.append(line)
    else:
        out.append(line)
    if inblock and "*/" in line:
        out.extend(format_block(cur, args[0]+":%d"%lineidx))
        cur = []
        inblock = False

assert(cur==[])

for line in out:
    print (line)