import argparse import logging import os import re import sys from enum import Enum class LineEnding(Enum): CR = '\r', '\\r', 'cr', re.compile(r'\r', re.DOTALL) CRLF = '\r\n', '\\r\\n', 'crlf', re.compile(r'\r\n', re.DOTALL) LF = '\n', '\\n', 'lf', re.compile(r'(? 0 lf_found = lf_nb > 0 logging.debug('_detect_line_ending: crlf_nb = %d, lf_nb = %d, ' 'crlf_found = %s, lf_found = %s', crlf_nb, lf_nb, crlf_found, lf_found) if crlf_nb == lf_nb: return MixedLineDetection.UNKNOWN if crlf_found ^ lf_found: return MixedLineDetection.NOT_MIXED if crlf_nb > lf_nb: return MixedLineDetection.MIXED_MOSTLY_CRLF else: return MixedLineDetection.MIXED_MOSTLY_LF def _process_no_fix(filenames): logging.info('Checking if the files have mixed line ending.') mle_found = False mle_filenames = [] for filename in filenames: detect_result = _detect_line_ending(filename) logging.debug('mixed_line_ending: detect_result = %s', detect_result) if detect_result.mle_found: mle_found = True mle_filenames.append(filename) logging.debug(filename) logging.debug(mle_found) logging.debug(str(mle_filenames)) if mle_filenames: logging.info('The following files have mixed line endings:\n\t%s', '\n\t'.join(mle_filenames)) return 1 if mle_found else 0 def _process_fix_auto(filenames): mle_found = False for filename in filenames: detect_result = _detect_line_ending(filename) logging.debug('mixed_line_ending: detect_result = %s', detect_result) if detect_result == MixedLineDetection.NOT_MIXED: logging.info('The file %s has no mixed line ending', filename) mle_found |= False elif detect_result == MixedLineDetection.UNKNOWN: logging.info('Could not define most frequent line ending in ' 'file %s. File skiped.', filename) mle_found = True else: le_enum = detect_result.line_ending_enum logging.info('The file %s has mixed line ending with a ' 'majority of "%s". Converting...', filename, le_enum.str_print) _convert_line_ending(filename, le_enum.string) mle_found = True logging.info('The file %s has been converted to "%s" line ' 'ending.', filename, le_enum.str_print) return 1 if mle_found else 0 def _process_fix_force(filenames, line_ending_enum): for filename in filenames: _convert_line_ending(filename, line_ending_enum.string) logging.info('The file %s has been forced to "%s" line ending.', filename, line_ending_enum.str_print) return 1 def _convert_line_ending(filename, line_ending): # read the file fin = open(filename, 'r') bufin = fin.read() fin.close() # convert line ending bufout = ANY_LINE_ENDING_PATTERN.sub(line_ending, bufin) # write the result in the file fout = open(filename, 'w') fout.write(bufout) fout.close() if __name__ == '__main__': sys.exit(mixed_line_ending())