3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
7 import sys, stat, time, math
8 from errno import EACCES
11 from bup import hashsplit, git, options, index, client, metadata, hlinkdb
12 from bup.helpers import *
13 from bup.hashsplit import GIT_MODE_TREE, GIT_MODE_FILE, GIT_MODE_SYMLINK
17 bup save [-tc] [-n name] <filenames...>
19 r,remote= hostname:/path/to/repo of remote repository
20 t,tree output a tree id
21 c,commit output a commit id
22 n,name= name of backup set to update (if any)
23 d,date= date for the commit (seconds since the epoch)
24 v,verbose increase log output (can be used more than once)
25 q,quiet don't show progress meter
26 smaller= only back up files smaller than n bytes
27 bwlimit= maximum bytes/sec to transmit to server
28 f,indexfile= the name of the index file (normally BUP_DIR/bupindex)
29 strip strips the path to every filename given
30 strip-path= path-prefix to be stripped when saving
31 graft= a graft point *old_path*=*new_path* (can be used more than once)
32 #,compress= set compression level to # (0-9, 9 is highest) [1]
34 o = options.Options(optspec)
35 (opt, flags, extra) = o.parse(sys.argv[1:])
37 git.check_repo_or_die()
38 if not (opt.tree or opt.commit or opt.name):
39 o.fatal("use one or more of -t, -c, -n")
41 o.fatal("no filenames given")
43 opt.progress = (istty2 and not opt.quiet)
44 opt.smaller = parse_num(opt.smaller or 0)
46 client.bwlimit = parse_num(opt.bwlimit)
49 date = parse_date_or_fatal(opt.date, o.fatal)
53 if opt.strip and opt.strip_path:
54 o.fatal("--strip is incompatible with --strip-path")
59 o.fatal("--strip is incompatible with --graft")
62 o.fatal("--strip-path is incompatible with --graft")
64 for (option, parameter) in flags:
65 if option == "--graft":
66 splitted_parameter = parameter.split('=')
67 if len(splitted_parameter) != 2:
68 o.fatal("a graft point must be of the form old_path=new_path")
69 old_path, new_path = splitted_parameter
70 if not (old_path and new_path):
71 o.fatal("a graft point cannot be empty")
72 graft_points.append((resolve_parent(old_path),
73 resolve_parent(new_path)))
75 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
76 if is_reverse and opt.remote:
77 o.fatal("don't use -r in reverse mode; it's automatic")
79 if opt.name and opt.name.startswith('.'):
80 o.fatal("'%s' is not a valid branch name" % opt.name)
81 refname = opt.name and 'refs/heads/%s' % opt.name or None
82 if opt.remote or is_reverse:
84 cli = client.Client(opt.remote)
85 except client.ClientError as e:
88 oldref = refname and cli.read_ref(refname) or None
89 w = cli.new_packwriter(compression_level=opt.compress)
92 oldref = refname and git.read_ref(refname) or None
93 w = git.PackWriter(compression_level=opt.compress)
105 # Metadata is stored in a file named .bupm in each directory. The
106 # first metadata entry will be the metadata for the current directory.
107 # The remaining entries will be for each of the other directory
108 # elements, in the order they're listed in the index.
110 # Since the git tree elements are sorted according to
111 # git.shalist_item_sort_key, the metalist items are accumulated as
112 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
113 # created. The sort_key must be computed using the element's real
114 # name and mode rather than the git mode and (possibly mangled) name.
116 # Maintain a stack of information representing the current location in
117 # the archive being constructed. The current path is recorded in
118 # parts, which will be something like ['', 'home', 'someuser'], and
119 # the accumulated content and metadata for of the dirs in parts is
120 # stored in parallel stacks in shalists and metalists.
122 parts = [] # Current archive position (stack of dir names).
123 shalists = [] # Hashes for each dir in paths.
124 metalists = [] # Metadata for each dir in paths.
127 def _push(part, metadata):
128 # Enter a new archive directory -- make it the current directory.
131 metalists.append([('', metadata)]) # This dir's metadata (no name).
134 def _pop(force_tree, dir_metadata=None):
135 # Leave the current archive directory and add its tree to its parent.
136 assert(len(parts) >= 1)
138 shalist = shalists.pop()
139 metalist = metalists.pop()
140 if metalist and not force_tree:
141 if dir_metadata: # Override the original metadata pushed for this dir.
142 metalist = [('', dir_metadata)] + metalist[1:]
143 sorted_metalist = sorted(metalist, key = lambda x : x[0])
144 metadata = ''.join([m[1].encode() for m in sorted_metalist])
145 metadata_f = BytesIO(metadata)
146 mode, id = hashsplit.split_to_blob_or_tree(w.new_blob, w.new_tree,
148 keep_boundaries=False)
149 shalist.append((mode, '.bupm', id))
150 # FIXME: only test if collision is possible (i.e. given --strip, etc.)?
158 if name in names_seen:
159 parent_path = '/'.join(parts) + '/'
160 add_error('error: ignoring duplicate path %r in %r'
161 % (name, parent_path))
165 tree = w.new_tree(clean_list)
167 shalists[-1].append((GIT_MODE_TREE,
168 git.mangle_name(part,
169 GIT_MODE_TREE, GIT_MODE_TREE),
175 def progress_report(n):
176 global count, subcount, lastremain
178 cc = count + subcount
179 pct = total and (cc*100.0/total) or 0
181 elapsed = now - tstart
182 kps = elapsed and int(cc/1024./elapsed)
183 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
184 kps = int(kps/kps_frac)*kps_frac
186 remain = elapsed*1.0/cc * (total-cc)
189 if (lastremain and (remain > lastremain)
190 and ((remain - lastremain)/lastremain < 0.05)):
194 hours = int(remain/60/60)
195 mins = int(remain/60 - hours*60)
196 secs = int(remain - hours*60*60 - mins*60)
201 kpsstr = '%dk/s' % kps
203 remainstr = '%dh%dm' % (hours, mins)
205 remainstr = '%dm%d' % (mins, secs)
207 remainstr = '%ds' % secs
208 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
209 % (pct, cc/1024, total/1024, fcount, ftotal,
213 indexfile = opt.indexfile or git.repo('bupindex')
214 r = index.Reader(indexfile)
216 msr = index.MetaStoreReader(indexfile + '.meta')
217 except IOError as ex:
218 if ex.errno != EACCES:
220 log('error: cannot access %r; have you run bup index?' % indexfile)
222 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
224 def already_saved(ent):
225 return ent.is_valid() and w.exists(ent.sha) and ent.sha
227 def wantrecurse_pre(ent):
228 return not already_saved(ent)
230 def wantrecurse_during(ent):
231 return not already_saved(ent) or ent.sha_missing()
233 def find_hardlink_target(hlink_db, ent):
234 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
235 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
241 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
242 if not (ftotal % 10024):
243 qprogress('Reading index: %d\r' % ftotal)
244 exists = ent.exists()
245 hashvalid = already_saved(ent)
246 ent.set_sha_missing(not hashvalid)
247 if not opt.smaller or ent.size < opt.smaller:
248 if exists and not hashvalid:
251 progress('Reading index: %d, done.\n' % ftotal)
252 hashsplit.progress_callback = progress_report
254 # Root collisions occur when strip or graft options map more than one
255 # path to the same directory (paths which originally had separate
256 # parents). When that situation is detected, use empty metadata for
257 # the parent. Otherwise, use the metadata for the common parent.
258 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
260 # FIXME: Add collision tests, or handle collisions some other way.
262 # FIXME: Detect/handle strip/graft name collisions (other than root),
263 # i.e. if '/foo/bar' and '/bar' both map to '/'.
266 root_collision = None
268 count = subcount = fcount = 0
271 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
272 (dir, file) = os.path.split(ent.name)
273 exists = (ent.flags & index.IX_EXISTS)
274 hashvalid = already_saved(ent)
275 wasmissing = ent.sha_missing()
281 if ent.sha == index.EMPTY_SHA:
288 log('%s %-70s\n' % (status, ent.name))
289 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
290 if not lastdir.startswith(dir):
291 log('%s %-70s\n' % (status, os.path.join(dir, '')))
300 if opt.smaller and ent.size >= opt.smaller:
301 if exists and not hashvalid:
303 log('skipping large file "%s"\n' % ent.name)
304 lastskip_name = ent.name
307 assert(dir.startswith('/'))
309 dirp = stripped_path_components(dir, extra)
311 dirp = stripped_path_components(dir, [opt.strip_path])
313 dirp = grafted_path_components(graft_points, dir)
315 dirp = path_components(dir)
317 # At this point, dirp contains a representation of the archive
318 # path that looks like [(archive_dir_name, real_fs_path), ...].
319 # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
320 # might look like this at some point:
321 # [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
323 # This dual representation supports stripping/grafting, where the
324 # archive path may not have a direct correspondence with the
325 # filesystem. The root directory is represented by an initial
326 # component named '', and any component that doesn't have a
327 # corresponding filesystem directory (due to grafting, for
328 # example) will have a real_fs_path of None, i.e. [('', None),
331 if first_root == None:
333 elif first_root != dirp[0]:
334 root_collision = True
336 # If switching to a new sub-tree, finish the current sub-tree.
337 while parts > [x[0] for x in dirp]:
338 _pop(force_tree = None)
340 # If switching to a new sub-tree, start a new sub-tree.
341 for path_component in dirp[len(parts):]:
342 dir_name, fs_path = path_component
343 # Not indexed, so just grab the FS metadata or use empty metadata.
345 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
346 except (OSError, IOError) as e:
348 lastskip_name = dir_name
349 meta = metadata.Metadata()
350 _push(dir_name, meta)
354 continue # We're at the top level -- keep the current root dir
355 # Since there's no filename, this is a subdir -- finish it.
356 oldtree = already_saved(ent) # may be None
357 newtree = _pop(force_tree = oldtree)
359 if lastskip_name and lastskip_name.startswith(ent.name):
362 ent.validate(GIT_MODE_TREE, newtree)
364 if exists and wasmissing:
368 # it's not a directory
372 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
373 git_info = (ent.gitmode, git_name, id)
374 shalists[-1].append(git_info)
375 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
376 meta = msr.metadata_at(ent.meta_ofs)
377 meta.hardlink_target = find_hardlink_target(hlink_db, ent)
378 # Restore the times that were cleared to 0 in the metastore.
379 (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
380 metalists[-1].append((sort_key, meta))
382 if stat.S_ISREG(ent.mode):
384 f = hashsplit.open_noatime(ent.name)
385 except (IOError, OSError) as e:
387 lastskip_name = ent.name
390 (mode, id) = hashsplit.split_to_blob_or_tree(
391 w.new_blob, w.new_tree, [f],
392 keep_boundaries=False)
393 except (IOError, OSError) as e:
394 add_error('%s: %s' % (ent.name, e))
395 lastskip_name = ent.name
397 if stat.S_ISDIR(ent.mode):
398 assert(0) # handled above
399 elif stat.S_ISLNK(ent.mode):
401 rl = os.readlink(ent.name)
402 except (OSError, IOError) as e:
404 lastskip_name = ent.name
406 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
408 # Everything else should be fully described by its
409 # metadata, so just record an empty blob, so the paths
410 # in the tree and .bupm will match up.
411 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
414 ent.validate(mode, id)
416 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
417 git_info = (mode, git_name, id)
418 shalists[-1].append(git_info)
419 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
420 hlink = find_hardlink_target(hlink_db, ent)
422 meta = metadata.from_path(ent.name, hardlink_target=hlink)
423 except (OSError, IOError) as e:
425 lastskip_name = ent.name
427 metalists[-1].append((sort_key, meta))
429 if exists and wasmissing:
435 pct = total and count*100.0/total or 100
436 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
437 % (pct, count/1024, total/1024, fcount, ftotal))
439 while len(parts) > 1: # _pop() all the parts above the root
440 _pop(force_tree = None)
441 assert(len(shalists) == 1)
442 assert(len(metalists) == 1)
444 # Finish the root directory.
445 tree = _pop(force_tree = None,
446 # When there's a collision, use empty metadata for the root.
447 dir_metadata = metadata.Metadata() if root_collision else None)
450 print tree.encode('hex')
451 if opt.commit or opt.name:
452 msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
453 commit = w.new_commit(oldref, tree, date, msg)
455 print commit.encode('hex')
458 w.close() # must close before we can update the ref
462 cli.update_ref(refname, commit, oldref)
464 git.update_ref(refname, commit, oldref)
470 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))