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