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