3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
7 export "BUP_ARGV_${arg_i}"="$arg"
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/bup-python" || exit $?
13 exec "$bup_python" "$0"
17 from __future__ import absolute_import
18 from stat import S_ISDIR
19 import copy, errno, os, sys, stat, re
21 from bup import compat, options, git, metadata, vfs
22 from bup._helpers import write_sparsely
23 from bup.compat import argv_bytes, fsencode, wrap_main
24 from bup.helpers import (add_error, chunkyreader, die_if_errors, handle_ctrl_c,
25 log, mkdirp, parse_rx_excludes, progress, qprogress,
26 saved_errors, should_rx_exclude_path, unlink)
27 from bup.io import byte_stream
28 from bup.repo import LocalRepo, RemoteRepo
32 bup restore [-r host:path] [-C outdir] </branch/revision/path/to/dir ...>
34 r,remote= remote repository path
35 C,outdir= change to given outdir before extracting files
36 numeric-ids restore numeric IDs (user, group, etc.) rather than names
37 exclude-rx= skip paths matching the unanchored regex (may be repeated)
38 exclude-rx-from= skip --exclude-rx patterns in file (may be repeated)
39 sparse create sparse files
40 v,verbose increase log output (can be used more than once)
41 map-user= given OLD=NEW, restore OLD user as NEW user
42 map-group= given OLD=NEW, restore OLD group as NEW group
43 map-uid= given OLD=NEW, restore OLD uid as NEW uid
44 map-gid= given OLD=NEW, restore OLD gid as NEW gid
45 q,quiet don't show progress meter
50 # stdout should be flushed after each line, even when not connected to a tty
51 stdoutfd = sys.stdout.fileno()
53 sys.stdout = os.fdopen(stdoutfd, 'w', 1)
54 out = byte_stream(sys.stdout)
56 def valid_restore_path(path):
57 path = os.path.normpath(path)
58 if path.startswith(b'/'):
63 def parse_owner_mappings(type, options, fatal):
64 """Traverse the options and parse all --map-TYPEs, or call Option.fatal()."""
65 opt_name = '--map-' + type
66 if type in ('uid', 'gid'):
67 value_rx = re.compile(br'^(-?[0-9]+)=(-?[0-9]+)$')
69 value_rx = re.compile(br'^([^=]+)=([^=]*)$')
72 (option, parameter) = flag
73 if option != opt_name:
75 parameter = argv_bytes(parameter)
76 match = value_rx.match(parameter)
78 raise fatal("couldn't parse %r as %s mapping" % (parameter, type))
79 old_id, new_id = match.groups()
80 if type in ('uid', 'gid'):
83 owner_map[old_id] = new_id
86 def apply_metadata(meta, name, restore_numeric_ids, owner_map):
87 m = copy.deepcopy(meta)
88 m.user = owner_map['user'].get(m.user, m.user)
89 m.group = owner_map['group'].get(m.group, m.group)
90 m.uid = owner_map['uid'].get(m.uid, m.uid)
91 m.gid = owner_map['gid'].get(m.gid, m.gid)
92 m.apply_to_path(name, restore_numeric_ids = restore_numeric_ids)
94 def hardlink_compatible(prev_path, prev_item, new_item, top):
95 prev_candidate = top + prev_path
96 if not os.path.exists(prev_candidate):
98 prev_meta, new_meta = prev_item.meta, new_item.meta
99 if new_item.oid != prev_item.oid \
100 or new_meta.mtime != prev_meta.mtime \
101 or new_meta.ctime != prev_meta.ctime \
102 or new_meta.mode != prev_meta.mode:
104 # FIXME: should we be checking the path on disk, or the recorded metadata?
105 # The exists() above might seem to suggest the former.
106 if not new_meta.same_file(prev_meta):
110 def hardlink_if_possible(fullname, item, top, hardlinks):
111 """Find a suitable hardlink target, link to it, and return true,
112 otherwise return false."""
113 # The cwd will be dirname(fullname), and fullname will be
114 # absolute, i.e. /foo/bar, and the caller is expected to handle
115 # restoring the metadata if hardlinking isn't possible.
117 # FIXME: we can probably replace the target_vfs_path with the
120 # hardlinks tracks a list of (restore_path, vfs_path, meta)
121 # triples for each path we've written for a given hardlink_target.
122 # This allows us to handle the case where we restore a set of
123 # hardlinks out of order (with respect to the original save
124 # call(s)) -- i.e. when we don't restore the hardlink_target path
125 # first. This data also allows us to attempt to handle other
126 # situations like hardlink sets that change on disk during a save,
127 # or between index and save.
129 target = item.meta.hardlink_target
131 assert(fullname.startswith(b'/'))
132 target_versions = hardlinks.get(target)
134 # Check every path in the set that we've written so far for a match.
135 for prev_path, prev_item in target_versions:
136 if hardlink_compatible(prev_path, prev_item, item, top):
138 os.link(top + prev_path, top + fullname)
141 if e.errno != errno.EXDEV:
145 hardlinks[target] = target_versions
146 target_versions.append((fullname, item))
149 def write_file_content(repo, dest_path, vfs_file):
150 with vfs.fopen(repo, vfs_file) as inf:
151 with open(dest_path, 'wb') as outf:
152 for b in chunkyreader(inf):
155 def write_file_content_sparsely(repo, dest_path, vfs_file):
156 with vfs.fopen(repo, vfs_file) as inf:
157 outfd = os.open(dest_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
160 for b in chunkyreader(inf):
161 trailing_zeros = write_sparsely(outfd, b, 512, trailing_zeros)
162 pos = os.lseek(outfd, trailing_zeros, os.SEEK_END)
163 os.ftruncate(outfd, pos)
167 def restore(repo, parent_path, name, item, top, sparse, numeric_ids, owner_map,
168 exclude_rxs, verbosity, hardlinks):
169 global total_restored
170 mode = vfs.item_mode(item)
171 treeish = S_ISDIR(mode)
172 fullname = parent_path + b'/' + name
173 # Match behavior of index --exclude-rx with respect to paths.
174 if should_rx_exclude_path(fullname + (b'/' if treeish else b''),
179 # Do this now so we'll have meta.symlink_target for verbose output
180 item = vfs.augment_item_meta(repo, item, include_size=True)
182 assert(meta.mode == mode)
184 if stat.S_ISDIR(mode):
186 out.write(b'%s/\n' % fullname)
187 elif stat.S_ISLNK(mode):
188 assert(meta.symlink_target)
190 out.write(b'%s@ -> %s\n' % (fullname, meta.symlink_target))
193 out.write(fullname + '\n')
195 orig_cwd = os.getcwd()
198 # Assumes contents() returns '.' with the full metadata first
199 sub_items = vfs.contents(repo, item, want_meta=True)
200 dot, item = next(sub_items, None)
202 item = vfs.augment_item_meta(repo, item, include_size=True)
204 meta.create_path(name)
208 qprogress('Restoring: %d\r' % total_restored)
209 for sub_name, sub_item in sub_items:
210 restore(repo, fullname, sub_name, sub_item, top, sparse,
211 numeric_ids, owner_map, exclude_rxs, verbosity,
214 apply_metadata(meta, name, numeric_ids, owner_map)
216 created_hardlink = False
217 if meta.hardlink_target:
218 created_hardlink = hardlink_if_possible(fullname, item, top,
220 if not created_hardlink:
221 meta.create_path(name)
222 if stat.S_ISREG(meta.mode):
224 write_file_content_sparsely(repo, name, item)
226 write_file_content(repo, name, item)
229 qprogress('Restoring: %d\r' % total_restored)
230 if not created_hardlink:
231 apply_metadata(meta, name, numeric_ids, owner_map)
236 o = options.Options(optspec)
237 opt, flags, extra = o.parse(compat.argv[1:])
238 verbosity = (opt.verbose or 0) if not opt.quiet else -1
240 opt.remote = argv_bytes(opt.remote)
242 opt.outdir = argv_bytes(opt.outdir)
244 git.check_repo_or_die()
247 o.fatal('must specify at least one filename to restore')
249 exclude_rxs = parse_rx_excludes(flags, o.fatal)
252 for map_type in ('user', 'group', 'uid', 'gid'):
253 owner_map[map_type] = parse_owner_mappings(map_type, flags, o.fatal)
259 repo = RemoteRepo(opt.remote) if opt.remote else LocalRepo()
260 top = fsencode(os.getcwd())
262 for path in [argv_bytes(x) for x in extra]:
263 if not valid_restore_path(path):
264 add_error("path %r doesn't include a branch and revision" % path)
267 resolved = vfs.resolve(repo, path, want_meta=True, follow=False)
268 except vfs.IOError as e:
271 if len(resolved) == 3 and resolved[2][0] == b'latest':
272 # Follow latest symlink to the actual save
274 resolved = vfs.resolve(repo, b'latest', parent=resolved[:-1],
276 except vfs.IOError as e:
279 # Rename it back to 'latest'
280 resolved = tuple(elt if i != 2 else (b'latest',) + elt[1:]
281 for i, elt in enumerate(resolved))
282 path_parent, path_name = os.path.split(path)
283 leaf_name, leaf_item = resolved[-1]
285 add_error('error: cannot access %r in %r'
286 % ('/'.join(name for name, item in resolved),
289 if not path_name or path_name == b'.':
290 # Source is /foo/what/ever/ or /foo/what/ever/. -- extract
291 # what/ever/* to the current directory, and if name == '.'
292 # (i.e. /foo/what/ever/.), then also restore what/ever's
293 # metadata to the current directory.
294 treeish = vfs.item_mode(leaf_item)
296 add_error('%r cannot be restored as a directory' % path)
298 items = vfs.contents(repo, leaf_item, want_meta=True)
299 dot, leaf_item = next(items, None)
301 for sub_name, sub_item in items:
302 restore(repo, b'', sub_name, sub_item, top,
303 opt.sparse, opt.numeric_ids, owner_map,
304 exclude_rxs, verbosity, hardlinks)
305 if path_name == b'.':
306 leaf_item = vfs.augment_item_meta(repo, leaf_item,
308 apply_metadata(leaf_item.meta, b'.',
309 opt.numeric_ids, owner_map)
311 restore(repo, b'', leaf_name, leaf_item, top,
312 opt.sparse, opt.numeric_ids, owner_map,
313 exclude_rxs, verbosity, hardlinks)
316 progress('Restoring: %d, done.\n' % total_restored)