1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
#!/usr/bin/env python
"""look through the files given for datetime-like numbers. if found, add a
comment to the end of the line with a human readable version. filename and
linenumber are written to stderr.
"""
from datetime import datetime
import argparse
import fileinput
import re
import sys
COMMENT = {
"": ("#", None), # default
"py": ("#", None),
"hs": ("--", None),
"c": ("/*", "*/"),
"nix": ("#", None),
"js": ("/*", "*/"),
}
REGEX = re.compile(r"(\d{10})")
def find_datetime(line):
"""return the date if the line contains what looks like a second-encoded date,
otherwise None
"""
m = REGEX.match(line)
if m:
return int(m.group(1))
else:
return None
def empty(s):
return "" if s is None else s
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument(
"files", nargs="*", metavar="FILE", help="file(s) to operate on, or omit for stdin"
)
cli.add_argument(
"-d",
"--dry",
action="store_true",
help="dry run, don't actually write to files, but print what would happen",
)
args = cli.parse_args()
for line in fileinput.input(files=args.files, inplace=True):
# python3.8: use := operator here
found = find_datetime(line)
if found:
sys.stderr.write(f"{fileinput.filename()}:{fileinput.lineno()}\n")
human = datetime.fromtimestamp(found).strftime("%Y-%m-%d %H:%M")
ext = fileinput.filename().split(".")[-1]
(left, right) = COMMENT[ext]
if args.dry:
print(line, end="")
else:
print(f"{line.strip()} {left} {human} {empty(right)}", end="")
|