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