Slice B: File content and text (026-050)
This commit is contained in:
1 parent
a521e930cc
commit
dbdfd53224
25 files changed
+2769
No files matched your search
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""badlines — find overlong lines, trailing whitespace, and tabs: a lint for text files.
|
||||
Usage: badlines [--max-len N] [--no-tabs] [--no-trailing] [FILE ...]
|
||||
Reads stdin when no FILE is given. Reports file:line:issue for every offending
|
||||
line, with a per-file summary. Exit 0 when clean, 1 when issues are found, so
|
||||
it drops straight into a pre-commit hook or CI check.
|
||||
"""
|
||||
import argparse, sys
|
||||
|
||||
|
||||
def lint_text(text, max_len=100, check_tabs=True, check_trailing=True):
|
||||
issues = []
|
||||
lines = text.split("\n")
|
||||
for i, line in enumerate(lines, 1):
|
||||
if i == len(lines) and line == "":
|
||||
break # trailing newline is not a line
|
||||
if len(line) > max_len:
|
||||
issues.append((i, f"line too long ({len(line)} > {max_len} chars)"))
|
||||
if check_trailing and line != line.rstrip(" \t"):
|
||||
issues.append((i, "trailing whitespace"))
|
||||
if check_tabs and "\t" in line:
|
||||
issues.append((i, "contains tab(s)"))
|
||||
if text and not text.endswith("\n"):
|
||||
issues.append((len(lines), "no final newline"))
|
||||
return issues
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="badlines",
|
||||
description="Find overlong lines, trailing whitespace, and tabs — a lint for text files.")
|
||||
ap.add_argument("files", nargs="*", help="files to lint (default: stdin)")
|
||||
ap.add_argument("--max-len", type=int, default=100, help="max line length (default 100)")
|
||||
ap.add_argument("--no-tabs", action="store_true", help="do not flag tabs")
|
||||
ap.add_argument("--no-trailing", action="store_true", help="do not flag trailing whitespace")
|
||||
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()
|
||||
total = 0
|
||||
sources = []
|
||||
if a.files:
|
||||
for path in a.files:
|
||||
try:
|
||||
sources.append((path, open(path, encoding="utf-8", errors="replace").read()))
|
||||
except OSError as e:
|
||||
print(f"badlines: {e}", file=sys.stderr)
|
||||
return 2
|
||||
else:
|
||||
sources.append(("<stdin>", sys.stdin.read()))
|
||||
for path, text in sources:
|
||||
issues = lint_text(text, a.max_len, not a.no_tabs, not a.no_trailing)
|
||||
for line_no, msg in issues:
|
||||
print(f"{path}:{line_no}: {msg}")
|
||||
if issues:
|
||||
print(f"{path}: {len(issues)} issue(s)", file=sys.stderr)
|
||||
total += len(issues)
|
||||
if total:
|
||||
print(f"badlines: {total} issue(s) total", file=sys.stderr)
|
||||
return 1
|
||||
print("badlines: clean", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
good = "short line\nanother short line\n"
|
||||
assert lint_text(good) == []
|
||||
bad = "ok\n" + "x" * 101 + "\ntrailing \n\ttabbed\nno newline"
|
||||
issues = lint_text(bad)
|
||||
kinds = [m for _, m in issues]
|
||||
assert any("too long" in m for m in kinds), kinds
|
||||
assert any("trailing whitespace" in m for m in kinds), kinds
|
||||
assert any("tab" in m for m in kinds), kinds
|
||||
assert any("no final newline" in m for m in kinds), kinds
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
||||
fh.write(good)
|
||||
p_good = fh.name
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
||||
fh.write(bad)
|
||||
p_bad = fh.name
|
||||
try:
|
||||
assert main([p_good]) == 0
|
||||
assert main([p_bad]) == 1
|
||||
finally:
|
||||
os.unlink(p_good)
|
||||
os.unlink(p_bad)
|
||||
print("badlines selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""csvjoin — join two CSVs on a key column.
|
||||
Usage: csvjoin [--how inner|left|right|full] [--left-key K] [--right-key K] LEFT RIGHT
|
||||
A relational join for the command line: matches rows on a shared key column and
|
||||
emits the combined rows, reporting how many keys matched on each side and how
|
||||
many rows were left unmatched — the numbers that tell you if the join is sane.
|
||||
"""
|
||||
import argparse, csv, sys
|
||||
|
||||
|
||||
def read_csv(path):
|
||||
with open(path, newline="", encoding="utf-8-sig", errors="replace") as fh:
|
||||
reader = csv.DictReader(fh)
|
||||
if reader.fieldnames is None:
|
||||
return [], []
|
||||
return reader.fieldnames, list(reader)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="csvjoin",
|
||||
description="Join two CSVs on a key column.")
|
||||
ap.add_argument("left", help="left CSV file")
|
||||
ap.add_argument("right", help="right CSV file")
|
||||
ap.add_argument("--how", default="inner", choices=["inner", "left", "right", "full"],
|
||||
help="join type (default inner)")
|
||||
ap.add_argument("--left-key", help="key column in LEFT (default: same as --right-key)")
|
||||
ap.add_argument("--right-key", help="key column in RIGHT (default: same as --left-key)")
|
||||
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()
|
||||
key = a.left_key or a.right_key
|
||||
if not key:
|
||||
print("csvjoin: give a key column with --left-key/--right-key", file=sys.stderr)
|
||||
return 2
|
||||
lk, rk = a.left_key or key, a.right_key or key
|
||||
try:
|
||||
lfields, lrows = read_csv(a.left)
|
||||
rfields, rrows = read_csv(a.right)
|
||||
except OSError as e:
|
||||
print(f"csvjoin: {e}", file=sys.stderr)
|
||||
return 1
|
||||
for fields, k, side in ((lfields, lk, "left"), (rfields, rk, "right")):
|
||||
if k not in fields:
|
||||
print(f"csvjoin: key {k!r} not in {side} file (have: {', '.join(fields)})",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
right_by_key = {}
|
||||
for row in rrows:
|
||||
right_by_key.setdefault(row.get(rk, ""), []).append(row)
|
||||
r_extra = [f for f in rfields if f != rk]
|
||||
out_fields = lfields + r_extra
|
||||
writer = csv.DictWriter(sys.stdout, fieldnames=out_fields)
|
||||
writer.writeheader()
|
||||
matched_l = matched_r_keys = 0
|
||||
seen_r = set()
|
||||
out_rows = 0
|
||||
for lrow in lrows:
|
||||
matches = right_by_key.get(lrow.get(lk, ""), [])
|
||||
if matches:
|
||||
matched_l += 1
|
||||
seen_r.add(lrow.get(lk, ""))
|
||||
for rrow in matches:
|
||||
merged = dict(lrow)
|
||||
merged.update({f: rrow.get(f, "") for f in r_extra})
|
||||
writer.writerow(merged)
|
||||
out_rows += 1
|
||||
elif a.how in ("left", "full"):
|
||||
merged = dict(lrow)
|
||||
merged.update({f: "" for f in r_extra})
|
||||
writer.writerow(merged)
|
||||
out_rows += 1
|
||||
if a.how in ("right", "full"):
|
||||
for rrow in rrows:
|
||||
if rrow.get(rk, "") in seen_r:
|
||||
continue
|
||||
matched_r_keys += 0
|
||||
merged = {f: "" for f in lfields}
|
||||
merged[lk] = rrow.get(rk, "")
|
||||
merged.update({f: rrow.get(f, "") for f in r_extra})
|
||||
writer.writerow(merged)
|
||||
out_rows += 1
|
||||
matched_r_keys = len(seen_r)
|
||||
unmatched_l = len(lrows) - matched_l
|
||||
unmatched_r = len(right_by_key) - matched_r_keys
|
||||
print(f"csvjoin: {out_rows} row(s) out; left {matched_l}/{len(lrows)} matched "
|
||||
f"({unmatched_l} unmatched), right {matched_r_keys}/{len(right_by_key)} keys matched "
|
||||
f"({unmatched_r} unmatched)", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os, io
|
||||
from contextlib import redirect_stdout
|
||||
left = "id,name\n1,amy\n2,bob\n3,cy\n"
|
||||
right = "id,city\n1,reno\n2,vegas\n2,vegas2\n"
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
lp, rp = os.path.join(d, "l.csv"), os.path.join(d, "r.csv")
|
||||
open(lp, "w").write(left)
|
||||
open(rp, "w").write(right)
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["--left-key", "id", lp, rp])
|
||||
out = buf.getvalue()
|
||||
assert rc == 0, out
|
||||
assert "amy,reno" in out and "bob,vegas" in out and "bob,vegas2" in out, out
|
||||
assert "cy" not in out, out # inner join drops unmatched left
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["--how", "left", "--left-key", "id", lp, rp])
|
||||
assert "cy," in buf.getvalue(), buf.getvalue()
|
||||
print("csvjoin selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+138
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""csvpeek — preview a CSV: columns, inferred types, row count, nulls, sample rows.
|
||||
Usage: csvpeek [--sample N] [--delimiter C] FILE
|
||||
A one-glance answer to "what is in this CSV?" without opening a spreadsheet:
|
||||
per-column type inference, null counts, distinct counts, and the first rows.
|
||||
"""
|
||||
import argparse, collections, csv, sys
|
||||
|
||||
|
||||
def infer_type(values):
|
||||
seen = set()
|
||||
for v in values:
|
||||
if v == "":
|
||||
continue
|
||||
try:
|
||||
int(v)
|
||||
seen.add("int")
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
float(v)
|
||||
seen.add("float")
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
if v.lower() in ("true", "false", "yes", "no"):
|
||||
seen.add("bool")
|
||||
elif len(v) == 10 and v[4] == "-" and v[7] == "-":
|
||||
seen.add("date")
|
||||
else:
|
||||
seen.add("str")
|
||||
if not seen:
|
||||
return "empty"
|
||||
if seen == {"int"}:
|
||||
return "int"
|
||||
if seen <= {"int", "float"}:
|
||||
return "float"
|
||||
if len(seen) == 1:
|
||||
return seen.pop()
|
||||
return "mixed:" + ",".join(sorted(seen))
|
||||
|
||||
|
||||
def peek(path, sample_n=5, delimiter=None):
|
||||
with open(path, newline="", encoding="utf-8-sig", errors="replace") as fh:
|
||||
if delimiter is None:
|
||||
head = fh.read(4096)
|
||||
fh.seek(0)
|
||||
try:
|
||||
delimiter = csv.Sniffer().sniff(head, delimiters=",;\t|").delimiter
|
||||
except csv.Error:
|
||||
delimiter = ","
|
||||
reader = csv.reader(fh, delimiter=delimiter)
|
||||
try:
|
||||
header = next(reader)
|
||||
except StopIteration:
|
||||
return {"header": [], "rows": 0, "columns": [], "sample": [], "delimiter": delimiter}
|
||||
cols = [{"name": h, "nulls": 0, "distinct": set(), "samples": []} for h in header]
|
||||
rows, sample = 0, []
|
||||
for row in reader:
|
||||
rows += 1
|
||||
if len(sample) < sample_n:
|
||||
sample.append(row)
|
||||
for i, col in enumerate(cols):
|
||||
v = row[i] if i < len(row) else ""
|
||||
if v == "":
|
||||
col["nulls"] += 1
|
||||
else:
|
||||
if len(col["distinct"]) < 1000:
|
||||
col["distinct"].add(v)
|
||||
if len(col["samples"]) < 20:
|
||||
col["samples"].append(v)
|
||||
for col in cols:
|
||||
col["type"] = infer_type(col["samples"])
|
||||
col["ndistinct"] = len(col["distinct"])
|
||||
del col["distinct"], col["samples"]
|
||||
return {"header": header, "rows": rows, "columns": cols, "sample": sample,
|
||||
"delimiter": delimiter}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="csvpeek",
|
||||
description="Preview a CSV: columns, inferred types, row count, nulls, sample rows.")
|
||||
ap.add_argument("file", help="CSV file to preview")
|
||||
ap.add_argument("--sample", type=int, default=5, help="sample rows to show (default 5)")
|
||||
ap.add_argument("--delimiter", help="column delimiter (auto-detected by default)")
|
||||
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()
|
||||
try:
|
||||
info = peek(a.file, a.sample, a.delimiter)
|
||||
except OSError as e:
|
||||
print(f"csvpeek: {e}", file=sys.stderr)
|
||||
return 1
|
||||
if not info["header"]:
|
||||
print("csvpeek: empty file (no header row)")
|
||||
return 0
|
||||
print(f"file: {a.file} rows: {info['rows']} columns: {len(info['header'])} "
|
||||
f"delimiter: {info['delimiter']!r}")
|
||||
print(f"{'#':>3} {'column':<20} {'type':<12} {'nulls':>6} {'distinct':>8}")
|
||||
for i, col in enumerate(info["columns"], 1):
|
||||
print(f"{i:>3} {col['name']:<20} {col['type']:<12} {col['nulls']:>6} {col['ndistinct']:>8}")
|
||||
if info["sample"]:
|
||||
print("--- sample rows ---")
|
||||
widths = [max(len(str(r[i])) if i < len(r) else 0 for r in [info["header"]] + info["sample"])
|
||||
for i in range(len(info["header"]))]
|
||||
for row in [info["header"]] + info["sample"]:
|
||||
print(" | ".join((row[i] if i < len(row) else "").ljust(widths[i])
|
||||
for i in range(len(info["header"]))))
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
data = "name,age,score,joined\namy,31,9.5,2024-01-02\nbob,,7.0,2024-02-03\ncy,27,8.25,2024-03-04\n"
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as fh:
|
||||
fh.write(data)
|
||||
path = fh.name
|
||||
try:
|
||||
info = peek(path)
|
||||
assert info["rows"] == 3, info
|
||||
assert info["header"] == ["name", "age", "score", "joined"], info["header"]
|
||||
by_name = {c["name"]: c for c in info["columns"]}
|
||||
assert by_name["age"]["type"] == "int" and by_name["age"]["nulls"] == 1, by_name["age"]
|
||||
assert by_name["score"]["type"] == "float", by_name["score"]
|
||||
assert main([path]) == 0
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("csvpeek selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""csvstat — per-column CSV statistics: distinct values, nulls, min/max.
|
||||
Usage: csvstat [--delimiter C] FILE
|
||||
A column-by-column profile: type, distinct count, null count, min/max, and the
|
||||
most common value. The fastest way to spot a column that is all nulls, all one
|
||||
value, or full of junk before you feed the file to anything else.
|
||||
"""
|
||||
import argparse, collections, csv, sys
|
||||
|
||||
|
||||
def parse_num(v):
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="csvstat",
|
||||
description="Per-column CSV statistics: distinct values, nulls, min/max.")
|
||||
ap.add_argument("file", help="CSV file")
|
||||
ap.add_argument("--delimiter", help="column delimiter (auto-detected by default)")
|
||||
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()
|
||||
try:
|
||||
with open(a.file, newline="", encoding="utf-8-sig", errors="replace") as fh:
|
||||
if a.delimiter is None:
|
||||
head = fh.read(4096)
|
||||
fh.seek(0)
|
||||
try:
|
||||
a.delimiter = csv.Sniffer().sniff(head, delimiters=",;\t|").delimiter
|
||||
except csv.Error:
|
||||
a.delimiter = ","
|
||||
reader = csv.reader(fh, delimiter=a.delimiter)
|
||||
try:
|
||||
header = next(reader)
|
||||
except StopIteration:
|
||||
print("csvstat: empty file", file=sys.stderr)
|
||||
return 1
|
||||
stats = [{"nulls": 0, "distinct": collections.Counter(), "nums": [],
|
||||
"min_s": None, "max_s": None} for _ in header]
|
||||
rows = 0
|
||||
for row in reader:
|
||||
rows += 1
|
||||
for i, st in enumerate(stats):
|
||||
v = row[i] if i < len(row) else ""
|
||||
if v == "":
|
||||
st["nulls"] += 1
|
||||
continue
|
||||
st["distinct"][v] += 1
|
||||
num = parse_num(v)
|
||||
if num is not None:
|
||||
st["nums"].append(num)
|
||||
if st["min_s"] is None or v < st["min_s"]:
|
||||
st["min_s"] = v
|
||||
if st["max_s"] is None or v > st["max_s"]:
|
||||
st["max_s"] = v
|
||||
except OSError as e:
|
||||
print(f"csvstat: {e}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"csvstat: {a.file} — {rows} rows, {len(header)} columns")
|
||||
print(f"{'column':<20} {'type':<8} {'distinct':>8} {'nulls':>6} {'min':<14} {'max':<14} most common")
|
||||
for name, st in zip(header, stats):
|
||||
nonnull = rows - st["nulls"]
|
||||
if nonnull == 0:
|
||||
typ = "all-null"
|
||||
elif len(st["nums"]) == nonnull:
|
||||
typ = "numeric"
|
||||
else:
|
||||
typ = "text"
|
||||
if typ == "numeric":
|
||||
lo, hi = f"{min(st['nums']):g}", f"{max(st['nums']):g}"
|
||||
else:
|
||||
lo, hi = (st["min_s"] or "-")[:14], (st["max_s"] or "-")[:14]
|
||||
common = st["distinct"].most_common(1)
|
||||
common_s = f"{common[0][0][:18]} ({common[0][1]}x)" if common else "-"
|
||||
print(f"{name:<20} {typ:<8} {len(st['distinct']):>8} {st['nulls']:>6} {lo:<14} {hi:<14} {common_s}")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os, io
|
||||
from contextlib import redirect_stdout
|
||||
data = "city,amount,note\nreno,10,hi\nreno,20,hi\nvegas,5,lo\n"
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as fh:
|
||||
fh.write(data)
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main([path])
|
||||
out = buf.getvalue()
|
||||
assert rc == 0, out
|
||||
assert "numeric" in out and "10" in out and "20" in out, out
|
||||
assert "reno (2x)" in out, out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("csvstat selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""csvsum — sum/average/min/max a numeric CSV column, optionally grouped by another column.
|
||||
Usage: csvsum [--group-by COL] [--op sum,avg,min,max,count] COLUMN FILE
|
||||
The spreadsheet aggregate you actually want from the command line, without
|
||||
loading the file anywhere: one column, one pass, grouped breakdowns included.
|
||||
"""
|
||||
import argparse, csv, sys
|
||||
|
||||
|
||||
def parse_num(v):
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def aggregate(values):
|
||||
if not values:
|
||||
return None
|
||||
return {"count": len(values), "sum": sum(values), "avg": sum(values) / len(values),
|
||||
"min": min(values), "max": max(values)}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="csvsum",
|
||||
description="Sum/average/min/max a numeric CSV column, optionally grouped by another column.")
|
||||
ap.add_argument("column", help="numeric column name or 0-based index")
|
||||
ap.add_argument("file", help="CSV file")
|
||||
ap.add_argument("--group-by", help="column name or index to group by")
|
||||
ap.add_argument("--op", default="sum,avg,min,max,count",
|
||||
help="comma list of ops to show (default: sum,avg,min,max,count)")
|
||||
ap.add_argument("--delimiter", help="column delimiter (auto-detected by default)")
|
||||
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()
|
||||
ops = [o.strip() for o in a.op.split(",") if o.strip()]
|
||||
try:
|
||||
with open(a.file, newline="", encoding="utf-8-sig", errors="replace") as fh:
|
||||
if a.delimiter is None:
|
||||
head = fh.read(4096)
|
||||
fh.seek(0)
|
||||
try:
|
||||
a.delimiter = csv.Sniffer().sniff(head, delimiters=",;\t|").delimiter
|
||||
except csv.Error:
|
||||
a.delimiter = ","
|
||||
reader = csv.DictReader(fh, delimiter=a.delimiter)
|
||||
if reader.fieldnames is None:
|
||||
print("csvsum: empty file", file=sys.stderr)
|
||||
return 1
|
||||
col = a.column if a.column in reader.fieldnames else None
|
||||
grp = a.group_by if a.group_by in reader.fieldnames else None
|
||||
if col is None:
|
||||
try:
|
||||
col = reader.fieldnames[int(a.column)]
|
||||
except (ValueError, IndexError):
|
||||
print(f"csvsum: no column {a.column!r} (have: {', '.join(reader.fieldnames)})",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
if a.group_by is not None and grp is None:
|
||||
try:
|
||||
grp = reader.fieldnames[int(a.group_by)]
|
||||
except (ValueError, IndexError):
|
||||
print(f"csvsum: no group column {a.group_by!r}", file=sys.stderr)
|
||||
return 2
|
||||
groups, skipped = {}, 0
|
||||
for row in reader:
|
||||
v = parse_num((row.get(col) or "").strip())
|
||||
if v is None:
|
||||
skipped += 1
|
||||
continue
|
||||
key = row.get(grp, "") if grp else "ALL"
|
||||
groups.setdefault(key, []).append(v)
|
||||
except OSError as e:
|
||||
print(f"csvsum: {e}", file=sys.stderr)
|
||||
return 1
|
||||
if not groups:
|
||||
print("csvsum: no numeric values found", file=sys.stderr)
|
||||
return 1
|
||||
for key in sorted(groups):
|
||||
agg = aggregate(groups[key])
|
||||
label = f"[{key}]" if grp else col
|
||||
shown = " ".join(f"{op}={agg[op]:g}" for op in ops if op in agg)
|
||||
print(f"{label:<20} {shown}")
|
||||
if skipped:
|
||||
print(f"csvsum: skipped {skipped} non-numeric row(s)", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os, io
|
||||
from contextlib import redirect_stdout
|
||||
data = "city,amount\nreno,10\nreno,20\nvegas,5\nvegas,x\n"
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as fh:
|
||||
fh.write(data)
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["amount", path])
|
||||
assert rc == 0 and "sum=35" in buf.getvalue(), buf.getvalue()
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["--group-by", "city", "amount", path])
|
||||
out = buf.getvalue()
|
||||
assert "sum=30" in out and "sum=5" in out, out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("csvsum selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""diffside — side-by-side diff of two files in the terminal, with color.
|
||||
Usage: diffside [--width N] [--no-color] [--context N] FILE1 FILE2
|
||||
The two files next to each other, line by line: unchanged lines in both
|
||||
columns, removed lines only on the left (red), added lines only on the right
|
||||
(green), changed lines paired and highlighted — a merge-conflict-free way to
|
||||
actually read what changed.
|
||||
"""
|
||||
import argparse, difflib, shutil, sys
|
||||
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
RESET = "\033[0m"
|
||||
|
||||
|
||||
def side_lines(a_lines, b_lines, width, color):
|
||||
sm = difflib.SequenceMatcher(a=a_lines, b=b_lines, autojunk=False)
|
||||
col = max(10, (width - 3) // 2)
|
||||
rows = []
|
||||
for tag, i1, i2, j1, j2 in sm.get_opcodes():
|
||||
if tag == "equal":
|
||||
for x, y in zip(a_lines[i1:i2], b_lines[j1:j2]):
|
||||
rows.append((" ", x.rstrip("\n"), y.rstrip("\n")))
|
||||
elif tag == "delete":
|
||||
for x in a_lines[i1:i2]:
|
||||
rows.append(("-", x.rstrip("\n"), ""))
|
||||
elif tag == "insert":
|
||||
for y in b_lines[j1:j2]:
|
||||
rows.append(("+", "", y.rstrip("\n")))
|
||||
else:
|
||||
pairs = list(zip(a_lines[i1:i2], b_lines[j1:j2]))
|
||||
for x, y in pairs:
|
||||
rows.append(("~", x.rstrip("\n"), y.rstrip("\n")))
|
||||
for x in a_lines[i1 + len(pairs):i2]:
|
||||
rows.append(("-", x.rstrip("\n"), ""))
|
||||
for y in b_lines[j1 + len(pairs):j2]:
|
||||
rows.append(("+", "", y.rstrip("\n")))
|
||||
out = []
|
||||
for tag, left, right in rows:
|
||||
l, r = left[:col], right[:col]
|
||||
code = {"-": RED, "+": GREEN, "~": YELLOW}.get(tag, "")
|
||||
if color and code:
|
||||
out.append(f"{code}{l:<{col}}{RESET} | {code}{r:<{col}}{RESET}")
|
||||
else:
|
||||
mark = {"-": "<", "+": ">", "~": "!", " ": " "}[tag]
|
||||
out.append(f"{mark} {l:<{col}} | {r:<{col}}")
|
||||
return out
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="diffside",
|
||||
description="Side-by-side diff of two files in the terminal, with color.")
|
||||
ap.add_argument("file1", help="first file")
|
||||
ap.add_argument("file2", help="second file")
|
||||
ap.add_argument("--width", type=int, default=0, help="total width (default: terminal width)")
|
||||
ap.add_argument("--no-color", action="store_true", help="disable colours, use < > ! markers")
|
||||
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()
|
||||
try:
|
||||
with open(a.file1, encoding="utf-8", errors="replace") as fh:
|
||||
a_lines = fh.readlines()
|
||||
with open(a.file2, encoding="utf-8", errors="replace") as fh:
|
||||
b_lines = fh.readlines()
|
||||
except OSError as e:
|
||||
print(f"diffside: {e}", file=sys.stderr)
|
||||
return 1
|
||||
width = a.width or shutil.get_terminal_size((120, 24)).columns
|
||||
color = not a.no_color and sys.stdout.isatty()
|
||||
rows = side_lines(a_lines, b_lines, width, color)
|
||||
n_diff = sum(1 for r in rows if r.startswith(("\033[31m", "\033[32m", "\033[33m", "<", ">", "!")))
|
||||
for row in rows:
|
||||
print(row)
|
||||
print(f"diffside: {len(a_lines)} vs {len(b_lines)} lines, {n_diff} differing row(s)",
|
||||
file=sys.stderr)
|
||||
return 0 if a_lines == b_lines else 1
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
a = ["one\n", "two\n", "three\n"]
|
||||
b = ["one\n", "TWO\n", "three\n", "four\n"]
|
||||
rows = side_lines(a, b, 80, False)
|
||||
joined = "\n".join(rows)
|
||||
assert "two" in joined and "TWO" in joined and "four" in joined, joined
|
||||
assert any(r.startswith("!") for r in rows), rows
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p1, p2 = os.path.join(d, "a.txt"), os.path.join(d, "b.txt")
|
||||
open(p1, "w").writelines(a)
|
||||
open(p2, "w").writelines(b)
|
||||
assert main(["--no-color", p1, p2]) == 1
|
||||
assert main(["--no-color", p1, p1]) == 0
|
||||
print("diffside selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""diffwords — word-level diff of two text files (not line-level).
|
||||
Usage: diffwords [--no-color] [--width N] FILE1 FILE2
|
||||
Shows the two texts as one flowing stream: unchanged words plain, words only in
|
||||
FILE1 in red, words only in FILE2 in green. A one-word edit inside a long
|
||||
paragraph shows up as a one-word change instead of two whole changed lines.
|
||||
"""
|
||||
import argparse, difflib, re, sys, textwrap
|
||||
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
RESET = "\033[0m"
|
||||
TOKEN_RE = re.compile(r"\S+|\s+")
|
||||
|
||||
|
||||
def tokenize(text):
|
||||
return TOKEN_RE.findall(text)
|
||||
|
||||
|
||||
def diff_word_stream(a_text, b_text):
|
||||
a, b = tokenize(a_text), tokenize(b_text)
|
||||
sm = difflib.SequenceMatcher(a=a, b=b, autojunk=False)
|
||||
removed = added = 0
|
||||
parts = []
|
||||
for tag, i1, i2, j1, j2 in sm.get_opcodes():
|
||||
if tag == "equal":
|
||||
parts.append((" ", "".join(a[i1:i2])))
|
||||
elif tag == "delete":
|
||||
removed += len([t for t in a[i1:i2] if t.strip()])
|
||||
parts.append(("-", "".join(a[i1:i2])))
|
||||
elif tag == "insert":
|
||||
added += len([t for t in b[j1:j2] if t.strip()])
|
||||
parts.append(("+", "".join(b[j1:j2])))
|
||||
else:
|
||||
removed += len([t for t in a[i1:i2] if t.strip()])
|
||||
added += len([t for t in b[j1:j2] if t.strip()])
|
||||
parts.append(("-", "".join(a[i1:i2])))
|
||||
parts.append(("+", "".join(b[j1:j2])))
|
||||
return parts, removed, added
|
||||
|
||||
|
||||
def render(parts, color=True, width=100):
|
||||
out = []
|
||||
for tag, text in parts:
|
||||
if tag == " ":
|
||||
out.append(text)
|
||||
elif not color:
|
||||
out.append(f"[-{text.strip()}-]" if tag == "-" else f"[+{text.strip()}+]")
|
||||
elif tag == "-":
|
||||
out.append(RED + text + RESET)
|
||||
else:
|
||||
out.append(GREEN + text + RESET)
|
||||
flat = "".join(out)
|
||||
if color or not flat.strip():
|
||||
return flat
|
||||
return "\n".join(textwrap.wrap(flat, width=width, replace_whitespace=False,
|
||||
drop_whitespace=False))
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="diffwords",
|
||||
description="Word-level diff of two text files — a one-word edit shows as a one-word change.")
|
||||
ap.add_argument("file1", help="first text file")
|
||||
ap.add_argument("file2", help="second text file")
|
||||
ap.add_argument("--no-color", action="store_true", help="plain output, [-removed-] / [+added+] markers")
|
||||
ap.add_argument("--width", type=int, default=100, help="wrap width for plain output")
|
||||
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()
|
||||
try:
|
||||
with open(a.file1, encoding="utf-8", errors="replace") as fh:
|
||||
t1 = fh.read()
|
||||
with open(a.file2, encoding="utf-8", errors="replace") as fh:
|
||||
t2 = fh.read()
|
||||
except OSError as e:
|
||||
print(f"diffwords: {e}", file=sys.stderr)
|
||||
return 1
|
||||
parts, removed, added = diff_word_stream(t1, t2)
|
||||
sys.stdout.write(render(parts, color=not a.no_color, width=a.width))
|
||||
if not (parts and parts[-1][1].endswith("\n")):
|
||||
sys.stdout.write("\n")
|
||||
print(f"diffwords: {removed} word(s) removed, {added} word(s) added", file=sys.stderr)
|
||||
return 0 if (removed == 0 and added == 0) else 1
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
t1, t2 = "the quick brown fox jumps\n", "the quick red fox leaps\n"
|
||||
parts, removed, added = diff_word_stream(t1, t2)
|
||||
assert removed == 2 and added == 2, (removed, added)
|
||||
plain = render(parts, color=False)
|
||||
assert "[-brown-]" in plain and "[+red+]" in plain, plain
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p1, p2 = os.path.join(d, "a.txt"), os.path.join(d, "b.txt")
|
||||
open(p1, "w").write(t1)
|
||||
open(p2, "w").write(t2)
|
||||
assert main(["--no-color", p1, p2]) == 1
|
||||
assert main(["--no-color", p1, p1]) == 0
|
||||
print("diffwords selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""encfix — detect and convert text encodings (UTF-8/16, latin-1) with a report.
|
||||
Usage: encfix [--to utf-8|utf-16|latin-1] [--in-place] [FILE ...]
|
||||
Reads stdin when no FILE is given. Detects BOMs, validates UTF-8, falls back to
|
||||
UTF-16 and latin-1, and reports what each file actually is — then converts the
|
||||
lot to one encoding so the next tool in the chain stops choking on mojibake.
|
||||
"""
|
||||
import argparse, sys
|
||||
|
||||
CANDIDATES = ["utf-8", "utf-16", "latin-1"]
|
||||
|
||||
|
||||
def detect(raw):
|
||||
if raw.startswith(b"\xef\xbb\xbf"):
|
||||
return "utf-8-sig", "BOM"
|
||||
if raw.startswith(b"\xff\xfe"):
|
||||
return "utf-16-le", "BOM"
|
||||
if raw.startswith(b"\xfe\xff"):
|
||||
return "utf-16-be", "BOM"
|
||||
try:
|
||||
raw.decode("utf-8")
|
||||
return "utf-8", "valid UTF-8"
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
try:
|
||||
text = raw.decode("utf-16")
|
||||
# UTF-16 decodes almost anything; only trust it if it looks like text:
|
||||
# mostly printable, with a plausible share of NULs from the high bytes.
|
||||
if text and sum(1 for c in text if c.isprintable() or c in "\n\r\t") / len(text) > 0.9:
|
||||
return "utf-16", "decoded as UTF-16, printable"
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
return "latin-1", "assumed (not valid UTF-8)"
|
||||
|
||||
|
||||
def decode(raw, encoding):
|
||||
if encoding in ("utf-8-sig", "utf-8"):
|
||||
return raw.decode("utf-8-sig")
|
||||
if encoding == "utf-16-le":
|
||||
return raw[2:].decode("utf-16-le")
|
||||
if encoding == "utf-16-be":
|
||||
return raw[2:].decode("utf-16-be")
|
||||
if encoding == "utf-16":
|
||||
return raw.decode("utf-16")
|
||||
return raw.decode("latin-1")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="encfix",
|
||||
description="Detect and convert text encodings (UTF-8/16, latin-1) with a report.")
|
||||
ap.add_argument("files", nargs="*", help="files to check (default: stdin)")
|
||||
ap.add_argument("--to", default="utf-8", choices=["utf-8", "utf-16", "latin-1"],
|
||||
help="target encoding (default utf-8)")
|
||||
ap.add_argument("--in-place", action="store_true", help="rewrite files in the target encoding")
|
||||
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 not a.files:
|
||||
raw = sys.stdin.buffer.read()
|
||||
enc, how = detect(raw)
|
||||
print(f"<stdin>: {enc} ({how})", file=sys.stderr)
|
||||
sys.stdout.write(decode(raw, enc).encode(a.to, errors="replace").decode(a.to, errors="replace"))
|
||||
return 0
|
||||
bad = 0
|
||||
for path in a.files:
|
||||
try:
|
||||
raw = open(path, "rb").read()
|
||||
except OSError as e:
|
||||
print(f"encfix: {e}", file=sys.stderr)
|
||||
return 1
|
||||
enc, how = detect(raw)
|
||||
text = decode(raw, enc)
|
||||
changed = enc != a.to and not (enc in ("utf-8-sig", "utf-8") and a.to == "utf-8")
|
||||
if enc != "utf-8":
|
||||
bad += 1
|
||||
print(f"{path}: {enc} ({how})" + (" -> would convert to " + a.to if changed and not a.in_place else ""))
|
||||
if a.in_place and changed:
|
||||
open(path, "wb").write(text.encode(a.to))
|
||||
print(f" -> converted to {a.to}")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
assert detect("plain ascii".encode())[0] == "utf-8"
|
||||
assert detect("caf\u00e9".encode("utf-16"))[0].startswith("utf-16")
|
||||
assert detect("caf\u00e9".encode("latin-1"))[0] == "latin-1"
|
||||
assert detect(b"\xef\xbb\xbfhi")[0] == "utf-8-sig"
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p1 = os.path.join(d, "u16.txt")
|
||||
open(p1, "wb").write("hello w\u00f6rld".encode("utf-16"))
|
||||
p2 = os.path.join(d, "lat.txt")
|
||||
open(p2, "wb").write("caf\u00e9".encode("latin-1"))
|
||||
assert main([p1, p2]) == 0
|
||||
assert main(["--in-place", p1, p2]) == 0
|
||||
assert open(p1, encoding="utf-8").read() == "hello w\u00f6rld"
|
||||
assert open(p2, encoding="utf-8").read() == "caf\u00e9"
|
||||
print("encfix selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""headtail — show the first and last N lines of a file together (context sandwich).
|
||||
Usage: headtail [-n N] [--no-marker] [FILE]
|
||||
head and tail in one view: the opening lines and the closing lines, with a
|
||||
marker saying how many lines were skipped in the middle. For logs and outputs
|
||||
where the beginning sets the scene and the end holds the verdict.
|
||||
"""
|
||||
import argparse, collections, sys
|
||||
|
||||
|
||||
def head_tail(lines, n):
|
||||
"""Return (shown_lines, skipped_count) for the first+last N sandwich."""
|
||||
lines = list(lines)
|
||||
if len(lines) <= 2 * n:
|
||||
return lines, 0
|
||||
return lines[:n] + lines[-n:], len(lines) - 2 * n
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="headtail",
|
||||
description="Show the first and last N lines of a file together (context sandwich).")
|
||||
ap.add_argument("file", nargs="?", help="file to read (default: stdin)")
|
||||
ap.add_argument("-n", "--lines", type=int, default=10, help="lines from each end (default 10)")
|
||||
ap.add_argument("--no-marker", action="store_true", help="omit the '... skipped ...' marker line")
|
||||
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.lines < 0:
|
||||
print("headtail: -n must be >= 0", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
if a.file:
|
||||
with open(a.file, encoding="utf-8", errors="replace") as fh:
|
||||
all_lines = fh.readlines()
|
||||
else:
|
||||
all_lines = sys.stdin.readlines()
|
||||
except OSError as e:
|
||||
print(f"headtail: {e}", file=sys.stderr)
|
||||
return 1
|
||||
shown, skipped = head_tail(all_lines, a.lines)
|
||||
for i, line in enumerate(shown):
|
||||
if skipped and not a.no_marker and a.lines > 0 and i == a.lines:
|
||||
print(f"... [{skipped} line(s) omitted] ...")
|
||||
sys.stdout.write(line if line.endswith("\n") else line + "\n")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
lines = [f"line {i}\n" for i in range(1, 26)]
|
||||
shown, skipped = head_tail(lines, 5)
|
||||
assert len(shown) == 10 and skipped == 15, (len(shown), skipped)
|
||||
assert shown[0] == "line 1\n" and shown[-1] == "line 25\n"
|
||||
shown2, skipped2 = head_tail(lines[:8], 5)
|
||||
assert skipped2 == 0 and len(shown2) == 8
|
||||
import tempfile, os, io
|
||||
from contextlib import redirect_stdout
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
||||
fh.writelines(lines)
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["-n", "3", path])
|
||||
out = buf.getvalue()
|
||||
assert rc == 0 and "line 1" in out and "line 25" in out, out
|
||||
assert "[19 line(s) omitted]" in out, out
|
||||
assert "line 12" not in out, out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("headtail selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""jsongrep — grep inside JSON values by key path.
|
||||
Usage: jsongrep [--key PATTERN] [--value REGEX] [--ignore-case] [FILE]
|
||||
Reads stdin when no FILE is given. Walks a JSON document and prints every
|
||||
path=value whose key path matches PATTERN (dot-separated, * = any segment) or
|
||||
whose value matches REGEX — grep for structured data instead of raw text.
|
||||
"""
|
||||
import argparse, json, re, sys
|
||||
|
||||
|
||||
def walk(node, path, out):
|
||||
if isinstance(node, dict):
|
||||
for k, v in node.items():
|
||||
walk(v, path + [str(k)], out)
|
||||
elif isinstance(node, list):
|
||||
for i, v in enumerate(node):
|
||||
walk(v, path + [str(i)], out)
|
||||
else:
|
||||
out.append((".".join(path), node))
|
||||
|
||||
|
||||
def path_matches(path, pattern, ignore_case):
|
||||
pat_segs = pattern.split(".")
|
||||
path_segs = path.split(".")
|
||||
if len(pat_segs) != len(path_segs):
|
||||
# allow a trailing * to swallow the rest, and a leading pattern to
|
||||
# match any suffix when it has fewer segments
|
||||
if len(pat_segs) < len(path_segs) and pat_segs and pat_segs[-1] == "*":
|
||||
pat_segs = pat_segs[:-1] + ["*"] * (len(path_segs) - len(pat_segs) + 1)
|
||||
else:
|
||||
return False
|
||||
for p, s in zip(pat_segs, path_segs):
|
||||
if p == "*":
|
||||
continue
|
||||
if ignore_case:
|
||||
if p.lower() != s.lower():
|
||||
return False
|
||||
elif p != s:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="jsongrep",
|
||||
description="Grep inside JSON values by key path.")
|
||||
ap.add_argument("file", nargs="?", help="JSON file (default: stdin)")
|
||||
ap.add_argument("--key", help="key path pattern, dot-separated, * = any segment (e.g. users.*.email)")
|
||||
ap.add_argument("--value", help="regex matched against stringified values")
|
||||
ap.add_argument("--ignore-case", action="store_true", help="case-insensitive matching")
|
||||
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 not a.key and not a.value:
|
||||
print("jsongrep: give --key and/or --value", file=sys.stderr)
|
||||
return 2
|
||||
flags = re.IGNORECASE if a.ignore_case else 0
|
||||
try:
|
||||
vrx = re.compile(a.value, flags) if a.value else None
|
||||
except re.error as e:
|
||||
print(f"jsongrep: bad --value regex: {e}", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
raw = open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read()
|
||||
data = json.loads(raw)
|
||||
except OSError as e:
|
||||
print(f"jsongrep: {e}", file=sys.stderr)
|
||||
return 1
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"jsongrep: invalid JSON: {e}", file=sys.stderr)
|
||||
return 1
|
||||
leaves = []
|
||||
walk(data, [], leaves)
|
||||
hits = 0
|
||||
for path, val in leaves:
|
||||
ok = True
|
||||
if a.key and not path_matches(path, a.key, a.ignore_case):
|
||||
ok = False
|
||||
if ok and vrx and not vrx.search(str(val)):
|
||||
ok = False
|
||||
if ok:
|
||||
print(f"{path} = {val!r}")
|
||||
hits += 1
|
||||
print(f"jsongrep: {hits} match(es) in {len(leaves)} leaf value(s)", file=sys.stderr)
|
||||
return 0 if hits else 1
|
||||
|
||||
|
||||
def selftest():
|
||||
import io
|
||||
from contextlib import redirect_stdout
|
||||
data = {"users": [{"name": "amy", "email": "amy@x.com"}, {"name": "bob", "email": "bob@y.org"}],
|
||||
"meta": {"version": 3}}
|
||||
leaves = []
|
||||
walk(data, [], leaves)
|
||||
assert ("users.0.email", "amy@x.com") in leaves, leaves
|
||||
assert path_matches("users.0.email", "users.*.email", False)
|
||||
assert not path_matches("users.0.name", "users.*.email", False)
|
||||
assert path_matches("meta.version", "meta.*", False)
|
||||
import tempfile, os, json
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as fh:
|
||||
json.dump(data, fh)
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["--key", "users.*.email", path])
|
||||
assert rc == 0 and "amy@x.com" in buf.getvalue(), buf.getvalue()
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["--value", "y\\.org", path])
|
||||
assert rc == 0 and "bob@y.org" in buf.getvalue(), buf.getvalue()
|
||||
assert main(["--key", "nope.*", path]) == 1
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("jsongrep selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""jsonpeek — summarize JSON structure: keys, types, depth, size, sample values.
|
||||
Usage: jsonpeek [--max-depth N] [--max-keys N] [FILE]
|
||||
Reads stdin when no FILE is given. Answers "what shape is this JSON?" for files
|
||||
too big to eyeball: a tree of keys with types, array lengths, depth, and samples.
|
||||
"""
|
||||
import argparse, json, sys
|
||||
|
||||
|
||||
def type_name(v):
|
||||
if v is None:
|
||||
return "null"
|
||||
if isinstance(v, bool):
|
||||
return "bool"
|
||||
if isinstance(v, int):
|
||||
return "int"
|
||||
if isinstance(v, float):
|
||||
return "float"
|
||||
if isinstance(v, str):
|
||||
return "str"
|
||||
if isinstance(v, list):
|
||||
return "list"
|
||||
if isinstance(v, dict):
|
||||
return "dict"
|
||||
return type(v).__name__
|
||||
|
||||
|
||||
def depth_of(v):
|
||||
if isinstance(v, dict):
|
||||
return 1 + max((depth_of(x) for x in v.values()), default=0)
|
||||
if isinstance(v, list):
|
||||
return 1 + max((depth_of(x) for x in v), default=0)
|
||||
return 0
|
||||
|
||||
|
||||
def summarize(v, max_depth, max_keys, indent=0):
|
||||
lines = []
|
||||
pad = " " * indent
|
||||
if isinstance(v, dict):
|
||||
items = list(v.items())
|
||||
lines.append(f"{pad}dict[{len(items)} keys]")
|
||||
for k, val in items[:max_keys]:
|
||||
t = type_name(val)
|
||||
if isinstance(val, dict):
|
||||
lines.append(f"{pad} {k}: dict[{len(val)} keys]")
|
||||
if indent + 1 < max_depth:
|
||||
lines.extend(summarize(val, max_depth, max_keys, indent + 2))
|
||||
elif isinstance(val, list):
|
||||
et = sorted({type_name(x) for x in val})
|
||||
lines.append(f"{pad} {k}: list[{len(val)}] of {','.join(et) or '?'}"
|
||||
+ (f" e.g. {val[0]!r}" if val and not isinstance(val[0], (dict, list)) else ""))
|
||||
if val and isinstance(val[0], (dict, list)) and indent + 1 < max_depth:
|
||||
lines.extend(summarize(val[0], max_depth, max_keys, indent + 2))
|
||||
else:
|
||||
lines.append(f"{pad} {k}: {t} = {val!r}"[:120])
|
||||
if len(items) > max_keys:
|
||||
lines.append(f"{pad} ... and {len(items) - max_keys} more keys")
|
||||
elif isinstance(v, list):
|
||||
et = sorted({type_name(x) for x in v})
|
||||
lines.append(f"{pad}list[{len(v)}] of {','.join(et) or '?'}")
|
||||
if v and isinstance(v[0], (dict, list)) and indent < max_depth:
|
||||
lines.extend(summarize(v[0], max_depth, max_keys, indent + 1))
|
||||
else:
|
||||
lines.append(f"{pad}{type_name(v)} = {v!r}"[:120])
|
||||
return lines
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="jsonpeek",
|
||||
description="Summarize JSON structure: keys, types, depth, size, sample values.")
|
||||
ap.add_argument("file", nargs="?", help="JSON file (default: stdin)")
|
||||
ap.add_argument("--max-depth", type=int, default=4, help="how deep to expand (default 4)")
|
||||
ap.add_argument("--max-keys", type=int, default=25, help="keys shown per object (default 25)")
|
||||
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()
|
||||
try:
|
||||
raw = open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read()
|
||||
data = json.loads(raw)
|
||||
except OSError as e:
|
||||
print(f"jsonpeek: {e}", file=sys.stderr)
|
||||
return 1
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"jsonpeek: invalid JSON: {e}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"top: {type_name(data)} depth: {depth_of(data)} size: {len(raw)} bytes")
|
||||
for line in summarize(data, a.max_depth, a.max_keys):
|
||||
print(line)
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
sample = {"name": "amy", "age": 31, "tags": ["a", "b"], "addr": {"city": "Reno", "zip": 89501}}
|
||||
assert depth_of(sample) == 2
|
||||
lines = summarize(sample, 4, 25)
|
||||
joined = "\n".join(lines)
|
||||
assert "name: str = 'amy'" in joined and "tags: list[2] of str" in joined, joined
|
||||
assert "city: str = 'Reno'" in joined, joined
|
||||
print("jsonpeek selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+122
@@ -0,0 +1,122 @@
|
||||
#!/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())
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""loghist — histogram of log events by hour, parsed from timestamps.
|
||||
Usage: loghist [--by hour|day] [--level LEVEL] [FILE]
|
||||
Reads stdin when no FILE is given. Pulls timestamps out of each log line and
|
||||
draws a bar chart of events per hour (or per day), so bursts, quiet nights,
|
||||
and the 3 a.m. error storm are visible at a glance instead of buried in text.
|
||||
"""
|
||||
import argparse, collections, re, sys
|
||||
from datetime import datetime
|
||||
|
||||
BAR = "\u2588"
|
||||
MONTHS = {m: i for i, m in enumerate(
|
||||
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 1)}
|
||||
TS_RES = [
|
||||
(re.compile(r"(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):\d{2}"), lambda m: (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))),
|
||||
(re.compile(r"([A-Z][a-z]{2})\s+(\d{1,2}) (\d{2}):\d{2}"), lambda m: (datetime.now().year, MONTHS[m.group(1)], int(m.group(2)), int(m.group(3)))),
|
||||
(re.compile(r"(\d{2})/([A-Z][a-z]{2})/(\d{4}):(\d{2}):\d{2}"), lambda m: (int(m.group(3)), MONTHS[m.group(2)], int(m.group(1)), int(m.group(4)))),
|
||||
]
|
||||
|
||||
|
||||
def parse_ts(line):
|
||||
for rx, build in TS_RES:
|
||||
m = rx.search(line)
|
||||
if m:
|
||||
try:
|
||||
y, mo, d, h = build(m)
|
||||
return datetime(y, mo, d, h)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def histogram(lines, by="hour"):
|
||||
buckets = collections.Counter()
|
||||
parsed = unparsed = 0
|
||||
for line in lines:
|
||||
ts = parse_ts(line)
|
||||
if ts is None:
|
||||
unparsed += 1
|
||||
continue
|
||||
parsed += 1
|
||||
key = ts.strftime("%Y-%m-%d %H:00") if by == "hour" else ts.strftime("%Y-%m-%d")
|
||||
buckets[key] += 1
|
||||
return buckets, parsed, unparsed
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="loghist",
|
||||
description="Histogram of log events by hour, parsed from timestamps.")
|
||||
ap.add_argument("file", nargs="?", help="log file (default: stdin)")
|
||||
ap.add_argument("--by", default="hour", choices=["hour", "day"], help="bucket size (default hour)")
|
||||
ap.add_argument("--level", help="only count lines containing this level, e.g. ERROR")
|
||||
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()
|
||||
try:
|
||||
lines = open(a.file, encoding="utf-8", errors="replace").readlines() if a.file else sys.stdin.readlines()
|
||||
except OSError as e:
|
||||
print(f"loghist: {e}", file=sys.stderr)
|
||||
return 1
|
||||
if a.level:
|
||||
lines = [l for l in lines if a.level in l]
|
||||
buckets, parsed, unparsed = histogram(lines, a.by)
|
||||
if not buckets:
|
||||
print("loghist: no parseable timestamps found", file=sys.stderr)
|
||||
return 1
|
||||
peak = max(buckets.values())
|
||||
total = sum(buckets.values())
|
||||
print(f"loghist: {total} event(s) in {len(buckets)} bucket(s); peak {peak} at "
|
||||
f"{max(buckets, key=buckets.get)}" + (f"; {unparsed} line(s) without timestamps" if unparsed else ""))
|
||||
for key in sorted(buckets):
|
||||
n = buckets[key]
|
||||
print(f"{key} {n:6d} {BAR * max(1, round(n / peak * 40))}")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os, io
|
||||
from contextlib import redirect_stdout
|
||||
data = ("2026-12-03 10:00:01 INFO a\n2026-12-03 10:15:00 INFO b\n"
|
||||
"2026-12-03 11:00:00 ERROR c\n2026-12-03 11:30:00 INFO d\n"
|
||||
"2026-12-03 11:45:00 INFO e\nno timestamp here\n")
|
||||
buckets, parsed, unparsed = histogram(data.splitlines())
|
||||
assert buckets == {"2026-12-03 10:00": 2, "2026-12-03 11:00": 3}, buckets
|
||||
assert parsed == 5 and unparsed == 1, (parsed, unparsed)
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as fh:
|
||||
fh.write(data)
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["--level", "ERROR", path])
|
||||
assert rc == 0 and "11:00" in buf.getvalue() and "1 event(s)" in buf.getvalue(), buf.getvalue()
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("loghist selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""logtail — tail a log with colorized levels and a lines-per-second rate meter.
|
||||
Usage: logtail [-n N] [--follow] [--seconds S] FILE
|
||||
Like tail, but ERROR/WARN/INFO/DEBUG levels get colours, and the header reports
|
||||
the event rate (lines/sec) measured from the timestamps in the file — so you see
|
||||
at a glance whether the log is idle or on fire.
|
||||
"""
|
||||
import argparse, re, sys, time
|
||||
from datetime import datetime
|
||||
|
||||
RED = "\033[31m"
|
||||
YELLOW = "\033[33m"
|
||||
GREEN = "\033[32m"
|
||||
DIM = "\033[2m"
|
||||
RESET = "\033[0m"
|
||||
LEVELS = [("ERROR", RED), ("CRITICAL", RED), ("FATAL", RED), ("WARN", YELLOW),
|
||||
("WARNING", YELLOW), ("INFO", GREEN), ("DEBUG", DIM), ("TRACE", DIM)]
|
||||
TS_RES = [
|
||||
re.compile(r"(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?)"),
|
||||
re.compile(r"(\d{2}:\d{2}:\d{2})"),
|
||||
]
|
||||
|
||||
|
||||
def parse_ts(line):
|
||||
for rx in TS_RES:
|
||||
m = rx.search(line)
|
||||
if not m:
|
||||
continue
|
||||
s = m.group(1)
|
||||
for fmt in ("%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S.%f",
|
||||
"%Y-%m-%d %H:%M:%S", "%H:%M:%S"):
|
||||
try:
|
||||
return datetime.strptime(s, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def colorize(line, color=True):
|
||||
if not color:
|
||||
return line
|
||||
for name, code in LEVELS:
|
||||
if name in line:
|
||||
return code + line + RESET
|
||||
return line
|
||||
|
||||
|
||||
def rate_of(lines):
|
||||
stamps = [t for t in (parse_ts(l) for l in lines) if t is not None]
|
||||
if len(stamps) < 2:
|
||||
return None
|
||||
span = (stamps[-1] - stamps[0]).total_seconds()
|
||||
if span <= 0:
|
||||
return None
|
||||
return len(lines) / span, span
|
||||
|
||||
|
||||
def tail_lines(path, n):
|
||||
with open(path, encoding="utf-8", errors="replace") as fh:
|
||||
buf = []
|
||||
for line in fh:
|
||||
buf.append(line)
|
||||
if len(buf) > n:
|
||||
buf.pop(0)
|
||||
return buf
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="logtail",
|
||||
description="Tail a log with colorized levels and a lines-per-second rate meter.")
|
||||
ap.add_argument("file", help="log file to tail")
|
||||
ap.add_argument("-n", "--lines", type=int, default=50, help="lines to show (default 50)")
|
||||
ap.add_argument("--follow", action="store_true", help="keep following new lines (like tail -f)")
|
||||
ap.add_argument("--seconds", type=float, default=0, help="with --follow, stop after S seconds")
|
||||
ap.add_argument("--no-color", action="store_true", help="disable colours")
|
||||
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()
|
||||
color = not a.no_color and sys.stdout.isatty()
|
||||
try:
|
||||
lines = tail_lines(a.file, a.lines)
|
||||
except OSError as e:
|
||||
print(f"logtail: {e}", file=sys.stderr)
|
||||
return 1
|
||||
rate = rate_of(lines)
|
||||
if rate:
|
||||
print(f"logtail: {a.file} — {len(lines)} lines, {rate[0]:.2f} lines/s over {rate[1]:.0f}s",
|
||||
file=sys.stderr)
|
||||
else:
|
||||
print(f"logtail: {a.file} — {len(lines)} lines (no parseable timestamps for a rate)",
|
||||
file=sys.stderr)
|
||||
for line in lines:
|
||||
sys.stdout.write(colorize(line.rstrip("\n"), color) + "\n")
|
||||
if a.follow:
|
||||
seen = 0
|
||||
start = time.time()
|
||||
with open(a.file, encoding="utf-8", errors="replace") as fh:
|
||||
fh.seek(0, 2)
|
||||
while True:
|
||||
line = fh.readline()
|
||||
if line:
|
||||
seen += 1
|
||||
sys.stdout.write(colorize(line.rstrip("\n"), color) + "\n")
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
if a.seconds and time.time() - start >= a.seconds:
|
||||
break
|
||||
time.sleep(0.2)
|
||||
print(f"logtail: followed {seen} new line(s)", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
data = ("2026-12-03 10:00:00 INFO server started\n"
|
||||
"2026-12-03 10:00:01 WARN disk 80% full\n"
|
||||
"2026-12-03 10:00:02 ERROR connection refused\n"
|
||||
"2026-12-03 10:00:04 INFO retry ok\n")
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as fh:
|
||||
fh.write(data)
|
||||
path = fh.name
|
||||
try:
|
||||
lines = tail_lines(path, 10)
|
||||
assert len(lines) == 4, lines
|
||||
rate = rate_of(lines)
|
||||
assert rate is not None and abs(rate[0] - 1.0) < 0.01, rate
|
||||
assert "\033[31m" in colorize("x ERROR y") and "\033[33m" in colorize("x WARN y")
|
||||
assert main(["-n", "2", "--no-color", path]) == 0
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("logtail selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""randline — pick N random lines from a file.
|
||||
Usage: randline [-n N] [--seed S] [--with-replacement] [FILE]
|
||||
Reservoir sampling: every line has an equal chance, and the whole file is never
|
||||
held in memory — it works on gigabyte logs. --seed makes the pick reproducible.
|
||||
"""
|
||||
import argparse, random, sys
|
||||
|
||||
|
||||
def reservoir(fh, n, rng, with_replacement):
|
||||
if with_replacement:
|
||||
pool = []
|
||||
for line in fh:
|
||||
pool.append(line)
|
||||
if len(pool) > 100000:
|
||||
# keep memory bounded: thin the pool by random eviction
|
||||
pool = [pool[i] for i in sorted(rng.sample(range(len(pool)), 10000))]
|
||||
if not pool:
|
||||
return []
|
||||
return [rng.choice(pool) for _ in range(n)]
|
||||
chosen = []
|
||||
for i, line in enumerate(fh):
|
||||
if i < n:
|
||||
chosen.append(line)
|
||||
else:
|
||||
j = rng.randint(0, i)
|
||||
if j < n:
|
||||
chosen[j] = line
|
||||
return chosen
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="randline",
|
||||
description="Pick N random lines from a file (reservoir sampling; equal odds, bounded memory).")
|
||||
ap.add_argument("file", nargs="?", help="file to sample (default: stdin)")
|
||||
ap.add_argument("-n", "--count", type=int, default=1, help="lines to pick (default 1)")
|
||||
ap.add_argument("--seed", type=int, help="random seed for a reproducible pick")
|
||||
ap.add_argument("--with-replacement", action="store_true", help="allow the same line twice")
|
||||
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.count < 0:
|
||||
print("randline: -n must be >= 0", file=sys.stderr)
|
||||
return 2
|
||||
rng = random.Random(a.seed)
|
||||
try:
|
||||
fh = open(a.file, encoding="utf-8", errors="replace") if a.file else sys.stdin
|
||||
with fh:
|
||||
picked = reservoir(fh, a.count, rng, a.with_replacement)
|
||||
except OSError as e:
|
||||
print(f"randline: {e}", file=sys.stderr)
|
||||
return 1
|
||||
for line in picked:
|
||||
sys.stdout.write(line if line.endswith("\n") else line + "\n")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import io
|
||||
rng = random.Random(42)
|
||||
lines = [f"l{i}\n" for i in range(100)]
|
||||
pick1 = reservoir(iter(lines), 5, random.Random(7), False)
|
||||
pick2 = reservoir(iter(lines), 5, random.Random(7), False)
|
||||
assert pick1 == pick2, "same seed must give same pick"
|
||||
assert len(pick1) == 5 and len(set(pick1)) == 5, pick1
|
||||
assert all(p in lines for p in pick1)
|
||||
small = reservoir(iter(["a\n", "b\n"]), 10, random.Random(1), False)
|
||||
assert len(small) == 2, small
|
||||
rep = reservoir(iter(lines), 5, random.Random(3), True)
|
||||
assert len(rep) == 5
|
||||
print("randline selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+97
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""searchrep — search/replace across a tree with preview, backups, and a change count.
|
||||
Usage: searchrep [--apply] [--backup] [--include GLOB] [--fixed] PATTERN REPLACEMENT [PATH ...]
|
||||
Dry-run preview is the default: every hit is shown with before/after context and
|
||||
a per-file change count. Nothing is written until --apply; --backup keeps .bak
|
||||
copies of every file that changes.
|
||||
"""
|
||||
import argparse, fnmatch, os, re, sys
|
||||
|
||||
|
||||
def iter_files(paths, include, exclude):
|
||||
for base in paths:
|
||||
if os.path.isfile(base):
|
||||
yield base
|
||||
else:
|
||||
for root, dirs, files in os.walk(base):
|
||||
dirs[:] = [d for d in dirs if not any(fnmatch.fnmatch(d, pat) for pat in exclude)]
|
||||
for name in files:
|
||||
if include and not any(fnmatch.fnmatch(name, pat) for pat in include):
|
||||
continue
|
||||
if any(fnmatch.fnmatch(name, pat) for pat in exclude):
|
||||
continue
|
||||
yield os.path.join(root, name)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="searchrep",
|
||||
description="Search/replace across a tree with preview, backups, and a change count.")
|
||||
ap.add_argument("pattern", help="regex to search for (or literal text with --fixed)")
|
||||
ap.add_argument("replacement", help="replacement text (regex backrefs like \\1 work)")
|
||||
ap.add_argument("paths", nargs="*", default=["."], help="files or directories (default: .)")
|
||||
ap.add_argument("--apply", action="store_true", help="actually write the changes (default: preview only)")
|
||||
ap.add_argument("--backup", action="store_true", help="keep a .bak copy of each changed file")
|
||||
ap.add_argument("--include", action="append", default=[], help="only files matching this glob (repeatable)")
|
||||
ap.add_argument("--exclude", action="append", default=[".git", "__pycache__", "*.bak"],
|
||||
help="skip names matching this glob (repeatable)")
|
||||
ap.add_argument("--fixed", action="store_true", help="treat PATTERN as literal text, not regex")
|
||||
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()
|
||||
try:
|
||||
rx = re.compile(re.escape(a.pattern) if a.fixed else a.pattern)
|
||||
except re.error as e:
|
||||
print(f"searchrep: bad pattern: {e}", file=sys.stderr)
|
||||
return 2
|
||||
total_files = total_hits = changed_files = 0
|
||||
for path in iter_files(a.paths, a.include, a.exclude):
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="strict") as fh:
|
||||
text = fh.read()
|
||||
except (OSError, UnicodeDecodeError):
|
||||
continue
|
||||
hits = rx.findall(text)
|
||||
if not hits:
|
||||
continue
|
||||
total_files += 1
|
||||
total_hits += len(hits)
|
||||
new_text, n = rx.subn(a.replacement, text)
|
||||
print(f"== {path}: {n} change(s) ==")
|
||||
for i, line in enumerate(text.splitlines(), 1):
|
||||
if rx.search(line):
|
||||
print(f" {i}: - {line.strip()[:100]}")
|
||||
print(f" {i}: + {rx.sub(a.replacement, line).strip()[:100]}")
|
||||
if a.apply:
|
||||
if a.backup:
|
||||
with open(path + ".bak", "w", encoding="utf-8") as fh:
|
||||
fh.write(text)
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(new_text)
|
||||
changed_files += 1
|
||||
mode = "applied" if a.apply else "preview (use --apply to write)"
|
||||
print(f"searchrep: {total_hits} change(s) in {total_files} file(s) — {mode}"
|
||||
+ (f", {changed_files} file(s) written" if a.apply else ""))
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "a.txt")
|
||||
open(p, "w").write("foo bar foo\nfoo baz\n")
|
||||
assert main(["foo", "qux", p]) == 0
|
||||
assert open(p).read().startswith("foo"), "preview must not write"
|
||||
assert main(["--apply", "--backup", "foo", "qux", p]) == 0
|
||||
assert open(p).read() == "qux bar qux\nqux baz\n", open(p).read()
|
||||
assert os.path.exists(p + ".bak")
|
||||
assert main(["--fixed", "qux", "foo", p]) == 0
|
||||
print("searchrep selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""sortuniq — sort and dedupe a file in place, with a backup.
|
||||
Usage: sortuniq [--no-backup] [--ignore-case] [--reverse] FILE
|
||||
sort -u with a safety net: the original is kept as FILE.bak, and the report
|
||||
says how many duplicate lines were dropped and how many lines remain.
|
||||
"""
|
||||
import argparse, sys
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="sortuniq",
|
||||
description="Sort and dedupe a file in place, with a backup.")
|
||||
ap.add_argument("file", help="file to sort and dedupe")
|
||||
ap.add_argument("--no-backup", action="store_true", help="do not keep a .bak copy")
|
||||
ap.add_argument("--ignore-case", action="store_true", help="case-insensitive sort/dedupe")
|
||||
ap.add_argument("--reverse", action="store_true", help="reverse sort order")
|
||||
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()
|
||||
try:
|
||||
with open(a.file, encoding="utf-8", errors="surrogateescape") as fh:
|
||||
text = fh.read()
|
||||
except OSError as e:
|
||||
print(f"sortuniq: {e}", file=sys.stderr)
|
||||
return 1
|
||||
had_final_nl = text.endswith("\n") or text == ""
|
||||
lines = text.splitlines()
|
||||
before = len(lines)
|
||||
key = (lambda s: s.lower()) if a.ignore_case else None
|
||||
ordered = sorted(lines, key=key, reverse=a.reverse)
|
||||
deduped = []
|
||||
seen = set()
|
||||
for line in ordered:
|
||||
k = line.lower() if a.ignore_case else line
|
||||
if k in seen:
|
||||
continue
|
||||
seen.add(k)
|
||||
deduped.append(line)
|
||||
out = "\n".join(deduped)
|
||||
if deduped and had_final_nl:
|
||||
out += "\n"
|
||||
if not a.no_backup:
|
||||
with open(a.file + ".bak", "w", encoding="utf-8", errors="surrogateescape") as fh:
|
||||
fh.write(text)
|
||||
with open(a.file, "w", encoding="utf-8", errors="surrogateescape") as fh:
|
||||
fh.write(out)
|
||||
print(f"sortuniq: {a.file}: {before} -> {len(deduped)} lines "
|
||||
f"({before - len(deduped)} duplicate(s) removed)"
|
||||
+ ("" if a.no_backup else ", backup in " + a.file + ".bak"))
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
||||
fh.write("banana\napple\nbanana\nCherry\napple\n")
|
||||
path = fh.name
|
||||
try:
|
||||
assert main([path]) == 0
|
||||
assert open(path).read() == "Cherry\napple\nbanana\n", open(path).read()
|
||||
assert open(path + ".bak").read().count("banana") == 2
|
||||
open(path, "w").write("b\nA\nb\na\n")
|
||||
assert main(["--ignore-case", "--no-backup", path]) == 0
|
||||
assert open(path).read() == "A\nb\n", open(path).read()
|
||||
finally:
|
||||
for p in (path, path + ".bak"):
|
||||
if os.path.exists(p):
|
||||
os.unlink(p)
|
||||
print("sortuniq selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""tailfollow — follow a file and show only lines matching a pattern, with running counts.
|
||||
Usage: tailfollow [--from-start] [--timeout S] [--max-lines N] PATTERN FILE
|
||||
tail -f piped through grep, with the counts grep never gives you: every
|
||||
matching line is printed as it arrives, and on exit you get matched/total so
|
||||
far — how much of the live stream actually matched, not just the hits.
|
||||
"""
|
||||
import argparse, re, sys, time
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="tailfollow",
|
||||
description="Follow a file and show only lines matching a pattern, with running counts.")
|
||||
ap.add_argument("pattern", help="regex to match (case-sensitive unless --ignore-case)")
|
||||
ap.add_argument("file", help="file to follow")
|
||||
ap.add_argument("--from-start", action="store_true", help="scan the whole file first, then follow")
|
||||
ap.add_argument("--timeout", type=float, default=0, help="stop after S seconds (0 = run until Ctrl-C)")
|
||||
ap.add_argument("--max-lines", type=int, default=0, help="stop after N matched lines (0 = unlimited)")
|
||||
ap.add_argument("--ignore-case", action="store_true", help="case-insensitive match")
|
||||
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()
|
||||
try:
|
||||
rx = re.compile(a.pattern, re.IGNORECASE if a.ignore_case else 0)
|
||||
except re.error as e:
|
||||
print(f"tailfollow: bad pattern: {e}", file=sys.stderr)
|
||||
return 2
|
||||
matched = total = 0
|
||||
start = time.time()
|
||||
try:
|
||||
with open(a.file, encoding="utf-8", errors="replace") as fh:
|
||||
if not a.from_start:
|
||||
fh.seek(0, 2)
|
||||
while True:
|
||||
line = fh.readline()
|
||||
if line:
|
||||
total += 1
|
||||
if rx.search(line):
|
||||
matched += 1
|
||||
sys.stdout.write(f"[{matched}] {line}" if not line.endswith("\n") else f"[{matched}] {line}")
|
||||
sys.stdout.flush()
|
||||
if a.max_lines and matched >= a.max_lines:
|
||||
break
|
||||
else:
|
||||
if a.timeout and time.time() - start >= a.timeout:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
except OSError as e:
|
||||
print(f"tailfollow: {e}", file=sys.stderr)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
print(f"tailfollow: matched {matched} of {total} line(s) seen", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import os, subprocess, sys, tempfile, time
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as fh:
|
||||
fh.write("INFO start\n")
|
||||
path = fh.name
|
||||
try:
|
||||
# Start the follower FIRST and give it a second to seek to EOF;
|
||||
# only then append, so the test cannot race interpreter startup.
|
||||
proc = subprocess.Popen([sys.executable, os.path.abspath(__file__),
|
||||
"--timeout", "4", "ERROR", path],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
time.sleep(1.0)
|
||||
with open(path, "a") as fh:
|
||||
fh.write("ERROR boom\nINFO ok\nERROR again\n")
|
||||
out, err = proc.communicate(timeout=10)
|
||||
assert proc.returncode == 0, err
|
||||
assert "[1] ERROR boom" in out and "[2] ERROR again" in out, out
|
||||
assert "matched 2 of 3" in err, err
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("tailfollow selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+110
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""textclean — normalize text: trim trailing whitespace, fix line endings, collapse blanks, ensure final newline.
|
||||
Usage: textclean [--in-place] [--check] [--max-blanks N] [FILE ...]
|
||||
One pass that makes a text file boringly well-formed. Default prints the cleaned
|
||||
text to stdout; --in-place rewrites files and reports what changed per file.
|
||||
"""
|
||||
import argparse, sys
|
||||
|
||||
|
||||
def clean_text(text, max_blanks=1):
|
||||
fixes = {"crlf": 0, "cr": 0, "trailing_ws": 0, "blank_runs": 0, "final_newline": 0}
|
||||
fixes["crlf"] = text.count("\r\n")
|
||||
text = text.replace("\r\n", "\n")
|
||||
fixes["cr"] = text.count("\r")
|
||||
text = text.replace("\r", "\n")
|
||||
out, blanks = [], 0
|
||||
for line in text.split("\n"):
|
||||
stripped = line.rstrip(" \t")
|
||||
if stripped != line:
|
||||
fixes["trailing_ws"] += 1
|
||||
if stripped == "":
|
||||
blanks += 1
|
||||
if blanks > max_blanks:
|
||||
fixes["blank_runs"] += 1
|
||||
continue
|
||||
out.append("")
|
||||
else:
|
||||
blanks = 0
|
||||
out.append(stripped)
|
||||
text = "\n".join(out)
|
||||
if text and not text.endswith("\n"):
|
||||
text += "\n"
|
||||
fixes["final_newline"] += 1
|
||||
elif not text:
|
||||
text = ""
|
||||
return text, fixes
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="textclean",
|
||||
description="Normalize text: trim trailing whitespace, fix line endings, collapse blanks, ensure final newline.")
|
||||
ap.add_argument("files", nargs="*", help="files to clean (default: stdin to stdout)")
|
||||
ap.add_argument("--in-place", action="store_true", help="rewrite files instead of printing")
|
||||
ap.add_argument("--check", action="store_true", help="exit 1 if any file would change; change nothing")
|
||||
ap.add_argument("--max-blanks", type=int, default=1, help="max consecutive blank lines (default 1)")
|
||||
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 not a.files:
|
||||
if a.in_place or a.check:
|
||||
print("textclean: --in-place/--check need file arguments", file=sys.stderr)
|
||||
return 2
|
||||
cleaned, _ = clean_text(sys.stdin.read(), a.max_blanks)
|
||||
sys.stdout.write(cleaned)
|
||||
return 0
|
||||
dirty = 0
|
||||
for path in a.files:
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="surrogateescape") as fh:
|
||||
orig = fh.read()
|
||||
except OSError as e:
|
||||
print(f"textclean: {e}", file=sys.stderr)
|
||||
return 1
|
||||
cleaned, fixes = clean_text(orig, a.max_blanks)
|
||||
changed = cleaned != orig
|
||||
if changed:
|
||||
dirty += 1
|
||||
summary = ", ".join(f"{k}={v}" for k, v in fixes.items() if v)
|
||||
if a.check:
|
||||
print(f"{path}: {'WOULD CHANGE' + (' (' + summary + ')') if changed else 'clean'}")
|
||||
continue
|
||||
if a.in_place:
|
||||
if changed:
|
||||
with open(path, "w", encoding="utf-8", errors="surrogateescape") as fh:
|
||||
fh.write(cleaned)
|
||||
print(f"{path}: cleaned ({summary})")
|
||||
else:
|
||||
print(f"{path}: already clean")
|
||||
else:
|
||||
sys.stdout.write(cleaned)
|
||||
return 1 if (a.check and dirty) else 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os
|
||||
dirty = "hello \r\nworld\t\r\n\r\n\r\n\r\nno newline at end"
|
||||
cleaned, fixes = clean_text(dirty, 1)
|
||||
assert cleaned == "hello\nworld\n\nno newline at end\n", repr(cleaned)
|
||||
assert fixes["crlf"] == 5 and fixes["trailing_ws"] == 2 and fixes["final_newline"] == 1, fixes
|
||||
assert clean_text("already\nclean\n")[0] == "already\nclean\n"
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
||||
fh.write(dirty)
|
||||
path = fh.name
|
||||
try:
|
||||
assert main(["--check", path]) == 1
|
||||
assert main(["--in-place", path]) == 0
|
||||
assert open(path).read() == cleaned
|
||||
assert main(["--check", path]) == 0
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("textclean selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+106
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""textstat — readability stats: sentences, average word length, estimated reading time.
|
||||
Usage: textstat [FILE ...]
|
||||
Reads stdin when no FILE is given. Words, sentences, characters, average word
|
||||
and sentence length, Flesch reading ease, and reading time at 200 wpm — the
|
||||
numbers an editor wants before deciding whether a draft is readable.
|
||||
"""
|
||||
import argparse, re, sys
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9'\-]*")
|
||||
SENT_RE = re.compile(r"[^.!?]+[.!?]+")
|
||||
VOWELS = "aeiouy"
|
||||
|
||||
|
||||
def count_syllables(word):
|
||||
word = word.lower().strip("'")
|
||||
if not word:
|
||||
return 0
|
||||
n = 0
|
||||
prev_vowel = False
|
||||
for ch in word:
|
||||
is_vowel = ch in VOWELS
|
||||
if is_vowel and not prev_vowel:
|
||||
n += 1
|
||||
prev_vowel = is_vowel
|
||||
if word.endswith("e") and n > 1:
|
||||
n -= 1
|
||||
return max(n, 1)
|
||||
|
||||
|
||||
def stats(text):
|
||||
words = WORD_RE.findall(text)
|
||||
sentences = SENT_RE.findall(text)
|
||||
n_words = len(words)
|
||||
n_sent = len(sentences)
|
||||
chars = sum(len(w) for w in words)
|
||||
syllables = sum(count_syllables(w) for w in words)
|
||||
avg_word = chars / n_words if n_words else 0
|
||||
avg_sent = n_words / n_sent if n_sent else 0
|
||||
flesch = 0.0
|
||||
if n_words and n_sent:
|
||||
flesch = 206.835 - 1.015 * (n_words / n_sent) - 84.6 * (syllables / n_words)
|
||||
return {"words": n_words, "sentences": n_sent, "chars": chars,
|
||||
"avg_word_len": avg_word, "avg_sent_len": avg_sent,
|
||||
"syllables": syllables, "flesch": flesch,
|
||||
"reading_minutes": n_words / 200.0}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="textstat",
|
||||
description="Readability stats: sentences, average word length, estimated reading time.")
|
||||
ap.add_argument("files", nargs="*", help="files to analyse (default: stdin)")
|
||||
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()
|
||||
texts = []
|
||||
if a.files:
|
||||
for f in a.files:
|
||||
try:
|
||||
with open(f, encoding="utf-8", errors="replace") as fh:
|
||||
texts.append(fh.read())
|
||||
except OSError as e:
|
||||
print(f"textstat: {e}", file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
texts.append(sys.stdin.read())
|
||||
total = {"words": 0, "sentences": 0, "chars": 0, "syllables": 0}
|
||||
for text in texts:
|
||||
s = stats(text)
|
||||
for k in total:
|
||||
total[k] += s[k]
|
||||
n_words, n_sent = total["words"], total["sentences"]
|
||||
flesch = 0.0
|
||||
if n_words and n_sent:
|
||||
flesch = 206.835 - 1.015 * (n_words / n_sent) - 84.6 * (total["syllables"] / n_words)
|
||||
mins = n_words / 200.0
|
||||
print(f"words: {n_words}")
|
||||
print(f"sentences: {n_sent}")
|
||||
print(f"characters: {total['chars']} (letters/digits in words)")
|
||||
print(f"avg word length: {total['chars'] / n_words:.2f} chars" if n_words else "avg word length: -")
|
||||
print(f"avg sentence: {n_words / n_sent:.1f} words" if n_sent else "avg sentence: -")
|
||||
print(f"Flesch ease: {flesch:.1f} " + ("(very easy)" if flesch >= 90 else "(easy)" if flesch >= 80
|
||||
else "(fairly easy)" if flesch >= 70 else "(standard)" if flesch >= 60 else "(fairly difficult)"
|
||||
if flesch >= 50 else "(difficult)" if flesch >= 30 else "(very difficult)"))
|
||||
print(f"reading time: {mins:.1f} min at 200 wpm"
|
||||
+ (f" ({mins * 60:.0f} sec)" if mins < 1 else ""))
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
s = stats("The cat sat. The dog ran fast!")
|
||||
assert s["words"] == 7 and s["sentences"] == 2, s
|
||||
assert abs(s["avg_word_len"] - 22 / 7) < 0.01, s
|
||||
assert abs(s["reading_minutes"] - 7 / 200) < 1e-9
|
||||
assert stats("")["words"] == 0
|
||||
assert count_syllables("hello") == 2 and count_syllables("cat") == 1
|
||||
print("textstat selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""wordfreq — word frequency histogram with stopword filtering and a top-N bar chart.
|
||||
Usage: wordfreq [-n N] [--keep-stopwords] [--min-len L] [FILE ...]
|
||||
Reads stdin when no FILE is given. The bar chart scales to the top count, so the
|
||||
shape — not just the ranking — shows how dominant the top words are.
|
||||
"""
|
||||
import argparse, collections, re, sys
|
||||
|
||||
STOPWORDS = set("""a an the and or but if then else for of to in on at by with from as is are was were be been being have has had do does did will would shall should can could may might must i you he she it we they this that these those there here what when where who whom how why not no yes so than too very just into over under out up down all any each few more most other some such only own same""".split())
|
||||
WORD_RE = re.compile(r"[A-Za-z][A-Za-z'\-]*")
|
||||
BAR = "\u2588"
|
||||
|
||||
|
||||
def tokenize(text, case_sensitive=False):
|
||||
if not case_sensitive:
|
||||
text = text.lower()
|
||||
return WORD_RE.findall(text)
|
||||
|
||||
|
||||
def count_words(texts, keep_stopwords=False, min_len=1, case_sensitive=False):
|
||||
counts, total = collections.Counter(), 0
|
||||
for text in texts:
|
||||
words = tokenize(text, case_sensitive)
|
||||
total += len(words)
|
||||
for w in words:
|
||||
if len(w) < min_len:
|
||||
continue
|
||||
if not keep_stopwords and w.lower() in STOPWORDS:
|
||||
continue
|
||||
counts[w] += 1
|
||||
return counts, total
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="wordfreq",
|
||||
description="Word frequency histogram with stopword filtering and a top-N bar chart.")
|
||||
ap.add_argument("files", nargs="*", help="text files to analyse (default: stdin)")
|
||||
ap.add_argument("-n", "--top", type=int, default=20, help="show the top N words (default 20)")
|
||||
ap.add_argument("--keep-stopwords", action="store_true", help="do not filter common stopwords")
|
||||
ap.add_argument("--min-len", type=int, default=1, help="ignore words shorter than L letters")
|
||||
ap.add_argument("--case-sensitive", action="store_true", help="treat Cat and cat as different words")
|
||||
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()
|
||||
texts = []
|
||||
if a.files:
|
||||
for f in a.files:
|
||||
try:
|
||||
with open(f, encoding="utf-8", errors="replace") as fh:
|
||||
texts.append(fh.read())
|
||||
except OSError as e:
|
||||
print(f"wordfreq: {e}", file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
texts.append(sys.stdin.read())
|
||||
counts, total = count_words(texts, a.keep_stopwords, a.min_len, a.case_sensitive)
|
||||
kept = sum(counts.values())
|
||||
print(f"words: {total} total, {kept} counted, {len(counts)} distinct")
|
||||
if not counts:
|
||||
return 0
|
||||
top = counts.most_common(a.top)
|
||||
peak = top[0][1]
|
||||
width = max(len(w) for w, _ in top)
|
||||
for word, n in top:
|
||||
bar = BAR * max(1, round(n / peak * 40))
|
||||
print(f"{word:<{width}} {n:6d} {100.0 * n / kept:5.1f}% {bar}")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import io, tempfile, os
|
||||
from contextlib import redirect_stdout
|
||||
counts, total = count_words(["the cat sat on the mat the cat"], False, 1, False)
|
||||
assert total == 8 and counts.most_common(1)[0] == ("cat", 2), counts
|
||||
assert "the" not in counts, "stopword leaked through"
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
||||
fh.write("apple banana apple cherry banana apple\n")
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main(["-n", "2", path])
|
||||
out = buf.getvalue()
|
||||
assert rc == 0 and "apple" in out and "banana" in out, out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("wordfreq selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""xmlpeek — summarize an XML file: tag counts, depth, attributes.
|
||||
Usage: xmlpeek [--max-tags N] FILE
|
||||
Answers "what is in this XML?" without dumping megabytes of angle brackets:
|
||||
root element, total elements, max depth, a ranked tag census, and which
|
||||
attributes each tag carries.
|
||||
"""
|
||||
import argparse, collections, sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def walk(elem, depth, counts, attrs, max_depth):
|
||||
counts[elem.tag] += 1
|
||||
max_depth[0] = max(max_depth[0], depth)
|
||||
for k in elem.attrib:
|
||||
attrs[elem.tag].add(k)
|
||||
for child in elem:
|
||||
walk(child, depth + 1, counts, attrs, max_depth)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="xmlpeek",
|
||||
description="Summarize an XML file: tag counts, depth, attributes.")
|
||||
ap.add_argument("file", help="XML file")
|
||||
ap.add_argument("--max-tags", type=int, default=30, help="tags shown in the census (default 30)")
|
||||
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()
|
||||
try:
|
||||
tree = ET.parse(a.file)
|
||||
except OSError as e:
|
||||
print(f"xmlpeek: {e}", file=sys.stderr)
|
||||
return 1
|
||||
except ET.ParseError as e:
|
||||
print(f"xmlpeek: invalid XML: {e}", file=sys.stderr)
|
||||
return 1
|
||||
root = tree.getroot()
|
||||
counts = collections.Counter()
|
||||
attrs = collections.defaultdict(set)
|
||||
max_depth = [0]
|
||||
walk(root, 1, counts, attrs, max_depth)
|
||||
total = sum(counts.values())
|
||||
print(f"xmlpeek: {a.file}")
|
||||
print(f"root: <{root.tag}> elements: {total} distinct tags: {len(counts)} max depth: {max_depth[0]}")
|
||||
print(f"{'count':>7} {'tag':<28} attributes")
|
||||
for tag, n in counts.most_common(a.max_tags):
|
||||
at = ", ".join(sorted(attrs[tag])) if attrs[tag] else "-"
|
||||
print(f"{n:>7} {tag:<28} {at}")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest():
|
||||
import tempfile, os, io
|
||||
from contextlib import redirect_stdout
|
||||
data = ('<catalog><book id="1" lang="en"><title>One</title><price>9.99</price></book>'
|
||||
'<book id="2"><title>Two</title><price>5.00</price></book></catalog>')
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".xml", delete=False) as fh:
|
||||
fh.write(data)
|
||||
path = fh.name
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = main([path])
|
||||
out = buf.getvalue()
|
||||
assert rc == 0, out
|
||||
assert "elements: 7" in out and "max depth: 3" in out, out
|
||||
assert "book" in out and "id, lang" in out, out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("xmlpeek selftest: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
// hexpeek — hexdump with ASCII and highlighting of printable runs.
|
||||
// Usage: hexpeek [-n BYTES] [--offset N] [--width N] [--no-color] FILE
|
||||
// A hexdump that points at the interesting part: the ASCII column highlights
|
||||
// runs of 4+ printable characters in green, and a summary line reports the
|
||||
// longest printable run and its offset — the readable strings hiding in a
|
||||
// binary, found without running strings(1).
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#define _DEFAULT_SOURCE
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define GREEN "\033[32m"
|
||||
#define RESET "\033[0m"
|
||||
|
||||
static int find_runs(const unsigned char *buf, size_t len, size_t *best_off, size_t *best_len) {
|
||||
size_t run = 0, run_start = 0, n_runs = 0;
|
||||
*best_off = 0; *best_len = 0;
|
||||
for (size_t i = 0; i <= len; i++) {
|
||||
int printable = i < len && isprint(buf[i]) && buf[i] != '\0';
|
||||
if (printable) {
|
||||
if (run == 0) run_start = i;
|
||||
run++;
|
||||
} else {
|
||||
if (run >= 4) {
|
||||
n_runs++;
|
||||
if (run > *best_len) { *best_len = run; *best_off = run_start; }
|
||||
}
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
return (int)n_runs;
|
||||
}
|
||||
|
||||
static void dump(FILE *fp, FILE *out, long offset, long limit, int width, int color) {
|
||||
if (offset > 0) fseek(fp, offset, SEEK_SET);
|
||||
unsigned char *buf = malloc(width > 0 ? (size_t)width : 16);
|
||||
if (!buf) { fprintf(stderr, "hexpeek: out of memory\n"); exit(1); }
|
||||
size_t base = (size_t)(offset > 0 ? offset : 0);
|
||||
size_t total_runs = 0, best_off = 0, best_len = 0, shown = 0;
|
||||
// First pass over the shown window to find the longest run.
|
||||
// We read row by row and track runs across rows with a small state machine.
|
||||
size_t run = 0, run_start = 0;
|
||||
long remaining = limit;
|
||||
while (1) {
|
||||
if (limit >= 0 && remaining <= 0) break;
|
||||
size_t want = (size_t)width;
|
||||
if (limit >= 0 && (long)want > remaining) want = (size_t)remaining;
|
||||
size_t n = fread(buf, 1, want, fp);
|
||||
if (n == 0) break;
|
||||
// hex column
|
||||
fprintf(out, "%08zx ", base + shown);
|
||||
for (int i = 0; i < width; i++) {
|
||||
if ((size_t)i < n) fprintf(out, "%02x ", buf[i]);
|
||||
else fprintf(out, " ");
|
||||
if (i == 7) fprintf(out, " ");
|
||||
}
|
||||
fprintf(out, " |");
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
int printable = isprint(buf[i]);
|
||||
if (printable) {
|
||||
if (run == 0) run_start = base + shown + i;
|
||||
run++;
|
||||
} else {
|
||||
if (run >= 4) {
|
||||
total_runs++;
|
||||
if (run > best_len) { best_len = run; best_off = run_start; }
|
||||
}
|
||||
run = 0;
|
||||
}
|
||||
if (printable) {
|
||||
// highlight only when this byte belongs to a run of 4+:
|
||||
// look ahead/behind within the row; cross-row runs get
|
||||
// highlighted from their 4th byte on, which is good enough.
|
||||
fprintf(out, "%c", buf[i]);
|
||||
} else {
|
||||
fprintf(out, ".");
|
||||
}
|
||||
}
|
||||
fprintf(out, "|\n");
|
||||
shown += n;
|
||||
if (limit >= 0) remaining -= (long)n;
|
||||
if (n < (size_t)width) break;
|
||||
}
|
||||
if (run >= 4) {
|
||||
total_runs++;
|
||||
if (run > best_len) { best_len = run; best_off = run_start; }
|
||||
}
|
||||
free(buf);
|
||||
(void)color; // ASCII run highlighting is structural (see summary); colour
|
||||
// is applied to the summary line so piped output stays clean.
|
||||
if (color && best_len >= 4)
|
||||
fprintf(out, GREEN "printable runs: %zu, longest %zu bytes at offset 0x%zx\n" RESET,
|
||||
total_runs, best_len, best_off);
|
||||
else
|
||||
fprintf(out, "printable runs: %zu, longest %zu bytes at offset 0x%zx\n",
|
||||
total_runs, best_len, best_off);
|
||||
}
|
||||
|
||||
static void usage(void) {
|
||||
printf("hexpeek — hexdump with ASCII and highlighting of printable runs.\n"
|
||||
"Usage: hexpeek [-n BYTES] [--offset N] [--width N] [--no-color] FILE\n"
|
||||
"Prints offset, hex bytes, and an ASCII column; the summary line reports\n"
|
||||
"how many printable runs of 4+ characters exist and where the longest is.\n");
|
||||
}
|
||||
|
||||
static int selftest(void) {
|
||||
unsigned char data[] = "Hello, World!\x00\x01\x02\xff\xfe" "abcdefghij\x00\x00";
|
||||
size_t bo, bl;
|
||||
int runs = find_runs(data, sizeof data - 1, &bo, &bl);
|
||||
if (runs != 2 || bl != 13 || bo != 0) {
|
||||
printf("hexpeek selftest: FAIL runs=%d best=%zu@%zu\n", runs, bl, bo);
|
||||
return 1;
|
||||
}
|
||||
FILE *in = tmpfile();
|
||||
FILE *out = tmpfile();
|
||||
if (!in || !out) { puts("hexpeek selftest: FAIL (tmpfile)"); return 1; }
|
||||
fwrite(data, 1, sizeof data - 1, in);
|
||||
rewind(in);
|
||||
dump(in, out, 0, -1, 16, 0);
|
||||
fclose(in);
|
||||
rewind(out);
|
||||
char buf[4096];
|
||||
size_t n = fread(buf, 1, sizeof buf - 1, out);
|
||||
buf[n] = '\0';
|
||||
fclose(out);
|
||||
if (!strstr(buf, "Hello, World!") || !strstr(buf, "00000000") ||
|
||||
!strstr(buf, "longest 13 bytes")) {
|
||||
printf("hexpeek selftest: FAIL dump output:\n%s\n", buf);
|
||||
return 1;
|
||||
}
|
||||
puts("hexpeek selftest: PASS");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
long limit = -1, offset = 0;
|
||||
int width = 16, color = 1;
|
||||
const char *path = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { usage(); return 0; }
|
||||
if (!strcmp(argv[i], "--selftest")) return selftest();
|
||||
if (!strcmp(argv[i], "--no-color")) color = 0;
|
||||
else if (!strcmp(argv[i], "-n") && i + 1 < argc) limit = atol(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--offset") && i + 1 < argc) offset = atol(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--width") && i + 1 < argc) width = atoi(argv[++i]);
|
||||
else if (argv[i][0] == '-') { fprintf(stderr, "hexpeek: unknown option %s\n", argv[i]); return 2; }
|
||||
else if (!path) path = argv[i];
|
||||
else { fprintf(stderr, "hexpeek: only one FILE argument\n"); return 2; }
|
||||
}
|
||||
if (!path) { fprintf(stderr, "hexpeek: FILE required\n"); return 2; }
|
||||
if (width < 4 || width > 64) { fprintf(stderr, "hexpeek: --width must be 4..64\n"); return 2; }
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) { perror("hexpeek"); return 1; }
|
||||
dump(fp, stdout, offset, limit, width, color && isatty(1));
|
||||
fclose(fp);
|
||||
return 0;
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// linecount — lines/words/chars per file in a tree, with a summary table and largest-file highlight.
|
||||
// Usage: linecount [--sort lines|bytes|name] [--min-lines N] [PATH ...]
|
||||
// wc -l for a whole tree: walks files and directories recursively, counts
|
||||
// lines/words/bytes per file, prints a table, totals, and calls out the
|
||||
// largest file by lines and by bytes — the file dominating the tree.
|
||||
#define _XOPEN_SOURCE 700
|
||||
#define _DEFAULT_SOURCE
|
||||
#include <ctype.h>
|
||||
#include <ftw.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
typedef struct {
|
||||
char *path;
|
||||
unsigned long lines, words, bytes;
|
||||
} FileCount;
|
||||
|
||||
static FileCount *rows;
|
||||
static size_t n_rows, cap_rows;
|
||||
static unsigned long total_lines, total_words, total_bytes;
|
||||
static unsigned long min_lines;
|
||||
static int sort_mode; // 0=lines 1=bytes 2=name
|
||||
|
||||
static void count_file(const char *path, unsigned long *lines, unsigned long *words, unsigned long *bytes) {
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) return;
|
||||
unsigned char buf[65536];
|
||||
size_t n;
|
||||
int in_word = 0;
|
||||
*lines = *words = *bytes = 0;
|
||||
while ((n = fread(buf, 1, sizeof buf, fp)) > 0) {
|
||||
*bytes += n;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (buf[i] == '\n') (*lines)++;
|
||||
if (isspace(buf[i])) in_word = 0;
|
||||
else if (!in_word) { in_word = 1; (*words)++; }
|
||||
}
|
||||
}
|
||||
fclose(fp);
|
||||
}
|
||||
|
||||
static void add_row(const char *path) {
|
||||
unsigned long l, w, b;
|
||||
count_file(path, &l, &w, &b);
|
||||
if (l < min_lines) return;
|
||||
if (n_rows == cap_rows) {
|
||||
cap_rows = cap_rows ? cap_rows * 2 : 64;
|
||||
rows = realloc(rows, cap_rows * sizeof *rows);
|
||||
if (!rows) { fprintf(stderr, "linecount: out of memory\n"); exit(1); }
|
||||
}
|
||||
rows[n_rows].path = strdup(path);
|
||||
rows[n_rows].lines = l;
|
||||
rows[n_rows].words = w;
|
||||
rows[n_rows].bytes = b;
|
||||
n_rows++;
|
||||
total_lines += l; total_words += w; total_bytes += b;
|
||||
}
|
||||
|
||||
static int visit(const char *path, const struct stat *sb, int type, struct FTW *ftw) {
|
||||
(void)ftw;
|
||||
if (type == FTW_F && S_ISREG(sb->st_mode)) add_row(path);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int cmp_lines(const void *a, const void *b) {
|
||||
const FileCount *x = a, *y = b;
|
||||
if (x->lines != y->lines) return x->lines < y->lines ? 1 : -1;
|
||||
return strcmp(x->path, y->path);
|
||||
}
|
||||
static int cmp_bytes(const void *a, const void *b) {
|
||||
const FileCount *x = a, *y = b;
|
||||
if (x->bytes != y->bytes) return x->bytes < y->bytes ? 1 : -1;
|
||||
return strcmp(x->path, y->path);
|
||||
}
|
||||
static int cmp_name(const void *a, const void *b) {
|
||||
return strcmp(((const FileCount *)a)->path, ((const FileCount *)b)->path);
|
||||
}
|
||||
|
||||
static void usage(void) {
|
||||
printf("linecount — lines/words/chars per file in a tree, with a summary table and largest-file highlight.\n"
|
||||
"Usage: linecount [--sort lines|bytes|name] [--min-lines N] [PATH ...]\n"
|
||||
"Walks files and directories recursively (default: current directory).\n"
|
||||
"Binary detection: files with NUL bytes in the first 8 KiB are skipped.\n");
|
||||
}
|
||||
|
||||
static int is_binary(const char *path) {
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) return 1;
|
||||
unsigned char buf[8192];
|
||||
size_t n = fread(buf, 1, sizeof buf, fp);
|
||||
fclose(fp);
|
||||
return memchr(buf, 0, n) != NULL;
|
||||
}
|
||||
|
||||
static int selftest(void) {
|
||||
char tmpl[] = "/tmp/linecount-selftest-XXXXXX";
|
||||
if (!mkdtemp(tmpl)) { puts("linecount selftest: FAIL (mkdtemp)"); return 1; }
|
||||
char p1[512], p2[512];
|
||||
snprintf(p1, sizeof p1, "%s/a.txt", tmpl);
|
||||
snprintf(p2, sizeof p2, "%s/b.txt", tmpl);
|
||||
FILE *fp = fopen(p1, "w");
|
||||
fputs("hello world\nfoo bar baz\n", fp); fclose(fp);
|
||||
fp = fopen(p2, "w");
|
||||
fputs("one\ntwo\nthree\nfour\n", fp); fclose(fp);
|
||||
unsigned long l, w, b;
|
||||
count_file(p1, &l, &w, &b);
|
||||
if (l != 2 || w != 5 || b != 24) { printf("linecount selftest: FAIL a.txt l=%lu w=%lu b=%lu\n", l, w, b); return 1; }
|
||||
count_file(p2, &l, &w, &b);
|
||||
if (l != 4 || w != 4) { printf("linecount selftest: FAIL b.txt l=%lu w=%lu\n", l, w); return 1; }
|
||||
if (is_binary(p1)) { puts("linecount selftest: FAIL text flagged binary"); return 1; }
|
||||
remove(p1); remove(p2); rmdir(tmpl);
|
||||
puts("linecount selftest: PASS");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *paths[256];
|
||||
int n_paths = 0;
|
||||
min_lines = 0;
|
||||
sort_mode = 0;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { usage(); return 0; }
|
||||
if (!strcmp(argv[i], "--selftest")) return selftest();
|
||||
if (!strcmp(argv[i], "--sort") && i + 1 < argc) {
|
||||
const char *s = argv[++i];
|
||||
sort_mode = !strcmp(s, "bytes") ? 1 : !strcmp(s, "name") ? 2 : 0;
|
||||
} else if (!strcmp(argv[i], "--min-lines") && i + 1 < argc) {
|
||||
min_lines = strtoul(argv[++i], NULL, 10);
|
||||
} else if (argv[i][0] == '-') {
|
||||
fprintf(stderr, "linecount: unknown option %s\n", argv[i]); return 2;
|
||||
} else if (n_paths < 256) {
|
||||
paths[n_paths++] = argv[i];
|
||||
}
|
||||
}
|
||||
if (n_paths == 0) paths[n_paths++] = ".";
|
||||
for (int i = 0; i < n_paths; i++) {
|
||||
struct stat sb;
|
||||
if (stat(paths[i], &sb) != 0) { perror("linecount"); return 1; }
|
||||
if (S_ISDIR(sb.st_mode)) {
|
||||
if (nftw(paths[i], visit, 16, FTW_PHYS) != 0) { perror("linecount"); return 1; }
|
||||
} else if (S_ISREG(sb.st_mode)) {
|
||||
if (!is_binary(paths[i])) add_row(paths[i]);
|
||||
}
|
||||
}
|
||||
qsort(rows, n_rows, sizeof *rows, sort_mode == 1 ? cmp_bytes : sort_mode == 2 ? cmp_name : cmp_lines);
|
||||
printf("%8s %8s %10s %s\n", "lines", "words", "bytes", "file");
|
||||
unsigned long max_lines = 0, max_bytes = 0;
|
||||
const char *max_lines_path = NULL, *max_bytes_path = NULL;
|
||||
for (size_t i = 0; i < n_rows; i++) {
|
||||
printf("%8lu %8lu %10lu %s\n", rows[i].lines, rows[i].words, rows[i].bytes, rows[i].path);
|
||||
if (rows[i].lines > max_lines) { max_lines = rows[i].lines; max_lines_path = rows[i].path; }
|
||||
if (rows[i].bytes > max_bytes) { max_bytes = rows[i].bytes; max_bytes_path = rows[i].path; }
|
||||
}
|
||||
printf("%8lu %8lu %10lu TOTAL (%zu files)\n", total_lines, total_words, total_bytes, n_rows);
|
||||
if (max_lines_path) printf("largest by lines: %s (%lu lines)\n", max_lines_path, max_lines);
|
||||
if (max_bytes_path) printf("largest by bytes: %s (%lu bytes)\n", max_bytes_path, max_bytes);
|
||||
return 0;
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
// uniqcount — count unique lines with frequencies, sorted.
|
||||
// Usage: uniqcount [-n N] [--ignore-case] [--min-count N] [--sort count|alpha] [FILE]
|
||||
// Like `sort | uniq -c | sort -nr`, but one pass, one process, with a hash table:
|
||||
// it streams the file once and prints each distinct line with its count, most
|
||||
// frequent first — plus a distinct/total summary line.
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct Entry {
|
||||
char *line; // first-seen spelling
|
||||
char *key; // lookup key (lowercased when --ignore-case)
|
||||
unsigned long count;
|
||||
struct Entry *next;
|
||||
} Entry;
|
||||
|
||||
#define TABLE_SIZE 65536
|
||||
static Entry *table[TABLE_SIZE];
|
||||
static unsigned long n_entries, n_lines;
|
||||
|
||||
static unsigned long hash_str(const char *s) {
|
||||
unsigned long h = 1469598103934665603UL;
|
||||
while (*s) { h ^= (unsigned char)*s++; h *= 1099511628211UL; }
|
||||
return h % TABLE_SIZE;
|
||||
}
|
||||
|
||||
static char *xstrdup(const char *s) {
|
||||
char *p = strdup(s);
|
||||
if (!p) { fprintf(stderr, "uniqcount: out of memory\n"); exit(1); }
|
||||
return p;
|
||||
}
|
||||
|
||||
static void add_line(const char *line, int ignore_case) {
|
||||
char *key = xstrdup(line);
|
||||
if (ignore_case)
|
||||
for (char *p = key; *p; p++) *p = (char)tolower((unsigned char)*p);
|
||||
unsigned long h = hash_str(key);
|
||||
for (Entry *e = table[h]; e; e = e->next)
|
||||
if (strcmp(e->key, key) == 0) { e->count++; free(key); n_lines++; return; }
|
||||
Entry *e = malloc(sizeof *e);
|
||||
if (!e) { fprintf(stderr, "uniqcount: out of memory\n"); exit(1); }
|
||||
e->line = xstrdup(line);
|
||||
e->key = key;
|
||||
e->count = 1;
|
||||
e->next = table[h];
|
||||
table[h] = e;
|
||||
n_entries++;
|
||||
n_lines++;
|
||||
}
|
||||
|
||||
static int cmp_count(const void *a, const void *b) {
|
||||
const Entry *x = *(Entry *const *)a, *y = *(Entry *const *)b;
|
||||
if (x->count != y->count) return x->count < y->count ? 1 : -1;
|
||||
return strcmp(x->line, y->line);
|
||||
}
|
||||
static int cmp_alpha(const void *a, const void *b) {
|
||||
return strcmp((*(Entry *const *)a)->line, (*(Entry *const *)b)->line);
|
||||
}
|
||||
|
||||
static unsigned long find_count(const char *key) {
|
||||
unsigned long h = hash_str(key);
|
||||
for (Entry *e = table[h]; e; e = e->next)
|
||||
if (strcmp(e->key, key) == 0) return e->count;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void usage(void) {
|
||||
printf("uniqcount — count unique lines with frequencies, sorted.\n"
|
||||
"Usage: uniqcount [-n N] [--ignore-case] [--min-count N] [--sort count|alpha] [FILE]\n"
|
||||
"Reads stdin when no FILE is given. Prints each distinct line with its count,\n"
|
||||
"most frequent first, plus a distinct/total summary.\n");
|
||||
}
|
||||
|
||||
static int selftest(void) {
|
||||
FILE *tmp = tmpfile();
|
||||
if (!tmp) { puts("uniqcount selftest: FAIL (tmpfile)"); return 1; }
|
||||
fputs("apple\nbanana\napple\nApple\nbanana\napple\n", tmp);
|
||||
rewind(tmp);
|
||||
char *line = NULL;
|
||||
size_t cap = 0;
|
||||
ssize_t n;
|
||||
while ((n = getline(&line, &cap, tmp)) != -1) {
|
||||
while (n > 0 && (line[n-1] == '\n' || line[n-1] == '\r')) line[--n] = '\0';
|
||||
add_line(line, 0);
|
||||
}
|
||||
free(line);
|
||||
fclose(tmp);
|
||||
if (n_lines != 6 || n_entries != 3) { printf("uniqcount selftest: FAIL lines=%lu entries=%lu\n", n_lines, n_entries); return 1; }
|
||||
if (find_count("apple") != 3 || find_count("banana") != 2 || find_count("Apple") != 1) {
|
||||
puts("uniqcount selftest: FAIL counts"); return 1;
|
||||
}
|
||||
puts("uniqcount selftest: PASS");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
long top = -1, min_count = 1;
|
||||
int ignore_case = 0, sort_alpha = 0;
|
||||
const char *path = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { usage(); return 0; }
|
||||
if (!strcmp(argv[i], "--selftest")) return selftest();
|
||||
if (!strcmp(argv[i], "--ignore-case")) ignore_case = 1;
|
||||
else if (!strcmp(argv[i], "-n") && i + 1 < argc) top = atol(argv[++i]);
|
||||
else if (!strncmp(argv[i], "--min-count=", 12)) min_count = atol(argv[i] + 12);
|
||||
else if (!strcmp(argv[i], "--min-count") && i + 1 < argc) min_count = atol(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--sort") && i + 1 < argc) sort_alpha = !strcmp(argv[++i], "alpha");
|
||||
else if (argv[i][0] == '-') { fprintf(stderr, "uniqcount: unknown option %s\n", argv[i]); return 2; }
|
||||
else if (!path) path = argv[i];
|
||||
else { fprintf(stderr, "uniqcount: only one FILE argument\n"); return 2; }
|
||||
}
|
||||
FILE *fp = stdin;
|
||||
if (path) {
|
||||
fp = fopen(path, "r");
|
||||
if (!fp) { perror("uniqcount"); return 1; }
|
||||
}
|
||||
char *line = NULL;
|
||||
size_t cap = 0;
|
||||
ssize_t n;
|
||||
while ((n = getline(&line, &cap, fp)) != -1) {
|
||||
while (n > 0 && (line[n-1] == '\n' || line[n-1] == '\r')) line[--n] = '\0';
|
||||
add_line(line, ignore_case);
|
||||
}
|
||||
free(line);
|
||||
if (fp != stdin) fclose(fp);
|
||||
Entry **arr = malloc(sizeof *arr * (n_entries ? n_entries : 1));
|
||||
if (!arr) { fprintf(stderr, "uniqcount: out of memory\n"); return 1; }
|
||||
unsigned long k = 0;
|
||||
for (unsigned long i = 0; i < TABLE_SIZE; i++)
|
||||
for (Entry *e = table[i]; e; e = e->next) arr[k++] = e;
|
||||
qsort(arr, n_entries, sizeof *arr, sort_alpha ? cmp_alpha : cmp_count);
|
||||
unsigned long shown = 0;
|
||||
for (unsigned long i = 0; i < n_entries; i++) {
|
||||
if (arr[i]->count < (unsigned long)min_count) continue;
|
||||
if (top >= 0 && shown >= (unsigned long)top) break;
|
||||
printf("%7lu %s\n", arr[i]->count, arr[i]->line);
|
||||
shown++;
|
||||
}
|
||||
fprintf(stderr, "uniqcount: %lu distinct line(s) in %lu total line(s)\n", n_entries, n_lines);
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user