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