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