2 import sys, stat, time, math
3 from bup import hashsplit, git, options, index, client, metadata, hlinkdb
4 from bup.helpers import *
5 from bup.hashsplit import GIT_MODE_TREE, GIT_MODE_FILE, GIT_MODE_SYMLINK
9 bup save [-tc] [-n name] <filenames...>
11 r,remote= hostname:/path/to/repo of remote repository
12 t,tree output a tree id
13 c,commit output a commit id
14 n,name= name of backup set to update (if any)
15 d,date= date for the commit (seconds since the epoch)
16 v,verbose increase log output (can be used more than once)
17 q,quiet don't show progress meter
18 smaller= only back up files smaller than n bytes
19 bwlimit= maximum bytes/sec to transmit to server
20 f,indexfile= the name of the index file (normally BUP_DIR/bupindex)
21 strip strips the path to every filename given
22 strip-path= path-prefix to be stripped when saving
23 graft= a graft point *old_path*=*new_path* (can be used more than once)
24 #,compress= set compression level to # (0-9, 9 is highest) [1]
26 o = options.Options(optspec)
27 (opt, flags, extra) = o.parse(sys.argv[1:])
29 git.check_repo_or_die()
30 if not (opt.tree or opt.commit or opt.name):
31 o.fatal("use one or more of -t, -c, -n")
33 o.fatal("no filenames given")
35 opt.progress = (istty2 and not opt.quiet)
36 opt.smaller = parse_num(opt.smaller or 0)
38 client.bwlimit = parse_num(opt.bwlimit)
41 date = parse_date_or_fatal(opt.date, o.fatal)
45 if opt.strip and opt.strip_path:
46 o.fatal("--strip is incompatible with --strip-path")
51 o.fatal("--strip is incompatible with --graft")
54 o.fatal("--strip-path is incompatible with --graft")
56 for (option, parameter) in flags:
57 if option == "--graft":
58 splitted_parameter = parameter.split('=')
59 if len(splitted_parameter) != 2:
60 o.fatal("a graft point must be of the form old_path=new_path")
61 old_path, new_path = splitted_parameter
62 if not (old_path and new_path):
63 o.fatal("a graft point cannot be empty")
64 graft_points.append((realpath(old_path), realpath(new_path)))
66 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
67 if is_reverse and opt.remote:
68 o.fatal("don't use -r in reverse mode; it's automatic")
70 if opt.name and opt.name.startswith('.'):
71 o.fatal("'%s' is not a valid branch name" % opt.name)
72 refname = opt.name and 'refs/heads/%s' % opt.name or None
73 if opt.remote or is_reverse:
74 cli = client.Client(opt.remote)
75 oldref = refname and cli.read_ref(refname) or None
76 w = cli.new_packwriter()
79 oldref = refname and git.read_ref(refname) or None
80 w = git.PackWriter(compression_level=opt.compress)
92 # Metadata is stored in a file named .bupm in each directory. The
93 # first metadata entry will be the metadata for the current directory.
94 # The remaining entries will be for each of the other directory
95 # elements, in the order they're listed in the index.
97 # Since the git tree elements are sorted according to
98 # git.shalist_item_sort_key, the metalist items are accumulated as
99 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
100 # created. The sort_key must be computed using the element's real
101 # name and mode rather than the git mode and (possibly mangled) name.
107 def _push(part, metadata):
111 # First entry is dir metadata, which is represented with an empty name.
112 metalists.append([('', metadata)])
114 def _pop(force_tree):
115 assert(len(parts) >= 1)
117 shalist = shalists.pop()
118 metalist = metalists.pop()
120 sorted_metalist = sorted(metalist, key = lambda x : x[0])
121 metadata = ''.join([m[1].encode() for m in sorted_metalist])
122 shalist.append((0100644, '.bupm', w.new_blob(metadata)))
123 tree = force_tree or w.new_tree(shalist)
125 shalists[-1].append((GIT_MODE_TREE,
126 git.mangle_name(part,
127 GIT_MODE_TREE, GIT_MODE_TREE),
130 # This was the toplevel, so put it back for sanity (i.e. cd .. from /).
131 shalists.append(shalist)
132 metalists.append(metalist)
136 def progress_report(n):
137 global count, subcount, lastremain
139 cc = count + subcount
140 pct = total and (cc*100.0/total) or 0
142 elapsed = now - tstart
143 kps = elapsed and int(cc/1024./elapsed)
144 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
145 kps = int(kps/kps_frac)*kps_frac
147 remain = elapsed*1.0/cc * (total-cc)
150 if (lastremain and (remain > lastremain)
151 and ((remain - lastremain)/lastremain < 0.05)):
155 hours = int(remain/60/60)
156 mins = int(remain/60 - hours*60)
157 secs = int(remain - hours*60*60 - mins*60)
162 kpsstr = '%dk/s' % kps
164 remainstr = '%dh%dm' % (hours, mins)
166 remainstr = '%dm%d' % (mins, secs)
168 remainstr = '%ds' % secs
169 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
170 % (pct, cc/1024, total/1024, fcount, ftotal,
174 indexfile = opt.indexfile or git.repo('bupindex')
175 r = index.Reader(indexfile)
176 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
178 def already_saved(ent):
179 return ent.is_valid() and w.exists(ent.sha) and ent.sha
181 def wantrecurse_pre(ent):
182 return not already_saved(ent)
184 def wantrecurse_during(ent):
185 return not already_saved(ent) or ent.sha_missing()
187 def find_hardlink_target(hlink_db, ent):
188 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
189 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
195 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
196 if not (ftotal % 10024):
197 qprogress('Reading index: %d\r' % ftotal)
198 exists = ent.exists()
199 hashvalid = already_saved(ent)
200 ent.set_sha_missing(not hashvalid)
201 if not opt.smaller or ent.size < opt.smaller:
202 if exists and not hashvalid:
205 progress('Reading index: %d, done.\n' % ftotal)
206 hashsplit.progress_callback = progress_report
209 count = subcount = fcount = 0
212 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
213 (dir, file) = os.path.split(ent.name)
214 exists = (ent.flags & index.IX_EXISTS)
215 hashvalid = already_saved(ent)
216 wasmissing = ent.sha_missing()
222 if ent.sha == index.EMPTY_SHA:
229 log('%s %-70s\n' % (status, ent.name))
230 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
231 if not lastdir.startswith(dir):
232 log('%s %-70s\n' % (status, os.path.join(dir, '')))
241 if opt.smaller and ent.size >= opt.smaller:
242 if exists and not hashvalid:
243 add_error('skipping large file "%s"' % ent.name)
244 lastskip_name = ent.name
247 assert(dir.startswith('/'))
249 dirp = stripped_path_components(dir, extra)
251 dirp = stripped_path_components(dir, [opt.strip_path])
253 dirp = grafted_path_components(graft_points, dir)
255 dirp = path_components(dir)
257 while parts > [x[0] for x in dirp]:
258 _pop(force_tree = None)
261 for path_component in dirp[len(parts):]:
262 dir_name, fs_path = path_component
264 meta = metadata.from_path(fs_path)
266 meta = metadata.Metadata()
267 _push(dir_name, meta)
270 # no filename portion means this is a subdir. But
271 # sub/parentdirectories already handled in the pop/push() part above.
272 oldtree = already_saved(ent) # may be None
273 newtree = _pop(force_tree = oldtree)
275 if lastskip_name and lastskip_name.startswith(ent.name):
278 ent.validate(GIT_MODE_TREE, newtree)
280 if exists and wasmissing:
284 # it's not a directory
288 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
289 git_info = (ent.gitmode, git_name, id)
290 shalists[-1].append(git_info)
291 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
292 hlink = find_hardlink_target(hlink_db, ent)
293 metalists[-1].append((sort_key,
294 metadata.from_path(ent.name,
295 hardlink_target=hlink)))
297 if stat.S_ISREG(ent.mode):
299 f = hashsplit.open_noatime(ent.name)
300 except (IOError, OSError), e:
302 lastskip_name = ent.name
305 (mode, id) = hashsplit.split_to_blob_or_tree(
306 w.new_blob, w.new_tree, [f],
307 keep_boundaries=False)
308 except (IOError, OSError), e:
309 add_error('%s: %s' % (ent.name, e))
310 lastskip_name = ent.name
312 if stat.S_ISDIR(ent.mode):
313 assert(0) # handled above
314 elif stat.S_ISLNK(ent.mode):
316 rl = os.readlink(ent.name)
317 except (OSError, IOError), e:
319 lastskip_name = ent.name
321 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
323 # Everything else should be fully described by its
324 # metadata, so just record an empty blob, so the paths
325 # in the tree and .bupm will match up.
326 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
329 ent.validate(mode, id)
331 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
332 git_info = (mode, git_name, id)
333 shalists[-1].append(git_info)
334 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
335 hlink = find_hardlink_target(hlink_db, ent)
336 metalists[-1].append((sort_key,
337 metadata.from_path(ent.name,
338 hardlink_target=hlink)))
339 if exists and wasmissing:
345 pct = total and count*100.0/total or 100
346 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
347 % (pct, count/1024, total/1024, fcount, ftotal))
349 while len(parts) > 1: # _pop() all the parts above the indexed items.
350 _pop(force_tree = None)
351 assert(len(shalists) == 1)
352 assert(len(metalists) == 1)
354 if not (opt.strip or opt.strip_path or graft_points):
355 # For now, only save metadata for the root directory when there
356 # isn't any path grafting or stripping that might create multiple
358 shalist = shalists[-1]
359 metadata = ''.join([metadata.from_path('/').encode()])
360 shalist.append((0100644, '.bupm', w.new_blob(metadata)))
361 tree = w.new_tree(shalists[-1])
364 print tree.encode('hex')
365 if opt.commit or opt.name:
366 msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
367 commit = w.new_commit(oldref, tree, date, msg)
369 print commit.encode('hex')
371 w.close() # must close before we can update the ref
375 cli.update_ref(refname, commit, oldref)
377 git.update_ref(refname, commit, oldref)
383 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))