Files

123 lines
4.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""lineend — detect and convert line endings (CRLF/LF/CR) with a report.
Usage: lineend [--to lf|crlf|cr] [--in-place] [FILE ...]
Reads stdin when no FILE is given. Reports the exact mix of LF, CRLF, and lone
CR endings per file — including the line numbers where a minority style hides —
and converts the whole file to one style on request.
"""
import argparse, sys
NAMES = {"lf": "LF (Unix)", "crlf": "CRLF (Windows)", "cr": "CR (old Mac)"}
TARGET = {"lf": "\n", "crlf": "\r\n", "cr": "\r"}
def analyse(data):
counts = {"lf": 0, "crlf": 0, "cr": 0}
minority_lines = []
i, line_no = 0, 1
while i < len(data):
j = data.find("\n", i)
k = data.find("\r", i)
if j == -1 and k == -1:
break
if k != -1 and (j == -1 or k < j):
if k + 1 < len(data) and data[k + 1] == "\n":
counts["crlf"] += 1
i, line_no = k + 2, line_no + 1
else:
counts["cr"] += 1
minority_lines.append(line_no)
i, line_no = k + 1, line_no + 1
else:
counts["lf"] += 1
i, line_no = j + 1, line_no + 1
return counts, minority_lines
def convert(data, target):
data = data.replace("\r\n", "\n").replace("\r", "\n")
if target == "lf":
return data
return data.replace("\n", TARGET[target])
def main(argv=None):
ap = argparse.ArgumentParser(prog="lineend",
description="Detect and convert line endings (CRLF/LF/CR) with a report.")
ap.add_argument("files", nargs="*", help="files to check (default: stdin)")
ap.add_argument("--to", choices=["lf", "crlf", "cr"], help="convert to this style")
ap.add_argument("--in-place", action="store_true", help="rewrite files (needs --to)")
ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
argv_list = list(argv) if argv is not None else sys.argv[1:]
if "--selftest" in argv_list:
return selftest()
a = ap.parse_args(argv)
if a.selftest:
return selftest()
if a.in_place and not a.to:
print("lineend: --in-place needs --to", file=sys.stderr)
return 2
if not a.files:
data = sys.stdin.buffer.read().decode("utf-8", errors="surrogateescape")
counts, minority = analyse(data)
print(report("<stdin>", counts, minority))
if a.to:
sys.stdout.write(convert(data, a.to))
return 0
mixed = 0
for path in a.files:
try:
data = open(path, encoding="utf-8", errors="surrogateescape", newline="").read()
except OSError as e:
print(f"lineend: {e}", file=sys.stderr)
return 1
counts, minority = analyse(data)
kinds = [k for k, v in counts.items() if v]
if len(kinds) > 1:
mixed += 1
print(report(path, counts, minority))
if a.to and a.in_place:
new = convert(data, a.to)
if new != data:
open(path, "w", encoding="utf-8", errors="surrogateescape", newline="").write(new)
print(f" -> converted to {NAMES[a.to]}")
if a.to and a.in_place:
return 0
return 1 if mixed else 0
def report(path, counts, minority):
total = sum(counts.values())
if total == 0:
return f"{path}: no line endings (single line or empty)"
parts = [f"{k}={v}" for k, v in counts.items() if v]
verdict = "uniform" if len([v for v in counts.values() if v]) == 1 else "MIXED"
extra = f" minority CR lines: {minority[:10]}" if minority else ""
return f"{path}: {', '.join(parts)} [{verdict}]{extra}"
def selftest():
import tempfile, os
counts, _ = analyse("a\r\nb\r\nc\n")
assert counts == {"lf": 1, "crlf": 2, "cr": 0}, counts
counts, _ = analyse("a\rb\rc\r")
assert counts["cr"] == 3, counts
assert convert("a\r\nb\rc\n", "lf") == "a\nb\nc\n"
assert convert("a\nb\n", "crlf") == "a\r\nb\r\n"
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, newline="") as fh:
fh.write("a\r\nb\r\nc\n")
path = fh.name
try:
assert main([path]) == 1 # mixed
assert main(["--to", "lf", "--in-place", path]) == 0
assert open(path, newline="").read() == "a\nb\nc\n"
assert main([path]) == 0
finally:
os.unlink(path)
print("lineend selftest: PASS")
return 0
if __name__ == "__main__":
sys.exit(main())