Repository navigation
Expand file tree
/
Copy pathdiffer.py
More file actions
executable file
·2024 lines (1786 loc) · 64.1 KB
/
Copy pathdiffer.py
File metadata and controls
executable file
·2024 lines (1786 loc) · 64.1 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Show a git diff in Phabricator's Differential side-by-side view.
differ [git diff arguments]
The arguments go to `git diff`, so `differ`, `differ --staged` and `differ HEAD~3` all work. The
page is written to /tmp/differ-<repository>-<hash>.html, named after the repository and the diff,
and opened with xdg-open.
This is a port of the code that renders a diff in Phabricator, from Phabricator, Arcanist and
libphutil. Each section names the PHP it comes from. Phabricator works on bytes rather than
characters, and so does this port, since the intraline highlighting counts bytes.
"""
import base64
import hashlib
import os
import re
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.realpath(__file__))
# DifferentialChangesetParser
CONTEXT_LINES = 8
HIGHLIGHT_BYTE_LIMIT = 262144
# PhabricatorDifferentialConfigOptions, "differential.whitespace-matters".
WHITESPACE_MATTERS = [r'\.py$', r'\.l?hs$', r'\.ya?ml$']
# Characters PHP's trim() removes.
PHP_WS = b' \t\n\r\0\x0b'
SHOW_ALL = 'show-all'
IGNORE_MOST = 'ignore-most'
class DiffError(Exception):
pass
# -- HTML ---------------------------------------------------------------------
def escape(text):
"""PHP's htmlspecialchars() with ENT_QUOTES, on bytes."""
if isinstance(text, str):
text = text.encode()
return (
text.replace(b'&', b'&')
.replace(b'<', b'<')
.replace(b'>', b'>')
.replace(b'"', b'"')
.replace(b"'", b''')
)
def tag(name, attrs=(), content=b''):
"""phutil_tag(): attributes whose value is None are left out. Content is a list of
already-escaped HTML, or None."""
out = [b'<', name.encode()]
for key, value in attrs:
if value is None:
continue
out += [b' ', key.encode(), b'="', escape(str(value)), b'"']
out.append(b'>')
if isinstance(content, (list, tuple)):
out += [c for c in content if c]
elif content:
out.append(content)
out += [b'</', name.encode(), b'>']
return b''.join(out)
# -- Utilities (libphutil utils.php and utf8.php) -----------------------------
def split_lines(corpus):
"""phutil_split_lines(), keeping line endings."""
if not corpus:
return [b'']
lines = re.split(rb'(?<=\n)', corpus)
if lines[-1] == b'':
lines.pop()
return lines
def is_combining(char):
for cp in map(ord, char.decode()):
if (
0x0300 <= cp <= 0x036F
or 0x1DC0 <= cp <= 0x1DFF
or 0x20D0 <= cp <= 0x20FF
or 0xFE20 <= cp <= 0xFE2F
):
return True
return False
def utf8v_combined(string):
"""phutil_utf8v_combined(): characters with combining marks merged. A leading combining mark
gets a space in front of it, as in PHP."""
chars = [c.encode() for c in string.decode()]
if not chars:
return []
buf = b' ' if is_combining(chars[0]) else None
parts = []
for char in chars:
if len(char) > 1 and is_combining(char):
buf += char
else:
if buf is not None:
parts.append(buf)
buf = char
parts.append(buf)
return parts
def stripcslashes(text):
"""PHP's stripcslashes(), for quoted git paths."""
simple = {'n': 10, 't': 9, 'r': 13, 'a': 7, 'v': 11, 'b': 8, 'f': 12}
out = bytearray()
data = text.encode('utf-8', 'surrogateescape')
i = 0
while i < len(data):
c = data[i]
if c != 0x5C or i + 1 == len(data):
out.append(c)
i += 1
continue
i += 1
n = chr(data[i])
if n in simple:
out.append(simple[n])
i += 1
elif n == 'x' and i + 1 < len(data) and re.match(rb'[0-9a-fA-F]', data[i + 1 : i + 2]):
m = re.match(rb'[0-9a-fA-F]{1,2}', data[i + 1 :])
out.append(int(m.group(0), 16))
i += 1 + len(m.group(0))
elif n in '01234567':
m = re.match(rb'[0-7]{1,3}', data[i:])
out.append(int(m.group(0), 8) & 0xFF)
i += len(m.group(0))
else:
out.append(data[i])
i += 1
return out.decode('utf-8', 'replace')
# -- Parsing git diffs (arcanist ArcanistDiffParser) --------------------------
class Hunk:
"""DifferentialHunk."""
def __init__(self, old_offset, old_len, new_offset, new_len, changes):
self.old_offset = old_offset
self.old_len = old_len
self.new_offset = new_offset
self.new_len = new_len
self.changes = changes
self.lines = split_lines(changes)
def make_file(self, include):
"""makeContent(), joined: the file text this hunk covers."""
results = []
use_next_newline = False
for line in self.lines:
first = line[:1]
if not first:
continue
if first == b'\\':
if use_next_newline:
results[-1] = results[-1].rstrip(b'\n')
elif first not in include:
use_next_newline = False
else:
use_next_newline = True
results.append(line[1:])
return b''.join(results)
def structured_file(self, kind):
"""getStructuredFile(): line number to {'type', 'text'}."""
number = self.new_offset if kind == b'+' else self.old_offset
lines = []
for line in self.lines:
# getStructuredLines() skips lines whose first byte is empty.
if not line[:1] or line[:1] == b'0':
continue
lines.append({'type': line[:1], 'text': line[1:]})
result = {}
keep = True
for line in lines:
if line['type'] in (b' ', kind):
result[number] = line
number += 1
keep = True
elif line['type'] == b'\\':
if keep and number - 1 in result:
prev = result[number - 1]
result[number - 1] = dict(prev, text=prev['text'].rstrip(b'\r\n'))
result[number] = line
number += 1
keep = False
else:
keep = False
return result
def count(self, kind):
return sum(1 for line in self.lines if line[:1] == kind)
class Changeset:
"""ArcanistDiffChange and DifferentialChangeset."""
def __init__(self, path):
self.filename = path
self.old_file = None
self.change_type = 'change'
self.file_type = 'text'
self.hunks = []
self.old_props = {}
self.new_props = {}
self.away_paths = []
self.copy_lines = {}
def make_old_file(self):
return b''.join(h.make_file(b' -') for h in self.hunks)
def make_new_file(self):
return b''.join(h.make_file(b' +') for h in self.hunks)
def affected_line_count(self):
return sum(h.count(b'+') + h.count(b'-') for h in self.hunks)
def sort_key(self):
return self.filename.replace('.h', '.!h')
def unescape_filename(name):
if re.match(r'^".+"$', name):
return stripcslashes(name[1:-1])
return name
def extract_git_common_filename(paths):
"""extractGitCommonFilename(): the path in "diff --git a/x b/x", or None for a rename."""
prefix = r'(?:[^/]+/)?'
pattern = (
r'^(?P<old>(?P<oldq>"?)' + prefix + r'(?P<common>.+)(?P=oldq))'
r' (?P<new>(?P<newq>"?)' + prefix + r'(?P=common)(?P=newq))$'
)
m = re.match(pattern, paths.rstrip('\r\n'))
if not m:
return None
return unescape_filename(m.group('newq') + m.group('common') + m.group('newq'))
HUNK_HEADER = re.compile(rb'^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@')
def parse_hunks(lines, i):
"""Read hunks starting at lines[i]. Returns (hunks, next index)."""
hunks = []
while i < len(lines):
m = HUNK_HEADER.match(lines[i])
if not m:
break
old_offset = int(m.group(1))
old_len = 1 if m.group(2) is None else int(m.group(2))
new_offset = int(m.group(3))
new_len = 1 if m.group(4) is None else int(m.group(4))
i += 1
old_left, new_left = old_len, new_len
body = []
while i < len(lines) and (old_left > 0 or new_left > 0 or lines[i][:1] == b'\\'):
line = lines[i]
first = line[:1]
if first == b'+':
new_left -= 1
elif first == b'-':
old_left -= 1
elif first != b'\\':
old_left -= 1
new_left -= 1
body.append(line)
i += 1
hunks.append(Hunk(old_offset, old_len, new_offset, new_len, b''.join(body)))
return hunks, i
GIT_HEADERS = [
r'(?P<new>new) file mode (?P<newmode>\d+)',
r'(?P<deleted>deleted) file mode (?P<oldmode>\d+)',
r'old mode (?P<oldmode>\d+)',
r'new mode (?P<newmode>\d+)',
r'similarity index ',
r'rename from (?P<old>.*)',
r'(?P<move>rename) to (?P<cur>.*)',
r'copy from (?P<old>.*)',
r'(?P<copy>copy) to (?P<cur>.*)',
]
def parse_git_diff(data):
"""Parse `git diff` output into changesets, as parseDiff() and parseIndexHunk() do for git."""
changes = {}
def build(path):
if path is not None and path in changes:
return changes[path]
change = Changeset(path)
if path is not None:
changes[path] = change
return change
lines = split_lines(data)
i = 0
while i < len(lines):
line = lines[i]
if not line.startswith(b'diff --git '):
i += 1
continue
oldnew = line[len(b'diff --git ') :].decode('utf-8', 'replace')
path = extract_git_common_filename(oldnew)
change = build(path)
if path is not None:
change.old_file = path
i += 1
# The header lines that describe modes, moves and copies.
while i < len(lines):
text = lines[i].rstrip(b'\r\n').decode('utf-8', 'replace')
for pattern in GIT_HEADERS:
m = re.match('^' + pattern, text)
if m:
break
if not m:
break
groups = m.groupdict()
if groups.get('oldmode'):
change.old_props['unix:filemode'] = groups['oldmode']
if groups.get('newmode'):
change.new_props['unix:filemode'] = groups['newmode']
if groups.get('deleted'):
change.change_type = 'delete'
if groups.get('new'):
if change.change_type == 'delete':
change.change_type = 'change'
else:
change.change_type = 'add'
if groups.get('old'):
change.old_file = unescape_filename(groups['old'])
if groups.get('cur'):
cur = unescape_filename(groups['cur'])
if change.filename is None:
change.filename = cur
changes[cur] = change
if groups.get('copy'):
change.change_type = 'copy-here'
old = build(change.old_file)
if old.change_type == 'move-away':
old.change_type = 'multicopy'
else:
old.change_type = 'copy-away'
old.away_paths.append(change.filename)
if groups.get('move'):
change.change_type = 'move-here'
old = build(change.old_file)
if old.change_type in ('multicopy', 'move-away', 'copy-away'):
old.change_type = 'multicopy'
else:
old.change_type = 'move-away'
old.away_paths.append(change.filename)
i += 1
if i < len(lines) and lines[i].startswith(b'index '):
i += 1
if i >= len(lines) or lines[i].startswith(b'diff --git '):
continue
text = lines[i].rstrip(b'\r\n')
if re.match(rb'^(Binary files|Files) .* and .* differ$', text):
change.file_type = 'binary'
i += 1
continue
if text == b'GIT binary patch':
change.file_type = 'binary'
i += 1
while i < len(lines) and not lines[i].startswith(b'diff --git '):
i += 1
continue
if lines[i].startswith(b'--- '):
i += 1
if i < len(lines) and lines[i].startswith(b'+++ '):
i += 1
change.hunks, i = parse_hunks(lines, i)
return list(changes.values())
# -- Hunks to lines (phabricator DifferentialHunkParser) ----------------------
def parse_line_data(hunks):
"""parseHunksForLineData()"""
old_lines = []
new_lines = []
for hunk in hunks:
types = []
texts = []
for index, line in enumerate(hunk.lines):
first = line[:1]
if not first:
types.append(None)
texts.append(b'')
elif first == b' ':
types.append(None)
texts.append(line[1:])
elif first in (b'\r', b'\n'):
types.append(None)
texts.append(line)
elif first in (b'+', b'-', b'\\'):
types.append(first.decode())
texts.append(line[1:])
else:
raise DiffError(
'Unexpected leading character %r at line index %d!' % (first, index)
)
old_line = hunk.old_offset
new_line = hunk.new_offset
for cursor, type_ in enumerate(types):
data = {'type': type_, 'text': texts[cursor], 'line': new_line}
if type_ == '\\':
type_ = types[cursor - 1] if cursor else None
data['text'] = data['text'].lstrip(PHP_WS)
if type_ == '+':
new_lines.append(data)
new_line += 1
elif type_ == '-':
data['line'] = old_line
old_lines.append(data)
old_line += 1
else:
new_lines.append(data)
old_lines.append(dict(data, line=old_line))
new_line += 1
old_line += 1
return old_lines, new_lines
def line_type_map(lines):
return {line['line']: line['type'] for line in lines if line}
def apply_line_type_map(lines, type_map):
for line in lines:
line['type'] = type_map.get(line['line'])
def reparse_hunks(old_lines, new_lines, mode):
"""reparseHunksForSpecialAttributes(): pair the two sides up, padding with None, then
updateChangeTypesForWhitespaceMode()."""
olds = list(reversed(old_lines))
news = list(reversed(new_lines))
rebuild_old = []
rebuild_new = []
while olds or news:
old = olds.pop() if olds else None
new = news.pop() if news else None
o_type = old['type'] if old else None
n_type = new['type'] if new else None
if o_type is not None and n_type is None:
rebuild_old.append(old)
rebuild_new.append(None)
if new:
news.append(new)
continue
if n_type is not None and o_type is None:
rebuild_old.append(None)
rebuild_new.append(new)
if old:
olds.append(old)
continue
rebuild_old.append(old)
rebuild_new.append(new)
if mode != SHOW_ALL:
# Lines marked unchanged that differ by internal whitespace are marked changed. Leading and
# trailing whitespace is ignored.
for old, new in zip(rebuild_old, rebuild_new):
if not old or not new:
continue
if old['type'] is None and new['type'] is None:
old_text, new_text = old['text'], new['text']
if old_text != new_text and old_text.strip(PHP_WS) != new_text.strip(PHP_WS):
old['type'] = '-'
new['type'] = '+'
return rebuild_old, rebuild_new
def has_changes(old_lines, new_lines, any_change):
"""getHasChanges(): 'any' when any_change, otherwise 'text'."""
for old, new in zip(old_lines, new_lines):
if old is None or new is None:
return True
if old['type'] != new['type']:
return True
if old['text'] != new['text']:
if any_change:
return True
if old['text'].strip(PHP_WS) != new['text'].strip(PHP_WS):
return True
return False
def is_deleted(old_lines, new_lines):
if any(new_lines):
return False
return any(old_lines)
def intraline_diffs(old_lines, new_lines):
"""generateIntraLineDiffs()"""
diffs = {}
for key, (old, new) in enumerate(zip(old_lines, new_lines)):
if not old or not new:
continue
if old['type'] != new['type']:
diffs[key] = generate_intraline_diff(old['text'], new['text'])
return diffs
def visible_lines_mask(old_lines, new_lines, lines_context):
"""generateVisibileLinesMask()"""
def changed(lines, offset):
return offset < len(lines) and lines[offset] and lines[offset]['type']
max_length = max(len(old_lines), len(new_lines))
visible = False
last = 0
mask = set()
for cursor in range(-lines_context, max_length):
offset = cursor + lines_context
if changed(old_lines, offset) or changed(new_lines, offset):
visible = True
last = offset
elif cursor > last + lines_context:
visible = False
if visible and cursor > 0:
mask.add(cursor)
return mask
def corpus(lines):
"""getCorpus()"""
out = []
for line in lines:
if (line['type'] if line else None) != '\\':
out.append(line['text'] if line else b'\n')
return out
# -- Intraline edits (arcanist ArcanistDiffUtils, PhutilEditDistanceMatrix) ---
def edit_string(x, y, max_length):
"""generateEditString(): one of s(ame), i(nsert), d(elete) and x (replace) per character, with
internal smoothing."""
insert_cost = 1
delete_cost = 1
replace_cost = 2
alter_cost = 1 / (max_length * 2)
xl, yl = len(x), len(y)
shortest = min(xl, yl)
prefix = 0
while prefix < shortest and x[prefix] == y[prefix]:
prefix += 1
suffix = 0
for ii in range(1, shortest - prefix + 1):
if x[xl - ii] != y[yl - ii]:
break
suffix += 1
x = x[prefix : xl - suffix]
y = y[prefix : yl - suffix]
def pad(s):
return 's' * prefix + s + 's' * suffix
if not x and not y:
return pad('')
if not x:
return pad('i' * len(y))
if not y:
return pad('d' * len(x))
if x == y:
return pad('s' * len(x))
if len(x) > max_length or len(y) > max_length:
return pad('d' * len(x) + 'i' * len(y))
xl, yl = len(x), len(y)
m = [[0] * (yl + 1) for _ in range(xl + 1)]
t = [[''] * (yl + 1) for _ in range(xl + 1)]
for xx in range(xl + 1):
m[xx][0] = xx * delete_cost
t[xx][0] = 'd'
for yy in range(yl + 1):
m[0][yy] = yy * insert_cost
t[0][yy] = 'i'
t[0][0] = 's'
for xx in range(1, xl + 1):
for yy in range(1, yl + 1):
if x[xx - 1] == y[yy - 1]:
rep_cost = m[xx - 1][yy - 1] + 0
rep_type = 's'
else:
rep_cost = m[xx - 1][yy - 1] + replace_cost
rep_type = 'x'
del_cost = m[xx - 1][yy] + delete_cost
ins_cost = m[xx][yy - 1] + insert_cost
if t[xx - 1][yy] != 'd':
del_cost += alter_cost
if t[xx][yy - 1] != 'i':
ins_cost += alter_cost
if t[xx - 1][yy - 1] != rep_type:
rep_cost += alter_cost
if rep_cost <= del_cost and rep_cost <= ins_cost:
cost, kind = rep_cost, rep_type
elif ins_cost <= del_cost:
cost, kind = ins_cost, 'i'
else:
cost, kind = del_cost, 'd'
m[xx][yy] = cost
t[xx][yy] = kind
xx, yy = xl, yl
out = []
while True:
kind = t[xx][yy]
if kind in ('s', 'x'):
xx -= 1
yy -= 1
elif kind == 'i':
yy -= 1
else:
xx -= 1
out.append(kind)
if xx <= 0 and yy <= 0:
break
s = ''.join(reversed(out))
# SMOOTHING_INTERNAL: short runs of unchanged characters inside a change become replacements.
while True:
original = s
s = re.sub(r'([xdi])(s{3})([xdi])', r'\1xxx\3', s)
s = re.sub(r'([xdi])(s{2})([xdi])', r'\1xx\3', s)
s = re.sub(r'([xdi])(s{1})([xdi])', r'\1x\3', s)
if s == original:
break
return pad(s)
def collapse_runs(runs):
"""collapseIntralineRuns()"""
runs = [list(r) for r in runs]
keep = [True] * len(runs)
for ii in range(len(runs) - 1):
if runs[ii][0] == runs[ii + 1][0]:
runs[ii + 1][1] += runs[ii][1]
keep[ii] = False
return [r for r, k in zip(runs, keep) if k]
def generate_intraline_diff(o, n):
"""generateIntralineDiff(): byte runs of (highlight, length) for the old and the new line."""
ol, nl = len(o), len(n)
if o == n or not ol or not nl:
return [[0, ol]], [[0, nl]]
max_glyphs = 80
if ol + nl > 16 * max_glyphs:
return [[1, ol]], [[1, nl]]
# computeIntralineEdits()
if re.search(rb'[\x80-\xff]', o + n):
ov = utf8v_combined(o)
nv = utf8v_combined(n)
multibyte = True
else:
ov = [o[i : i + 1] for i in range(ol)]
nv = [n[i : i + 1] for i in range(nl)]
multibyte = False
result = edit_string(ov, nv, max_glyphs)
o_pos = n_pos = 0
o_run = []
n_run = []
old_char_len = new_char_len = 1
for c in result:
if multibyte:
old_char_len = len(ov[o_pos]) if o_pos < len(ov) else 0
new_char_len = len(nv[n_pos]) if n_pos < len(nv) else 0
if c in ('s', 'x'):
byte_o, byte_n = old_char_len, new_char_len
o_pos += 1
n_pos += 1
elif c == 'i':
byte_o, byte_n = 0, new_char_len
n_pos += 1
else:
byte_o, byte_n = old_char_len, 0
o_pos += 1
if byte_o:
o_run.append([0 if c == 's' else 1, byte_o])
if byte_n:
n_run.append([0 if c == 's' else 1, byte_n])
return collapse_runs(o_run), collapse_runs(n_run)
def apply_intraline_diff(text, runs):
"""applyIntralineDiff(): wrap changed bytes of highlighted HTML in <span class="bright">,
stepping over tags and counting each entity as one byte."""
open_tag = b'<span class="bright">'
close_tag = b'</span>'
stack = list(runs)
buf = []
p = s = e = 0
highlight = in_tag = in_ent = False
n = len(text)
for i in range(n):
if p == e:
while True:
if not stack:
buf.append(text[i:])
return b''.join(buf)
run = stack.pop(0)
s = e
e += run[1]
if run[0] != 0:
break
if not highlight and not in_tag and not in_ent and p == s:
buf.append(open_tag)
highlight = True
ch = text[i : i + 1]
if ch == b'<':
in_tag = True
if highlight:
buf.append(close_tag)
if not in_tag:
if ch == b'&':
in_ent = True
if in_ent and ch == b';':
in_ent = False
if not in_ent:
p += 1
buf.append(ch)
if in_tag and ch == b'>':
in_tag = False
if highlight:
buf.append(open_tag)
if highlight and (p == e or i == n - 1):
buf.append(close_tag)
highlight = False
return b''.join(buf)
# -- Copied and moved code (DifferentialChangesetParser::detectCopiedCode) ----
def detect_copied_code(changesets, min_width=30, min_lines=3):
code_map = {}
files = {}
types = {}
for cs in changesets:
name = cs.filename
for hunk in cs.hunks:
for line, info in hunk.structured_file(b'-').items():
if info['type'] == b'\\':
continue
types.setdefault(name, {})[line] = info['type']
text = info['text'].strip(PHP_WS)
files.setdefault(name, {})[line] = text
if len(text) >= min_width:
code_map.setdefault(text, []).append((name, line))
for cs in changesets:
copies = {}
best_file = best_line = best_offset = None
for hunk in cs.hunks:
added_info = hunk.structured_file(b'+')
atype = {line: info['type'] for line, info in added_info.items()}
added = {line: info['text'].strip(PHP_WS) for line, info in added_info.items()}
skip_lines = 0
for line, code in added.items():
if skip_lines:
skip_lines -= 1
continue
if atype[line] != b'+':
continue
if not code_map.get(code):
continue
if len(code_map[code]) > 16:
continue
best_length = 0
for name, orig_line in code_map[code]:
length = 1
for direction in (-1, 1):
offset = direction
while True:
if line + offset in copies:
break
if line + offset not in added:
break
if orig_line + offset not in files[name]:
break
if files[name][orig_line + offset] != added[line + offset]:
break
length += 1
offset += direction
if length < best_length:
continue
if length == best_length:
if types[name].get(orig_line) != b'-':
continue
best_length = length
best_offset = offset - 1
best_file = name
best_line = orig_line
source = '' if best_file == cs.filename else best_file
for i in range(best_length - 1, -1, -1):
orig = best_line + best_offset - i
if best_length < min_lines:
copies[line + best_offset - i] = None
else:
copies[line + best_offset - i] = (source, orig, types[best_file].get(orig))
skip_lines = best_offset
cs.copy_lines = {k: v for k, v in copies.items() if v}
# -- Syntax highlighting (libphutil markup/syntax) ----------------------------
def highlight_console(source):
"""PhutilConsoleSyntaxHighlighter"""
in_command = False
lines = source.split(b'\n')
for key, line in enumerate(lines):
if in_command:
pattern = rb'()(.*?)(#.*|\\)?$'
else:
pattern = rb'^(\S+[\\/] )?([$] .*?)(#.*|\\)?$'
m = re.search(pattern, line)
if m:
comment = m.group(3) or b''
lines[key] = (
escape(m.group(1) or b'')
+ b'<span class="gp">'
+ escape(m.group(2))
+ b'</span>'
+ (b'<span class="k">' + escape(comment) + b'</span>' if comment else b'')
)
in_command = comment == b'\\'
else:
lines[key] = b'<span class="go">' + escape(line) + b'</span>'
return b'\n'.join(lines)
# PhutilPygmentsSyntaxHighlighter::getPygmentsLexerNameFromLanguageName()
PYGMENTS_NAMES = {
'adb': 'ada',
'ads': 'ada',
'ahkl': 'ahk',
'as': 'as3',
'asax': 'aspx-vb',
'ascx': 'aspx-vb',
'ashx': 'aspx-vb',
'ASM': 'nasm',
'asm': 'nasm',
'asmx': 'aspx-vb',
'aspx': 'aspx-vb',
'autodelegate': 'myghty',
'autohandler': 'mason',
'aux': 'tex',
'axd': 'aspx-vb',
'b': 'brainfuck',
'bas': 'vb.net',
'bf': 'brainfuck',
'bmx': 'blitzmax',
'c++': 'cpp',
'c++-objdump': 'cpp-objdump',
'cc': 'cpp',
'cfc': 'cfm',
'cfg': 'ini',
'cfml': 'cfm',
'cl': 'common-lisp',
'clj': 'clojure',
'cmd': 'bat',
'coffee': 'coffee-script',
'cs': 'csharp',
'csh': 'tcsh',
'cw': 'redcode',
'cxx': 'cpp',
'cxx-objdump': 'cpp-objdump',
'darcspatch': 'dpatch',
'def': 'modula2',
'dhandler': 'mason',
'di': 'd',
'duby': 'rb',
'dyl': 'dylan',
'ebuild': 'bash',
'eclass': 'bash',
'el': 'common-lisp',
'eps': 'postscript',
'erl': 'erlang',
'erl-sh': 'erl',
'f': 'fortran',
'f90': 'fortran',
'feature': 'Cucumber',
'fhtml': 'velocity',
'flx': 'felix',
'flxh': 'felix',
'frag': 'glsl',
'g': 'antlr-ruby',
'G': 'antlr-ruby',
'gdc': 'gooddata-cl',
'gemspec': 'rb',
'geo': 'glsl',
'GNUmakefile': 'make',
'h': 'c',
'h++': 'cpp',
'hh': 'cpp',
'hpp': 'cpp',
'hql': 'sql',
'hrl': 'erlang',
'hs': 'haskell',
'htaccess': 'apacheconf',
'htm': 'html',
'html': 'html+evoque',
'hxx': 'cpp',
'hy': 'hybris',
'hyb': 'hybris',
'ik': 'ioke',
'inc': 'pov',
'j': 'objective-j',
'jbst': 'duel',
'kid': 'genshi',
'ksh': 'bash',
'less': 'css',
'lgt': 'logtalk',
'lisp': 'common-lisp',
'll': 'llvm',
'm': 'objective-c',
'mak': 'make',
'Makefile': 'make',
'makefile': 'make',
'man': 'groff',
'mao': 'mako',
'mc': 'mason',
'md': 'minid',
'mhtml': 'mason',
'mi': 'mason',
'ml': 'ocaml',
'mli': 'ocaml',
'mll': 'ocaml',
'mly': 'ocaml',
'mm': 'objective-c',
'mo': 'modelica',
'mod': 'modula2',
'moo': 'moocode',
'mu': 'mupad',
'myt': 'myghty',
'ns2': 'newspeak',
'pas': 'delphi',
'patch': 'diff',
'phtml': 'html+php',
'pl': 'prolog',
'plot': 'gnuplot',
'plt': 'gnuplot',
'pm': 'perl',
'po': 'pot',
'pp': 'puppet',