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