-
Notifications
You must be signed in to change notification settings - Fork 173
/
treestate.py
executable file
·92 lines (71 loc) · 2.06 KB
/
treestate.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python3
# Record the current state of a tree in the filesystem
import os
import sys
import json
DIR = 1
LINK = 2
FILE = 3
# Scan filesystem
def scanTreeState(path):
if os.path.islink(path):
yield [LINK, path ]
elif os.path.isdir(path):
yield [DIR, path]
for leaf in os.listdir(path):
p = os.path.join(path, leaf)
for item in scanTreeState(p):
yield item
else:
yield [FILE, path, os.path.getmtime(path)]
# Write the tree in JSON format
def writeTree(filename, tree):
with open(filename, 'w') as f:
json.dump(list(tree), f, indent=1)
def readTree(filename):
with open(filename, "r") as f:
if f == None:
print("*** couldn't open {} ***".format(filename))
return json.load(f)
# Find updates in tree between states A and B
def findUpdates(a, b):
a_map = {}
# Build mapping of filename -> modified time in A
for o in a:
if o[0] == FILE:
a_map[ o[1] ] = o[2]
else:
a_map[ o[1] ] = True
# Find updated or new items in B
for o in b:
if o[1] in a_map:
if o[0] == FILE and o[2] != a_map[ o[1] ]:
print(o[1])
elif o[0] == FILE or o[0] == LINK:
print(o[1])
def help():
print("Syntax:")
print(" {} scan path stateFile".format(sys.argv[0]))
print(" Record the state of <path> in <stateFile>")
print(" {} updates stateFile path".format(sys.argv[0]))
print(" Print the paths of objects in <path> which have updated since <stateFile>")
exit()
# Process arguments
if len(sys.argv) < 2:
help()
if sys.argv[1] == 'scan':
if len(sys.argv) != 4:
help()
path = sys.argv[2]
stateFile = sys.argv[3]
tree = scanTreeState(path)
writeTree(stateFile, tree)
elif sys.argv[1] == 'updates':
if len(sys.argv) != 4:
help()
a = sys.argv[2]
b = sys.argv[3]
findUpdates(readTree(a), scanTreeState(b))
else:
print("Unknown command: {}".format(sys.argv[1]))
help()