File: check-line-length.py

package info (click to toggle)
bornagain 23.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,948 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 318; ruby: 173; xml: 130; makefile: 51; ansic: 24
file content (88 lines) | stat: -rwxr-xr-x 2,101 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python3

"""
Check line length of Python files in or under current working directory.
Used by BornAgain CI to ensure that published example code can be nicely
displayed in the online documentation.

Copyright Forschungszentrum Jülich GmbH 2025.
License:  Public Domain
"""

import glob, os, re, sys
from io import open

if len(sys.argv)<2:
    print( """
Usage: check-line-length <max_mum_chars_per_line>

Returns 1 if any given file in or under the current working directory
    - exceeds the given number of characters per line,
    - or contains a tab.
Returns 0 otherwise.
""" )
    sys.exit(-1)

fworst = ""
lworst = 0
totlin = 0
totexc = 0
tottab = 0
nftot = 0
nfexc = 0
nftab = 0

limit = int(sys.argv[1])
flist = glob.glob(os.path.join('.', "**/*.py"), recursive=True)

for fn in flist:
    # read in
    fd = open( fn, 'r' )
    txt = fd.read().split( '\n' )
    fd.close

    n = len(txt)
    maxlen = 0
    maxwhere = -1
    nexclin = 0
    ntablin = 0
    for i in range(n):
        lin = txt[i]
        if re.match(r'\s*\/\/', lin):
            continue # ignore comment lines
        if '\t' in lin:
            ntablin += 1
            lin = lin.replace( '\t', '    ' )
        l = len(lin)
        if l>maxlen:
            maxlen = l
            maxwhere = i
        if l>limit:
            nexclin += 1

    if nexclin>0:
        print( "%s: %i/%i lines too long, line %i longest with %i chars" %
               (fn, nexclin, n, maxwhere+1, maxlen) )
        totexc += nexclin
        nfexc += 1
    if ntablin>0:
        print( "%s: %i/%i lines contain a TAB" % (fn, ntablin, n) )
        tottab += ntablin
        nftab += 1
    totlin += n
    nftot += 1
    if maxlen>lworst:
        lworst = maxlen
        fworst = fn

exitval = 0
if nfexc>0:
    print( "total: %i/%i lines too long, in %i/%i files, longest in %s with %i chars" %
           (totexc, totlin, nfexc, nftot, fworst, lworst) )
    exitval = 1
if nftab>0:
    print( "total: %i/%i lines contain a TAB, in %i/%i files" %
           (tottab, totlin, nftab, nftot) )
    exitval = 1

sys.exit(exitval)