]> arthur.barton.de Git - bup.git/blob - cmd/index-cmd.py
cb358809a4caa6312f2dc53d4c0bdc990a992163
[bup.git] / cmd / index-cmd.py
1 #!/usr/bin/env python
2
3 import sys, stat, time, os, errno
4 from bup import metadata, options, git, index, drecurse, hlinkdb
5 from bup.helpers import *
6 from bup.hashsplit import GIT_MODE_TREE, GIT_MODE_FILE
7
8 class IterHelper:
9     def __init__(self, l):
10         self.i = iter(l)
11         self.cur = None
12         self.next()
13
14     def next(self):
15         try:
16             self.cur = self.i.next()
17         except StopIteration:
18             self.cur = None
19         return self.cur
20
21
22 def check_index(reader):
23     try:
24         log('check: checking forward iteration...\n')
25         e = None
26         d = {}
27         for e in reader.forward_iter():
28             if e.children_n:
29                 if opt.verbose:
30                     log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
31                                             e.name))
32                 assert(e.children_ofs)
33                 assert(e.name.endswith('/'))
34                 assert(not d.get(e.children_ofs))
35                 d[e.children_ofs] = 1
36             if e.flags & index.IX_HASHVALID:
37                 assert(e.sha != index.EMPTY_SHA)
38                 assert(e.gitmode)
39         assert(not e or e.name == '/')  # last entry is *always* /
40         log('check: checking normal iteration...\n')
41         last = None
42         for e in reader:
43             if last:
44                 assert(last > e.name)
45             last = e.name
46     except:
47         log('index error! at %r\n' % e)
48         raise
49     log('check: passed.\n')
50
51
52 def clear_index(indexfile):
53     indexfiles = [indexfile, indexfile + '.meta', indexfile + '.hlink']
54     cleared = False
55     for indexfile in indexfiles:
56         path = git.repo(indexfile)
57         try:
58             os.remove(path)
59             if opt.verbose:
60                 log('clear: removed %s\n' % path)
61             cleared = True
62         except OSError, e:
63             if e.errno != errno.ENOENT:
64                 raise
65
66
67 def update_index(top, excluded_paths):
68     # tmax and start must be epoch nanoseconds.
69     tmax = (time.time() - 1) * 10**9
70     ri = index.Reader(indexfile)
71     msw = index.MetaStoreWriter(indexfile + '.meta')
72     wi = index.Writer(indexfile, msw, tmax)
73     rig = IterHelper(ri.iter(name=top))
74     tstart = int(time.time()) * 10**9
75
76     hlinks = hlinkdb.HLinkDB(indexfile + '.hlink')
77
78     hashgen = None
79     if opt.fake_valid:
80         def hashgen(name):
81             return (GIT_MODE_FILE, index.FAKE_SHA)
82
83     total = 0
84     bup_dir = os.path.abspath(git.repo())
85     for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev,
86                                                  bup_dir=bup_dir,
87                                                  excluded_paths=excluded_paths):
88         if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
89             sys.stdout.write('%s\n' % path)
90             sys.stdout.flush()
91             qprogress('Indexing: %d\r' % total)
92         elif not (total % 128):
93             qprogress('Indexing: %d\r' % total)
94         total += 1
95         while rig.cur and rig.cur.name > path:  # deleted paths
96             if rig.cur.exists():
97                 rig.cur.set_deleted()
98                 rig.cur.repack()
99                 if rig.cur.nlink > 1 and not stat.S_ISDIR(rig.cur.mode):
100                     hlinks.del_path(rig.cur.name)
101             rig.next()
102         if rig.cur and rig.cur.name == path:    # paths that already existed
103             if not stat.S_ISDIR(rig.cur.mode) and rig.cur.nlink > 1:
104                 hlinks.del_path(rig.cur.name)
105             if not stat.S_ISDIR(pst.st_mode) and pst.st_nlink > 1:
106                 hlinks.add_path(path, pst.st_dev, pst.st_ino)
107             meta = metadata.from_path(path, statinfo=pst)
108             # Clear these so they don't bloat the store -- they're
109             # already in the index (since they vary a lot and they're
110             # fixed length).  If you've noticed "tmax", you might
111             # wonder why it's OK to do this, since that code may
112             # adjust (mangle) the index mtime and ctime -- producing
113             # fake values which must not end up in a .bupm.  However,
114             # it looks like that shouldn't be possible:  (1) When
115             # "save" validates the index entry, it always reads the
116             # metadata from the filesytem. (2) Metadata is only
117             # read/used from the index if hashvalid is true. (3) index
118             # always invalidates "faked" entries, because "old != new"
119             # in from_stat().
120             meta.ctime = meta.mtime = meta.atime = 0
121             meta_ofs = msw.store(meta)
122             rig.cur.from_stat(pst, meta_ofs, tstart)
123             if not (rig.cur.flags & index.IX_HASHVALID):
124                 if hashgen:
125                     (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
126                     rig.cur.flags |= index.IX_HASHVALID
127             if opt.fake_invalid:
128                 rig.cur.invalidate()
129             rig.cur.repack()
130             rig.next()
131         else:  # new paths
132             meta = metadata.from_path(path, statinfo=pst)
133             # See same assignment to 0, above, for rationale.
134             meta.atime = meta.mtime = meta.ctime = 0
135             meta_ofs = msw.store(meta)
136             wi.add(path, pst, meta_ofs, hashgen = hashgen)
137             if not stat.S_ISDIR(pst.st_mode) and pst.st_nlink > 1:
138                 hlinks.add_path(path, pst.st_dev, pst.st_ino)
139
140     progress('Indexing: %d, done.\n' % total)
141     
142     hlinks.prepare_save()
143
144     if ri.exists():
145         ri.save()
146         wi.flush()
147         if wi.count:
148             wr = wi.new_reader()
149             if opt.check:
150                 log('check: before merging: oldfile\n')
151                 check_index(ri)
152                 log('check: before merging: newfile\n')
153                 check_index(wr)
154             mi = index.Writer(indexfile, msw, tmax)
155
156             for e in index.merge(ri, wr):
157                 # FIXME: shouldn't we remove deleted entries eventually?  When?
158                 mi.add_ixentry(e)
159
160             ri.close()
161             mi.close()
162             wr.close()
163         wi.abort()
164     else:
165         wi.close()
166
167     msw.close()
168     hlinks.commit_save()
169
170
171 optspec = """
172 bup index <-p|m|s|u> [options...] <filenames...>
173 --
174  Modes:
175 p,print    print the index entries for the given names (also works with -u)
176 m,modified print only added/deleted/modified files (implies -p)
177 s,status   print each filename with a status char (A/M/D) (implies -p)
178 u,update   recursively update the index entries for the given file/dir names (default if no mode is specified)
179 check      carefully check index file integrity
180 clear      clear the index
181  Options:
182 H,hash     print the hash for each object next to its name
183 l,long     print more information about each file
184 fake-valid mark all index entries as up-to-date even if they aren't
185 fake-invalid mark all index entries as invalid
186 f,indexfile=  the name of the index file (normally BUP_DIR/bupindex)
187 exclude=   a path to exclude from the backup (can be used more than once)
188 exclude-from= a file that contains exclude paths (can be used more than once)
189 v,verbose  increase log output (can be used more than once)
190 x,xdev,one-file-system  don't cross filesystem boundaries
191 """
192 o = options.Options(optspec)
193 (opt, flags, extra) = o.parse(sys.argv[1:])
194
195 if not (opt.modified or \
196         opt['print'] or \
197         opt.status or \
198         opt.update or \
199         opt.check or \
200         opt.clear):
201     opt.update = 1
202 if (opt.fake_valid or opt.fake_invalid) and not opt.update:
203     o.fatal('--fake-{in,}valid are meaningless without -u')
204 if opt.fake_valid and opt.fake_invalid:
205     o.fatal('--fake-valid is incompatible with --fake-invalid')
206
207 # FIXME: remove this once we account for timestamp races, i.e. index;
208 # touch new-file; index.  It's possible for this to happen quickly
209 # enough that new-file ends up with the same timestamp as the first
210 # index, and then bup will ignore it.
211 tick_start = time.time()
212 time.sleep(1 - (tick_start - int(tick_start)))
213
214 git.check_repo_or_die()
215 indexfile = opt.indexfile or git.repo('bupindex')
216
217 handle_ctrl_c()
218
219 if opt.check:
220     log('check: starting initial check.\n')
221     check_index(index.Reader(indexfile))
222
223 if opt.clear:
224     log('clear: clearing index.\n')
225     clear_index(indexfile)
226
227 excluded_paths = drecurse.parse_excludes(flags)
228
229 paths = index.reduce_paths(extra)
230
231 if opt.update:
232     if not extra:
233         o.fatal('update mode (-u) requested but no paths given')
234     for (rp,path) in paths:
235         update_index(rp, excluded_paths)
236
237 if opt['print'] or opt.status or opt.modified:
238     for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
239         if (opt.modified 
240             and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
241             continue
242         line = ''
243         if opt.status:
244             if ent.is_deleted():
245                 line += 'D '
246             elif not ent.is_valid():
247                 if ent.sha == index.EMPTY_SHA:
248                     line += 'A '
249                 else:
250                     line += 'M '
251             else:
252                 line += '  '
253         if opt.hash:
254             line += ent.sha.encode('hex') + ' '
255         if opt.long:
256             line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
257         print line + (name or './')
258
259 if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
260     log('check: starting final check.\n')
261     check_index(index.Reader(indexfile))
262
263 if saved_errors:
264     log('WARNING: %d errors encountered.\n' % len(saved_errors))
265     sys.exit(1)