2 import sys, stat, time, math
3 from bup import hashsplit, git, options, index, client, metadata
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 graft_points.append((realpath(splitted_parameter[0]),
62 realpath(splitted_parameter[1])))
64 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
65 if is_reverse and opt.remote:
66 o.fatal("don't use -r in reverse mode; it's automatic")
68 if opt.name and opt.name.startswith('.'):
69 o.fatal("'%s' is not a valid branch name" % opt.name)
70 refname = opt.name and 'refs/heads/%s' % opt.name or None
71 if opt.remote or is_reverse:
72 cli = client.Client(opt.remote)
73 oldref = refname and cli.read_ref(refname) or None
74 w = cli.new_packwriter()
77 oldref = refname and git.read_ref(refname) or None
78 w = git.PackWriter(compression_level=opt.compress)
90 # Metadata is stored in a file named .bupm in each directory. The
91 # first metadata entry will be the metadata for the current directory.
92 # The remaining entries will be for each of the other directory
93 # elements, in the order they're listed in the index.
95 # Since the git tree elements are sorted according to
96 # git.shalist_item_sort_key, the metalist items are accumulated as
97 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
98 # created. The sort_key must be computed using the element's real
99 # name and mode rather than the git mode and (possibly mangled) name.
105 def _push(part, metadata):
109 # First entry is dir metadata, which is represented with an empty name.
110 metalists.append([('', metadata)])
112 def _pop(force_tree):
113 assert(len(parts) >= 1)
115 shalist = shalists.pop()
116 metalist = metalists.pop()
118 sorted_metalist = sorted(metalist, key = lambda x : x[0])
119 metadata = ''.join([m[1].encode() for m in sorted_metalist])
120 shalist.append((0100644, '.bupm', w.new_blob(metadata)))
121 tree = force_tree or w.new_tree(shalist)
123 shalists[-1].append((GIT_MODE_TREE,
124 git.mangle_name(part,
125 GIT_MODE_TREE, GIT_MODE_TREE),
128 # This was the toplevel, so put it back for sanity (i.e. cd .. from /).
129 shalists.append(shalist)
130 metalists.append(metalist)
134 def progress_report(n):
135 global count, subcount, lastremain
137 cc = count + subcount
138 pct = total and (cc*100.0/total) or 0
140 elapsed = now - tstart
141 kps = elapsed and int(cc/1024./elapsed)
142 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
143 kps = int(kps/kps_frac)*kps_frac
145 remain = elapsed*1.0/cc * (total-cc)
148 if (lastremain and (remain > lastremain)
149 and ((remain - lastremain)/lastremain < 0.05)):
153 hours = int(remain/60/60)
154 mins = int(remain/60 - hours*60)
155 secs = int(remain - hours*60*60 - mins*60)
160 kpsstr = '%dk/s' % kps
162 remainstr = '%dh%dm' % (hours, mins)
164 remainstr = '%dm%d' % (mins, secs)
166 remainstr = '%ds' % secs
167 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
168 % (pct, cc/1024, total/1024, fcount, ftotal,
172 indexfile = opt.indexfile or git.repo('bupindex')
173 r = index.Reader(indexfile)
175 def already_saved(ent):
176 return ent.is_valid() and w.exists(ent.sha) and ent.sha
178 def wantrecurse_pre(ent):
179 return not already_saved(ent)
181 def wantrecurse_during(ent):
182 return not already_saved(ent) or ent.sha_missing()
187 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
188 if not (ftotal % 10024):
189 qprogress('Reading index: %d\r' % ftotal)
190 exists = ent.exists()
191 hashvalid = already_saved(ent)
192 ent.set_sha_missing(not hashvalid)
193 if not opt.smaller or ent.size < opt.smaller:
194 if exists and not hashvalid:
197 progress('Reading index: %d, done.\n' % ftotal)
198 hashsplit.progress_callback = progress_report
201 count = subcount = fcount = 0
204 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
205 (dir, file) = os.path.split(ent.name)
206 exists = (ent.flags & index.IX_EXISTS)
207 hashvalid = already_saved(ent)
208 wasmissing = ent.sha_missing()
214 if ent.sha == index.EMPTY_SHA:
221 log('%s %-70s\n' % (status, ent.name))
222 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
223 if not lastdir.startswith(dir):
224 log('%s %-70s\n' % (status, os.path.join(dir, '')))
233 if opt.smaller and ent.size >= opt.smaller:
234 if exists and not hashvalid:
235 add_error('skipping large file "%s"' % ent.name)
236 lastskip_name = ent.name
239 assert(dir.startswith('/'))
241 dirp = stripped_path_components(dir, extra)
243 dirp = stripped_path_components(dir, [opt.strip_path])
245 dirp = grafted_path_components(graft_points, dir)
247 dirp = path_components(dir)
249 while parts > [x[0] for x in dirp]:
250 _pop(force_tree = None)
253 for path_component in dirp[len(parts):]:
254 dir_name, fs_path = path_component
256 meta = metadata.from_path(fs_path)
258 meta = metadata.Metadata()
259 _push(dir_name, meta)
262 # no filename portion means this is a subdir. But
263 # sub/parentdirectories already handled in the pop/push() part above.
264 oldtree = already_saved(ent) # may be None
265 newtree = _pop(force_tree = oldtree)
267 if lastskip_name and lastskip_name.startswith(ent.name):
270 ent.validate(GIT_MODE_TREE, newtree)
272 if exists and wasmissing:
276 # it's not a directory
280 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
281 git_info = (ent.gitmode, git_name, id)
282 shalists[-1].append(git_info)
283 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
284 metalists[-1].append((sort_key, metadata.from_path(ent.name)))
286 if stat.S_ISREG(ent.mode):
288 f = hashsplit.open_noatime(ent.name)
289 except (IOError, OSError), e:
291 lastskip_name = ent.name
294 (mode, id) = hashsplit.split_to_blob_or_tree(
295 w.new_blob, w.new_tree, [f],
296 keep_boundaries=False)
297 except (IOError, OSError), e:
298 add_error('%s: %s' % (ent.name, e))
299 lastskip_name = ent.name
301 if stat.S_ISDIR(ent.mode):
302 assert(0) # handled above
303 elif stat.S_ISLNK(ent.mode):
305 rl = os.readlink(ent.name)
306 except (OSError, IOError), e:
308 lastskip_name = ent.name
310 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
312 # Everything else should be fully described by its
313 # metadata, so just record an empty blob, so the paths
314 # in the tree and .bupm will match up.
315 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
318 ent.validate(mode, id)
320 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
321 git_info = (mode, git_name, id)
322 shalists[-1].append(git_info)
323 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
324 metalists[-1].append((sort_key, metadata.from_path(ent.name)))
325 if exists and wasmissing:
331 pct = total and count*100.0/total or 100
332 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
333 % (pct, count/1024, total/1024, fcount, ftotal))
335 while len(parts) > 1: # _pop() all the parts above the indexed items.
336 _pop(force_tree = None)
337 assert(len(shalists) == 1)
338 assert(len(metalists) == 1)
340 if not (opt.strip or opt.strip_path or graft_points):
341 # For now, only save metadata for the root directory when there
342 # isn't any path grafting or stripping that might create multiple
344 shalist = shalists[-1]
345 metadata = ''.join([metadata.from_path('/').encode()])
346 shalist.append((0100644, '.bupm', w.new_blob(metadata)))
347 tree = w.new_tree(shalists[-1])
350 print tree.encode('hex')
351 if opt.commit or opt.name:
352 msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
353 commit = w.new_commit(oldref, tree, date, msg)
355 print commit.encode('hex')
357 w.close() # must close before we can update the ref
361 cli.update_ref(refname, commit, oldref)
363 git.update_ref(refname, commit, oldref)
369 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))