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