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