]> arthur.barton.de Git - bup.git/blob - lib/cmd/cat-file-cmd.py
Prefer python 3, and mention intent to drop python 2 support
[bup.git] / lib / cmd / cat-file-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
5 arg_i=1
6 for arg in "$@"; do
7     export "BUP_ARGV_${arg_i}"="$arg"
8     shift
9     arg_i=$((arg_i + 1))
10 done
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/../../config/bin/python" || exit $?
13 exec "$bup_python" "$0"
14 """
15 # end of bup preamble
16
17 from __future__ import absolute_import
18 import os.path, re, stat, sys
19
20 sys.path[:0] = [os.path.dirname(os.path.realpath(__file__)) + '/..']
21
22 from bup import compat, options, git, vfs
23 from bup.compat import argv_bytes
24 from bup.helpers import chunkyreader, handle_ctrl_c, log, saved_errors
25 from bup.io import byte_stream
26 from bup.repo import LocalRepo
27
28 optspec = """
29 bup cat-file [--meta|--bupm] /branch/revision/[path]
30 --
31 meta        print the target's metadata entry (decoded then reencoded) to stdout
32 bupm        print the target directory's .bupm file directly to stdout
33 """
34
35 handle_ctrl_c()
36
37 o = options.Options(optspec)
38 opt, flags, extra = o.parse(compat.argv[1:])
39
40 git.check_repo_or_die()
41
42 if not extra:
43     o.fatal('must specify a target')
44 if len(extra) > 1:
45     o.fatal('only one target file allowed')
46 if opt.bupm and opt.meta:
47     o.fatal('--meta and --bupm are incompatible')
48     
49 target = argv_bytes(extra[0])
50
51 if not re.match(br'/*[^/]+/[^/]+', target):
52     o.fatal("path %r doesn't include a branch and revision" % target)
53
54 repo = LocalRepo()
55 resolved = vfs.resolve(repo, target, follow=False)
56 leaf_name, leaf_item = resolved[-1]
57 if not leaf_item:
58     log('error: cannot access %r in %r\n'
59         % ('/'.join(name for name, item in resolved), path))
60     sys.exit(1)
61
62 mode = vfs.item_mode(leaf_item)
63
64 sys.stdout.flush()
65 out = byte_stream(sys.stdout)
66
67 if opt.bupm:
68     if not stat.S_ISDIR(mode):
69         o.fatal('%r is not a directory' % target)
70     _, bupm_oid = vfs.tree_data_and_bupm(repo, leaf_item.oid)
71     if bupm_oid:
72         with vfs.tree_data_reader(repo, bupm_oid) as meta_stream:
73             out.write(meta_stream.read())
74 elif opt.meta:
75     augmented = vfs.augment_item_meta(repo, leaf_item, include_size=True)
76     out.write(augmented.meta.encode())
77 else:
78     if stat.S_ISREG(mode):
79         with vfs.fopen(repo, leaf_item) as f:
80             for b in chunkyreader(f):
81                 out.write(b)
82     else:
83         o.fatal('%r is not a plain file' % target)
84
85 if saved_errors:
86     log('warning: %d errors encountered\n' % len(saved_errors))
87     sys.exit(1)