~rom1-chal/bzr-builder/merge-all-what-can-be

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
from bzrlib import (
    errors,
    revision,
    annotate, 
    osutils,    
    _format_version_tuple
    )
import time

class GlobalReport(object):
    
    def __init__(self, basebranch, recipename):
        self.basebranch = basebranch
        self.recipe=recipename
        
        self.report_elements = []
        self.conflicts_notes = []
        # Attributes to render a nice looking ReST table
        self.branch_length=8
        self.message_length=9
        # impacted developers
        self.impacted_developers = []
        
    def __str__(self):
    
        # If the report_elements array has been initialized, no need to regenerate it. 
        # FIXME : this elements generation should be elsewhere...
        if len(self.report_elements) == 0:
            self.stringify_element(self.basebranch.report)
            for child in self.basebranch.child_branches : 
                self.stringify_element(child.recipe_branch.report)
                for nest_child in child.recipe_branch.child_branches:
                    self.stringify_element(nest_child.recipe_branch.report)
    
        report = '''
------------
Build report
------------

Build of branch %s from recipe ``%s``

%s


--------
Manifest
--------

Generated manifest file:

>>>
%s


''' % (self.basebranch.url, self.recipe, 
        self.format_elements_table(), 
        self.basebranch)
       
        return report


    def generate_conflicts_notes(self, branch_url, file, conflicts_details):
        msg = 'Conflicts reported from %s in branch %s:\n' % (file, branch_url)
        
        for c in conflicts : 
            msg += ':' % (file, branch_url)
        
        self.conflicts_notes.append(msg)
        print str(conflicts_details)
        
        
    def stringify_element(self, report_element):
        
        # TODO : may have other cases than conflicts of non valid results, for instance, build result ? 
        status = '  NOK   '
        if report_element.__class__ not in [UnresolvedConflicts, ConflictsFromMerge, UndoneAction]:
            status = '   OK   '

        # Branch url
        this_branch_length = len(report_element.recipebranch.url)
        if this_branch_length > self.branch_length:
            self.branch_length = this_branch_length

        # Report message
        this_message_length = len(str(report_element))
        if this_message_length > self.message_length:
            self.message_length = this_message_length
        
        # Conflicted files
        conflicted_files=[]
        conflicts_details = []
        for file, developers, conflicts in report_element.conflicts : 
            conflicted_file = "``%s`` (modifications from %s)" % (file, ', '.join(developers))
            self.impacted_developers.extend(developers)
            #conflicted_file = "``%s`` in conflict" % (file)
            this_conflicted_file_length = len(conflicted_file)
            if this_conflicted_file_length > self.message_length:
                self.message_length = this_conflicted_file_length
            
            conflicted_files.append(conflicted_file)
        
            #self.generate_conflicts_notes(report_element.recipebranch.url, file, conflicts)
        
        # Get the revno from the revid for an easier log
        report_element.recipebranch.branch.lock_read()
        revno = report_element.recipebranch.branch.revision_id_to_dotted_revno(report_element.recipebranch.revid)
        str_revno = '.'.join(str(v) for v in revno)
        report_element.recipebranch.branch.unlock()
        
        # Append the self.elements with (status, branch url, revision, report msg, conflicted_files)
        tuple_report_strings = (status, report_element.recipebranch.url, str_revno, str(report_element), conflicted_files)
        
        self.report_elements.append( tuple_report_strings )

    def format_elements_table(self):
        # Format table header
        # +--------+--------+-------+---------+
        # | Status | Branch | Revno | Message |
        # +========+========+=======+=========+
        horizontal_line  = "+--------+%s+-------+%s+\n" % ("-"*(self.branch_length+2), "-"*(self.message_length+2))
        report = horizontal_line
        report += "| Status | Branch%s | Revno | Message%s |\n" % ("".rjust(self.branch_length-6), "".rjust(self.message_length-7))
        report += "+========+%s+=======+%s+\n" % ("="*(self.branch_length+2), "="*(self.message_length+2))
        
        # Line for each report element
        for (status, branch, revno, message, conflicted_files) in self.report_elements:
            report += "|%s| %s | %s | %s |\n" % (
                                            status, 
                                            branch.rjust(self.branch_length), 
                                            revno.rjust(5), 
                                            message.rjust(self.message_length)
                                            )
            report += horizontal_line 
            for f in conflicted_files:
                report += "|%s| %s |\n" % ( ' '*(19+self.branch_length), str(f).ljust(self.message_length) )
                report += horizontal_line 

        report += '\n\n'
        return report
        
    def to_html(self):
        from docutils import core

        overrides = {'input_encoding': 'unicode',
                     'doctitle_xform': 'Build report',
                     'initial_header_level': 1}
        parts = core.publish_parts(
            source=unicode(str(self)),
            writer_name='html', 
            settings_overrides=overrides)
        return parts['html_body']
        

