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