
import os
import sys

from bzrlib.branch import Branch
from bzrlib.errors import NotBranchError


branchdir, tagsdir = sys.argv[1:]

branch = Branch.open(branchdir)

# Create a Tag name -> revid mapping
tags = {}
for tag in os.listdir(tagsdir):
    try:
        tagbranch = Branch.open(os.path.join(tagsdir, tag))
    except NotBranchError:
        continue
    tags[tag] = tagbranch.last_revision()

# Add tags where the corresponding revids are in the ancestry
branch.lock_write()
try:
    ancestry = set(branch.repository.get_ancestry(branch.last_revision()))
    for (tag, revid) in sorted(tags.items()):
        if revid in ancestry:
            branch.tags.set_tag(tag, revid)
            print "Set tag %s to %s" % (tag, revid)
        elif branch.tags.has_tag(tag):
            branch.tags.delete_tag(tag)
            print "Unset tag %s" % tag
finally:
    branch.unlock()
