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