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