#!/usr/bin/env python
# Copyright (c) 2009 Aymeric Augustin

"""Check line endings.

This script considers that all lines must be terminated by \\n.
"""

from __future__ import with_statement

import logging
import os.path
import sys


def check_file(f):
    ok = True
    with open(f) as h:
        i = 0
        while True:
            l = h.readline()
            i += 1
            # Test for EOF
            if l == '':
                return ok
            # Test for CR
            elif l.endswith('\r'):
                logging.error("    Line %d ends with \\r", i)
                ok = False
            # Test for CRLF
            elif l.endswith('\r\n'):
                logging.error("    Line %d ends with \\r\\n", i)
                ok = False
            # Test for LF
            elif l.endswith('\n'):
                continue
            # readline() returned something not terminated by a new line
            elif h.readline() == '':
                logging.error("    File ends at line %d without a new line", i)
                return False
            else:
                logging.critical("    Assertion failed: readline() returned "
                                 "an incomplete line before reaching EOF")
                return False

def check_files(files):
    l = len(files)
    all_valid = True
    for i, f in enumerate(files):
        if l > 1:
            logging.info("Analysing %s (%d/%d)", f, i + 1, l)
        try:
            if not check_file(f):
                all_valid = False
        except IOError, e:
            logging.error("Error while reading file %s:", f)
            logging.error("    %s", e)
            sys.exit(1)
    if l > 1:
        logging.info('-' * 72)
    if all_valid:
        logging.error("No problems were found")
    else:
        logging.error("Some problems were found")
    return all_valid


def usage():
    script = os.path.basename(sys.argv[0])
    print 'Usage: %s file [file2 ...]' % script
    print '       %s --help' % script
    print '       %s --selftest' % script


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    if len(sys.argv) == 1: # no args
        usage()
        sys.exit(2)
    elif sys.argv[1] == '--help':
        usage()
        print '\n', __doc__
        sys.exit(0)
    elif sys.argv[1] == '--selftest':
        sys.argv = [sys.argv[0], sys.argv[0]]
    sys.exit(0 if check_files(sys.argv[1:]) else 1)
