]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
save-cmd: open files with O_NOATIME on OSes that support it.
[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     wasmissing = ent.sha_missing()
141     oldsize = ent.size
142     if opt.verbose:
143         if not exists:
144             status = 'D'
145         elif not hashvalid:
146             if ent.sha == index.EMPTY_SHA:
147                 status = 'A'
148             else:
149                 status = 'M'
150         else:
151             status = ' '
152         if opt.verbose >= 2:
153             log('%s %-70s\n' % (status, ent.name))
154         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
155             if not lastdir.startswith(dir):
156                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
157             lastdir = dir
158
159     if opt.progress:
160         progress_report(0)
161     fcount += 1
162     
163     if not exists:
164         continue
165     if opt.smaller and ent.size >= opt.smaller:
166         if exists and not hashvalid:
167             add_error('skipping large file "%s"' % ent.name)
168             lastskip_name = ent.name
169         continue
170
171     assert(dir.startswith('/'))
172     dirp = dir.split('/')
173     while parts > dirp:
174         _pop(force_tree = None)
175     if dir != '/':
176         for part in dirp[len(parts):]:
177             _push(part)
178
179     if not file:
180         # sub/parentdirectories already handled in the pop/push() part above.
181         oldtree = already_saved(ent) # may be None
182         newtree = _pop(force_tree = oldtree)
183         if not oldtree:
184             if lastskip_name and lastskip_name.startswith(ent.name):
185                 ent.invalidate()
186             else:
187                 ent.validate(040000, newtree)
188             ent.repack()
189         if exists and wasmissing:
190             count += oldsize
191         continue
192
193     # it's not a directory
194     id = None
195     if hashvalid:
196         mode = '%o' % ent.gitmode
197         id = ent.sha
198         shalists[-1].append((mode, file, id))
199     else:
200         if stat.S_ISREG(ent.mode):
201             try:
202                 f = hashsplit.open_noatime(ent.name)
203             except IOError, e:
204                 add_error(e)
205                 lastskip_name = ent.name
206             except OSError, e:
207                 add_error(e)
208                 lastskip_name = ent.name
209             else:
210                 (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
211         else:
212             if stat.S_ISDIR(ent.mode):
213                 assert(0)  # handled above
214             elif stat.S_ISLNK(ent.mode):
215                 try:
216                     rl = os.readlink(ent.name)
217                 except OSError, e:
218                     add_error(e)
219                     lastskip_name = ent.name
220                 except IOError, e:
221                     add_error(e)
222                     lastskip_name = ent.name
223                 else:
224                     (mode, id) = ('120000', w.new_blob(rl))
225             else:
226                 add_error(Exception('skipping special file "%s"' % ent.name))
227                 lastskip_name = ent.name
228         if id:
229             ent.validate(int(mode, 8), id)
230             ent.repack()
231             shalists[-1].append((mode, file, id))
232     if exists and wasmissing:
233         count += oldsize
234         subcount = 0
235
236
237 if opt.progress:
238     pct = total and count*100.0/total or 100
239     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
240              % (pct, count/1024, total/1024, fcount, ftotal))
241
242 while len(parts) > 1:
243     _pop(force_tree = None)
244 assert(len(shalists) == 1)
245 tree = w.new_tree(shalists[-1])
246 if opt.tree:
247     print tree.encode('hex')
248 if opt.commit or opt.name:
249     msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
250     ref = opt.name and ('refs/heads/%s' % opt.name) or None
251     commit = w.new_commit(oldref, tree, msg)
252     if opt.commit:
253         print commit.encode('hex')
254
255 w.close()  # must close before we can update the ref
256         
257 if opt.name:
258     if cli:
259         cli.update_ref(refname, commit, oldref)
260     else:
261         git.update_ref(refname, commit, oldref)
262
263 if cli:
264     cli.close()
265
266 if saved_errors:
267     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))