]> arthur.barton.de Git - bup.git/blob - lib/cmd/tag-cmd.py
Move cmd to lib/ and reverse symlink
[bup.git] / lib / cmd / tag-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
9 from binascii import hexlify
10 import os, sys
11
12 from bup import git, options
13 from bup.compat import argv_bytes
14 from bup.helpers import debug1, handle_ctrl_c, log
15 from bup.io import byte_stream, path_msg
16
17 # FIXME: review for safe writes.
18
19 handle_ctrl_c()
20
21 optspec = """
22 bup tag
23 bup tag [-f] <tag name> <commit>
24 bup tag [-f] -d <tag name>
25 --
26 d,delete=   Delete a tag
27 f,force     Overwrite existing tag, or ignore missing tag when deleting
28 """
29
30 o = options.Options(optspec)
31 (opt, flags, extra) = o.parse(sys.argv[1:])
32
33 git.check_repo_or_die()
34
35 tags = [t for sublist in git.tags().values() for t in sublist]
36
37 if opt.delete:
38     # git.delete_ref() doesn't complain if a ref doesn't exist.  We
39     # could implement this verification but we'd need to read in the
40     # contents of the tag file and pass the hash, and we already know
41     # about the tag's existance via "tags".
42     tag_name = argv_bytes(opt.delete)
43     if not opt.force and tag_name not in tags:
44         log("error: tag '%s' doesn't exist\n" % path_msg(tag_name))
45         sys.exit(1)
46     tag_file = b'refs/tags/%s' % tag_name
47     git.delete_ref(tag_file)
48     sys.exit(0)
49
50 if not extra:
51     for t in tags:
52         sys.stdout.flush()
53         out = byte_stream(sys.stdout)
54         out.write(t)
55         out.write(b'\n')
56     sys.exit(0)
57 elif len(extra) != 2:
58     o.fatal('expected commit ref and hash')
59
60 tag_name, commit = map(argv_bytes, extra[:2])
61 if not tag_name:
62     o.fatal("tag name must not be empty.")
63 debug1("args: tag name = %s; commit = %s\n"
64        % (path_msg(tag_name), commit.decode('ascii')))
65
66 if tag_name in tags and not opt.force:
67     log("bup: error: tag '%s' already exists\n" % path_msg(tag_name))
68     sys.exit(1)
69
70 if tag_name.startswith(b'.'):
71     o.fatal("'%s' is not a valid tag name." % path_msg(tag_name))
72
73 try:
74     hash = git.rev_parse(commit)
75 except git.GitError as e:
76     log("bup: error: %s" % e)
77     sys.exit(2)
78
79 if not hash:
80     log("bup: error: commit %s not found.\n" % commit.decode('ascii'))
81     sys.exit(2)
82
83 pL = git.PackIdxList(git.repo(b'objects/pack'))
84 if not pL.exists(hash):
85     log("bup: error: commit %s not found.\n" % commit.decode('ascii'))
86     sys.exit(2)
87
88 tag_file = git.repo(b'refs/tags/' + tag_name)
89 try:
90     tag = open(tag_file, 'wb')
91 except OSError as e:
92     log("bup: error: could not create tag '%s': %s" % (path_msg(tag_name), e))
93     sys.exit(3)
94 with tag as tag:
95     tag.write(hexlify(hash))
96     tag.write(b'\n')