forked from spcau/godiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
godiff.go
1943 lines (1692 loc) · 49.4 KB
/
godiff.go
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
//
// File/Directory diff tool with HTML output
// Copyright (C) 2012 Siu Pin Chao
//
// 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, either version 3 of the License, or
// (at your option) any later version.
//
// 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, see <http://www.gnu.org/licenses/>.
//
// Description:
// This program can be use to compare files and directories for differences.
// When comparing directories, it iterates through all files in both directories
// and compare files having the same name.
//
// It uses the algorithm from "An O(ND) Difference Algorithm and its Variations"
// by Eugene Myers Algorithmica Vol. 1 No. 2, 1986, p 251.
//
// Main Features:
// * Supports UTF8 file.
// * Show differences within a line
// * Options for ignore case, white spaces compare, blank lines etc.
//
// Main aim of the application is to try out the features in the go programming language. (golang.org)
// * Slices: Used extensively, and re-slicing too whenever it make sense.
// * File I/O: Use Mmap for reading text files
// * Function Closure: Use in callbacks functions to handle both file and line compare
// * Goroutines: for running multiple file compares concurrently, using channels and mutex too.
//
//
// History
// -------
// 2012/09/20 Created
//
//
package main
import (
"bufio"
"bytes"
"compress/bzip2"
"compress/gzip"
"flag"
"fmt"
"hash/crc32"
"html"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"runtime/pprof"
"sort"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/rsrini7/go-csv"
"github.com/rsrini7/godiff/utils"
)
const (
// Version number
VERSION = "0.5"
// Scan at up to this size in file for '\0' in test for binary file
BINARY_CHECK_SIZE = 65536
// Output buffer size
OUTPUT_BUF_SIZE = 65536
// default number of context lines to display
CONTEXT_LINES = 3
// convenient shortcut
PATH_SEPARATOR = string(os.PathSeparator)
// use mmap for file greather than this size, for smaller files just use Read() instead.
MMAP_THRESHOLD = 8 * 1024
// Number of lines to print for previewing file
NUM_PREVIEW_LINES = 10
)
// Error Messages
const (
MSG_FILE_SIZE_ZERO = "File has size 0"
MSG_FILE_NOT_EXISTS = "File does not exist"
MSG_DIR_NOT_EXISTS = "Directory does not exist"
MSG_FILE_IS_BINARY = "This is a binary file"
MSG_FILE_DIFFERS = "File differs"
MSG_BIN_FILE_DIFFERS = "File differs. This is a binary file"
MSG_FILE_IDENTICAL = "Files are the same"
MSG_FILE_TOO_BIG = "File too big"
MSG_THIS_IS_DIR = "This is a directory"
MSG_THIS_IS_FILE = "This is a file"
)
// file data
type Filedata struct {
name string
info os.FileInfo
osfile *os.File
errormsg string
is_binary bool
is_mapped bool
data []byte
}
// Output to diff as html or text format
type OutputFormat struct {
buf1, buf2 bytes.Buffer
name1, name2 string
fileinfo1, fileinfo2 os.FileInfo
header_printed bool
lineno_width int
diffbuf bytes.Buffer
}
const (
DIFF_OP_SAME = 1
DIFF_OP_MODIFY = 2
DIFF_OP_INSERT = 3
DIFF_OP_REMOVE = 4
)
type DiffOp struct {
op int
start1, end1 int
start2, end2 int
}
// Interface for report_diff() callbacks.
type DiffChanger interface {
diff_lines([]DiffOp)
}
// Data use by DiffChanger
type DiffChangerData struct {
*OutputFormat
file1, file2 [][]byte
}
// changes to be output in Text format
type DiffChangerText struct {
DiffChangerData
}
// changes to be output in Unified Text format
type DiffChangerUnifiedText struct {
DiffChangerData
}
// changes to be output in Html format
type DiffChangerHtml struct {
DiffChangerData
}
// changes to be output in Unified Html format
type DiffChangerUnifiedHtml struct {
DiffChangerData
}
const HTML_HEADER = `<!doctype html><html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">`
const HTML_CSS = `<style type="text/css">
.tab {border-color:#808080; border-style:solid; border-width:1px 1px 1px 1px; border-collapse:collapse;}
.tth {border-color:#808080; border-style:solid; border-width:1px 1px 1px 1px; border-collapse:collapse; padding:4px; vertical-align:top; text-align:left; background-color:#E0E0E0;}
.ttd {border-color:#808080; border-style:solid; border-width:1px 1px 1px 1px; border-collapse:collapse; padding:4px; vertical-align:top; text-align:left;}
.hdr {color:black; font-size:85%;}
.inf {color:#C08000; font-size:85%;}
.err {color:red; font-size:85%; font-weight:bold; margin:0;}
.msg {color:#508050; font-size:85%; font-weight:bold; margin:0;}
.lno {color:#C08000; background-color:white; font-style:italic; margin:0;}
.nop {color:black; font-size:75%; font-family:monospace; white-space:pre; margin:0; display:block;}
.upd {color:black; font-size:75%; font-family:monospace; white-space:pre; margin:0; background-color:#CFCFFF; display:block;}
.emp {color:black; font-size:75%; font-family:monospace; white-space:pre; margin:0; background-color:#E0E0E0; display:block;}
.add {color:black; font-size:75%; font-family:monospace; white-space:pre; margin:0; background-color:#CFFFCF; display:block;}
.del {color:black; font-size:75%; font-family:monospace; white-space:pre; margin:0; background-color:#FFCFCF; display:block;}
.chg {color:#C00080; background-color:#AFAFDF;}
</style>`
const HTML_LEGEND = `<br><b>Legend:</b><br><table class="tab">
<tr><td class="tth"><span class="hdr">filename 1</span></td><td class="tth"><span class="hdr">filename 2</span></td></tr>
<tr><td class="ttd">
<span class="del"><span class="lno">1 </span>line deleted</span>
<span class="nop"><span class="lno">2 </span>no change</span>
<span class="upd"><span class="lno">3 </span>line modified</span>
</td>
<td class="ttd">
<span class="add"><span class="lno">1 </span>line added</span>
<span class="nop"><span class="lno">2 </span>no change</span>
<span class="upd"><span class="lno">3 </span><span class="chg">L</span>ine <span class="chg">M</span>odified</span>
</td></tr>
</table>
`
// command line arguments
var (
flag_pprof_file string
flag_version bool = false
flag_cmp_ignore_case bool = false
flag_cmp_ignore_blank_lines bool = false
flag_cmp_ignore_space_change bool = false
flag_cmp_ignore_all_space bool = false
flag_unicode_case_and_space bool = false
flag_show_identical_files bool = false
flag_suppress_line_changes bool = false
flag_suppress_missing_file bool = false
flag_output_as_text bool = false
flag_unified_context bool = false
flag_context_lines int = CONTEXT_LINES
flag_exclude_files string
flag_max_goroutines = 1
flag_p_keys string
flag_html_output string = "diff.html"
flag_txt_output string = "diff.txt"
flag_csv_delta string = "delta.csv"
flag_out_folder string = "output-diff"
flag_timeit bool = false
)
// Job queue for goroutines
type JobQueue struct {
name1, name2 string
info1, info2 os.FileInfo
}
// Queue queue for goroutines diff_file
var (
job_queue chan JobQueue
job_wait sync.WaitGroup
)
// Files/Dirs to excludes
var regexp_exclude_files *regexp.Regexp
// Buffered stdout
var (
out *bufio.Writer
out_lock sync.Mutex
outputFile *os.File
errF error
)
// html entity strings
var (
html_entity_amp = html.EscapeString("&")
html_entity_gt = html.EscapeString(">")
html_entity_lt = html.EscapeString("<")
html_entity_squote = html.EscapeString("'")
html_entity_dquote = html.EscapeString("\"")
)
// functions to compare line and computer hash values,
// these will be setup based on flags: -b -w -U etc.
var (
compare_line func([]byte, []byte) bool
compute_hash func([]byte) uint32
)
var blank_line = make([]byte, 0)
var (
csvHeaderData []string
csvDelimiter string
)
func version() {
fmt.Printf("godiff. Version %s\n", VERSION)
fmt.Printf("Copyright (C) 2012 Siu Pin Chao.\n")
}
func usage(msg string) {
if msg != "" {
fmt.Fprintf(os.Stderr, "%s\n", msg)
}
fmt.Fprint(os.Stderr, "A text file comparison tool displaying differenes in HTML\n\n")
fmt.Fprint(os.Stderr, "usage: godiff <options> <file|dir> <file|dir>\n")
flag.PrintDefaults()
os.Exit(2)
}
func usage0() {
usage("")
}
// Main routine.
func main() {
// setup command line options
flag.Usage = usage0
flag.StringVar(&flag_pprof_file, "prof", "", "Write pprof output to file")
flag.StringVar(&flag_exclude_files, "X", "", "Exclude files/directories matching this regexp pattern")
flag.BoolVar(&flag_version, "v", flag_version, "Print version information")
flag.IntVar(&flag_context_lines, "c", flag_context_lines, "Include N lines of context before and after changes")
flag.IntVar(&flag_max_goroutines, "g", flag_max_goroutines, "Max number of goroutines to use for file comparison")
flag.BoolVar(&flag_cmp_ignore_space_change, "b", flag_cmp_ignore_space_change, "Ignore changes in the amount of white space")
flag.BoolVar(&flag_cmp_ignore_all_space, "w", flag_cmp_ignore_all_space, "Ignore all white space")
flag.BoolVar(&flag_cmp_ignore_case, "i", flag_cmp_ignore_case, "Ignore case differences in file contents")
flag.BoolVar(&flag_cmp_ignore_blank_lines, "B", flag_cmp_ignore_blank_lines, "Ignore changes whose lines are all blank")
flag.BoolVar(&flag_unicode_case_and_space, "unicode", flag_unicode_case_and_space, "Apply unicode rules for white space and upper/lower case")
flag.BoolVar(&flag_show_identical_files, "s", flag_show_identical_files, "Report when two files are the identical")
flag.BoolVar(&flag_suppress_line_changes, "l", flag_suppress_line_changes, "Do not display changes within lines")
flag.BoolVar(&flag_suppress_missing_file, "m", flag_suppress_missing_file, "Do not show content if corresponding file is missing")
flag.BoolVar(&flag_unified_context, "u", flag_unified_context, "Unified context")
flag.BoolVar(&flag_output_as_text, "txt", flag_output_as_text, "Output using 'diff' text format instead of HTML")
flag.StringVar(&flag_txt_output, "n", flag_txt_output, "Generate given txt diff file")
flag.StringVar(&flag_p_keys, "key", "", "The Primary Key Columns")
flag.StringVar(&flag_html_output, "html", flag_html_output, "Generate HTML diff file")
flag.StringVar(&flag_csv_delta, "csv", flag_csv_delta, "Generate CSV delta file")
flag.StringVar(&flag_out_folder, "diff-dir", flag_out_folder, "Generate diff files in the specified folder")
flag.BoolVar(&flag_timeit, "timeit", flag_timeit, "Measure time and print")
//flags.StringVar(&numericKey, "numeric", "", "The specified columns are treated as numeric strings.")
//flags.StringVar(&reverseKey, "reverse", "", "The specified columns are sorted in reverse order.")
flag.Parse()
if flag_txt_output != "diff.txt" {
flag_output_as_text = true
}
CreateDirIfNotExist(flag_out_folder)
flag_html_output = path.Join(flag_out_folder, flag_html_output)
if flag_output_as_text {
outputFile, errF = os.Create(flag_txt_output)
} else {
outputFile, errF = os.Create(flag_html_output)
}
if errF != nil {
usage(errF.Error())
}
out = bufio.NewWriterSize(outputFile, OUTPUT_BUF_SIZE)
if flag_version {
version()
os.Exit(0)
}
if flag_timeit {
defer utils.TimeTrack(time.Now(), "godiff")
}
// write pprof info
if flag_pprof_file != "" {
pf, err := os.Create(flag_pprof_file)
if err != nil {
usage(err.Error())
}
pprof.StartCPUProfile(pf)
defer pprof.StopCPUProfile()
}
if flag_exclude_files != "" {
r, err := regexp.Compile(flag_exclude_files)
if err != nil {
usage("Invlid exclude regex: " + err.Error())
}
regexp_exclude_files = r
}
// flush output on termination
defer func() {
out.Flush()
outputFile.Close()
}()
// choose which compare and hash function to use
if flag_cmp_ignore_case || flag_cmp_ignore_space_change || flag_cmp_ignore_all_space {
if flag_unicode_case_and_space {
compute_hash = compute_hash_unicode
compare_line = compare_line_unicode
} else {
compute_hash = compute_hash_bytes
compare_line = compare_line_bytes
}
} else {
compute_hash = compute_hash_exact
compare_line = bytes.Equal
}
// get command line args
args := flag.Args()
if len(args) < 2 {
usage("Missing files")
}
if len(args) > 2 {
usage("Too many files")
}
// get the directory name or filename
file1, file2 := args[0], args[1]
// check file type
finfo1, err1 := os.Stat(file1)
finfo2, err2 := os.Stat(file2)
// Unable to find either file/directory
if err1 != nil || err2 != nil {
if err1 != nil {
fmt.Fprintf(os.Stderr, "%s\n", err1.Error())
}
if err2 != nil {
fmt.Fprintf(os.Stderr, "%s\n", err2.Error())
}
os.Exit(1)
}
if finfo1.IsDir() != finfo2.IsDir() {
usage("Unable to compare file and directory")
}
if flag_p_keys == "" && filepath.Ext(file1) == ".csv" {
usage("-key is must for csv files - primary key column/s")
}
if filepath.Ext(file1) == ".csv" {
flag_csv_delta = path.Join(flag_out_folder, flag_csv_delta)
csvDelimiter = utils.DetectCsvDelimiter(file1)
}
if !flag_output_as_text {
out.WriteString(HTML_HEADER)
fmt.Fprintf(out, "<title>Compare %s vs %s</title>\n", html.EscapeString(file1), html.EscapeString(file2))
out.WriteString(HTML_CSS)
out.WriteString("</head><body>\n")
fmt.Fprintf(out, "<p>Compare <strong>%s</strong> vs <strong>%s</strong></p>\n", html.EscapeString(file1), html.EscapeString(file2))
}
switch {
case !finfo1.IsDir() && !finfo2.IsDir():
diff_file(file1, file2, finfo1, finfo2)
case finfo1.IsDir() && finfo2.IsDir():
job_queue_init()
diff_dirs(file1, file2, finfo1, finfo2)
job_queue_finish()
}
if !flag_output_as_text {
fmt.Fprintf(out, "Generated on %s<br>", time.Now().Format(time.RFC1123))
out.WriteString(HTML_LEGEND)
out.WriteString("</body></html>\n")
}
}
//
// Call the diff algorithm.
//
func do_diff(data1, data2 []int) ([]bool, []bool) {
len1, len2 := len(data1), len(data2)
change1, change2 := make([]bool, len1), make([]bool, len2)
size := (len1+len2+1)*2 + 2
v := make([]int, size*2)
// Run diff compare algorithm.
algorithm_lcs(data1, data2, change1, change2, v)
return change1, change2
}
//
// Find the begin/end of this 'changed' segment
//
func next_change_segment(start int, change []bool, data []int) (int, int, int) {
// find the end of this changes segment
end := start + 1
for end < len(change) && change[end] {
end++
}
// skip blank lines in the begining and end of the changes
i, j := start, end
for i < end && data[i] == 0 {
i++
}
for j > i && data[j-1] == 0 {
j--
}
return end, i, j
}
//
// Add segment to the group of changes. Add context lines before and after if necessary
//
func add_change_segment(chg DiffChanger, ops []DiffOp, op DiffOp) []DiffOp {
last1, last2 := 0, 0
if len(ops) > 0 {
last_op := ops[len(ops)-1]
last1, last2 = last_op.end1, last_op.end2
}
gap1, gap2 := op.start1-last1, op.start2-last2
if len(ops) > 0 && (op.op == 0 || (gap1 > flag_context_lines*2 && gap2 > flag_context_lines*2)) {
e1, e2 := utils.MinInt(op.start1, last1+flag_context_lines), utils.MinInt(op.start2, last2+flag_context_lines)
if e1 > last1 || e2 > last2 {
ops = append(ops, DiffOp{DIFF_OP_SAME, last1, e1, last2, e2})
}
chg.diff_lines(ops)
ops = ops[:0]
}
c1, c2 := utils.MaxInt(last1, op.start1-flag_context_lines), utils.MaxInt(last2, op.start2-flag_context_lines)
if c1 < op.start1 || c2 < op.start2 {
ops = append(ops, DiffOp{DIFF_OP_SAME, c1, op.start1, c2, op.start2})
}
if op.op != 0 {
ops = append(ops, op)
}
return ops
}
//
// Report diff changes.
// For each group of change, call the diff_lines() function
//
func report_diff(chg DiffChanger, data1, data2 []int, change1, change2 []bool) bool {
len1, len2 := len(change1), len(change2)
i1, i2 := 0, 0
ops := make([]DiffOp, 0, 16)
changed := false
var m1start, m1end, m2start, m2end int
// scan for changes
for i1 < len1 || i2 < len2 {
switch {
// no change, advance both i1 and i2 to to next set of changes
case i1 < len1 && i2 < len2 && !change1[i1] && !change2[i2]:
i1++
i2++
// change in both lists
case i1 < len1 && i2 < len2 && change1[i1] && change2[i2]:
i1, m1start, m1end = next_change_segment(i1, change1, data1)
i2, m2start, m2end = next_change_segment(i2, change2, data2)
op_mode := 0
switch {
case m1start < m1end && m2start < m2end:
op_mode = DIFF_OP_MODIFY
case m1start < m1end:
op_mode = DIFF_OP_REMOVE
case m2start < m2end:
op_mode = DIFF_OP_INSERT
}
if op_mode != 0 {
ops = add_change_segment(chg, ops, DiffOp{op_mode, m1start, m1end, m2start, m2end})
changed = true
}
case i1 < len1 && change1[i1]:
i1, m1start, m1end = next_change_segment(i1, change1, data1)
if m1start < m1end {
ops = add_change_segment(chg, ops, DiffOp{DIFF_OP_REMOVE, m1start, m1end, i2, i2})
changed = true
}
case i2 < len2 && change2[i2]:
i2, m2start, m2end = next_change_segment(i2, change2, data2)
if m2start < m2end {
ops = add_change_segment(chg, ops, DiffOp{DIFF_OP_INSERT, i1, i1, m2start, m2end})
changed = true
}
default: // should not reach here
return true
}
}
if len(ops) > 0 {
add_change_segment(chg, ops, DiffOp{0, len1, len1, len2, len2})
}
return changed
}
//
// split text into array of individual rune position, and another array for comparison.
//
func split_runes(s []byte) ([]int, []int) {
pos := make([]int, len(s)+1)
cmp := make([]int, len(s))
var h, i, n int
for i < len(s) {
pos[n] = i
b := s[i]
if b < utf8.RuneSelf {
if flag_cmp_ignore_case {
if flag_unicode_case_and_space {
h = int(unicode.ToLower(rune(b)))
} else {
h = int(utils.ToLowerByte(b))
}
} else {
h = int(b)
}
i++
} else {
r, rsize := utf8.DecodeRune(s[i:])
if flag_cmp_ignore_case && flag_unicode_case_and_space {
h = int(unicode.ToLower(r))
} else {
h = int(r)
}
i += rsize
}
cmp[n] = h
n = n + 1
}
pos[n] = i
return pos[:n+1], cmp[:n]
}
func output_diff_message_content(filename1, filename2 string, info1, info2 os.FileInfo, msg1, msg2 string, data1, data2 [][]byte, is_error bool) {
if flag_output_as_text {
GenerateText(filename1, filename2, msg1, msg2)
} else {
GenerateHtml(filename1, filename2, info1, info2, msg1, msg2, data1, data2, is_error)
}
}
func output_diff_message(filename1, filename2 string, info1, info2 os.FileInfo, msg1, msg2 string, is_error bool) {
output_diff_message_content(filename1, filename2, info1, info2, msg1, msg2, nil, nil, is_error)
}
func print_line_numbers(mode string, start1, end1, start2, end2 int) {
if end1 < 0 || end1-start1 == 1 {
fmt.Fprintf(out, "%d%s", start1+1, mode)
} else {
fmt.Fprintf(out, "%d,%d%s", start1+1, end1, mode)
}
if end2 < 0 || end2-start2 == 1 {
fmt.Fprintf(out, "%d\n", start2+1)
} else {
fmt.Fprintf(out, "%d,%d\n", start2+1, end2)
}
}
func skip_space_rune(line []byte, i int) int {
for i < len(line) {
b, size := utf8.DecodeRune(line[i:])
if !unicode.IsSpace(b) {
return i
}
i += size
}
return i
}
//
// Get the next rune, and skip spaces after it
//
func get_next_rune_nonspace(line []byte, i int) (rune, int) {
b, size := utf8.DecodeRune(line[i:])
return b, skip_space_rune(line, i+size)
}
//
// Get the next rune, and determine if there is a space after it.
// Also ignore trailing spaces at end-of-line
//
func get_next_rune_xspace(line []byte, i int) (rune, bool, int) {
b, size := utf8.DecodeRune(line[i:])
i += size
space_after := false
for i < len(line) {
s, size := utf8.DecodeRune(line[i:])
if !unicode.IsSpace(s) {
break
}
space_after = true
i += size
}
if space_after && i >= len(line) {
space_after = false
}
return b, space_after, i
}
func skip_space_byte(line []byte, i int) int {
for i < len(line) {
if !utils.IsSpace(line[i]) {
return i
}
i++
}
return i
}
func get_next_byte_nonspace(line []byte, i int) (byte, int) {
return line[i], skip_space_byte(line, i+1)
}
func get_next_byte_xspace(line []byte, i int) (byte, bool, int) {
b, i := line[i], i+1
space_after := false
for i < len(line) {
if !utils.IsSpace(line[i]) {
break
}
space_after = true
i++
}
if space_after && i >= len(line) {
space_after = false
}
return b, space_after, i
}
func compare_line_bytes(line1, line2 []byte) bool {
len1, len2 := len(line1), len(line2)
var i, j int
var v1, v2 byte
switch {
case flag_cmp_ignore_all_space:
i = skip_space_byte(line1, 0)
j = skip_space_byte(line2, 0)
for i < len1 && j < len2 {
v1, i = get_next_byte_nonspace(line1, i)
v2, j = get_next_byte_nonspace(line2, j)
if flag_cmp_ignore_case && v1 != v2 {
v1, v2 = utils.ToLowerByte(v1), utils.ToLowerByte(v2)
}
if v1 != v2 {
return false
}
}
if i < len1 || j < len2 {
return false
}
case flag_cmp_ignore_space_change:
var space_after1, space_after2 bool
i = skip_space_byte(line1, 0)
j = skip_space_byte(line2, 0)
for i < len1 && j < len2 {
v1, space_after1, i = get_next_byte_xspace(line1, i)
v2, space_after2, j = get_next_byte_xspace(line2, j)
if flag_cmp_ignore_case && v1 != v2 {
v1, v2 = utils.ToLowerByte(v1), utils.ToLowerByte(v2)
}
if v1 != v2 || space_after1 != space_after2 {
return false
}
}
if i < len1 || j < len2 {
return false
}
case flag_cmp_ignore_case:
if len1 != len2 {
return false
}
for i < len1 && j < len2 {
if utils.ToLowerByte(line1[i]) != utils.ToLowerByte(line2[j]) {
return false
}
i, j = i+1, j+1
}
if i < len1 || j < len2 {
return false
}
}
return true
}
func compare_line_unicode(line1, line2 []byte) bool {
len1, len2 := len(line1), len(line2)
var i, j int
var v1, v2 rune
var size1, size2 int
switch {
case flag_cmp_ignore_all_space:
i = skip_space_rune(line1, 0)
j = skip_space_rune(line2, 0)
for i < len1 && j < len2 {
v1, i = get_next_rune_nonspace(line1, i)
v2, j = get_next_rune_nonspace(line2, j)
if flag_cmp_ignore_case && v1 != v2 {
v1, v2 = unicode.ToLower(v1), unicode.ToLower(v2)
}
if v1 != v2 {
return false
}
}
if i < len1 || j < len2 {
return false
}
case flag_cmp_ignore_space_change:
i = skip_space_rune(line1, 0)
j = skip_space_rune(line2, 0)
var space_after1, space_after2 bool
for i < len1 && j < len2 {
v1, space_after1, i = get_next_rune_xspace(line1, i)
v2, space_after2, j = get_next_rune_xspace(line2, j)
if flag_cmp_ignore_case && v1 != v2 {
v1, v2 = unicode.ToLower(v1), unicode.ToLower(v2)
}
if v1 != v2 || space_after1 != space_after2 {
return false
}
}
if i < len1 || j < len2 {
return false
}
case flag_cmp_ignore_case:
if len1 != len2 {
return false
}
for i < len1 && j < len2 {
v1, size1 = utf8.DecodeRune(line1[i:])
v2, size2 = utf8.DecodeRune(line2[j:])
if v1 != v2 && unicode.ToLower(v1) != unicode.ToLower(v2) {
return false
}
i, j = i+size1, j+size2
}
if i < len1 || j < len2 {
return false
}
}
return true
}
var crc_table = crc32.MakeTable(crc32.Castagnoli)
func hash32(h uint32, b byte) uint32 {
return crc_table[byte(h)^b] ^ (h >> 8)
}
func hash32_unicode(h uint32, r rune) uint32 {
for r != 0 {
h = hash32(h, byte(r))
r = r >> 8
}
return h
}
func compute_hash_exact(data []byte) uint32 {
// On amd64, this will be using the SSE4.2 hardware instructions, much faster!
return crc32.Update(0, crc_table, data)
}
func compute_hash_bytes(line1 []byte) uint32 {
var hash uint32
switch {
case flag_cmp_ignore_all_space:
for _, v1 := range line1 {
if !utils.IsSpace(v1) {
if flag_cmp_ignore_case {
v1 = utils.ToLowerByte(v1)
}
hash = hash32(hash, v1)
}
}
case flag_cmp_ignore_space_change:
last_hash := hash
last_space := true
for _, v1 := range line1 {
if utils.IsSpace(v1) {
if !last_space {
last_hash = hash
hash = hash32(hash, ' ')
}
last_space = true
} else {
if flag_cmp_ignore_case {
v1 = utils.ToLowerByte(v1)
}
hash = hash32(hash, v1)
last_space = false
}
}
if last_space {
hash = last_hash
}
case flag_cmp_ignore_case:
for _, v1 := range line1 {
v1 = utils.ToLowerByte(v1)
hash = hash32(hash, v1)
}
}
return hash
}
func compute_hash_unicode(line1 []byte) uint32 {
var hash uint32
i, len1 := 0, len(line1)
switch {
case flag_cmp_ignore_all_space:
for i < len1 {
v1, size := utf8.DecodeRune(line1[i:])
i = i + size
if !unicode.IsSpace(v1) {
if flag_cmp_ignore_case {
v1 = unicode.ToLower(v1)
}
hash = hash32_unicode(hash, v1)
}
}
case flag_cmp_ignore_space_change:
last_hash := hash
last_space := true
for i < len1 {
v1, size := utf8.DecodeRune(line1[i:])
i += size
if unicode.IsSpace(v1) {
if !last_space {
last_hash = hash
hash = hash32(hash, ' ')
}
last_space = true
} else {
if flag_cmp_ignore_case {
v1 = unicode.ToLower(v1)
}
hash = hash32_unicode(hash, v1)
last_space = false
}
}
if last_space {
hash = last_hash
}
case flag_cmp_ignore_case:
for i < len1 {
v1, size := utf8.DecodeRune(line1[i:])
i = i + size
v1 = unicode.ToLower(v1)
hash = hash32_unicode(hash, v1)
}
}
return hash
}
type EquivClass struct {
id int
hash uint32
line *[]byte
next *EquivClass
}
type LinesData struct {
ids []int // Id's for each line,
zids []int // list of ids with unmatched lines replaced by a single entry (and blank lines removed)
zcount []int // Number of lines that represent each zids entry
change []bool
zids_start int
zids_end int
}
//
// Compute id's that represent the original lines, these numeric id's are use for faster line comparison.
//
func find_equiv_lines(lines1, lines2 [][]byte) (*LinesData, *LinesData) {
info1 := LinesData{
ids: make([]int, len(lines1)),
change: make([]bool, len(lines1)),
}
info2 := LinesData{
ids: make([]int, len(lines2)),
change: make([]bool, len(lines2)),
}
// since we already have a hashing function, it's faster to use arrays than to use go's builtin map
// Use bucket size that is power of 2
buckets := 1 << 9
for buckets < (len(lines1)+len(lines2))*2 {
buckets = buckets << 1