summaryrefslogtreecommitdiff
path: root/morphlib/sourcepool.py
blob: b340a9dec5e4caeb27eb3074602163ddbb432bff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Copyright (C) 2012-2015  Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.


import collections


class SourcePool(object):

    '''Manage a collection of Source objects.'''

    def __init__(self):
        self._sources = collections.defaultdict(dict)
        self._order = []

    def _key(self, repo_name, original_ref, filename):
        return (repo_name, original_ref, filename)

    def add(self, source):
        '''Add a source to the pool.'''
        key = self._key(source.repo_name,
                        source.original_ref,
                        source.filename)
        if key not in self._sources or source.name not in self._sources[key]:
            self._sources[key][source.name] = source
            self._order.append(source)

    def lookup(self, repo_name, original_ref, filename):
        '''Find a source in the pool.

        Raise KeyError if it is not found.

        '''

        key = self._key(repo_name, original_ref, filename)
        return self._sources[key].values()

    def __iter__(self):
        '''Iterate over sources in the pool, in the order they were added.'''
        for source in self._order:
            yield source

    def __len__(self):
        return len(self._sources)