]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
Add preliminary hardlink support for review.
[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 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 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
177
178 def already_saved(ent):
179     return ent.is_valid() and w.exists(ent.sha) and ent.sha
180
181 def wantrecurse_pre(ent):
182     return not already_saved(ent)
183
184 def wantrecurse_during(ent):
185     return not already_saved(ent) or ent.sha_missing()
186
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)
190         if link_paths:
191             return link_paths[0]
192
193 total = ftotal = 0
194 if opt.progress:
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:
203                 total += ent.size
204         ftotal += 1
205     progress('Reading index: %d, done.\n' % ftotal)
206     hashsplit.progress_callback = progress_report
207
208 tstart = time.time()
209 count = subcount = fcount = 0
210 lastskip_name = None
211 lastdir = ''
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()
217     oldsize = ent.size
218     if opt.verbose:
219         if not exists:
220             status = 'D'
221         elif not hashvalid:
222             if ent.sha == index.EMPTY_SHA:
223                 status = 'A'
224             else:
225                 status = 'M'
226         else:
227             status = ' '
228         if opt.verbose >= 2:
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, '')))
233             lastdir = dir
234
235     if opt.progress:
236         progress_report(0)
237     fcount += 1
238     
239     if not exists:
240         continue
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
245         continue
246
247     assert(dir.startswith('/'))
248     if opt.strip:
249         dirp = stripped_path_components(dir, extra)
250     elif opt.strip_path:
251         dirp = stripped_path_components(dir, [opt.strip_path])
252     elif graft_points:
253         dirp = grafted_path_components(graft_points, dir)
254     else:
255         dirp = path_components(dir)
256
257     while parts > [x[0] for x in dirp]:
258         _pop(force_tree = None)
259
260     if dir != '/':
261         for path_component in dirp[len(parts):]:
262             dir_name, fs_path = path_component
263             if fs_path:
264                 meta = metadata.from_path(fs_path)
265             else:
266                 meta = metadata.Metadata()
267             _push(dir_name, meta)
268
269     if not file:
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)
274         if not oldtree:
275             if lastskip_name and lastskip_name.startswith(ent.name):
276                 ent.invalidate()
277             else:
278                 ent.validate(GIT_MODE_TREE, newtree)
279             ent.repack()
280         if exists and wasmissing:
281             count += oldsize
282         continue
283
284     # it's not a directory
285     id = None
286     if hashvalid:
287         id = ent.sha
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)))
296     else:
297         if stat.S_ISREG(ent.mode):
298             try:
299                 f = hashsplit.open_noatime(ent.name)
300             except (IOError, OSError), e:
301                 add_error(e)
302                 lastskip_name = ent.name
303             else:
304                 try:
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
311         else:
312             if stat.S_ISDIR(ent.mode):
313                 assert(0)  # handled above
314             elif stat.S_ISLNK(ent.mode):
315                 try:
316                     rl = os.readlink(ent.name)
317                 except (OSError, IOError), e:
318                     add_error(e)
319                     lastskip_name = ent.name
320                 else:
321                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
322             else:
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(""))
327
328         if id:
329             ent.validate(mode, id)
330             ent.repack()
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:
340         count += oldsize
341         subcount = 0
342
343
344 if opt.progress:
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))
348
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)
353
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
357     # roots.
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])
362
363 if opt.tree:
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)
368     if opt.commit:
369         print commit.encode('hex')
370
371 w.close()  # must close before we can update the ref
372         
373 if opt.name:
374     if cli:
375         cli.update_ref(refname, commit, oldref)
376     else:
377         git.update_ref(refname, commit, oldref)
378
379 if cli:
380     cli.close()
381
382 if saved_errors:
383     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
384     sys.exit(1)