summaryrefslogtreecommitdiff
path: root/cad/src/tools/linelen.py
blob: c63b4e65afbde2cc570a488db41b5c81632d24db (plain)
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
#!/usr/bin/env python
"""
linelen.py - print max line length of each input file, assuming no tabs.
Also print line number of at least one line which is that long.

@author: Bruce
@version: $Id$
@copyright: 2007-2009 Nanorex, Inc.  See LICENSE file for details.
"""

import sys, os, time

# bruce 070304, added lineno 090126

def linelen(fn):
    """
    Given filename fn,
    return max line length (assuming no tabs and all lines \n-terminated),
    and one of the line numbers it occurs on (the first one, in current implem).
    """
    file = open(fn, 'rU')
    lines = file.readlines()
    file.close()
    if not lines:
        return 0, 0
    rawlengths = map(len, lines)
    maxlen = max(rawlengths) - 1 # -1 is for the terminating newline
        ###BUG if file ends non-\n
        ###BUG if file contains tabs
    lineno = 1 + rawlengths.index(maxlen + 1)
    return maxlen, lineno

# ==

if __name__ == '__main__':
    filenames = sys.argv[1:]

    program = os.path.basename(sys.argv[0])

    if not filenames:
        msg = "usage: %s <files> [no stdin reading supported for now]" % (program,)
        print >> sys.stderr, msg
        sys.exit(1)

    for fn in filenames:
        if os.path.isfile(fn):
            maxlen, lineno = linelen(fn)
            print "linelen(%r) = %d (line %d)" % (fn, maxlen, lineno)
        else:
            print "not found or not a plain file: %r" % fn
        continue

    print "done"

# end