3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
8 from errno import EACCES
10 import os, sys, stat, time, math
12 from bup import hashsplit, git, options, index, client, metadata, hlinkdb
13 from bup.hashsplit import GIT_MODE_TREE, GIT_MODE_FILE, GIT_MODE_SYMLINK
14 from bup.helpers import (add_error, grafted_path_components, handle_ctrl_c,
15 istty2, log, parse_date_or_fatal, parse_num,
16 path_components, progress, qprogress, resolve_parent,
17 saved_errors, stripped_path_components)
21 bup save [-tc] [-n name] <filenames...>
23 r,remote= hostname:/path/to/repo of remote repository
24 t,tree output a tree id
25 c,commit output a commit id
26 n,name= name of backup set to update (if any)
27 d,date= date for the commit (seconds since the epoch)
28 v,verbose increase log output (can be used more than once)
29 q,quiet don't show progress meter
30 smaller= only back up files smaller than n bytes
31 bwlimit= maximum bytes/sec to transmit to server
32 f,indexfile= the name of the index file (normally BUP_DIR/bupindex)
33 strip strips the path to every filename given
34 strip-path= path-prefix to be stripped when saving
35 graft= a graft point *old_path*=*new_path* (can be used more than once)
36 #,compress= set compression level to # (0-9, 9 is highest) [1]
38 o = options.Options(optspec)
39 (opt, flags, extra) = o.parse(sys.argv[1:])
41 git.check_repo_or_die()
42 if not (opt.tree or opt.commit or opt.name):
43 o.fatal("use one or more of -t, -c, -n")
45 o.fatal("no filenames given")
47 opt.progress = (istty2 and not opt.quiet)
48 opt.smaller = parse_num(opt.smaller or 0)
50 client.bwlimit = parse_num(opt.bwlimit)
53 date = parse_date_or_fatal(opt.date, o.fatal)
57 if opt.strip and opt.strip_path:
58 o.fatal("--strip is incompatible with --strip-path")
63 o.fatal("--strip is incompatible with --graft")
66 o.fatal("--strip-path is incompatible with --graft")
68 for (option, parameter) in flags:
69 if option == "--graft":
70 splitted_parameter = parameter.split('=')
71 if len(splitted_parameter) != 2:
72 o.fatal("a graft point must be of the form old_path=new_path")
73 old_path, new_path = splitted_parameter
74 if not (old_path and new_path):
75 o.fatal("a graft point cannot be empty")
76 graft_points.append((resolve_parent(old_path),
77 resolve_parent(new_path)))
79 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
80 if is_reverse and opt.remote:
81 o.fatal("don't use -r in reverse mode; it's automatic")
83 if opt.name and opt.name.startswith('.'):
84 o.fatal("'%s' is not a valid branch name" % opt.name)
85 refname = opt.name and 'refs/heads/%s' % opt.name or None
86 if opt.remote or is_reverse:
88 cli = client.Client(opt.remote)
89 except client.ClientError as e:
92 oldref = refname and cli.read_ref(refname) or None
93 w = cli.new_packwriter(compression_level=opt.compress)
96 oldref = refname and git.read_ref(refname) or None
97 w = git.PackWriter(compression_level=opt.compress)
103 if dir.endswith('/'):
109 # Metadata is stored in a file named .bupm in each directory. The
110 # first metadata entry will be the metadata for the current directory.
111 # The remaining entries will be for each of the other directory
112 # elements, in the order they're listed in the index.
114 # Since the git tree elements are sorted according to
115 # git.shalist_item_sort_key, the metalist items are accumulated as
116 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
117 # created. The sort_key must be computed using the element's real
118 # name and mode rather than the git mode and (possibly mangled) name.
120 # Maintain a stack of information representing the current location in
121 # the archive being constructed. The current path is recorded in
122 # parts, which will be something like ['', 'home', 'someuser'], and
123 # the accumulated content and metadata for of the dirs in parts is
124 # stored in parallel stacks in shalists and metalists.
126 parts = [] # Current archive position (stack of dir names).
127 shalists = [] # Hashes for each dir in paths.
128 metalists = [] # Metadata for each dir in paths.
131 def _push(part, metadata):
132 # Enter a new archive directory -- make it the current directory.
135 metalists.append([('', metadata)]) # This dir's metadata (no name).
138 def _pop(force_tree, dir_metadata=None):
139 # Leave the current archive directory and add its tree to its parent.
140 assert(len(parts) >= 1)
142 shalist = shalists.pop()
143 metalist = metalists.pop()
144 if metalist and not force_tree:
145 if dir_metadata: # Override the original metadata pushed for this dir.
146 metalist = [('', dir_metadata)] + metalist[1:]
147 sorted_metalist = sorted(metalist, key = lambda x : x[0])
148 metadata = ''.join([m[1].encode() for m in sorted_metalist])
149 metadata_f = BytesIO(metadata)
150 mode, id = hashsplit.split_to_blob_or_tree(w.new_blob, w.new_tree,
152 keep_boundaries=False)
153 shalist.append((mode, '.bupm', id))
154 # FIXME: only test if collision is possible (i.e. given --strip, etc.)?
162 if name in names_seen:
163 parent_path = '/'.join(parts) + '/'
164 add_error('error: ignoring duplicate path %r in %r'
165 % (name, parent_path))
169 tree = w.new_tree(clean_list)
171 shalists[-1].append((GIT_MODE_TREE,
172 git.mangle_name(part,
173 GIT_MODE_TREE, GIT_MODE_TREE),
179 def progress_report(n):
180 global count, subcount, lastremain
182 cc = count + subcount
183 pct = total and (cc*100.0/total) or 0
185 elapsed = now - tstart
186 kps = elapsed and int(cc/1024./elapsed)
187 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
188 kps = int(kps/kps_frac)*kps_frac
190 remain = elapsed*1.0/cc * (total-cc)
193 if (lastremain and (remain > lastremain)
194 and ((remain - lastremain)/lastremain < 0.05)):
198 hours = int(remain/60/60)
199 mins = int(remain/60 - hours*60)
200 secs = int(remain - hours*60*60 - mins*60)
205 kpsstr = '%dk/s' % kps
207 remainstr = '%dh%dm' % (hours, mins)
209 remainstr = '%dm%d' % (mins, secs)
211 remainstr = '%ds' % secs
212 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
213 % (pct, cc/1024, total/1024, fcount, ftotal,
217 indexfile = opt.indexfile or git.repo('bupindex')
218 r = index.Reader(indexfile)
220 msr = index.MetaStoreReader(indexfile + '.meta')
221 except IOError as ex:
222 if ex.errno != EACCES:
224 log('error: cannot access %r; have you run bup index?' % indexfile)
226 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
228 def already_saved(ent):
229 return ent.is_valid() and w.exists(ent.sha) and ent.sha
231 def wantrecurse_pre(ent):
232 return not already_saved(ent)
234 def wantrecurse_during(ent):
235 return not already_saved(ent) or ent.sha_missing()
237 def find_hardlink_target(hlink_db, ent):
238 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
239 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
245 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
246 if not (ftotal % 10024):
247 qprogress('Reading index: %d\r' % ftotal)
248 exists = ent.exists()
249 hashvalid = already_saved(ent)
250 ent.set_sha_missing(not hashvalid)
251 if not opt.smaller or ent.size < opt.smaller:
252 if exists and not hashvalid:
255 progress('Reading index: %d, done.\n' % ftotal)
256 hashsplit.progress_callback = progress_report
258 # Root collisions occur when strip or graft options map more than one
259 # path to the same directory (paths which originally had separate
260 # parents). When that situation is detected, use empty metadata for
261 # the parent. Otherwise, use the metadata for the common parent.
262 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
264 # FIXME: Add collision tests, or handle collisions some other way.
266 # FIXME: Detect/handle strip/graft name collisions (other than root),
267 # i.e. if '/foo/bar' and '/bar' both map to '/'.
270 root_collision = None
272 count = subcount = fcount = 0
275 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
276 (dir, file) = os.path.split(ent.name)
277 exists = (ent.flags & index.IX_EXISTS)
278 hashvalid = already_saved(ent)
279 wasmissing = ent.sha_missing()
285 if ent.sha == index.EMPTY_SHA:
292 log('%s %-70s\n' % (status, ent.name))
293 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
294 if not lastdir.startswith(dir):
295 log('%s %-70s\n' % (status, os.path.join(dir, '')))
304 if opt.smaller and ent.size >= opt.smaller:
305 if exists and not hashvalid:
307 log('skipping large file "%s"\n' % ent.name)
308 lastskip_name = ent.name
311 assert(dir.startswith('/'))
313 dirp = stripped_path_components(dir, extra)
315 dirp = stripped_path_components(dir, [opt.strip_path])
317 dirp = grafted_path_components(graft_points, dir)
319 dirp = path_components(dir)
321 # At this point, dirp contains a representation of the archive
322 # path that looks like [(archive_dir_name, real_fs_path), ...].
323 # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
324 # might look like this at some point:
325 # [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
327 # This dual representation supports stripping/grafting, where the
328 # archive path may not have a direct correspondence with the
329 # filesystem. The root directory is represented by an initial
330 # component named '', and any component that doesn't have a
331 # corresponding filesystem directory (due to grafting, for
332 # example) will have a real_fs_path of None, i.e. [('', None),
335 if first_root == None:
337 elif first_root != dirp[0]:
338 root_collision = True
340 # If switching to a new sub-tree, finish the current sub-tree.
341 while parts > [x[0] for x in dirp]:
342 _pop(force_tree = None)
344 # If switching to a new sub-tree, start a new sub-tree.
345 for path_component in dirp[len(parts):]:
346 dir_name, fs_path = path_component
347 # Not indexed, so just grab the FS metadata or use empty metadata.
349 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
350 except (OSError, IOError) as e:
352 lastskip_name = dir_name
353 meta = metadata.Metadata()
354 _push(dir_name, meta)
358 continue # We're at the top level -- keep the current root dir
359 # Since there's no filename, this is a subdir -- finish it.
360 oldtree = already_saved(ent) # may be None
361 newtree = _pop(force_tree = oldtree)
363 if lastskip_name and lastskip_name.startswith(ent.name):
366 ent.validate(GIT_MODE_TREE, newtree)
368 if exists and wasmissing:
372 # it's not a directory
376 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
377 git_info = (ent.gitmode, git_name, id)
378 shalists[-1].append(git_info)
379 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
380 meta = msr.metadata_at(ent.meta_ofs)
381 meta.hardlink_target = find_hardlink_target(hlink_db, ent)
382 # Restore the times that were cleared to 0 in the metastore.
383 (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
384 metalists[-1].append((sort_key, meta))
386 if stat.S_ISREG(ent.mode):
388 f = hashsplit.open_noatime(ent.name)
389 except (IOError, OSError) as e:
391 lastskip_name = ent.name
394 (mode, id) = hashsplit.split_to_blob_or_tree(
395 w.new_blob, w.new_tree, [f],
396 keep_boundaries=False)
397 except (IOError, OSError) as e:
398 add_error('%s: %s' % (ent.name, e))
399 lastskip_name = ent.name
401 if stat.S_ISDIR(ent.mode):
402 assert(0) # handled above
403 elif stat.S_ISLNK(ent.mode):
405 rl = os.readlink(ent.name)
406 except (OSError, IOError) as e:
408 lastskip_name = ent.name
410 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
412 # Everything else should be fully described by its
413 # metadata, so just record an empty blob, so the paths
414 # in the tree and .bupm will match up.
415 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
418 ent.validate(mode, id)
420 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
421 git_info = (mode, git_name, id)
422 shalists[-1].append(git_info)
423 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
424 hlink = find_hardlink_target(hlink_db, ent)
426 meta = metadata.from_path(ent.name, hardlink_target=hlink)
427 except (OSError, IOError) as e:
429 lastskip_name = ent.name
431 metalists[-1].append((sort_key, meta))
433 if exists and wasmissing:
439 pct = total and count*100.0/total or 100
440 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
441 % (pct, count/1024, total/1024, fcount, ftotal))
443 while len(parts) > 1: # _pop() all the parts above the root
444 _pop(force_tree = None)
445 assert(len(shalists) == 1)
446 assert(len(metalists) == 1)
448 # Finish the root directory.
449 tree = _pop(force_tree = None,
450 # When there's a collision, use empty metadata for the root.
451 dir_metadata = metadata.Metadata() if root_collision else None)
454 print tree.encode('hex')
455 if opt.commit or opt.name:
456 msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
457 commit = w.new_commit(oldref, tree, date, msg)
459 print commit.encode('hex')
462 w.close() # must close before we can update the ref
466 cli.update_ref(refname, commit, oldref)
468 git.update_ref(refname, commit, oldref)
474 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))