]> arthur.barton.de Git - bup.git/blob - lib/bup/cmd/cat_file.py
cat-file-cmd: copy to bup.cmd.cat_file
[bup.git] / lib / bup / cmd / cat_file.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
19 # Intentionally replace the dirname "$0" that python prepends
20 import os, sys
21 sys.path[0] = os.path.dirname(os.path.realpath(__file__)) + '/../..'
22
23 import os.path, re, stat
24
25 from bup import compat, options, git, vfs
26 from bup.compat import argv_bytes
27 from bup.helpers import chunkyreader, handle_ctrl_c, log, saved_errors
28 from bup.io import byte_stream
29 from bup.repo import LocalRepo
30
31 optspec = """
32 bup cat-file [--meta|--bupm] /branch/revision/[path]
33 --
34 meta        print the target's metadata entry (decoded then reencoded) to stdout
35 bupm        print the target directory's .bupm file directly to stdout
36 """
37
38 handle_ctrl_c()
39
40 o = options.Options(optspec)
41 opt, flags, extra = o.parse(compat.argv[1:])
42
43 git.check_repo_or_die()
44
45 if not extra:
46     o.fatal('must specify a target')
47 if len(extra) > 1:
48     o.fatal('only one target file allowed')
49 if opt.bupm and opt.meta:
50     o.fatal('--meta and --bupm are incompatible')
51
52 target = argv_bytes(extra[0])
53
54 if not re.match(br'/*[^/]+/[^/]+', target):
55     o.fatal("path %r doesn't include a branch and revision" % target)
56
57 repo = LocalRepo()
58 resolved = vfs.resolve(repo, target, follow=False)
59 leaf_name, leaf_item = resolved[-1]
60 if not leaf_item:
61     log('error: cannot access %r in %r\n'
62         % ('/'.join(name for name, item in resolved), path))
63     sys.exit(1)
64
65 mode = vfs.item_mode(leaf_item)
66
67 sys.stdout.flush()
68 out = byte_stream(sys.stdout)
69
70 if opt.bupm:
71     if not stat.S_ISDIR(mode):
72         o.fatal('%r is not a directory' % target)
73     _, bupm_oid = vfs.tree_data_and_bupm(repo, leaf_item.oid)
74     if bupm_oid:
75         with vfs.tree_data_reader(repo, bupm_oid) as meta_stream:
76             out.write(meta_stream.read())
77 elif opt.meta:
78     augmented = vfs.augment_item_meta(repo, leaf_item, include_size=True)
79     out.write(augmented.meta.encode())
80 else:
81     if stat.S_ISREG(mode):
82         with vfs.fopen(repo, leaf_item) as f:
83             for b in chunkyreader(f):
84                 out.write(b)
85     else:
86         o.fatal('%r is not a plain file' % target)
87
88 if saved_errors:
89     log('warning: %d errors encountered\n' % len(saved_errors))
90     sys.exit(1)