##// END OF EJS Templates
namespaces: add a method to the first matching node for a given name
Sean Farley -
r23559:3b3a962e default
parent child Browse files
Show More
@@ -1,60 +1,80 b''
1 from i18n import _
1 2 from mercurial import util
2 3 import weakref
3 4
4 5 def tolist(val):
5 6 """
6 7 a convenience method to return an empty list instead of None
7 8 """
8 9 if val is None:
9 10 return []
10 11 else:
11 12 return [val]
12 13
13 14 class namespaces(object):
14 15 """
15 16 provides an interface to register a generic many-to-many mapping between
16 17 some (namespaced) names and nodes. The goal here is to control the
17 18 pollution of jamming things into tags or bookmarks (in extension-land) and
18 19 to simplify internal bits of mercurial: log output, tab completion, etc.
19 20
20 21 More precisely, we define a list of names (the namespace) and a mapping of
21 22 names to nodes. This name mapping returns a list of nodes.
22 23
23 24 Furthermore, each name mapping will be passed a name to lookup which might
24 25 not be in its domain. In this case, each method should return an empty list
25 26 and not raise an error.
26 27
27 28 We'll have a dictionary '_names' where each key is a namespace and
28 29 its value is a dictionary of functions:
29 30 'namemap': function that takes a name and returns a list of nodes
30 31 """
31 32
32 33 _names_version = 0
33 34
34 35 def __init__(self, repo):
35 36 self._names = util.sortdict()
36 37 self._repo = weakref.ref(repo)
37 38
38 39 # we need current mercurial named objects (bookmarks, tags, and
39 40 # branches) to be initialized somewhere, so that place is here
40 41 self.addnamespace("bookmarks",
41 42 lambda repo, name: tolist(repo._bookmarks.get(name)))
42 43
43 44 @property
44 45 def repo(self):
45 46 return self._repo()
46 47
47 48 def addnamespace(self, namespace, namemap, order=None):
48 49 """
49 50 register a namespace
50 51
51 52 namespace: the name to be registered (in plural form)
52 53 namemap: function that inputs a node, output name(s)
53 54 order: optional argument to specify the order of namespaces
54 55 (e.g. 'branches' should be listed before 'bookmarks')
55 56 """
56 57 val = {'namemap': namemap}
57 58 if order is not None:
58 59 self._names.insert(order, namespace, val)
59 60 else:
60 61 self._names[namespace] = val
62
63 def singlenode(self, name):
64 """
65 Return the 'best' node for the given name. Best means the first node
66 in the first nonempty list returned by a name-to-nodes mapping function
67 in the defined precedence order.
68
69 Raises a KeyError if there is no such node.
70 """
71 for ns, v in self._names.iteritems():
72 n = v['namemap'](self.repo, name)
73 if n:
74 # return max revision number
75 if len(n) > 1:
76 cl = self.repo.changelog
77 maxrev = max(cl.rev(node) for node in n)
78 return cl.node(maxrev)
79 return n[0]
80 raise KeyError(_('no such name: %s') % name)
General Comments 0
You need to be logged in to leave comments. Login now