1#!/bin/sh
2"""": # -*-python-*-
3# https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4export "BUP_ARGV_0"="$0"
5arg_i=1
6for arg in "$@"; do
7    export "BUP_ARGV_${arg_i}"="$arg"
8    shift
9    arg_i=$((arg_i + 1))
10done
11# Here to end of preamble replaced during install
12bup_python="$(dirname "$0")/../../config/bin/python" || exit $?
13exec "$bup_python" "$0"
14"""
15# end of bup preamble
16
17from __future__ import absolute_import, print_function
18from binascii import hexlify, unhexlify
19import os, sys
20
21sys.path[:0] = [os.path.dirname(os.path.realpath(__file__)) + '/..']
22
23from bup import compat, git, options
24from bup.compat import argv_bytes
25from bup.helpers import add_error, handle_ctrl_c, log, qprogress, saved_errors
26from bup.io import byte_stream
27
28optspec = """
29bup list-idx [--find=<prefix>] <idxfilenames...>
30--
31find=   display only objects that start with <prefix>
32"""
33o = options.Options(optspec)
34opt, flags, extra = o.parse(compat.argv[1:])
35
36handle_ctrl_c()
37
38opt.find = argv_bytes(opt.find) if opt.find else b''
39
40if not extra:
41    o.fatal('you must provide at least one filename')
42
43if len(opt.find) > 40:
44    o.fatal('--find parameter must be <= 40 chars long')
45else:
46    if len(opt.find) % 2:
47        s = opt.find + b'0'
48    else:
49        s = opt.find
50    try:
51        bin = unhexlify(s)
52    except TypeError:
53        o.fatal('--find parameter is not a valid hex string')
54
55sys.stdout.flush()
56out = byte_stream(sys.stdout)
57find = opt.find.lower()
58count = 0
59idxfiles = [argv_bytes(x) for x in extra]
60for name in idxfiles:
61    try:
62        ix = git.open_idx(name)
63    except git.GitError as e:
64        add_error('%r: %s' % (name, e))
65        continue
66    if len(opt.find) == 40:
67        if ix.exists(bin):
68            out.write(b'%s %s\n' % (name, find))
69    else:
70        # slow, exhaustive search
71        for _i in ix:
72            i = hexlify(_i)
73            if i.startswith(find):
74                out.write(b'%s %s\n' % (name, i))
75            qprogress('Searching: %d\r' % count)
76            count += 1
77
78if saved_errors:
79    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
80    sys.exit(1)
81