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