def save_as(content, path):
    _f = open(path, 'wb')
    try:
        _f.write(content)
    finally:
        _f.close()


# Class for reporting. Main object handled in GLOBAL_REPORT dictionary
class BranchReport(object) : 
    def __init__(self, recipebranch, tree=None):
        """
        FIXME
        @param recipebranch:
        @type recipebranch: RecipeBranch
        @param tree:
        @type tree:
        """
        self.recipebranch = recipebranch
        self.branchname = self.recipebranch.name
        if self.branchname is None:
            self.branchname = "basebranch"
        self.tree = tree
        if self.tree is not None : 
            self.workingdir = self.tree.basedir
        self.conflicts = []

# Class to handle a report on a branch that has been merged on the recipe branch
class MergeReport(BranchReport) : 
    def __str__(self):
        return "%s has been merged in %s and committed." % (self.recipebranch.name, self.recipebranch.parent.url)

# Class to handle a report on a branch that has been merged on the recipe branch
class NestReport(BranchReport) : 
    def __str__(self):
        return "%s has been retrieved." % (self.recipebranch.name)

# Class to handle a report on a branch that is already merged in the recipe branch
class AlreadyMergedReport(BranchReport) : 
    def __str__(self):
        return "%s is already merged in %s." % (self.recipebranch.name, self.recipebranch.parent.url)
     
class ConflictsReport(errors.BzrError, BranchReport):
    def __init__(self, childbranch, tree):
        """
        FIXME
        @param childbranch:
        @type childbranch:RecipeBranch
        @param tree:
        @type tree:
        """
        errors.BzrError.__init__(self)
        BranchReport.__init__(self, childbranch, tree)
        self.analyse_conflicts()

    # Method analysing conflicted file in the tree
    def analyse_conflicts(self):

        # Init of the current revision : _expand_annotations does not work with None
        current_rev = revision.Revision(revision.CURRENT_REVISION)
        current_rev.parent_ids = self.tree.get_parent_ids()
        current_rev.committer = self.tree.branch.get_config().username() 
        current_rev.message = "?" 
        current_rev.timestamp = round(time.time(), 3)
        current_rev.timezone = osutils.local_time_offset()
        
        for conflicted_file in self.tree._iter_conflicts() : 
            # Annotate conflicted files
            fileid = self.tree.path2id(conflicted_file)
            annotations = list(self.tree.annotate_iter(fileid))
            annotation = list(annotate._expand_annotations(annotations, self.tree.branch, current_rev))            
            
            in_conflict_part = False
            developers = []
            conflict_report = []
            conflict = {'to' : '', 'from' : '' }
            # Retrieve the developpers name from the annotation inside the conflict block
            for annotate_element in annotation : 
                (revno_str, author, date_str, origin, text) = annotate_element
                if text.startswith( "=======") : 
                    target = 'to'
                    continue

                if text.startswith(">>>>>>> MERGE-SOURCE"):
                    in_conflict_part = False
                    continue
                    
                if in_conflict_part and len(author) > 0 : 
                    developers.append(author)
                    conflict[target] += text + '\n'
                
                if text.startswith("<<<<<<< TREE"):
                    target='from'
                    in_conflict_part = True
                    
            developers_set = set(developers)
            
            self.conflicts.append( (conflicted_file, developers_set, conflict) )
    
# Class to handle exception when merge produces conflicts
# The msg is targetted to give the necessary information to resolve the conflict
class ConflictsFromMerge(ConflictsReport) : 
    def __str__(self):
        return "Conflicts have been detected while merging %s in %s" % (self.recipebranch.name, self.recipebranch.parent.url)

# Unresolved conflicts are still present in the working dir the build is being done
class UnresolvedConflicts(ConflictsReport) : 
    _fmt = "Unresolved conflicts are still present in the working directory %(workingdir)s"

# Unresolved conflicts are still (exception sent without report)
class ExistingConflictsInTree(errors.BzrError) : 
    def __init__(self):
        errors.BzrError.__init__(self)    
        
# Initialisation of report element
class UndoneAction(BranchReport) : 
    def __str__(self) : 
        return "Undone action"