-
Notifications
You must be signed in to change notification settings - Fork 1
/
older-than
executable file
·77 lines (64 loc) · 2.12 KB
/
older-than
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
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python3
# Author: github.com/danielhoherd
# License: MIT
# Purpose: Return 0 if referenced file is older than the given time
#
# The idea for this was taken from <https://blog.afoolishmanifesto.com/posts/unreliable-cronjobs/>
import argparse
import datetime
import re
import sys
from pathlib import Path
time_units = {
"s": 1,
"m": 60,
"h": 3600,
"d": 86400,
}
def get_unix_mtime_of_file(file: str) -> int:
"""Return the mtime of the given file as a unix timestamp.
Exit 0 on missing file.
"""
file = Path(file)
try:
age = int(file.lstat().st_mtime)
except FileNotFoundError:
print(f"File not found: {file}")
sys.exit(0)
return age
def parse_timespec(spec: str) -> int:
"""Return the number of seconds the timespec represents."""
pattern = re.compile("([0-9]+)([smhd])")
try:
num, unit = pattern.match(spec).groups()
except AttributeError:
sys.exit("There was an error matching the timespec. Check your formatting. Units must be one of: s, m, h, d")
return int(num) * int(time_units[unit])
def main(file: str, timespec: str, verbose: bool) -> None:
"""Exit 0 if the referenced file is older than timespec."""
file_time = get_unix_mtime_of_file(file)
age_limit = parse_timespec(timespec)
now = int(datetime.datetime.now().strftime("%s"))
diff = now - file_time - age_limit
if diff > 0:
if verbose:
print(f"{diff} seconds past")
sys.exit(0)
else:
if verbose:
print(f"{-diff} seconds left to go")
sys.exit(1)
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="Filename to reference", type=str, required=True)
parser.add_argument("-v", "--verbose", help="Be verbose", default=False, action="store_true")
parser.add_argument(
"-t",
"--timespec",
help="Timespec to measure against in seconds, minutes, hours or days (eg: 5m, 1h, 3d)",
type=str,
required=True,
)
args = parser.parse_args()
if __name__ == "__main__":
args = parser.parse_args()
main(file=args.file, timespec=args.timespec, verbose=args.verbose)