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