]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
Save metadata during "bup save".
[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             graft_points.append((realpath(splitted_parameter[0]),
62                                  realpath(splitted_parameter[1])))
63
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")
67
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()
75 else:
76     cli = None
77     oldref = refname and git.read_ref(refname) or None
78     w = git.PackWriter(compression_level=opt.compress)
79
80 handle_ctrl_c()
81
82
83 def eatslash(dir):
84     if dir.endswith('/'):
85         return dir[:-1]
86     else:
87         return dir
88
89
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.
94 #
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.
100
101 parts = ['']
102 shalists = [[]]
103 metalists = [[]]
104
105 def _push(part, metadata):
106     assert(part)
107     parts.append(part)
108     shalists.append([])
109     # First entry is dir metadata, which is represented with an empty name.
110     metalists.append([('', metadata)])
111
112 def _pop(force_tree):
113     assert(len(parts) >= 1)
114     part = parts.pop()
115     shalist = shalists.pop()
116     metalist = metalists.pop()
117     if metalist:
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)
122     if shalists:
123         shalists[-1].append((GIT_MODE_TREE,
124                              git.mangle_name(part,
125                                              GIT_MODE_TREE, GIT_MODE_TREE),
126                              tree))
127     else:
128         # This was the toplevel, so put it back for sanity (i.e. cd .. from /).
129         shalists.append(shalist)
130         metalists.append(metalist)
131     return tree
132
133 lastremain = None
134 def progress_report(n):
135     global count, subcount, lastremain
136     subcount += n
137     cc = count + subcount
138     pct = total and (cc*100.0/total) or 0
139     now = time.time()
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
144     if cc:
145         remain = elapsed*1.0/cc * (total-cc)
146     else:
147         remain = 0.0
148     if (lastremain and (remain > lastremain)
149           and ((remain - lastremain)/lastremain < 0.05)):
150         remain = lastremain
151     else:
152         lastremain = remain
153     hours = int(remain/60/60)
154     mins = int(remain/60 - hours*60)
155     secs = int(remain - hours*60*60 - mins*60)
156     if elapsed < 30:
157         remainstr = ''
158         kpsstr = ''
159     else:
160         kpsstr = '%dk/s' % kps
161         if hours:
162             remainstr = '%dh%dm' % (hours, mins)
163         elif mins:
164             remainstr = '%dm%d' % (mins, secs)
165         else:
166             remainstr = '%ds' % secs
167     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
168               % (pct, cc/1024, total/1024, fcount, ftotal,
169                  remainstr, kpsstr))
170
171
172 indexfile = opt.indexfile or git.repo('bupindex')
173 r = index.Reader(indexfile)
174
175 def already_saved(ent):
176     return ent.is_valid() and w.exists(ent.sha) and ent.sha
177
178 def wantrecurse_pre(ent):
179     return not already_saved(ent)
180
181 def wantrecurse_during(ent):
182     return not already_saved(ent) or ent.sha_missing()
183
184
185 total = ftotal = 0
186 if opt.progress:
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:
195                 total += ent.size
196         ftotal += 1
197     progress('Reading index: %d, done.\n' % ftotal)
198     hashsplit.progress_callback = progress_report
199
200 tstart = time.time()
201 count = subcount = fcount = 0
202 lastskip_name = None
203 lastdir = ''
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()
209     oldsize = ent.size
210     if opt.verbose:
211         if not exists:
212             status = 'D'
213         elif not hashvalid:
214             if ent.sha == index.EMPTY_SHA:
215                 status = 'A'
216             else:
217                 status = 'M'
218         else:
219             status = ' '
220         if opt.verbose >= 2:
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, '')))
225             lastdir = dir
226
227     if opt.progress:
228         progress_report(0)
229     fcount += 1
230     
231     if not exists:
232         continue
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
237         continue
238
239     assert(dir.startswith('/'))
240     if opt.strip:
241         dirp = stripped_path_components(dir, extra)
242     elif opt.strip_path:
243         dirp = stripped_path_components(dir, [opt.strip_path])
244     elif graft_points:
245         dirp = grafted_path_components(graft_points, dir)
246     else:
247         dirp = path_components(dir)
248
249     while parts > [x[0] for x in dirp]:
250         _pop(force_tree = None)
251
252     if dir != '/':
253         for path_component in dirp[len(parts):]:
254             dir_name, fs_path = path_component
255             if fs_path:
256                 meta = metadata.from_path(fs_path)
257             else:
258                 meta = metadata.Metadata()
259             _push(dir_name, meta)
260
261     if not file:
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)
266         if not oldtree:
267             if lastskip_name and lastskip_name.startswith(ent.name):
268                 ent.invalidate()
269             else:
270                 ent.validate(GIT_MODE_TREE, newtree)
271             ent.repack()
272         if exists and wasmissing:
273             count += oldsize
274         continue
275
276     # it's not a directory
277     id = None
278     if hashvalid:
279         id = ent.sha
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)))
285     else:
286         if stat.S_ISREG(ent.mode):
287             try:
288                 f = hashsplit.open_noatime(ent.name)
289             except (IOError, OSError), e:
290                 add_error(e)
291                 lastskip_name = ent.name
292             else:
293                 try:
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
300         else:
301             if stat.S_ISDIR(ent.mode):
302                 assert(0)  # handled above
303             elif stat.S_ISLNK(ent.mode):
304                 try:
305                     rl = os.readlink(ent.name)
306                 except (OSError, IOError), e:
307                     add_error(e)
308                     lastskip_name = ent.name
309                 else:
310                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
311             else:
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(""))
316
317         if id:
318             ent.validate(mode, id)
319             ent.repack()
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:
326         count += oldsize
327         subcount = 0
328
329
330 if opt.progress:
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))
334
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)
339
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
343     # roots.
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])
348
349 if opt.tree:
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)
354     if opt.commit:
355         print commit.encode('hex')
356
357 w.close()  # must close before we can update the ref
358         
359 if opt.name:
360     if cli:
361         cli.update_ref(refname, commit, oldref)
362     else:
363         git.update_ref(refname, commit, oldref)
364
365 if cli:
366     cli.close()
367
368 if saved_errors:
369     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
370     sys.exit(1)