]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
save-cmd.py, split-cmd.py: end the commit message with a newline.
[bup.git] / cmd / save-cmd.py
1 #!/usr/bin/env python
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
6
7
8 optspec = """
9 bup save [-tc] [-n name] <filenames...>
10 --
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]
25 """
26 o = options.Options(optspec)
27 (opt, flags, extra) = o.parse(sys.argv[1:])
28
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")
32 if not extra:
33     o.fatal("no filenames given")
34
35 opt.progress = (istty2 and not opt.quiet)
36 opt.smaller = parse_num(opt.smaller or 0)
37 if opt.bwlimit:
38     client.bwlimit = parse_num(opt.bwlimit)
39
40 if opt.date:
41     date = parse_date_or_fatal(opt.date, o.fatal)
42 else:
43     date = time.time()
44
45 if opt.strip and opt.strip_path:
46     o.fatal("--strip is incompatible with --strip-path")
47
48 graft_points = []
49 if opt.graft:
50     if opt.strip:
51         o.fatal("--strip is incompatible with --graft")
52
53     if opt.strip_path:
54         o.fatal("--strip-path is incompatible with --graft")
55
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)))
65
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")
69
70 if opt.name:
71     if opt.name.startswith('.'):
72         o.fatal('backup set names cannot start with "."')
73     if '/' in opt.name:
74         o.fatal('backup set names cannot contain "/"')
75 refname = opt.name and 'refs/heads/%s' % opt.name or None
76 if opt.remote or is_reverse:
77     cli = client.Client(opt.remote)
78     oldref = refname and cli.read_ref(refname) or None
79     w = cli.new_packwriter(compression_level=opt.compress)
80 else:
81     cli = None
82     oldref = refname and git.read_ref(refname) or None
83     w = git.PackWriter(compression_level=opt.compress)
84
85 handle_ctrl_c()
86
87
88 def eatslash(dir):
89     if dir.endswith('/'):
90         return dir[:-1]
91     else:
92         return dir
93
94
95 # Metadata is stored in a file named .bupm in each directory.  The
96 # first metadata entry will be the metadata for the current directory.
97 # The remaining entries will be for each of the other directory
98 # elements, in the order they're listed in the index.
99 #
100 # Since the git tree elements are sorted according to
101 # git.shalist_item_sort_key, the metalist items are accumulated as
102 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
103 # created.  The sort_key must be computed using the element's real
104 # name and mode rather than the git mode and (possibly mangled) name.
105
106 # Maintain a stack of information representing the current location in
107 # the archive being constructed.  The current path is recorded in
108 # parts, which will be something like ['', 'home', 'someuser'], and
109 # the accumulated content and metadata for of the dirs in parts is
110 # stored in parallel stacks in shalists and metalists.
111
112 parts = [] # Current archive position (stack of dir names).
113 shalists = [] # Hashes for each dir in paths.
114 metalists = [] # Metadata for each dir in paths.
115
116
117 def _push(part, metadata):
118     # Enter a new archive directory -- make it the current directory.
119     parts.append(part)
120     shalists.append([])
121     metalists.append([('', metadata)]) # This dir's metadata (no name).
122
123
124 def _pop(force_tree, dir_metadata=None):
125     # Leave the current archive directory and add its tree to its parent.
126     assert(len(parts) >= 1)
127     part = parts.pop()
128     shalist = shalists.pop()
129     metalist = metalists.pop()
130     if metalist and not force_tree:
131         if dir_metadata: # Override the original metadata pushed for this dir.
132             metalist = [('', dir_metadata)] + metalist[1:]
133         sorted_metalist = sorted(metalist, key = lambda x : x[0])
134         metadata = ''.join([m[1].encode() for m in sorted_metalist])
135         shalist.append((0100644, '.bupm', w.new_blob(metadata)))
136     tree = force_tree or w.new_tree(shalist)
137     if shalists:
138         shalists[-1].append((GIT_MODE_TREE,
139                              git.mangle_name(part,
140                                              GIT_MODE_TREE, GIT_MODE_TREE),
141                              tree))
142     return tree
143
144
145 lastremain = None
146 def progress_report(n):
147     global count, subcount, lastremain
148     subcount += n
149     cc = count + subcount
150     pct = total and (cc*100.0/total) or 0
151     now = time.time()
152     elapsed = now - tstart
153     kps = elapsed and int(cc/1024./elapsed)
154     kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
155     kps = int(kps/kps_frac)*kps_frac
156     if cc:
157         remain = elapsed*1.0/cc * (total-cc)
158     else:
159         remain = 0.0
160     if (lastremain and (remain > lastremain)
161           and ((remain - lastremain)/lastremain < 0.05)):
162         remain = lastremain
163     else:
164         lastremain = remain
165     hours = int(remain/60/60)
166     mins = int(remain/60 - hours*60)
167     secs = int(remain - hours*60*60 - mins*60)
168     if elapsed < 30:
169         remainstr = ''
170         kpsstr = ''
171     else:
172         kpsstr = '%dk/s' % kps
173         if hours:
174             remainstr = '%dh%dm' % (hours, mins)
175         elif mins:
176             remainstr = '%dm%d' % (mins, secs)
177         else:
178             remainstr = '%ds' % secs
179     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
180               % (pct, cc/1024, total/1024, fcount, ftotal,
181                  remainstr, kpsstr))
182
183
184 indexfile = opt.indexfile or git.repo('bupindex')
185 r = index.Reader(indexfile)
186 if not os.access(indexfile + '.meta', os.W_OK|os.R_OK):
187     log('error: cannot access "%s"; have you run bup index?' % indexfile)
188     sys.exit(1)
189 msr = index.MetaStoreReader(indexfile + '.meta')
190 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
191
192 def already_saved(ent):
193     return ent.is_valid() and w.exists(ent.sha) and ent.sha
194
195 def wantrecurse_pre(ent):
196     return not already_saved(ent)
197
198 def wantrecurse_during(ent):
199     return not already_saved(ent) or ent.sha_missing()
200
201 def find_hardlink_target(hlink_db, ent):
202     if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
203         link_paths = hlink_db.node_paths(ent.dev, ent.ino)
204         if link_paths:
205             return link_paths[0]
206
207 total = ftotal = 0
208 if opt.progress:
209     for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
210         if not (ftotal % 10024):
211             qprogress('Reading index: %d\r' % ftotal)
212         exists = ent.exists()
213         hashvalid = already_saved(ent)
214         ent.set_sha_missing(not hashvalid)
215         if not opt.smaller or ent.size < opt.smaller:
216             if exists and not hashvalid:
217                 total += ent.size
218         ftotal += 1
219     progress('Reading index: %d, done.\n' % ftotal)
220     hashsplit.progress_callback = progress_report
221
222 # Root collisions occur when strip or graft options map more than one
223 # path to the same directory (paths which originally had separate
224 # parents).  When that situation is detected, use empty metadata for
225 # the parent.  Otherwise, use the metadata for the common parent.
226 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
227
228 # FIXME: Add collision tests, or handle collisions some other way.
229
230 # FIXME: Detect/handle strip/graft name collisions (other than root),
231 # i.e. if '/foo/bar' and '/bar' both map to '/'.
232
233 first_root = None
234 root_collision = None
235 tstart = time.time()
236 count = subcount = fcount = 0
237 lastskip_name = None
238 lastdir = ''
239 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
240     (dir, file) = os.path.split(ent.name)
241     exists = (ent.flags & index.IX_EXISTS)
242     hashvalid = already_saved(ent)
243     wasmissing = ent.sha_missing()
244     oldsize = ent.size
245     if opt.verbose:
246         if not exists:
247             status = 'D'
248         elif not hashvalid:
249             if ent.sha == index.EMPTY_SHA:
250                 status = 'A'
251             else:
252                 status = 'M'
253         else:
254             status = ' '
255         if opt.verbose >= 2:
256             log('%s %-70s\n' % (status, ent.name))
257         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
258             if not lastdir.startswith(dir):
259                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
260             lastdir = dir
261
262     if opt.progress:
263         progress_report(0)
264     fcount += 1
265     
266     if not exists:
267         continue
268     if opt.smaller and ent.size >= opt.smaller:
269         if exists and not hashvalid:
270             add_error('skipping large file "%s"' % ent.name)
271             lastskip_name = ent.name
272         continue
273
274     assert(dir.startswith('/'))
275     if opt.strip:
276         dirp = stripped_path_components(dir, extra)
277     elif opt.strip_path:
278         dirp = stripped_path_components(dir, [opt.strip_path])
279     elif graft_points:
280         dirp = grafted_path_components(graft_points, dir)
281     else:
282         dirp = path_components(dir)
283
284     # At this point, dirp contains a representation of the archive
285     # path that looks like [(archive_dir_name, real_fs_path), ...].
286     # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
287     # might look like this at some point:
288     #   [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
289
290     # This dual representation supports stripping/grafting, where the
291     # archive path may not have a direct correspondence with the
292     # filesystem.  The root directory is represented by an initial
293     # component named '', and any component that doesn't have a
294     # corresponding filesystem directory (due to grafting, for
295     # example) will have a real_fs_path of None, i.e. [('', None),
296     # ...].
297
298     if first_root == None:
299         dir_name, fs_path = dirp[0]
300         first_root = dirp[0]
301         # Not indexed, so just grab the FS metadata or use empty metadata.
302         try:
303            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
304         except (OSError, IOError), e:
305             add_error(e)
306             lastskip_name = dir_name
307         else:
308            _push(dir_name, meta)
309     elif first_root != dirp[0]:
310         root_collision = True
311
312     # If switching to a new sub-tree, finish the current sub-tree.
313     while parts > [x[0] for x in dirp]:
314         _pop(force_tree = None)
315
316     # If switching to a new sub-tree, start a new sub-tree.
317     for path_component in dirp[len(parts):]:
318         dir_name, fs_path = path_component
319         # Not indexed, so just grab the FS metadata or use empty metadata.
320         try:
321            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
322         except (OSError, IOError), e:
323             add_error(e)
324             lastskip_name = dir_name
325         else:
326            _push(dir_name, meta)
327
328     if not file:
329         if len(parts) == 1:
330             continue # We're at the top level -- keep the current root dir
331         # Since there's no filename, this is a subdir -- finish it.
332         oldtree = already_saved(ent) # may be None
333         newtree = _pop(force_tree = oldtree)
334         if not oldtree:
335             if lastskip_name and lastskip_name.startswith(ent.name):
336                 ent.invalidate()
337             else:
338                 ent.validate(GIT_MODE_TREE, newtree)
339             ent.repack()
340         if exists and wasmissing:
341             count += oldsize
342         continue
343
344     # it's not a directory
345     id = None
346     if hashvalid:
347         id = ent.sha
348         git_name = git.mangle_name(file, ent.mode, ent.gitmode)
349         git_info = (ent.gitmode, git_name, id)
350         shalists[-1].append(git_info)
351         sort_key = git.shalist_item_sort_key((ent.mode, file, id))
352         meta = msr.metadata_at(ent.meta_ofs)
353         meta.hardlink_target = find_hardlink_target(hlink_db, ent)
354         # Restore the times that were cleared to 0 in the metastore.
355         (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
356         metalists[-1].append((sort_key, meta))
357     else:
358         if stat.S_ISREG(ent.mode):
359             try:
360                 f = hashsplit.open_noatime(ent.name)
361             except (IOError, OSError), e:
362                 add_error(e)
363                 lastskip_name = ent.name
364             else:
365                 try:
366                     (mode, id) = hashsplit.split_to_blob_or_tree(
367                                             w.new_blob, w.new_tree, [f],
368                                             keep_boundaries=False)
369                 except (IOError, OSError), e:
370                     add_error('%s: %s' % (ent.name, e))
371                     lastskip_name = ent.name
372         else:
373             if stat.S_ISDIR(ent.mode):
374                 assert(0)  # handled above
375             elif stat.S_ISLNK(ent.mode):
376                 try:
377                     rl = os.readlink(ent.name)
378                 except (OSError, IOError), e:
379                     add_error(e)
380                     lastskip_name = ent.name
381                 else:
382                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
383             else:
384                 # Everything else should be fully described by its
385                 # metadata, so just record an empty blob, so the paths
386                 # in the tree and .bupm will match up.
387                 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
388
389         if id:
390             ent.validate(mode, id)
391             ent.repack()
392             git_name = git.mangle_name(file, ent.mode, ent.gitmode)
393             git_info = (mode, git_name, id)
394             shalists[-1].append(git_info)
395             sort_key = git.shalist_item_sort_key((ent.mode, file, id))
396             hlink = find_hardlink_target(hlink_db, ent)
397             try:
398                 meta = metadata.from_path(ent.name, hardlink_target=hlink)
399             except (OSError, IOError), e:
400                 add_error(e)
401                 lastskip_name = ent.name
402             else:
403                 metalists[-1].append((sort_key, meta))
404
405     if exists and wasmissing:
406         count += oldsize
407         subcount = 0
408
409
410 if opt.progress:
411     pct = total and count*100.0/total or 100
412     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
413              % (pct, count/1024, total/1024, fcount, ftotal))
414
415 while len(parts) > 1: # _pop() all the parts above the root
416     _pop(force_tree = None)
417 assert(len(shalists) == 1)
418 assert(len(metalists) == 1)
419
420 # Finish the root directory.
421 tree = _pop(force_tree = None,
422             # When there's a collision, use empty metadata for the root.
423             dir_metadata = metadata.Metadata() if root_collision else None)
424
425 if opt.tree:
426     print tree.encode('hex')
427 if opt.commit or opt.name:
428     msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
429     commit = w.new_commit(oldref, tree, date, msg)
430     if opt.commit:
431         print commit.encode('hex')
432
433 msr.close()
434 w.close()  # must close before we can update the ref
435         
436 if opt.name:
437     if cli:
438         cli.update_ref(refname, commit, oldref)
439     else:
440         git.update_ref(refname, commit, oldref)
441
442 if cli:
443     cli.close()
444
445 if saved_errors:
446     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
447     sys.exit(1)