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