-
Notifications
You must be signed in to change notification settings - Fork 16
/
changes.py
273 lines (213 loc) · 7.66 KB
/
changes.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#
# Copyright (c) 2010-2013 Liraz Siri <[email protected]>
#
# This file is part of TKLBAM (TurnKey GNU/Linux BAckup and Migration).
#
# TKLBAM is open source software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of
# the License, or (at your option) any later version.
#
import sys
import os
from os.path import *
import types
from dirindex import DirIndex
from pathmap import PathMap
import stat
import errno
import pwd
import grp
class Error(Exception):
pass
def fmt_uid(uid):
try:
return pwd.getpwuid(uid).pw_name
except:
return str(uid)
def fmt_gid(gid):
try:
return grp.getgrgid(gid).gr_name
except:
return str(gid)
class Change:
"""
Example usage::
change = Change.parse(line)
print change
print change.path
if change.OP in ('o', 's'):
print change.uid, change.gid
if change.OP == 's':
print change.mode
# or instead of using OP we can do this
if isinstance(change, Change.Deleted):
assert change.OP == 'd'
"""
class Base:
OP = None
def __init__(self, path):
self.path = path
self._stat = None
def stat(self):
if not self._stat:
self._stat = os.lstat(self.path)
return self._stat
stat = property(stat)
def fmt(self, *args):
return "\t".join([self.OP, self.path] + map(str, args))
def __str__(self):
return self.fmt()
@classmethod
def fromline(cls, line):
args = line.rstrip().split('\t')
return cls(*args)
class Deleted(Base):
OP = 'd'
class Overwrite(Base):
OP = 'o'
def __init__(self, path, uid=None, gid=None):
Change.Base.__init__(self, path)
if uid is None:
self.uid = self.stat.st_uid
else:
self.uid = int(uid)
if gid is None:
self.gid = self.stat.st_gid
else:
self.gid = int(gid)
def __str__(self):
return self.fmt(self.uid, self.gid)
class Stat(Overwrite):
OP = 's'
def __init__(self, path, uid=None, gid=None, mode=None):
Change.Overwrite.__init__(self, path, uid, gid)
if mode is None:
self.mode = self.stat.st_mode
else:
if isinstance(mode, int):
self.mode = mode
else:
self.mode = int(mode, 8)
def __str__(self):
return self.fmt(self.uid, self.gid, oct(self.mode))
@classmethod
def parse(cls, line):
op2class = dict((val.OP, val) for val in cls.__dict__.values()
if isinstance(val, types.ClassType))
op = line[0]
if op not in op2class:
raise Error("illegal change line: " + line)
return op2class[op].fromline(line[2:])
def mkdir(path):
try:
os.makedirs(path)
except OSError, e:
if e.errno != errno.EEXIST:
raise
class Changes(list):
"""
A list of Change instances, which we can load from a file and write
back to a file.
The smarts is in statfixes() and deleted() methods which compare the
list of changes to the current filesystem and yield Action() instances.
Action()s can be printed (e.g., for simulation or verbosity) or called
to run the operation that needs to be performed.
"""
class Action:
def __init__(self, func, *args):
self.func = func
self.args = args
def __call__(self):
return self.func(*self.args)
def __str__(self):
func = self.func
args = self.args
if func is os.lchown:
path, uid, gid = args
return "chown -h %s:%s %s" % (fmt_uid(uid), fmt_gid(gid), path)
elif func is os.chmod:
path, mode = args
return "chmod %s %s" % (oct(mode), path)
elif func is os.remove:
path, = args
return "rm " + path
elif func is mkdir:
path, = args
return "mkdir -p " + path
def __add__(self, other):
cls = type(self)
return cls(list.__add__(self, other))
@classmethod
def fromfile(cls, f, paths=None):
if f == '-':
fh = sys.stdin
else:
fh = file(f)
changes = [ Change.parse(line) for line in fh.readlines() ]
if paths:
pathmap = PathMap(paths)
changes = [ change for change in changes
if change.path in pathmap ]
return cls(changes)
def tofile(self, f):
file(f, "w").writelines((str(change) + "\n" for change in self))
def deleted(self, optimized=True):
for change in self:
if change.OP != 'd':
continue
if optimized:
if not lexists(change.path):
continue
if not islink(change.path) and isdir(change.path):
continue
yield self.Action(os.remove, change.path)
def statfixes(self, uidmap={}, gidmap={}, optimized=True):
class TransparentMap(dict):
def __getitem__(self, key):
if key in self:
return dict.__getitem__(self, key)
return key
uidmap = TransparentMap(uidmap)
gidmap = TransparentMap(gidmap)
for change in self:
if not optimized or not lexists(change.path):
# backwards compat: old backups only stored IMODE in fsdelta, so we assume S_ISDIR
if change.OP == 's' and (stat.S_IMODE(change.mode) == change.mode or stat.S_ISDIR(change.mode)):
yield self.Action(mkdir, change.path)
yield self.Action(os.lchown, change.path, uidmap[change.uid], gidmap[change.gid])
yield self.Action(os.chmod, change.path, stat.S_IMODE(change.mode))
if optimized:
continue
if change.OP == 'd':
continue
# optimization: if not remapped we can skip 'o' changes
if change.OP == 'o' and \
change.uid not in uidmap and change.gid not in gidmap:
continue
st = os.lstat(change.path)
if change.OP in ('s', 'o'):
if not optimized or \
(st.st_uid != uidmap[change.uid] or \
st.st_gid != gidmap[change.gid]):
yield self.Action(os.lchown, change.path,
uidmap[change.uid], gidmap[change.gid])
if change.OP == 's':
if not optimized or \
(not islink(change.path) and \
stat.S_IMODE(st.st_mode) != stat.S_IMODE(change.mode)):
yield self.Action(os.chmod, change.path, stat.S_IMODE(change.mode))
def whatchanged(di_path, paths):
"""Compared current filesystem with a saved dirindex from before.
Returns a Changes() list."""
di_saved = DirIndex(di_path)
di_fs = DirIndex()
di_fs.walk(*paths)
new, edited, statfix = di_saved.diff(di_fs)
changes = Changes()
changes += [ Change.Overwrite(path) for path in new + edited ]
changes += [ Change.Stat(path) for path in statfix ]
di_saved.prune(*paths)
deleted = set(di_saved) - set(di_fs)
changes += [ Change.Deleted(path) for path in deleted ]
return changes