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