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