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