~joetalbott/tarmac/tarmac-test

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
# Copyright 2009 Paul Hummer
# Copyright 2009-2013 Canonical Ltd.
#
# Tarmac is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by
# the Free Software Foundation.
#
# Tarmac 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 Tarmac.  If not, see <http://www.gnu.org/licenses/>.

'''Tarmac branch tools.'''
import logging
import os
import shutil
import tempfile

from bzrlib import branch as bzr_branch
from bzrlib.errors import NoSuchRevision
from bzrlib.workingtree import WorkingTree

from tarmac.config import BranchConfig
from tarmac.exceptions import (
    BranchHasConflicts,
    InvalidWorkingTree,
    TarmacMergeError,
)


class Branch(object):

    def __init__(self, lp_branch, config=False, target=None, launchpad=None):
        self.lp_branch = lp_branch
        self.bzr_branch = bzr_branch.Branch.open(self.lp_branch.bzr_identity)
        if config:
            self.config = BranchConfig(lp_branch.bzr_identity, config)
        else:
            self.config = None

        self.launchpad = launchpad
        self.target = target
        self.logger = logging.getLogger('tarmac')

    def __del__(self):
        """Do some potenetially necessary cleanup during deletion."""
        try:
            # If we were using a temp directory, then remove it
            shutil.rmtree(self.temp_tree_dir)
        except AttributeError:
            # Not using a tempdir
            pass

    @classmethod
    def create(cls, lp_branch, config, create_tree=False, target=None,
               launchpad=None):
        clazz = cls(lp_branch, config=config, target=target,
                    launchpad=launchpad)
        if create_tree:
            clazz.create_tree()
        return clazz

    def create_tree(self):
        '''Create the dir and working tree.'''
        try:
            self.logger.debug(
                'Using tree in %(tree_dir)s' % {
                    'tree_dir': self.config.tree_dir})
            if os.path.exists(self.config.tree_dir):
                self.tree = WorkingTree.open(self.config.tree_dir)

                if self.tree.branch.user_url != self.bzr_branch.user_url:
                    self.logger.debug('Tree URLs do not match: %s - %s' % (
                        self.bzr_branch.user_url, self.tree.branch.user_url))
                    raise InvalidWorkingTree(
                        'The `tree_dir` option for the target branch is not a '
                        'lightweight checkout. Please ask a project '
                        'administrator to resolve the issue, and try again.')
            else:
                self.logger.debug('Tree does not exist.  Creating dir')
                # Create the path up to but not including tree_dir if it does
                # not exist.
                parent_dir = os.path.dirname(self.config.tree_dir)
                if not os.path.exists(parent_dir):
                    os.makedirs(parent_dir)
                self.tree = self.bzr_branch.create_checkout(
                    self.config.tree_dir, lightweight=True)
        except AttributeError:
            # Store this so we can rmtree later
            self.temp_tree_dir = tempfile.mkdtemp()
            self.logger.debug(
                'Using temp dir at %(tree_dir)s' % {
                    'tree_dir': self.temp_tree_dir})
            self.tree = self.bzr_branch.create_checkout(self.temp_tree_dir)

        self.cleanup()

    def cleanup(self):
        '''Remove the working tree from the temp dir.'''
        assert self.tree
        self.tree.revert()
        for filename in [self.tree.abspath(f) for f in self.unmanaged_files]:
            if os.path.isdir(filename) and not os.path.islink(filename):
                shutil.rmtree(filename)
            else:
                os.remove(filename)

        self.tree.update()

    def merge(self, branch, revid=None):
        '''Merge from another tarmac.branch.Branch instance.'''
        assert self.tree
        conflict_list = self.tree.merge_from_branch(
            branch.bzr_branch, to_revision=revid)
        if conflict_list:
            message = u'Conflicts merging branch.'
            lp_comment = (
                u'Attempt to merge into %(target)s failed due to conflicts: '
                u'\n\n%(output)s' % {
                    'target': self.lp_branch.display_name,
                    "output": self.conflicts})
            raise BranchHasConflicts(message, lp_comment)

    def merge_tags(self, branch):
        """Merge tags from another branch into this one."""
        branch.tags.merge_to(self.tags, overwrite=True)

    @property
    def unmanaged_files(self):
        """Get the list of ignored and unknown files in the tree."""
        unmanaged = []
        try:
            self.tree.lock_read()
            unmanaged = [x for x in self.tree.unknowns()]
            unmanaged.extend([x[0] for x in self.tree.ignored_files()])
        finally:
            self.tree.unlock()
        return unmanaged

    @property
    def conflicts(self):
        '''Print the conflicts.'''
        assert self.tree.conflicts()
        conflicts = []
        for conflict in self.tree.conflicts():
            conflicts.append(
                u'%s in %s' % (conflict.typestring, conflict.path))
        return '\n'.join(conflicts)

    def commit(self, commit_message, revprops=None, **kwargs):
        '''Commit changes.'''
        if not revprops:
            revprops = {}

        authors = kwargs.pop('authors', None)
        reviews = kwargs.pop('reviews', None)

        if not authors:
            authors = self.authors

        if reviews:
            for review in reviews:
                if '\n' in review:
                    raise TarmacMergeError('\\n is not a valid character in a '
                                           'review identity or vote.')
            revprops['reviews'] = '\n'.join(reviews)

        if self.launchpad is not None:
            committer = self.launchpad.me.display_name
        else:
            committer = 'Tarmac'

        try:
            self.tree.commit(commit_message, committer=committer,
                             revprops=revprops, authors=authors)
        except AssertionError as error:
            raise TarmacMergeError(str(error))

    @property
    def landing_candidates(self):
        '''Wrap the LP representation of landing_candidates.'''
        return self.lp_branch.landing_candidates

    @property
    def authors(self):
        author_list = []

        if self.target:
            try:
                self.bzr_branch.lock_read()
                self.target.bzr_branch.lock_read()

                graph = self.bzr_branch.repository.get_graph(
                    self.target.bzr_branch.repository)

                unique_ids = graph.find_unique_ancestors(
                    self.bzr_branch.last_revision(),
                    [self.target.bzr_branch.last_revision()])

                revs = self.bzr_branch.repository.get_revisions(unique_ids)
                for rev in revs:
                    apparent_authors = rev.get_apparent_authors()
                    for author in apparent_authors:
                        author.replace('\n', '')
                        if author not in author_list:
                            author_list.append(author)

            finally:
                self.target.bzr_branch.unlock()
                self.bzr_branch.unlock()
        else:
            last_rev = self.bzr_branch.last_revision()
            if last_rev != 'null:':
                rev = self.bzr_branch.repository.get_revision(last_rev)
                apparent_authors = rev.get_apparent_authors()
                author_list.extend(
                    [a.replace('\n', '') for a in apparent_authors])

        return author_list

    @property
    def fixed_bugs(self):
        """Return the list of bugs fixed by the branch."""
        bugs_list = []

        try:
            self.bzr_branch.lock_read()
            oldrevid = self.bzr_branch.get_rev_id(self.lp_branch.revision_count)
            for rev_info in self.bzr_branch.iter_merge_sorted_revisions(
                stop_revision_id=oldrevid):
                try:
                    rev = self.bzr_branch.repository.get_revision(rev_info[0])
                    for bug in rev.iter_bugs():
                        if bug[0].startswith('https://launchpad.net/bugs/'):
                            bugs_list.append(bug[0].replace(
                                    'https://launchpad.net/bugs/', ''))
                except NoSuchRevision:
                    continue

        finally:
            self.bzr_branch.unlock()
        return bugs_list

    @property
    def tags(self):
        """Return the Tags container for the bzr_branch."""
        return self.bzr_branch.tags