]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
Disallow empty graft points.
[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
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 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()
77 else:
78     cli = None
79     oldref = refname and git.read_ref(refname) or None
80     w = git.PackWriter(compression_level=opt.compress)
81
82 handle_ctrl_c()
83
84
85 def eatslash(dir):
86     if dir.endswith('/'):
87         return dir[:-1]
88     else:
89         return dir
90
91
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.
96 #
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.
102
103 parts = ['']
104 shalists = [[]]
105 metalists = [[]]
106
107 def _push(part, metadata):
108     assert(part)
109     parts.append(part)
110     shalists.append([])
111     # First entry is dir metadata, which is represented with an empty name.
112     metalists.append([('', metadata)])
113
114 def _pop(force_tree):
115     assert(len(parts) >= 1)
116     part = parts.pop()
117     shalist = shalists.pop()
118     metalist = metalists.pop()
119     if metalist:
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)
124     if shalists:
125         shalists[-1].append((GIT_MODE_TREE,
126                              git.mangle_name(part,
127                                              GIT_MODE_TREE, GIT_MODE_TREE),
128                              tree))
129     else:
130         # This was the toplevel, so put it back for sanity (i.e. cd .. from /).
131         shalists.append(shalist)
132         metalists.append(metalist)
133     return tree
134
135 lastremain = None
136 def progress_report(n):
137     global count, subcount, lastremain
138     subcount += n
139     cc = count + subcount
140     pct = total and (cc*100.0/total) or 0
141     now = time.time()
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
146     if cc:
147         remain = elapsed*1.0/cc * (total-cc)
148     else:
149         remain = 0.0
150     if (lastremain and (remain > lastremain)
151           and ((remain - lastremain)/lastremain < 0.05)):
152         remain = lastremain
153     else:
154         lastremain = remain
155     hours = int(remain/60/60)
156     mins = int(remain/60 - hours*60)
157     secs = int(remain - hours*60*60 - mins*60)
158     if elapsed < 30:
159         remainstr = ''
160         kpsstr = ''
161     else:
162         kpsstr = '%dk/s' % kps
163         if hours:
164             remainstr = '%dh%dm' % (hours, mins)
165         elif mins:
166             remainstr = '%dm%d' % (mins, secs)
167         else:
168             remainstr = '%ds' % secs
169     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
170               % (pct, cc/1024, total/1024, fcount, ftotal,
171                  remainstr, kpsstr))
172
173
174 indexfile = opt.indexfile or git.repo('bupindex')
175 r = index.Reader(indexfile)
176
177 def already_saved(ent):
178     return ent.is_valid() and w.exists(ent.sha) and ent.sha
179
180 def wantrecurse_pre(ent):
181     return not already_saved(ent)
182
183 def wantrecurse_during(ent):
184     return not already_saved(ent) or ent.sha_missing()
185
186
187 total = ftotal = 0
188 if opt.progress:
189     for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
190         if not (ftotal % 10024):
191             qprogress('Reading index: %d\r' % ftotal)
192         exists = ent.exists()
193         hashvalid = already_saved(ent)
194         ent.set_sha_missing(not hashvalid)
195         if not opt.smaller or ent.size < opt.smaller:
196             if exists and not hashvalid:
197                 total += ent.size
198         ftotal += 1
199     progress('Reading index: %d, done.\n' % ftotal)
200     hashsplit.progress_callback = progress_report
201
202 tstart = time.time()
203 count = subcount = fcount = 0
204 lastskip_name = None
205 lastdir = ''
206 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
207     (dir, file) = os.path.split(ent.name)
208     exists = (ent.flags & index.IX_EXISTS)
209     hashvalid = already_saved(ent)
210     wasmissing = ent.sha_missing()
211     oldsize = ent.size
212     if opt.verbose:
213         if not exists:
214             status = 'D'
215         elif not hashvalid:
216             if ent.sha == index.EMPTY_SHA:
217                 status = 'A'
218             else:
219                 status = 'M'
220         else:
221             status = ' '
222         if opt.verbose >= 2:
223             log('%s %-70s\n' % (status, ent.name))
224         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
225             if not lastdir.startswith(dir):
226                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
227             lastdir = dir
228
229     if opt.progress:
230         progress_report(0)
231     fcount += 1
232     
233     if not exists:
234         continue
235     if opt.smaller and ent.size >= opt.smaller:
236         if exists and not hashvalid:
237             add_error('skipping large file "%s"' % ent.name)
238             lastskip_name = ent.name
239         continue
240
241     assert(dir.startswith('/'))
242     if opt.strip:
243         dirp = stripped_path_components(dir, extra)
244     elif opt.strip_path:
245         dirp = stripped_path_components(dir, [opt.strip_path])
246     elif graft_points:
247         dirp = grafted_path_components(graft_points, dir)
248     else:
249         dirp = path_components(dir)
250
251     while parts > [x[0] for x in dirp]:
252         _pop(force_tree = None)
253
254     if dir != '/':
255         for path_component in dirp[len(parts):]:
256             dir_name, fs_path = path_component
257             if fs_path:
258                 meta = metadata.from_path(fs_path)
259             else:
260                 meta = metadata.Metadata()
261             _push(dir_name, meta)
262
263     if not file:
264         # no filename portion means this is a subdir.  But
265         # sub/parentdirectories already handled in the pop/push() part above.
266         oldtree = already_saved(ent) # may be None
267         newtree = _pop(force_tree = oldtree)
268         if not oldtree:
269             if lastskip_name and lastskip_name.startswith(ent.name):
270                 ent.invalidate()
271             else:
272                 ent.validate(GIT_MODE_TREE, newtree)
273             ent.repack()
274         if exists and wasmissing:
275             count += oldsize
276         continue
277
278     # it's not a directory
279     id = None
280     if hashvalid:
281         id = ent.sha
282         git_name = git.mangle_name(file, ent.mode, ent.gitmode)
283         git_info = (ent.gitmode, git_name, id)
284         shalists[-1].append(git_info)
285         sort_key = git.shalist_item_sort_key((ent.mode, file, id))
286         metalists[-1].append((sort_key, metadata.from_path(ent.name)))
287     else:
288         if stat.S_ISREG(ent.mode):
289             try:
290                 f = hashsplit.open_noatime(ent.name)
291             except (IOError, OSError), e:
292                 add_error(e)
293                 lastskip_name = ent.name
294             else:
295                 try:
296                     (mode, id) = hashsplit.split_to_blob_or_tree(
297                                             w.new_blob, w.new_tree, [f],
298                                             keep_boundaries=False)
299                 except (IOError, OSError), e:
300                     add_error('%s: %s' % (ent.name, e))
301                     lastskip_name = ent.name
302         else:
303             if stat.S_ISDIR(ent.mode):
304                 assert(0)  # handled above
305             elif stat.S_ISLNK(ent.mode):
306                 try:
307                     rl = os.readlink(ent.name)
308                 except (OSError, IOError), e:
309                     add_error(e)
310                     lastskip_name = ent.name
311                 else:
312                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
313             else:
314                 # Everything else should be fully described by its
315                 # metadata, so just record an empty blob, so the paths
316                 # in the tree and .bupm will match up.
317                 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
318
319         if id:
320             ent.validate(mode, id)
321             ent.repack()
322             git_name = git.mangle_name(file, ent.mode, ent.gitmode)
323             git_info = (mode, git_name, id)
324             shalists[-1].append(git_info)
325             sort_key = git.shalist_item_sort_key((ent.mode, file, id))
326             metalists[-1].append((sort_key, metadata.from_path(ent.name)))
327     if exists and wasmissing:
328         count += oldsize
329         subcount = 0
330
331
332 if opt.progress:
333     pct = total and count*100.0/total or 100
334     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
335              % (pct, count/1024, total/1024, fcount, ftotal))
336
337 while len(parts) > 1: # _pop() all the parts above the indexed items.
338     _pop(force_tree = None)
339 assert(len(shalists) == 1)
340 assert(len(metalists) == 1)
341
342 if not (opt.strip or opt.strip_path or graft_points):
343     # For now, only save metadata for the root directory when there
344     # isn't any path grafting or stripping that might create multiple
345     # roots.
346     shalist = shalists[-1]
347     metadata = ''.join([metadata.from_path('/').encode()])
348     shalist.append((0100644, '.bupm', w.new_blob(metadata)))
349 tree = w.new_tree(shalists[-1])
350
351 if opt.tree:
352     print tree.encode('hex')
353 if opt.commit or opt.name:
354     msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
355     commit = w.new_commit(oldref, tree, date, msg)
356     if opt.commit:
357         print commit.encode('hex')
358
359 w.close()  # must close before we can update the ref
360         
361 if opt.name:
362     if cli:
363         cli.update_ref(refname, commit, oldref)
364     else:
365         git.update_ref(refname, commit, oldref)
366
367 if cli:
368     cli.close()
369
370 if saved_errors:
371     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
372     sys.exit(1)