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