]> arthur.barton.de Git - bup.git/blob - cmd/restore-cmd.py
Streamline output: Exception messages
[bup.git] / cmd / restore-cmd.py
1 #!/usr/bin/env python
2 import copy, errno, sys, stat, re
3 from bup import options, git, metadata, vfs
4 from bup.helpers import *
5 from bup._helpers import write_sparsely
6
7 optspec = """
8 bup restore [-C outdir] </branch/revision/path/to/dir ...>
9 --
10 C,outdir=   change to given outdir before extracting files
11 numeric-ids restore numeric IDs (user, group, etc.) rather than names
12 exclude-rx= skip paths matching the unanchored regex (may be repeated)
13 exclude-rx-from= skip --exclude-rx patterns in file (may be repeated)
14 sparse      create sparse files
15 v,verbose   increase log output (can be used more than once)
16 map-user=   given OLD=NEW, restore OLD user as NEW user
17 map-group=  given OLD=NEW, restore OLD group as NEW group
18 map-uid=    given OLD=NEW, restore OLD uid as NEW uid
19 map-gid=    given OLD=NEW, restore OLD gid as NEW gid
20 q,quiet     don't show progress meter
21 """
22
23 total_restored = 0
24
25 # stdout should be flushed after each line, even when not connected to a tty
26 sys.stdout.flush()
27 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
28
29 def verbose1(s):
30     if opt.verbose >= 1:
31         print s
32
33
34 def verbose2(s):
35     if opt.verbose >= 2:
36         print s
37
38
39 def valid_restore_path(path):
40     path = os.path.normpath(path)
41     if path.startswith('/'):
42         path = path[1:]
43     if '/' in path:
44         return True
45
46
47 def print_info(n, fullname):
48     if stat.S_ISDIR(n.mode):
49         verbose1('%s/' % fullname)
50     elif stat.S_ISLNK(n.mode):
51         verbose2('%s@ -> %s' % (fullname, n.readlink()))
52     else:
53         verbose2(fullname)
54
55
56 def create_path(n, fullname, meta):
57     if meta:
58         meta.create_path(fullname)
59     else:
60         # These fallbacks are important -- meta could be null if, for
61         # example, save created a "fake" item, i.e. a new strip/graft
62         # path element, etc.  You can find cases like that by
63         # searching for "Metadata()".
64         unlink(fullname)
65         if stat.S_ISDIR(n.mode):
66             mkdirp(fullname)
67         elif stat.S_ISLNK(n.mode):
68             os.symlink(n.readlink(), fullname)
69
70
71 def parse_owner_mappings(type, options, fatal):
72     """Traverse the options and parse all --map-TYPEs, or call Option.fatal()."""
73     opt_name = '--map-' + type
74     value_rx = r'^([^=]+)=([^=]*)$'
75     if type in ('uid', 'gid'):
76         value_rx = r'^(-?[0-9]+)=(-?[0-9]+)$'
77     owner_map = {}
78     for flag in options:
79         (option, parameter) = flag
80         if option != opt_name:
81             continue
82         match = re.match(value_rx, parameter)
83         if not match:
84             raise fatal("Cannot parse %s as %s mapping" % (parameter, type))
85         old_id, new_id = match.groups()
86         if type in ('uid', 'gid'):
87             old_id = int(old_id)
88             new_id = int(new_id)
89         owner_map[old_id] = new_id
90     return owner_map
91
92
93 def apply_metadata(meta, name, restore_numeric_ids, owner_map):
94     m = copy.deepcopy(meta)
95     m.user = owner_map['user'].get(m.user, m.user)
96     m.group = owner_map['group'].get(m.group, m.group)
97     m.uid = owner_map['uid'].get(m.uid, m.uid)
98     m.gid = owner_map['gid'].get(m.gid, m.gid)
99     m.apply_to_path(name, restore_numeric_ids = restore_numeric_ids)
100
101
102 # Track a list of (restore_path, vfs_path, meta) triples for each path
103 # we've written for a given hardlink_target.  This allows us to handle
104 # the case where we restore a set of hardlinks out of order (with
105 # respect to the original save call(s)) -- i.e. when we don't restore
106 # the hardlink_target path first.  This data also allows us to attempt
107 # to handle other situations like hardlink sets that change on disk
108 # during a save, or between index and save.
109 targets_written = {}
110
111 def hardlink_compatible(target_path, target_vfs_path, target_meta,
112                         src_node, src_meta):
113     global top
114     if not os.path.exists(target_path):
115         return False
116     target_node = top.lresolve(target_vfs_path)
117     if src_node.mode != target_node.mode \
118             or src_node.mtime != target_node.mtime \
119             or src_node.ctime != target_node.ctime \
120             or src_node.hash != target_node.hash:
121         return False
122     if not src_meta.same_file(target_meta):
123         return False
124     return True
125
126
127 def hardlink_if_possible(fullname, node, meta):
128     """Find a suitable hardlink target, link to it, and return true,
129     otherwise return false."""
130     # Expect the caller to handle restoring the metadata if
131     # hardlinking isn't possible.
132     global targets_written
133     target = meta.hardlink_target
134     target_versions = targets_written.get(target)
135     if target_versions:
136         # Check every path in the set that we've written so far for a match.
137         for (target_path, target_vfs_path, target_meta) in target_versions:
138             if hardlink_compatible(target_path, target_vfs_path, target_meta,
139                                    node, meta):
140                 try:
141                     os.link(target_path, fullname)
142                     return True
143                 except OSError, e:
144                     if e.errno != errno.EXDEV:
145                         raise
146     else:
147         target_versions = []
148         targets_written[target] = target_versions
149     full_vfs_path = node.fullname()
150     target_versions.append((fullname, full_vfs_path, meta))
151     return False
152
153
154 def write_file_content(fullname, n):
155     outf = open(fullname, 'wb')
156     try:
157         for b in chunkyreader(n.open()):
158             outf.write(b)
159     finally:
160         outf.close()
161
162
163 def write_file_content_sparsely(fullname, n):
164     outfd = os.open(fullname, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0600)
165     try:
166         trailing_zeros = 0;
167         for b in chunkyreader(n.open()):
168             trailing_zeros = write_sparsely(outfd, b, 512, trailing_zeros)
169         pos = os.lseek(outfd, trailing_zeros, os.SEEK_END)
170         os.ftruncate(outfd, pos)
171     finally:
172         os.close(outfd)
173
174
175 def find_dir_item_metadata_by_name(dir, name):
176     """Find metadata in dir (a node) for an item with the given name,
177     or for the directory itself if the name is ''."""
178     meta_stream = None
179     try:
180         mfile = dir.metadata_file() # VFS file -- cannot close().
181         if mfile:
182             meta_stream = mfile.open()
183             # First entry is for the dir itself.
184             meta = metadata.Metadata.read(meta_stream)
185             if name == '':
186                 return meta
187             for sub in dir:
188                 if stat.S_ISDIR(sub.mode):
189                     meta = find_dir_item_metadata_by_name(sub, '')
190                 else:
191                     meta = metadata.Metadata.read(meta_stream)
192                 if sub.name == name:
193                     return meta
194     finally:
195         if meta_stream:
196             meta_stream.close()
197
198
199 def do_root(n, sparse, owner_map, restore_root_meta = True):
200     # Very similar to do_node(), except that this function doesn't
201     # create a path for n's destination directory (and so ignores
202     # n.fullname).  It assumes the destination is '.', and restores
203     # n's metadata and content there.
204     global total_restored, opt
205     meta_stream = None
206     try:
207         # Directory metadata is the first entry in any .bupm file in
208         # the directory.  Get it.
209         mfile = n.metadata_file() # VFS file -- cannot close().
210         root_meta = None
211         if mfile:
212             meta_stream = mfile.open()
213             root_meta = metadata.Metadata.read(meta_stream)
214         print_info(n, '.')
215         total_restored += 1
216         if not opt.quiet:
217             progress_update('Restoring: %d ...' % total_restored, False)
218         for sub in n:
219             m = None
220             # Don't get metadata if this is a dir -- handled in sub do_node().
221             if meta_stream and not stat.S_ISDIR(sub.mode):
222                 m = metadata.Metadata.read(meta_stream)
223             do_node(n, sub, sparse, owner_map, meta = m)
224         if root_meta and restore_root_meta:
225             apply_metadata(root_meta, '.', opt.numeric_ids, owner_map)
226     finally:
227         if meta_stream:
228             meta_stream.close()
229
230 def do_node(top, n, sparse, owner_map, meta = None):
231     # Create n.fullname(), relative to the current directory, and
232     # restore all of its metadata, when available.  The meta argument
233     # will be None for dirs, or when there is no .bupm (i.e. no
234     # metadata).
235     global total_restored, opt
236     meta_stream = None
237     write_content = sparse and write_file_content_sparsely or write_file_content
238     try:
239         fullname = n.fullname(stop_at=top)
240         # Match behavior of index --exclude-rx with respect to paths.
241         exclude_candidate = '/' + fullname
242         if(stat.S_ISDIR(n.mode)):
243             exclude_candidate += '/'
244         if should_rx_exclude_path(exclude_candidate, exclude_rxs):
245             return
246         # If this is a directory, its metadata is the first entry in
247         # any .bupm file inside the directory.  Get it.
248         if(stat.S_ISDIR(n.mode)):
249             mfile = n.metadata_file() # VFS file -- cannot close().
250             if mfile:
251                 meta_stream = mfile.open()
252                 meta = metadata.Metadata.read(meta_stream)
253         print_info(n, fullname)
254
255         created_hardlink = False
256         if meta and meta.hardlink_target:
257             created_hardlink = hardlink_if_possible(fullname, n, meta)
258
259         if not created_hardlink:
260             create_path(n, fullname, meta)
261             if meta:
262                 if stat.S_ISREG(meta.mode):
263                     write_content(fullname, n)
264             elif stat.S_ISREG(n.mode):
265                 write_content(fullname, n)
266
267         total_restored += 1
268         if not opt.quiet:
269             progress_update('Restoring: %d ...' % total_restored, False)
270         for sub in n:
271             m = None
272             # Don't get metadata if this is a dir -- handled in sub do_node().
273             if meta_stream and not stat.S_ISDIR(sub.mode):
274                 m = metadata.Metadata.read(meta_stream)
275             do_node(top, sub, sparse, owner_map, meta = m)
276         if meta and not created_hardlink:
277             apply_metadata(meta, fullname, opt.numeric_ids, owner_map)
278     finally:
279         if meta_stream:
280             meta_stream.close()
281         n.release()
282
283
284 handle_ctrl_c()
285
286 o = options.Options(optspec)
287 (opt, flags, extra) = o.parse(sys.argv[1:])
288
289 git.check_repo_or_die()
290 top = vfs.RefList(None)
291
292 if not extra:
293     o.fatal('must specify at least one filename to restore')
294     
295 exclude_rxs = parse_rx_excludes(flags, o.fatal)
296
297 owner_map = {}
298 for map_type in ('user', 'group', 'uid', 'gid'):
299     owner_map[map_type] = parse_owner_mappings(map_type, flags, o.fatal)
300
301 if opt.outdir:
302     mkdirp(opt.outdir)
303     os.chdir(opt.outdir)
304
305 ret = 0
306 for d in extra:
307     if not valid_restore_path(d):
308         add_error("Error: Path %r doesn't include a branch and revision!" % d)
309         continue
310     path,name = os.path.split(d)
311     try:
312         n = top.lresolve(d)
313     except vfs.NodeError, e:
314         add_error(e)
315         continue
316     isdir = stat.S_ISDIR(n.mode)
317     if not name or name == '.':
318         # Source is /foo/what/ever/ or /foo/what/ever/. -- extract
319         # what/ever/* to the current directory, and if name == '.'
320         # (i.e. /foo/what/ever/.), then also restore what/ever's
321         # metadata to the current directory.
322         if not isdir:
323             add_error('%r: Not a directory!' % d)
324         else:
325             do_root(n, opt.sparse, owner_map, restore_root_meta = (name == '.'))
326     else:
327         # Source is /foo/what/ever -- extract ./ever to cwd.
328         if isinstance(n, vfs.FakeSymlink):
329             # Source is actually /foo/what, i.e. a top-level commit
330             # like /foo/latest, which is a symlink to ../.commit/SHA.
331             # So dereference it, and restore ../.commit/SHA/. to
332             # "./what/.".
333             target = n.dereference()
334             mkdirp(n.name)
335             os.chdir(n.name)
336             do_root(target, opt.sparse, owner_map)
337         else: # Not a directory or fake symlink.
338             meta = find_dir_item_metadata_by_name(n.parent, n.name)
339             do_node(n.parent, n, opt.sparse, owner_map, meta = meta)
340
341 if not opt.quiet:
342     progress_end('Restoring: %d, done.' % total_restored)
343
344 if not check_saved_errors():
345     sys.exit(1)