1#!/usr/bin/env python2
 2
 3"""Run cloc to count lines of code over all our files, then format the output
 4to look like cloccount output for Hudson to parse.
 5"""
 6
 7import os
 8import sys
 9from argparse import ArgumentParser
10import logging
11import subprocess
12
13from pathlib import Path
14
15def count_lines(output, dirs):
16    defs = Path(__file__).parent.joinpath('cloc.defs')
17    logging.info('defs {d}'.format(d=defs))
18    try:
19        proc = subprocess.Popen([
20                'cloc',
21                '--read-lang-def={d}'.format(d=defs),
22                '--by-file',
23                '--csv',
24                '--quiet',
25                '--progress-rate=0'] + dirs,
26        stdout=subprocess.PIPE)
27    except OSError:
28        raise SystemExit('Cannot execute cloc')
29
30    out,err = proc.communicate()
31
32    handle = open(output, 'w')
33
34    for line in out.split('\n'):
35        fields = line.split(',')
36        if len(fields) <= 1:
37            continue
38
39        # skip certain files, dirs and filetypes
40        if (fields[0] == 'language' or
41            fields[0] == 'Bourne Again Shell' or
42            fields[0] == 'Fortran 90' or
43            fields[0] == 'Fortran 77' or
44            fields[0] == 'make' or
45            fields[1].startswith('chart/static') or
46            fields[1].startswith('charteps/charteps/alg/onera') or
47            fields[1].startswith('chart/web/static') or
48            (fields[1].startswith('chart/web/3rdparty.packages') and fields[1].endswith('.js')) or
49            fields[1] == 'charteps/charteps/db/rdr.py'):
50
51            continue
52
53        handle.write('{loc}\t{lang}\t{dir}\t{file}\n'.format(
54                loc=fields[4],
55                lang=fields[0],
56                dir=fields[1].split('/')[1],
57                file=fields[1]))
58
59    handle.close()
60
61    logging.info('cloc (with sloccount output format) complete')
62
63def main():
64    parser = ArgumentParser()
65    parser.add_argument('--output', '-o',
66                        default='sloccount.sc',
67                        help='Output file')
68    parser.add_argument('DIRS',
69                        nargs='+',
70                        help='Input directories')
71    args = parser.parse_args()
72    count_lines(args.output, args.DIRS)
73    parser.exit()
74
75if __name__ == '__main__':
76        main()