summaryrefslogtreecommitdiff
path: root/morphlib/cachedrepo.py
blob: aad3d84e030a3c9678ae6283a84a641738b5bae0 (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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (C) 2012-2014  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 cliapp
import logging
import os

import morphlib


class InvalidReferenceError(cliapp.AppException):

    def __init__(self, repo, ref):
        cliapp.AppException.__init__(
            self, 'Ref %s is an invalid reference for repo %s' % (ref, repo))


class UnresolvedNamedReferenceError(cliapp.AppException):

    def __init__(self, repo, ref):
        cliapp.AppException.__init__(
            self, 'Ref %s is not a SHA1 ref for repo %s' % (ref, repo))


class CheckoutDirectoryExistsError(cliapp.AppException):

    def __init__(self, repo, target_dir):
        cliapp.AppException.__init__(
            self,
            'Checkout directory %s for repo %s already exists' %
            (target_dir, repo))


class CloneError(cliapp.AppException):

    def __init__(self, repo, target_dir):
        cliapp.AppException.__init__(
            self,
            'Failed to clone %s into %s' % (repo.original_name, target_dir))


class CopyError(cliapp.AppException):

    def __init__(self, repo, target_dir):
        cliapp.AppException.__init__(
            self,
            'Failed to copy %s into %s' % (repo.original_name, target_dir))


class CheckoutError(cliapp.AppException):

    def __init__(self, repo, ref, target_dir):
        cliapp.AppException.__init__(
            self,
            'Failed to check out ref %s in %s' % (ref, target_dir))


class UpdateError(cliapp.AppException):

    def __init__(self, repo):
        cliapp.AppException.__init__(
            self, 'Failed to update cached version of repo %s' % repo)


class CachedRepo(object):

    '''A locally cached Git repository with an origin remote set up.

    On instance of this class represents a locally cached version of a
    remote Git repository. This remote repository is set up as the
    'origin' remote.

    Cached repositories are bare mirrors of the upstream.  Locally created
    branches will be lost the next time the repository updates.

    CachedRepo objects can resolve Git refs into SHA1s. Given a SHA1
    ref, they can also be asked to return the contents of a file via the
    cat() method. They can furthermore check out the repository into
    a local directory using a SHA1 ref. Last but not least, any cached
    repo may be updated from it's origin remote using the update()
    method.

    '''

    def __init__(self, app, original_name, url, path):
        '''Creates a new CachedRepo for a repo name, URL and local path.'''

        self.app = app
        self.original_name = original_name
        self.url = url
        self.path = path
        self.is_mirror = not url.startswith('file://')
        self.already_updated = False

    def ref_exists(self, ref):
        '''Returns True if the given ref exists in the repo'''

        try:
            self._rev_parse(ref)
        except cliapp.AppException:
            return False
        return True

    def resolve_ref(self, ref):
        '''Attempts to resolve a ref into its SHA1 and tree SHA1.

        Raises an InvalidReferenceError if the ref is not found in the
        repository.

        '''

        try:
            absref = self._rev_parse(ref)
        except cliapp.AppException:
            raise InvalidReferenceError(self, ref)

        try:
            tree = self._show_tree_hash(absref)
        except cliapp.AppException:
            raise InvalidReferenceError(self, ref)

        return absref, tree

    def cat(self, ref, filename):
        '''Attempts to read a file given a SHA1 ref.

        Raises an UnresolvedNamedReferenceError if the ref is not a SHA1
        ref. Raises an InvalidReferenceError if the SHA1 ref is not found
        in the repository. Raises an IOError if the requested file is not
        found in the ref.

        '''

        if not morphlib.git.is_valid_sha1(ref):
            raise UnresolvedNamedReferenceError(self, ref)
        try:
            sha1 = self._rev_parse(ref)
        except cliapp.AppException:
            raise InvalidReferenceError(self, ref)

        try:
            return self._cat_file(sha1, filename)
        except cliapp.AppException:
            raise IOError('File %s does not exist in ref %s of repo %s' %
                          (filename, ref, self))

    def clone_checkout(self, ref, target_dir):
        '''Clone from the cache into the target path and check out a given ref.

        Raises a CheckoutDirectoryExistsError if the target
        directory already exists. Raises an InvalidReferenceError if the
        ref is not found in the repository. Raises a CheckoutError if
        something else goes wrong while copying the repository or checking
        out the SHA1 ref.

        '''

        if os.path.exists(target_dir):
            raise CheckoutDirectoryExistsError(self, target_dir)

        self.resolve_ref(ref)

        self._clone_into(target_dir, ref)

    def checkout(self, ref, target_dir):
        '''Unpacks the repository in a directory and checks out a commit ref.

        Raises an InvalidReferenceError if the ref is not found in the
        repository. Raises a CopyError if something goes wrong with the copy
        of the repository. Raises a CheckoutError if something else goes wrong
        while copying the repository or checking out the SHA1 ref.

        '''

        if not os.path.exists(target_dir):
            os.mkdir(target_dir)

        # Note, we copy instead of cloning because it's much faster in the case
        # that the target is on a different filesystem from the cache. We then
        # take care to turn the copy into something as good as a real clone.
        self._copy_repository(self.path, target_dir)

        self._checkout_ref(ref, target_dir)

    def ls_tree(self, ref):
        '''Return file names found in root tree. Does not recurse to subtrees.

        Raises an UnresolvedNamedReferenceError if the ref is not a SHA1
        ref. Raises an InvalidReferenceError if the SHA1 ref is not found
        in the repository.

        '''

        if not morphlib.git.is_valid_sha1(ref):
            raise UnresolvedNamedReferenceError(self, ref)
        try:
            sha1 = self._rev_parse(ref)
        except cliapp.AppException:
            raise InvalidReferenceError(self, ref)

        return self._ls_tree(sha1)

    def requires_update_for_ref(self, ref):
        '''Returns False if there's no need to update this cached repo.

        If the ref points to a specific commit that's already available
        locally, there's never any need to update. If it's a named ref and this
        repo wasn't already updated in the lifetime of the current process,
        it's necessary to update.

        '''
        if not self.is_mirror:
            # Repos with file:/// URLs don't ever need updating.
            return False

        if self.already_updated:
            return False

        # Named refs that are valid SHA1s will confuse this code.
        ref_can_change = not morphlib.git.is_valid_sha1(ref)

        if ref_can_change or not self.ref_exists(ref):
            return True
        else:
            return False

    def update(self):
        '''Updates the cached repository using its origin remote.

        Raises an UpdateError if anything goes wrong while performing
        the update.

        '''

        if not self.is_mirror:
            return

        try:
            self._update()
            self.already_updated = True
        except cliapp.AppException, e:
            raise UpdateError(self)

    def _runcmd(self, *args, **kwargs):  # pragma: no cover
        if not 'cwd' in kwargs:
            kwargs['cwd'] = self.path
        return self.app.runcmd(*args, **kwargs)

    def _rev_parse(self, ref):  # pragma: no cover
        return morphlib.git.gitcmd(self._runcmd, 'rev-parse', '--verify',
                                   '%s^{commit}' % ref)[0:40]

    def _show_tree_hash(self, absref):  # pragma: no cover
        return morphlib.git.gitcmd(self._runcmd, 'rev-parse', '--verify',
                                   '%s^{tree}' % absref).strip()

    def _ls_tree(self, ref):  # pragma: no cover
        result = morphlib.git.gitcmd(self._runcmd, 'ls-tree',
                                     '--name-only', ref)
        return result.split('\n')

    def _cat_file(self, ref, filename):  # pragma: no cover
        return morphlib.git.gitcmd(self._runcmd, 'cat-file', 'blob',
                                   '%s:%s' % (ref, filename))

    def _clone_into(self, target_dir, ref):  #pragma: no cover
        '''Actually perform the clone'''
        try:
            morphlib.git.clone_into(self._runcmd, self.path, target_dir, ref)
        except cliapp.AppException:
            raise CloneError(self, target_dir)

    def _copy_repository(self, source_dir, target_dir):  # pragma: no cover
        try:
            morphlib.git.copy_repository(
                self._runcmd, source_dir, target_dir, self.is_mirror)
        except cliapp.AppException:
            raise CopyError(self, target_dir)

    def _checkout_ref(self, ref, target_dir):  # pragma: no cover
        try:
            morphlib.git.checkout_ref(self._runcmd, target_dir, ref)
        except cliapp.AppException:
            raise CheckoutError(self, ref, target_dir)

    def _update(self):  # pragma: no cover
        morphlib.git.gitcmd(self._runcmd, 'remote', 'update',
                            'origin', '--prune',
                            echo_stderr=self.app.settings['verbose'])

    def __str__(self):  # pragma: no cover
        return self.url