]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
Merge remote branch 'origin/master' into meta
[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
4 from bup.helpers import *
5
6
7 optspec = """
8 bup save [-tc] [-n name] <filenames...>
9 --
10 r,remote=  hostname:/path/to/repo of remote repository
11 t,tree     output a tree id
12 c,commit   output a commit id
13 n,name=    name of backup set to update (if any)
14 d,date=    date for the commit (seconds since the epoch)
15 v,verbose  increase log output (can be used more than once)
16 q,quiet    don't show progress meter
17 smaller=   only back up files smaller than n bytes
18 bwlimit=   maximum bytes/sec to transmit to server
19 f,indexfile=  the name of the index file (normally BUP_DIR/bupindex)
20 strip      strips the path to every filename given
21 strip-path= path-prefix to be stripped when saving
22 graft=     a graft point *old_path*=*new_path* (can be used morethan once)
23 """
24 o = options.Options(optspec)
25 (opt, flags, extra) = o.parse(sys.argv[1:])
26
27 git.check_repo_or_die()
28 if not (opt.tree or opt.commit or opt.name):
29     o.fatal("use one or more of -t, -c, -n")
30 if not extra:
31     o.fatal("no filenames given")
32
33 opt.progress = (istty and not opt.quiet)
34 opt.smaller = parse_num(opt.smaller or 0)
35 if opt.bwlimit:
36     client.bwlimit = parse_num(opt.bwlimit)
37
38 if opt.date:
39     date = parse_date_or_fatal(opt.date, o.fatal)
40 else:
41     date = time.time()
42
43 if opt.strip and opt.strip_path:
44     o.fatal("--strip is incompatible with --strip-path")
45
46 graft_points = []
47 if opt.graft:
48     if opt.strip:
49         o.fatal("--strip is incompatible with --graft")
50
51     if opt.strip_path:
52         o.fatal("--strip-path is incompatible with --graft")
53
54     for (option, parameter) in flags:
55         if option == "--graft":
56             splitted_parameter = parameter.split('=')
57             if len(splitted_parameter) != 2:
58                 o.fatal("a graft point must be of the form old_path=new_path")
59             graft_points.append((realpath(splitted_parameter[0]),
60                                  realpath(splitted_parameter[1])))
61
62 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
63 if is_reverse and opt.remote:
64     o.fatal("don't use -r in reverse mode; it's automatic")
65
66 if opt.name and opt.name.startswith('.'):
67     o.fatal("'%s' is not a valid branch name" % opt.name)
68 refname = opt.name and 'refs/heads/%s' % opt.name or None
69 if opt.remote or is_reverse:
70     cli = client.Client(opt.remote)
71     oldref = refname and cli.read_ref(refname) or None
72     w = cli.new_packwriter()
73 else:
74     cli = None
75     oldref = refname and git.read_ref(refname) or None
76     w = git.PackWriter()
77
78 handle_ctrl_c()
79
80
81 def eatslash(dir):
82     if dir.endswith('/'):
83         return dir[:-1]
84     else:
85         return dir
86
87
88 parts = ['']
89 shalists = [[]]
90
91 def _push(part):
92     assert(part)
93     parts.append(part)
94     shalists.append([])
95
96 def _pop(force_tree):
97     assert(len(parts) >= 1)
98     part = parts.pop()
99     shalist = shalists.pop()
100     tree = force_tree or w.new_tree(shalist)
101     if shalists:
102         shalists[-1].append(('40000',
103                              git.mangle_name(part, 040000, 40000),
104                              tree))
105     else:  # this was the toplevel, so put it back for sanity
106         shalists.append(shalist)
107     return tree
108
109 lastremain = None
110 def progress_report(n):
111     global count, subcount, lastremain
112     subcount += n
113     cc = count + subcount
114     pct = total and (cc*100.0/total) or 0
115     now = time.time()
116     elapsed = now - tstart
117     kps = elapsed and int(cc/1024./elapsed)
118     kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
119     kps = int(kps/kps_frac)*kps_frac
120     if cc:
121         remain = elapsed*1.0/cc * (total-cc)
122     else:
123         remain = 0.0
124     if (lastremain and (remain > lastremain)
125           and ((remain - lastremain)/lastremain < 0.05)):
126         remain = lastremain
127     else:
128         lastremain = remain
129     hours = int(remain/60/60)
130     mins = int(remain/60 - hours*60)
131     secs = int(remain - hours*60*60 - mins*60)
132     if elapsed < 30:
133         remainstr = ''
134         kpsstr = ''
135     else:
136         kpsstr = '%dk/s' % kps
137         if hours:
138             remainstr = '%dh%dm' % (hours, mins)
139         elif mins:
140             remainstr = '%dm%d' % (mins, secs)
141         else:
142             remainstr = '%ds' % secs
143     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
144               % (pct, cc/1024, total/1024, fcount, ftotal,
145                  remainstr, kpsstr))
146
147
148 indexfile = opt.indexfile or git.repo('bupindex')
149 r = index.Reader(indexfile)
150
151 def already_saved(ent):
152     return ent.is_valid() and w.exists(ent.sha) and ent.sha
153
154 def wantrecurse_pre(ent):
155     return not already_saved(ent)
156
157 def wantrecurse_during(ent):
158     return not already_saved(ent) or ent.sha_missing()
159
160 total = ftotal = 0
161 if opt.progress:
162     for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
163         if not (ftotal % 10024):
164             qprogress('Reading index: %d\r' % ftotal)
165         exists = ent.exists()
166         hashvalid = already_saved(ent)
167         ent.set_sha_missing(not hashvalid)
168         if not opt.smaller or ent.size < opt.smaller:
169             if exists and not hashvalid:
170                 total += ent.size
171         ftotal += 1
172     progress('Reading index: %d, done.\n' % ftotal)
173     hashsplit.progress_callback = progress_report
174
175 tstart = time.time()
176 count = subcount = fcount = 0
177 lastskip_name = None
178 lastdir = ''
179 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
180     (dir, file) = os.path.split(ent.name)
181     exists = (ent.flags & index.IX_EXISTS)
182     hashvalid = already_saved(ent)
183     wasmissing = ent.sha_missing()
184     oldsize = ent.size
185     if opt.verbose:
186         if not exists:
187             status = 'D'
188         elif not hashvalid:
189             if ent.sha == index.EMPTY_SHA:
190                 status = 'A'
191             else:
192                 status = 'M'
193         else:
194             status = ' '
195         if opt.verbose >= 2:
196             log('%s %-70s\n' % (status, ent.name))
197         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
198             if not lastdir.startswith(dir):
199                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
200             lastdir = dir
201
202     if opt.progress:
203         progress_report(0)
204     fcount += 1
205     
206     if not exists:
207         continue
208     if opt.smaller and ent.size >= opt.smaller:
209         if exists and not hashvalid:
210             add_error('skipping large file "%s"' % ent.name)
211             lastskip_name = ent.name
212         continue
213
214     assert(dir.startswith('/'))
215     if opt.strip:
216         stripped_base_path = strip_base_path(dir, extra)
217         dirp = stripped_base_path.split('/')
218     elif opt.strip_path:
219         dirp = strip_path(opt.strip_path, dir).split('/')
220     elif graft_points:
221         grafted = graft_path(graft_points, dir)
222         dirp = grafted.split('/')
223     else:
224         dirp = dir.split('/')
225     while parts > dirp:
226         _pop(force_tree = None)
227     if dir != '/':
228         for part in dirp[len(parts):]:
229             _push(part)
230
231     if not file:
232         # no filename portion means this is a subdir.  But
233         # sub/parentdirectories already handled in the pop/push() part above.
234         oldtree = already_saved(ent) # may be None
235         newtree = _pop(force_tree = oldtree)
236         if not oldtree:
237             if lastskip_name and lastskip_name.startswith(ent.name):
238                 ent.invalidate()
239             else:
240                 ent.validate(040000, newtree)
241             ent.repack()
242         if exists and wasmissing:
243             count += oldsize
244         continue
245
246     # it's not a directory
247     id = None
248     if hashvalid:
249         mode = '%o' % ent.gitmode
250         id = ent.sha
251         shalists[-1].append((mode, 
252                              git.mangle_name(file, ent.mode, ent.gitmode),
253                              id))
254     else:
255         if stat.S_ISREG(ent.mode):
256             try:
257                 f = hashsplit.open_noatime(ent.name)
258             except IOError, e:
259                 add_error(e)
260                 lastskip_name = ent.name
261             except OSError, e:
262                 add_error(e)
263                 lastskip_name = ent.name
264             else:
265                 try:
266                     (mode, id) = hashsplit.split_to_blob_or_tree(w, [f],
267                                             keep_boundaries=False)
268                 except IOError, e:
269                     add_error('%s: %s' % (ent.name, e))
270                     lastskip_name = ent.name
271         else:
272             if stat.S_ISDIR(ent.mode):
273                 assert(0)  # handled above
274             elif stat.S_ISLNK(ent.mode):
275                 try:
276                     rl = os.readlink(ent.name)
277                 except OSError, e:
278                     add_error(e)
279                     lastskip_name = ent.name
280                 except IOError, e:
281                     add_error(e)
282                     lastskip_name = ent.name
283                 else:
284                     (mode, id) = ('120000', w.new_blob(rl))
285             else:
286                 add_error(Exception('skipping special file "%s"' % ent.name))
287                 lastskip_name = ent.name
288         if id:
289             ent.validate(int(mode, 8), id)
290             ent.repack()
291             shalists[-1].append((mode,
292                                  git.mangle_name(file, ent.mode, ent.gitmode),
293                                  id))
294     if exists and wasmissing:
295         count += oldsize
296         subcount = 0
297
298
299 if opt.progress:
300     pct = total and count*100.0/total or 100
301     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
302              % (pct, count/1024, total/1024, fcount, ftotal))
303
304 while len(parts) > 1:
305     _pop(force_tree = None)
306 assert(len(shalists) == 1)
307 tree = w.new_tree(shalists[-1])
308 if opt.tree:
309     print tree.encode('hex')
310 if opt.commit or opt.name:
311     msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
312     commit = w.new_commit(oldref, tree, date, msg)
313     if opt.commit:
314         print commit.encode('hex')
315
316 w.close()  # must close before we can update the ref
317         
318 if opt.name:
319     if cli:
320         cli.update_ref(refname, commit, oldref)
321     else:
322         git.update_ref(refname, commit, oldref)
323
324 if cli:
325     cli.close()
326
327 if saved_errors:
328     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
329     sys.exit(1)