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