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