evennia/docs/pylib/fmtwidth.py

50 lines
1.1 KiB
Python
Raw Normal View History

2020-06-16 15:31:15 +02:00
#!/usr/bin python
# -*- coding: utf-8 -*-
"""
Format given files to a max width.
Usage:
2020-06-17 23:05:22 +02:00
python fmtwidth.py --width 79 ../source/**.md
2020-06-16 15:31:15 +02:00
"""
import glob
import textwrap
import argparse
_DEFAULT_WIDTH = 100
2020-06-16 15:31:15 +02:00
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("files")
2020-07-27 21:09:13 +02:00
parser.add_argument("-w", "--width", dest="width", type=int, default=_DEFAULT_WIDTH)
2020-06-16 15:31:15 +02:00
args = parser.parse_args()
2020-06-17 23:05:22 +02:00
filepaths = glob.glob(args.files, recursive=True)
width = args.width
2020-06-16 15:31:15 +02:00
2022-02-08 13:03:52 +01:00
wrapper = textwrap.TextWrapper(
width=width,
break_long_words=False,
expand_tabs=True,
)
2020-06-16 15:31:15 +02:00
count = 0
for filepath in filepaths:
2020-07-27 21:09:13 +02:00
with open(filepath, "r") as fil:
lines = fil.readlines()
outlines = [
2020-07-27 21:09:13 +02:00
"\n".join(wrapper.wrap(line)) if len(line) > width else line.strip("\n")
for line in lines
]
txt = "\n".join(outlines)
2020-07-27 21:09:13 +02:00
with open(filepath, "w") as fil:
2020-06-16 15:31:15 +02:00
fil.write(txt)
count += 1
print(f"Wrapped {count} files.")