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