]> arthur.barton.de Git - bup.git/blob - cmd/tag-cmd.py
5a3108f2236c0d9ba291acbae0e350cf41a6cf58
[bup.git] / cmd / tag-cmd.py
1 #!/usr/bin/env python
2 """Tag a commit in the bup repository.
3 Creating a tag on a commit can be used for avoiding automatic cleanup from
4 removing this commit due to old age.
5 """
6 import sys
7 import os
8
9 from bup import git, options
10 from bup.helpers import *
11
12 # FIXME: review for safe writes.
13
14 handle_ctrl_c()
15
16 optspec = """
17 bup tag
18 bup tag [-f] <tag name> <commit>
19 bup tag -d [-f] <tag name>
20 --
21 d,delete=   Delete a tag
22 f,force     Overwrite existing tag, or 'delete' a tag that doesn't exist
23 """
24
25 o = options.Options(optspec)
26 (opt, flags, extra) = o.parse(sys.argv[1:])
27
28 git.check_repo_or_die()
29
30 tags = [t for sublist in git.tags().values() for t in sublist]
31
32 if opt.delete:
33     # git.delete_ref() doesn't complain if a ref doesn't exist.  We
34     # could implement this verification but we'd need to read in the
35     # contents of the tag file and pass the hash, and we already know
36     # about the tag's existance via "tags".
37     if not opt.force and opt.delete not in tags:
38         log("error: tag '%s' doesn't exist\n" % opt.delete)
39         sys.exit(1)
40     tag_file = 'refs/tags/%s' % opt.delete
41     git.delete_ref(tag_file)
42     sys.exit(0)
43
44 if not extra:
45     for t in tags:
46         print t
47     sys.exit(0)
48 elif len(extra) < 2:
49     o.fatal('no commit ref or hash given.')
50
51 (tag_name, commit) = extra[:2]
52 if not tag_name:
53     o.fatal("tag name must not be empty.")
54 debug1("args: tag name = %s; commit = %s\n" % (tag_name, commit))
55
56 if tag_name in tags and not opt.force:
57     log("bup: error: tag '%s' already exists\n" % tag_name)
58     sys.exit(1)
59
60 if tag_name.startswith('.'):
61     o.fatal("'%s' is not a valid tag name." % tag_name)
62
63 try:
64     hash = git.rev_parse(commit)
65 except git.GitError, e:
66     log("bup: error: %s" % e)
67     sys.exit(2)
68
69 if not hash:
70     log("bup: error: commit %s not found.\n" % commit)
71     sys.exit(2)
72
73 pL = git.PackIdxList(git.repo('objects/pack'))
74 if not pL.exists(hash):
75     log("bup: error: commit %s not found.\n" % commit)
76     sys.exit(2)
77
78 tag_file = git.repo('refs/tags/%s' % tag_name)
79 try:
80     tag = file(tag_file, 'w')
81 except OSError, e:
82     log("bup: error: could not create tag '%s': %s" % (tag_name, e))
83     sys.exit(3)
84
85 tag.write(hash.encode('hex'))
86 tag.close()