##// END OF EJS Templates
logging: don't use root logger on codeblocks
marcink -
r2586:727a3d6d default
parent child Browse files
Show More
@@ -1,743 +1,743 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import difflib
23 23 from itertools import groupby
24 24
25 25 from pygments import lex
26 26 from pygments.formatters.html import _get_ttype_class as pygment_token_class
27 27 from pygments.lexers.special import TextLexer, Token
28 28
29 29 from rhodecode.lib.helpers import (
30 30 get_lexer_for_filenode, html_escape, get_custom_lexer)
31 31 from rhodecode.lib.utils2 import AttributeDict
32 32 from rhodecode.lib.vcs.nodes import FileNode
33 33 from rhodecode.lib.diff_match_patch import diff_match_patch
34 34 from rhodecode.lib.diffs import LimitedDiffContainer
35 35 from pygments.lexers import get_lexer_by_name
36 36
37 37 plain_text_lexer = get_lexer_by_name(
38 38 'text', stripall=False, stripnl=False, ensurenl=False)
39 39
40 40
41 log = logging.getLogger()
41 log = logging.getLogger(__name__)
42 42
43 43
44 44 def filenode_as_lines_tokens(filenode, lexer=None):
45 45 org_lexer = lexer
46 46 lexer = lexer or get_lexer_for_filenode(filenode)
47 47 log.debug('Generating file node pygment tokens for %s, %s, org_lexer:%s',
48 48 lexer, filenode, org_lexer)
49 49 tokens = tokenize_string(filenode.content, lexer)
50 50 lines = split_token_stream(tokens)
51 51 rv = list(lines)
52 52 return rv
53 53
54 54
55 55 def tokenize_string(content, lexer):
56 56 """
57 57 Use pygments to tokenize some content based on a lexer
58 58 ensuring all original new lines and whitespace is preserved
59 59 """
60 60
61 61 lexer.stripall = False
62 62 lexer.stripnl = False
63 63 lexer.ensurenl = False
64 64
65 65 if isinstance(lexer, TextLexer):
66 66 lexed = [(Token.Text, content)]
67 67 else:
68 68 lexed = lex(content, lexer)
69 69
70 70 for token_type, token_text in lexed:
71 71 yield pygment_token_class(token_type), token_text
72 72
73 73
74 74 def split_token_stream(tokens):
75 75 """
76 76 Take a list of (TokenType, text) tuples and split them by a string
77 77
78 78 split_token_stream([(TEXT, 'some\ntext'), (TEXT, 'more\n')])
79 79 [(TEXT, 'some'), (TEXT, 'text'),
80 80 (TEXT, 'more'), (TEXT, 'text')]
81 81 """
82 82
83 83 buffer = []
84 84 for token_class, token_text in tokens:
85 85 parts = token_text.split('\n')
86 86 for part in parts[:-1]:
87 87 buffer.append((token_class, part))
88 88 yield buffer
89 89 buffer = []
90 90
91 91 buffer.append((token_class, parts[-1]))
92 92
93 93 if buffer:
94 94 yield buffer
95 95
96 96
97 97 def filenode_as_annotated_lines_tokens(filenode):
98 98 """
99 99 Take a file node and return a list of annotations => lines, if no annotation
100 100 is found, it will be None.
101 101
102 102 eg:
103 103
104 104 [
105 105 (annotation1, [
106 106 (1, line1_tokens_list),
107 107 (2, line2_tokens_list),
108 108 ]),
109 109 (annotation2, [
110 110 (3, line1_tokens_list),
111 111 ]),
112 112 (None, [
113 113 (4, line1_tokens_list),
114 114 ]),
115 115 (annotation1, [
116 116 (5, line1_tokens_list),
117 117 (6, line2_tokens_list),
118 118 ])
119 119 ]
120 120 """
121 121
122 122 commit_cache = {} # cache commit_getter lookups
123 123
124 124 def _get_annotation(commit_id, commit_getter):
125 125 if commit_id not in commit_cache:
126 126 commit_cache[commit_id] = commit_getter()
127 127 return commit_cache[commit_id]
128 128
129 129 annotation_lookup = {
130 130 line_no: _get_annotation(commit_id, commit_getter)
131 131 for line_no, commit_id, commit_getter, line_content
132 132 in filenode.annotate
133 133 }
134 134
135 135 annotations_lines = ((annotation_lookup.get(line_no), line_no, tokens)
136 136 for line_no, tokens
137 137 in enumerate(filenode_as_lines_tokens(filenode), 1))
138 138
139 139 grouped_annotations_lines = groupby(annotations_lines, lambda x: x[0])
140 140
141 141 for annotation, group in grouped_annotations_lines:
142 142 yield (
143 143 annotation, [(line_no, tokens)
144 144 for (_, line_no, tokens) in group]
145 145 )
146 146
147 147
148 148 def render_tokenstream(tokenstream):
149 149 result = []
150 150 for token_class, token_ops_texts in rollup_tokenstream(tokenstream):
151 151
152 152 if token_class:
153 153 result.append(u'<span class="%s">' % token_class)
154 154 else:
155 155 result.append(u'<span>')
156 156
157 157 for op_tag, token_text in token_ops_texts:
158 158
159 159 if op_tag:
160 160 result.append(u'<%s>' % op_tag)
161 161
162 162 escaped_text = html_escape(token_text)
163 163
164 164 # TODO: dan: investigate showing hidden characters like space/nl/tab
165 165 # escaped_text = escaped_text.replace(' ', '<sp> </sp>')
166 166 # escaped_text = escaped_text.replace('\n', '<nl>\n</nl>')
167 167 # escaped_text = escaped_text.replace('\t', '<tab>\t</tab>')
168 168
169 169 result.append(escaped_text)
170 170
171 171 if op_tag:
172 172 result.append(u'</%s>' % op_tag)
173 173
174 174 result.append(u'</span>')
175 175
176 176 html = ''.join(result)
177 177 return html
178 178
179 179
180 180 def rollup_tokenstream(tokenstream):
181 181 """
182 182 Group a token stream of the format:
183 183
184 184 ('class', 'op', 'text')
185 185 or
186 186 ('class', 'text')
187 187
188 188 into
189 189
190 190 [('class1',
191 191 [('op1', 'text'),
192 192 ('op2', 'text')]),
193 193 ('class2',
194 194 [('op3', 'text')])]
195 195
196 196 This is used to get the minimal tags necessary when
197 197 rendering to html eg for a token stream ie.
198 198
199 199 <span class="A"><ins>he</ins>llo</span>
200 200 vs
201 201 <span class="A"><ins>he</ins></span><span class="A">llo</span>
202 202
203 203 If a 2 tuple is passed in, the output op will be an empty string.
204 204
205 205 eg:
206 206
207 207 >>> rollup_tokenstream([('classA', '', 'h'),
208 208 ('classA', 'del', 'ell'),
209 209 ('classA', '', 'o'),
210 210 ('classB', '', ' '),
211 211 ('classA', '', 'the'),
212 212 ('classA', '', 're'),
213 213 ])
214 214
215 215 [('classA', [('', 'h'), ('del', 'ell'), ('', 'o')],
216 216 ('classB', [('', ' ')],
217 217 ('classA', [('', 'there')]]
218 218
219 219 """
220 220 if tokenstream and len(tokenstream[0]) == 2:
221 221 tokenstream = ((t[0], '', t[1]) for t in tokenstream)
222 222
223 223 result = []
224 224 for token_class, op_list in groupby(tokenstream, lambda t: t[0]):
225 225 ops = []
226 226 for token_op, token_text_list in groupby(op_list, lambda o: o[1]):
227 227 text_buffer = []
228 228 for t_class, t_op, t_text in token_text_list:
229 229 text_buffer.append(t_text)
230 230 ops.append((token_op, ''.join(text_buffer)))
231 231 result.append((token_class, ops))
232 232 return result
233 233
234 234
235 235 def tokens_diff(old_tokens, new_tokens, use_diff_match_patch=True):
236 236 """
237 237 Converts a list of (token_class, token_text) tuples to a list of
238 238 (token_class, token_op, token_text) tuples where token_op is one of
239 239 ('ins', 'del', '')
240 240
241 241 :param old_tokens: list of (token_class, token_text) tuples of old line
242 242 :param new_tokens: list of (token_class, token_text) tuples of new line
243 243 :param use_diff_match_patch: boolean, will use google's diff match patch
244 244 library which has options to 'smooth' out the character by character
245 245 differences making nicer ins/del blocks
246 246 """
247 247
248 248 old_tokens_result = []
249 249 new_tokens_result = []
250 250
251 251 similarity = difflib.SequenceMatcher(None,
252 252 ''.join(token_text for token_class, token_text in old_tokens),
253 253 ''.join(token_text for token_class, token_text in new_tokens)
254 254 ).ratio()
255 255
256 256 if similarity < 0.6: # return, the blocks are too different
257 257 for token_class, token_text in old_tokens:
258 258 old_tokens_result.append((token_class, '', token_text))
259 259 for token_class, token_text in new_tokens:
260 260 new_tokens_result.append((token_class, '', token_text))
261 261 return old_tokens_result, new_tokens_result, similarity
262 262
263 263 token_sequence_matcher = difflib.SequenceMatcher(None,
264 264 [x[1] for x in old_tokens],
265 265 [x[1] for x in new_tokens])
266 266
267 267 for tag, o1, o2, n1, n2 in token_sequence_matcher.get_opcodes():
268 268 # check the differences by token block types first to give a more
269 269 # nicer "block" level replacement vs character diffs
270 270
271 271 if tag == 'equal':
272 272 for token_class, token_text in old_tokens[o1:o2]:
273 273 old_tokens_result.append((token_class, '', token_text))
274 274 for token_class, token_text in new_tokens[n1:n2]:
275 275 new_tokens_result.append((token_class, '', token_text))
276 276 elif tag == 'delete':
277 277 for token_class, token_text in old_tokens[o1:o2]:
278 278 old_tokens_result.append((token_class, 'del', token_text))
279 279 elif tag == 'insert':
280 280 for token_class, token_text in new_tokens[n1:n2]:
281 281 new_tokens_result.append((token_class, 'ins', token_text))
282 282 elif tag == 'replace':
283 283 # if same type token blocks must be replaced, do a diff on the
284 284 # characters in the token blocks to show individual changes
285 285
286 286 old_char_tokens = []
287 287 new_char_tokens = []
288 288 for token_class, token_text in old_tokens[o1:o2]:
289 289 for char in token_text:
290 290 old_char_tokens.append((token_class, char))
291 291
292 292 for token_class, token_text in new_tokens[n1:n2]:
293 293 for char in token_text:
294 294 new_char_tokens.append((token_class, char))
295 295
296 296 old_string = ''.join([token_text for
297 297 token_class, token_text in old_char_tokens])
298 298 new_string = ''.join([token_text for
299 299 token_class, token_text in new_char_tokens])
300 300
301 301 char_sequence = difflib.SequenceMatcher(
302 302 None, old_string, new_string)
303 303 copcodes = char_sequence.get_opcodes()
304 304 obuffer, nbuffer = [], []
305 305
306 306 if use_diff_match_patch:
307 307 dmp = diff_match_patch()
308 308 dmp.Diff_EditCost = 11 # TODO: dan: extract this to a setting
309 309 reps = dmp.diff_main(old_string, new_string)
310 310 dmp.diff_cleanupEfficiency(reps)
311 311
312 312 a, b = 0, 0
313 313 for op, rep in reps:
314 314 l = len(rep)
315 315 if op == 0:
316 316 for i, c in enumerate(rep):
317 317 obuffer.append((old_char_tokens[a+i][0], '', c))
318 318 nbuffer.append((new_char_tokens[b+i][0], '', c))
319 319 a += l
320 320 b += l
321 321 elif op == -1:
322 322 for i, c in enumerate(rep):
323 323 obuffer.append((old_char_tokens[a+i][0], 'del', c))
324 324 a += l
325 325 elif op == 1:
326 326 for i, c in enumerate(rep):
327 327 nbuffer.append((new_char_tokens[b+i][0], 'ins', c))
328 328 b += l
329 329 else:
330 330 for ctag, co1, co2, cn1, cn2 in copcodes:
331 331 if ctag == 'equal':
332 332 for token_class, token_text in old_char_tokens[co1:co2]:
333 333 obuffer.append((token_class, '', token_text))
334 334 for token_class, token_text in new_char_tokens[cn1:cn2]:
335 335 nbuffer.append((token_class, '', token_text))
336 336 elif ctag == 'delete':
337 337 for token_class, token_text in old_char_tokens[co1:co2]:
338 338 obuffer.append((token_class, 'del', token_text))
339 339 elif ctag == 'insert':
340 340 for token_class, token_text in new_char_tokens[cn1:cn2]:
341 341 nbuffer.append((token_class, 'ins', token_text))
342 342 elif ctag == 'replace':
343 343 for token_class, token_text in old_char_tokens[co1:co2]:
344 344 obuffer.append((token_class, 'del', token_text))
345 345 for token_class, token_text in new_char_tokens[cn1:cn2]:
346 346 nbuffer.append((token_class, 'ins', token_text))
347 347
348 348 old_tokens_result.extend(obuffer)
349 349 new_tokens_result.extend(nbuffer)
350 350
351 351 return old_tokens_result, new_tokens_result, similarity
352 352
353 353
354 354 class DiffSet(object):
355 355 """
356 356 An object for parsing the diff result from diffs.DiffProcessor and
357 357 adding highlighting, side by side/unified renderings and line diffs
358 358 """
359 359
360 360 HL_REAL = 'REAL' # highlights using original file, slow
361 361 HL_FAST = 'FAST' # highlights using just the line, fast but not correct
362 362 # in the case of multiline code
363 363 HL_NONE = 'NONE' # no highlighting, fastest
364 364
365 365 def __init__(self, highlight_mode=HL_REAL, repo_name=None,
366 366 source_repo_name=None,
367 367 source_node_getter=lambda filename: None,
368 368 target_node_getter=lambda filename: None,
369 369 source_nodes=None, target_nodes=None,
370 370 max_file_size_limit=150 * 1024, # files over this size will
371 371 # use fast highlighting
372 372 comments=None,
373 373 ):
374 374
375 375 self.highlight_mode = highlight_mode
376 376 self.highlighted_filenodes = {}
377 377 self.source_node_getter = source_node_getter
378 378 self.target_node_getter = target_node_getter
379 379 self.source_nodes = source_nodes or {}
380 380 self.target_nodes = target_nodes or {}
381 381 self.repo_name = repo_name
382 382 self.source_repo_name = source_repo_name or repo_name
383 383 self.comments = comments or {}
384 384 self.comments_store = self.comments.copy()
385 385 self.max_file_size_limit = max_file_size_limit
386 386
387 387 def render_patchset(self, patchset, source_ref=None, target_ref=None):
388 388 diffset = AttributeDict(dict(
389 389 lines_added=0,
390 390 lines_deleted=0,
391 391 changed_files=0,
392 392 files=[],
393 393 file_stats={},
394 394 limited_diff=isinstance(patchset, LimitedDiffContainer),
395 395 repo_name=self.repo_name,
396 396 source_repo_name=self.source_repo_name,
397 397 source_ref=source_ref,
398 398 target_ref=target_ref,
399 399 ))
400 400 for patch in patchset:
401 401 diffset.file_stats[patch['filename']] = patch['stats']
402 402 filediff = self.render_patch(patch)
403 403 filediff.diffset = diffset
404 404 diffset.files.append(filediff)
405 405 diffset.changed_files += 1
406 406 if not patch['stats']['binary']:
407 407 diffset.lines_added += patch['stats']['added']
408 408 diffset.lines_deleted += patch['stats']['deleted']
409 409
410 410 return diffset
411 411
412 412 _lexer_cache = {}
413 413
414 414 def _get_lexer_for_filename(self, filename, filenode=None):
415 415 # cached because we might need to call it twice for source/target
416 416 if filename not in self._lexer_cache:
417 417 if filenode:
418 418 lexer = filenode.lexer
419 419 extension = filenode.extension
420 420 else:
421 421 lexer = FileNode.get_lexer(filename=filename)
422 422 extension = filename.split('.')[-1]
423 423
424 424 lexer = get_custom_lexer(extension) or lexer
425 425 self._lexer_cache[filename] = lexer
426 426 return self._lexer_cache[filename]
427 427
428 428 def render_patch(self, patch):
429 429 log.debug('rendering diff for %r' % patch['filename'])
430 430
431 431 source_filename = patch['original_filename']
432 432 target_filename = patch['filename']
433 433
434 434 source_lexer = plain_text_lexer
435 435 target_lexer = plain_text_lexer
436 436
437 437 if not patch['stats']['binary']:
438 438 if self.highlight_mode == self.HL_REAL:
439 439 if (source_filename and patch['operation'] in ('D', 'M')
440 440 and source_filename not in self.source_nodes):
441 441 self.source_nodes[source_filename] = (
442 442 self.source_node_getter(source_filename))
443 443
444 444 if (target_filename and patch['operation'] in ('A', 'M')
445 445 and target_filename not in self.target_nodes):
446 446 self.target_nodes[target_filename] = (
447 447 self.target_node_getter(target_filename))
448 448
449 449 elif self.highlight_mode == self.HL_FAST:
450 450 source_lexer = self._get_lexer_for_filename(source_filename)
451 451 target_lexer = self._get_lexer_for_filename(target_filename)
452 452
453 453 source_file = self.source_nodes.get(source_filename, source_filename)
454 454 target_file = self.target_nodes.get(target_filename, target_filename)
455 455
456 456 source_filenode, target_filenode = None, None
457 457
458 458 # TODO: dan: FileNode.lexer works on the content of the file - which
459 459 # can be slow - issue #4289 explains a lexer clean up - which once
460 460 # done can allow caching a lexer for a filenode to avoid the file lookup
461 461 if isinstance(source_file, FileNode):
462 462 source_filenode = source_file
463 463 #source_lexer = source_file.lexer
464 464 source_lexer = self._get_lexer_for_filename(source_filename)
465 465 source_file.lexer = source_lexer
466 466
467 467 if isinstance(target_file, FileNode):
468 468 target_filenode = target_file
469 469 #target_lexer = target_file.lexer
470 470 target_lexer = self._get_lexer_for_filename(target_filename)
471 471 target_file.lexer = target_lexer
472 472
473 473 source_file_path, target_file_path = None, None
474 474
475 475 if source_filename != '/dev/null':
476 476 source_file_path = source_filename
477 477 if target_filename != '/dev/null':
478 478 target_file_path = target_filename
479 479
480 480 source_file_type = source_lexer.name
481 481 target_file_type = target_lexer.name
482 482
483 483 filediff = AttributeDict({
484 484 'source_file_path': source_file_path,
485 485 'target_file_path': target_file_path,
486 486 'source_filenode': source_filenode,
487 487 'target_filenode': target_filenode,
488 488 'source_file_type': target_file_type,
489 489 'target_file_type': source_file_type,
490 490 'patch': {'filename': patch['filename'], 'stats': patch['stats']},
491 491 'operation': patch['operation'],
492 492 'source_mode': patch['stats']['old_mode'],
493 493 'target_mode': patch['stats']['new_mode'],
494 494 'limited_diff': isinstance(patch, LimitedDiffContainer),
495 495 'hunks': [],
496 496 'diffset': self,
497 497 })
498 498
499 499 for hunk in patch['chunks'][1:]:
500 500 hunkbit = self.parse_hunk(hunk, source_file, target_file)
501 501 hunkbit.source_file_path = source_file_path
502 502 hunkbit.target_file_path = target_file_path
503 503 filediff.hunks.append(hunkbit)
504 504
505 505 left_comments = {}
506 506 if source_file_path in self.comments_store:
507 507 for lineno, comments in self.comments_store[source_file_path].items():
508 508 left_comments[lineno] = comments
509 509
510 510 if target_file_path in self.comments_store:
511 511 for lineno, comments in self.comments_store[target_file_path].items():
512 512 left_comments[lineno] = comments
513 513 # left comments are one that we couldn't place in diff lines.
514 514 # could be outdated, or the diff changed and this line is no
515 515 # longer available
516 516 filediff.left_comments = left_comments
517 517
518 518 return filediff
519 519
520 520 def parse_hunk(self, hunk, source_file, target_file):
521 521 result = AttributeDict(dict(
522 522 source_start=hunk['source_start'],
523 523 source_length=hunk['source_length'],
524 524 target_start=hunk['target_start'],
525 525 target_length=hunk['target_length'],
526 526 section_header=hunk['section_header'],
527 527 lines=[],
528 528 ))
529 529 before, after = [], []
530 530
531 531 for line in hunk['lines']:
532 532
533 533 if line['action'] == 'unmod':
534 534 result.lines.extend(
535 535 self.parse_lines(before, after, source_file, target_file))
536 536 after.append(line)
537 537 before.append(line)
538 538 elif line['action'] == 'add':
539 539 after.append(line)
540 540 elif line['action'] == 'del':
541 541 before.append(line)
542 542 elif line['action'] == 'old-no-nl':
543 543 before.append(line)
544 544 elif line['action'] == 'new-no-nl':
545 545 after.append(line)
546 546
547 547 result.lines.extend(
548 548 self.parse_lines(before, after, source_file, target_file))
549 549 result.unified = self.as_unified(result.lines)
550 550 result.sideside = result.lines
551 551
552 552 return result
553 553
554 554 def parse_lines(self, before_lines, after_lines, source_file, target_file):
555 555 # TODO: dan: investigate doing the diff comparison and fast highlighting
556 556 # on the entire before and after buffered block lines rather than by
557 557 # line, this means we can get better 'fast' highlighting if the context
558 558 # allows it - eg.
559 559 # line 4: """
560 560 # line 5: this gets highlighted as a string
561 561 # line 6: """
562 562
563 563 lines = []
564 564
565 565 before_newline = AttributeDict()
566 566 after_newline = AttributeDict()
567 567 if before_lines and before_lines[-1]['action'] == 'old-no-nl':
568 568 before_newline_line = before_lines.pop(-1)
569 569 before_newline.content = '\n {}'.format(
570 570 render_tokenstream(
571 571 [(x[0], '', x[1])
572 572 for x in [('nonl', before_newline_line['line'])]]))
573 573
574 574 if after_lines and after_lines[-1]['action'] == 'new-no-nl':
575 575 after_newline_line = after_lines.pop(-1)
576 576 after_newline.content = '\n {}'.format(
577 577 render_tokenstream(
578 578 [(x[0], '', x[1])
579 579 for x in [('nonl', after_newline_line['line'])]]))
580 580
581 581 while before_lines or after_lines:
582 582 before, after = None, None
583 583 before_tokens, after_tokens = None, None
584 584
585 585 if before_lines:
586 586 before = before_lines.pop(0)
587 587 if after_lines:
588 588 after = after_lines.pop(0)
589 589
590 590 original = AttributeDict()
591 591 modified = AttributeDict()
592 592
593 593 if before:
594 594 if before['action'] == 'old-no-nl':
595 595 before_tokens = [('nonl', before['line'])]
596 596 else:
597 597 before_tokens = self.get_line_tokens(
598 598 line_text=before['line'],
599 599 line_number=before['old_lineno'],
600 600 file=source_file)
601 601 original.lineno = before['old_lineno']
602 602 original.content = before['line']
603 603 original.action = self.action_to_op(before['action'])
604 604 original.comments = self.get_comments_for('old',
605 605 source_file, before['old_lineno'])
606 606
607 607 if after:
608 608 if after['action'] == 'new-no-nl':
609 609 after_tokens = [('nonl', after['line'])]
610 610 else:
611 611 after_tokens = self.get_line_tokens(
612 612 line_text=after['line'], line_number=after['new_lineno'],
613 613 file=target_file)
614 614 modified.lineno = after['new_lineno']
615 615 modified.content = after['line']
616 616 modified.action = self.action_to_op(after['action'])
617 617 modified.comments = self.get_comments_for('new',
618 618 target_file, after['new_lineno'])
619 619
620 620 # diff the lines
621 621 if before_tokens and after_tokens:
622 622 o_tokens, m_tokens, similarity = tokens_diff(
623 623 before_tokens, after_tokens)
624 624 original.content = render_tokenstream(o_tokens)
625 625 modified.content = render_tokenstream(m_tokens)
626 626 elif before_tokens:
627 627 original.content = render_tokenstream(
628 628 [(x[0], '', x[1]) for x in before_tokens])
629 629 elif after_tokens:
630 630 modified.content = render_tokenstream(
631 631 [(x[0], '', x[1]) for x in after_tokens])
632 632
633 633 if not before_lines and before_newline:
634 634 original.content += before_newline.content
635 635 before_newline = None
636 636 if not after_lines and after_newline:
637 637 modified.content += after_newline.content
638 638 after_newline = None
639 639
640 640 lines.append(AttributeDict({
641 641 'original': original,
642 642 'modified': modified,
643 643 }))
644 644
645 645 return lines
646 646
647 647 def get_comments_for(self, version, filename, line_number):
648 648 if hasattr(filename, 'unicode_path'):
649 649 filename = filename.unicode_path
650 650
651 651 if not isinstance(filename, basestring):
652 652 return None
653 653
654 654 line_key = {
655 655 'old': 'o',
656 656 'new': 'n',
657 657 }[version] + str(line_number)
658 658
659 659 if filename in self.comments_store:
660 660 file_comments = self.comments_store[filename]
661 661 if line_key in file_comments:
662 662 return file_comments.pop(line_key)
663 663
664 664 def get_line_tokens(self, line_text, line_number, file=None):
665 665 filenode = None
666 666 filename = None
667 667
668 668 if isinstance(file, basestring):
669 669 filename = file
670 670 elif isinstance(file, FileNode):
671 671 filenode = file
672 672 filename = file.unicode_path
673 673
674 674 if self.highlight_mode == self.HL_REAL and filenode:
675 675 lexer = self._get_lexer_for_filename(filename)
676 676 file_size_allowed = file.size < self.max_file_size_limit
677 677 if line_number and file_size_allowed:
678 678 return self.get_tokenized_filenode_line(
679 679 file, line_number, lexer)
680 680
681 681 if self.highlight_mode in (self.HL_REAL, self.HL_FAST) and filename:
682 682 lexer = self._get_lexer_for_filename(filename)
683 683 return list(tokenize_string(line_text, lexer))
684 684
685 685 return list(tokenize_string(line_text, plain_text_lexer))
686 686
687 687 def get_tokenized_filenode_line(self, filenode, line_number, lexer=None):
688 688
689 689 if filenode not in self.highlighted_filenodes:
690 690 tokenized_lines = filenode_as_lines_tokens(filenode, lexer)
691 691 self.highlighted_filenodes[filenode] = tokenized_lines
692 692 return self.highlighted_filenodes[filenode][line_number - 1]
693 693
694 694 def action_to_op(self, action):
695 695 return {
696 696 'add': '+',
697 697 'del': '-',
698 698 'unmod': ' ',
699 699 'old-no-nl': ' ',
700 700 'new-no-nl': ' ',
701 701 }.get(action, action)
702 702
703 703 def as_unified(self, lines):
704 704 """
705 705 Return a generator that yields the lines of a diff in unified order
706 706 """
707 707 def generator():
708 708 buf = []
709 709 for line in lines:
710 710
711 711 if buf and not line.original or line.original.action == ' ':
712 712 for b in buf:
713 713 yield b
714 714 buf = []
715 715
716 716 if line.original:
717 717 if line.original.action == ' ':
718 718 yield (line.original.lineno, line.modified.lineno,
719 719 line.original.action, line.original.content,
720 720 line.original.comments)
721 721 continue
722 722
723 723 if line.original.action == '-':
724 724 yield (line.original.lineno, None,
725 725 line.original.action, line.original.content,
726 726 line.original.comments)
727 727
728 728 if line.modified.action == '+':
729 729 buf.append((
730 730 None, line.modified.lineno,
731 731 line.modified.action, line.modified.content,
732 732 line.modified.comments))
733 733 continue
734 734
735 735 if line.modified:
736 736 yield (None, line.modified.lineno,
737 737 line.modified.action, line.modified.content,
738 738 line.modified.comments)
739 739
740 740 for b in buf:
741 741 yield b
742 742
743 743 return generator()
General Comments 0
You need to be logged in to leave comments. Login now