2 import sys, math, struct, glob, resource
3 from bup import options, git
4 from bup.helpers import *
7 SHA_PER_PAGE=PAGE_SIZE/20.
11 for i in xrange(0, len(l), count):
16 mf = min(resource.getrlimit(resource.RLIMIT_NOFILE))
18 mf -= 20 # just a safety margin
20 mf -= 6 # minimum safety margin
24 def merge(idxlist, bits, table):
26 for e in git.idxmerge(idxlist):
28 prefix = git.extract_bits(e, bits)
33 def do_midx(outdir, outfilename, infilenames):
36 sum = Sha1('\0'.join(infilenames)).hexdigest()
37 outfilename = '%s/midx-%s.midx' % (outdir, sum)
41 for name in infilenames:
42 ix = git.PackIdx(name)
46 log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
47 if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
48 or (opt.force and not total):
49 log('midx: nothing to do.\n')
52 pages = int(total/SHA_PER_PAGE) or 1
53 bits = int(math.ceil(math.log(pages, 2)))
55 log('Table size: %d (%d bits)\n' % (entries*4, bits))
60 os.unlink(outfilename)
63 f = open(outfilename + '.tmp', 'w+')
64 f.write('MIDX\0\0\0\2')
65 f.write(struct.pack('!I', bits))
66 assert(f.tell() == 12)
67 f.write('\0'*4*entries)
69 for e in merge(inp, bits, table):
72 f.write('\0'.join(os.path.basename(p) for p in infilenames))
75 f.write(struct.pack('!%dI' % entries, *table))
77 os.rename(outfilename + '.tmp', outfilename)
79 # this is just for testing
81 p = git.PackMidx(outfilename)
82 assert(len(p.idxnames) == len(infilenames))
84 assert(len(p) == total)
86 for i in merge(inp, total, bits, table):
87 assert(i == pi.next())
93 bup midx [options...] <idxnames...>
95 o,output= output midx filename (default: auto-generated)
96 a,auto automatically create .midx from any unindexed .idx files
97 f,force automatically create .midx from *all* .idx files
98 max-files= maximum number of idx files to open at once [-1]
100 o = options.Options('bup midx', optspec)
101 (opt, flags, extra) = o.parse(sys.argv[1:])
103 if extra and (opt.auto or opt.force):
104 o.fatal("you can't use -f/-a and also provide filenames")
106 git.check_repo_or_die()
108 if opt.max_files < 0:
109 opt.max_files = max_files()
110 assert(opt.max_files >= 5)
113 do_midx(git.repo('objects/pack'), opt.output, extra)
114 elif opt.auto or opt.force:
115 paths = [git.repo('objects/pack')]
116 paths += glob.glob(git.repo('index-cache/*/.'))
118 log('midx: scanning %s\n' % path)
120 idxs = glob.glob('%s/*.idx' % path)
121 for sublist in _group(idxs, opt.max_files):
122 do_midx(path, opt.output, sublist)
124 m = git.PackIdxList(path)
126 for pack in m.packs: # only .idx files without a .midx are open
127 if pack.name.endswith('.idx'):
128 needed[pack.name] = 1
130 do_midx(path, opt.output, needed.keys())
133 o.fatal("you must use -f or -a or provide input filenames")