summaryrefslogtreecommitdiff
path: root/morphlib/localrepocache.py
blob: b8dfea88a3cfea9a805c8912d01c669cee19b06b (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# Copyright (C) 2012  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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import logging
import os
import urllib2
import urlparse
import shutil

import morphlib


# urlparse.urljoin needs to know details of the URL scheme being used.
# It does not know about git:// by default, so we teach it here.
gitscheme=['git']
urlparse.uses_relative.extend(gitscheme)
urlparse.uses_netloc.extend(gitscheme)
urlparse.uses_params.extend(gitscheme)
urlparse.uses_query.extend(gitscheme)
urlparse.uses_fragment.extend(gitscheme)



class NoRemote(morphlib.Error):

    def __init__(self, reponame, errors):
        self.reponame = reponame
        self.errors = errors
    
    def __str__(self):
        return '\n\t'.join(['Cannot find remote git repository: %s' %
                            self.reponame] + self.errors)

class NotCached(morphlib.Error):
    def __init__(self, reponame):
        self.reponame = reponame

    def __str__(self): # pragma: no cover
        return 'Repository %s is not cached yet' % self.reponame


class LocalRepoCache(object):

    '''Manage locally cached git repositories.
    
    When we build stuff, we need a local copy of the git repository.
    To avoid having to clone the repositories for every build, we
    maintain a local cache of the repositories: we first clone the
    remote repository to the cache, and then make a local clone from
    the cache to the build environment. This class manages the local
    cached repositories.
    
    Repositories may be specified either using a full URL, in a form
    understood by git(1), or as a repository name to which a base url
    is prepended. The base urls are given to the class when it is
    created.
    
    Instead of cloning via a normal 'git clone' directly from the
    git server, we first try to download a bundle from a url, and
    if that works, we clone from the bundle.
    
    '''
    
    def __init__(self, cachedir, baseurls, bundle_base_url=None):
        self._cachedir = cachedir
        self._baseurls = baseurls
        if bundle_base_url and not bundle_base_url.endswith('/'):
            bundle_base_url += '/' # pragma: no cover
        self._bundle_base_url = bundle_base_url
        self._ex = morphlib.execute.Execute(cachedir, logging.debug)
        self._cached_repo_objects = {}

    def _exists(self, filename): # pragma: no cover
        '''Does a file exist?
        
        This is a wrapper around os.path.exists, so that unit tests may
        override it.
        
        '''
        
        return os.path.exists(filename)
    
    def _git(self, args, cwd=None): # pragma: no cover
        '''Execute git command.
        
        This is a method of its own so that unit tests can easily override
        all use of the external git command.
        
        '''
        
        self._ex.runv(['git'] + args, cwd=cwd)

    def _fetch(self, url, filename): # pragma: no cover
        '''Fetch contents of url into a file.
        
        This method is meant to be overridden by unit tests.
        
        '''
        
        source_handle = urllib2.urlopen(url)
        target_handle = open(filename, 'wb')

        data = source_handle.read(4096)
        while data:
            target_handle.write(data)
            data = source_handle.read(4096)

        source_handle.close()
        target_handle.close()

    def _mkdir(self, dirname): # pragma: no cover
        '''Create a directory.
        
        This method is meant to be overridden by unit tests.
        
        '''
        
        os.mkdir(dirname)

    def _remove(self, filename): # pragma: no cover
        '''Remove given file.
        
        This method is meant to be overridden by unit tests.
        
        '''
        
        os.remove(filename)

    def _rmtree(self, dirname): # pragma: no cover
        '''Remove given directory tree.

        This method is meant to be overridden by unit tests.

        '''
        
        shutil.rmtree(dirname)

    def _escape(self, url):
        '''Escape a URL so it can be used as a basename in a file.'''
        
        # FIXME: The following is a nicer way than what source manager does.
        # However, for compatibility, we need to use the same as the source
        # manager uses, since that's what the bundle server (set up by
        # Lorry) uses.
        # return urllib.quote(url, safe='')
        
        return morphlib.sourcemanager.quote_url(url)

    def _cache_name(self, url):
        basename = self._escape(url)
        path = os.path.join(self._cachedir, basename)
        return path
    
    def _base_iterate(self, reponame):
        for baseurl in self._baseurls:
            if not baseurl.endswith('/'):
                baseurl += '/' # pragma: no cover
            repourl = urlparse.urljoin(baseurl, reponame)
            path = self._cache_name(repourl)
            yield repourl, path
    
    def has_repo(self, reponame):
        '''Have we already got a cache of a given repo?'''
        for repourl, path in self._base_iterate(reponame):
            if self._exists(path):
                return True
        return False

    def _clone_with_bundle(self, repourl, path):
        escaped = self._escape(repourl)
        bundle_url = urlparse.urljoin(self._bundle_base_url, escaped) + '.bndl'
        bundle_path = path + '.bundle'

        try:
            self._fetch(bundle_url, bundle_path)
        except urllib2.URLError, e:
            return False, 'Unable to fetch bundle %s: %s' % (bundle_url, e)

        try:
            self._git(['clone', '-n', bundle_path, path])
            self._git(['remote', 'set-url', 'origin', repourl], cwd=path)
        except morphlib.execute.CommandFailure, e: # pragma: no cover
            if self._exists(path):
                shutil.rmtree(path)
            return False, 'Unable to extract bundle %s: %s' % (bundle_path, e)
        finally:
            if self._exists(bundle_path):
                self._remove(bundle_path)

        return True, None

    def cache_repo(self, reponame):
        '''Clone the given repo into the cache.
        
        If the repo is already cloned, do nothing.
        
        '''
        errors = []
        if not self._exists(self._cachedir):
            self._mkdir(self._cachedir)

        try:
            return self.get_repo(reponame)
        except NotCached, e:
            pass

        if self._bundle_base_url:
            for repourl, path in self._base_iterate(reponame):
                ok, error = self._clone_with_bundle(repourl, path)
                if ok:
                    return self.get_repo(reponame)
                else:
                   errors.append(error)

        for repourl, path in self._base_iterate(reponame):
            try:
                self._git(['clone', '-n', repourl, path])
            except morphlib.execute.CommandFailure, e:
                errors.append('Unable to clone from %s to %s: %s' %
                                                 (repourl, path, e))
            else:
                break
        else:
            raise NoRemote(reponame, errors)

        return self.get_repo(reponame)

    def get_repo(self, reponame):
        '''Return an object representing a cached repository.'''

        if reponame in self._cached_repo_objects:
            return self._cached_repo_objects[reponame]
        else:
            for repourl, path in self._base_iterate(reponame):
                if self._exists(path):
                    repo = morphlib.cachedrepo.CachedRepo(
                            reponame, repourl, path)
                    self._cached_repo_objects[reponame] = repo
                    return repo
        raise NotCached(reponame)