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