forked from jamessynge/diffmerge
/
diffmerge.go
311 lines (279 loc) · 8.89 KB
/
diffmerge.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
// Experiments with creating an alternate to diff3 and merge, motivated
// by my annoyance with these issues:
//
// 1) Ordered lists are not auto-merged. For example, C++ include lists
// and build dependencies are typically in lexically sorted ordered,
// so the merge tool should check to see if conflicting lines are
// part of such a list in all 3 files, and if so treat them as
// ordered sets, where
// we don't care about the conflicting lines, but rather about the
// set operations performed: insert and remove; and those operations
// won't be in conflict.
//
// 2) Mis-alignment of matches for added functions. For example, we desire
// this, where are the lines of the new function have been marked new:
//
// $diff -y file2 file1
// void func1() { void func1() {
// x += 1 x += 1
// } }
//
// > void functhreehalves() {
// > x += 1.5
// > }
// >
// void func2() { void func2() {
// x += 2 x += 2
// } }
//
// However, we often get this from diff, and hence from merge:
//
// $diff -y file2 file1
// void func1() { void func1() {
// x += 1 x += 1
// } > }
// >
// > void functhreehalves() {
// > x += 1.5
// }
//
// void func2() { void func2() {
// x += 2 x += 2
// } }
//
// (example from http://fabiensanglard.net/git_code_review/diff.php).
//
// 3) Non-conflicting intra-line changes are not recognized as such; for example:
//
// Base | Yours | Theirs
// if (y == x + 19) { | if (y == x + 17) { | if (z == x + 19) {
// | ^^ | ^
//
// merge considers the lines in conflict:
//
// <<<<<<< Yours
// if (oldVar == x + 17) {
// =======
// if (newVar == x + 19) {
// >>>>>>> Theirs
//
// 4) Moves of a block of lines should not be considered adds of new lines and
// deletes of old lines, but rather recognized as a move so that changes
// within the block of lines can be automatically merged.
//
// 5) If you've renamed a symbol in your file (i.e. changed ALL lines that
// contain that symbol), and the other file adds uses of that symbol,
// the tool should offer some means of automatically applying the renaming
// to the new uses. BONUS.
//
// 6) Changing the indentation of lines is treated as changing the entire line,
// rather than being treated as separate from changing the characters to the
// right of the indentation.
package main
import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/golang/glog"
"github.com/jamessynge/diffmerge/dm"
)
var (
pDiff3Flag = flag.Bool(
"diff3", false, "Find difference between 3 files.")
pStatusOnlyFlag = flag.Bool(
"brief", false, "Report (via exit code) whether there were differences "+
" (for diff) or conflicts (for diff3/merge) found.")
pSideBySideFlag = flag.Bool(
"side-by-side", true, "For diff of two files, display results side-by-side.")
)
// TODO Add support for merge(1)'s -L (label) flag, which can appear up to
// 3 times in the command line args. See https://play.golang.org/p/Ig5sm7jA14
// for an example of how to do this.
type CmdStatus int
const (
ConflictFree CmdStatus = iota
SomeConflicts
AnError
NoDifferences = ConflictFree
SomeDifferences = SomeConflicts
)
func FailWithMessage(showUsage bool, format string, a ...interface{}) {
msg := fmt.Sprintf(format, a...)
glog.Error(msg)
fmt.Fprintln(os.Stderr, msg)
if showUsage {
flag.Usage()
}
os.Exit(int(AnError) & 0xff)
}
type cmdInputs struct {
readingStdin bool
fileNames []string
files []*dm.File
perm os.FileMode
// Output used for merge with 3 inputs and one output.
outputFileName string
diffConfig dm.DifferencerConfig
}
func (p *cmdInputs) AddInputFile(fileName string) {
if fileName == "-" {
if p.readingStdin {
FailWithMessage(false, "Only one input file maybe '-' (for standard input).")
}
p.readingStdin = true
}
file, err := dm.ReadFile(fileName)
if err != nil {
FailWithMessage(false, "Failed to read file %s: %s", fileName, err)
os.Exit(int(AnError) & 0xff)
}
p.fileNames = append(p.fileNames, fileName)
p.files = append(p.files, file)
if p.perm == 0 && fileName != "-" {
fi, err := os.Stat(fileName)
if err == nil {
p.perm = fi.Mode().Perm()
}
}
}
func (p *cmdInputs) diff2Files(
fromFile, toFile *dm.File) (pairs dm.BlockPairs, status CmdStatus) {
pairs = dm.PerformDiff2(fromFile, toFile, p.diffConfig)
glog.Flush()
if len(pairs) == 1 && pairs[0].IsMatch {
status = NoDifferences
} else {
status = SomeDifferences
}
return
}
func (p *cmdInputs) diff3Files() *diff3State {
d3s := &diff3State{
ci: p,
yours: p.files[0],
base: p.files[1],
theirs: p.files[2],
}
d3s.b2yPairs, d3s.b2yStatus = p.diff2Files(d3s.base, d3s.yours)
d3s.b2tPairs, d3s.b2tStatus = p.diff2Files(d3s.base, d3s.theirs)
return d3s
}
func (p *cmdInputs) outputFile(f *dm.File) {
if p.outputFileName != "" {
err := ioutil.WriteFile(p.outputFileName, f.Body, p.perm)
if err != nil {
FailWithMessage(false, "Failed writing to %s; error: %s", p.outputFileName, err)
}
} else {
r := bytes.NewReader(f.Body)
_, err := io.Copy(os.Stdout, r)
if err != nil {
FailWithMessage(false, "Failed writing to stdout; error: %s", err)
}
}
}
func (p *cmdInputs) PerformDiff2() CmdStatus {
fromFile, toFile := p.files[0], p.files[1]
pairs, status := p.diff2Files(fromFile, toFile)
if *pSideBySideFlag {
dm.FormatSideBySide(
fromFile, toFile, pairs, false,
os.Stdout, dm.DefaultSideBySideConfig)
} else {
dm.FormatInterleaved(pairs, false, fromFile, toFile, os.Stdout, true)
}
return status
}
func (p *cmdInputs) PerformDiff3() CmdStatus {
d3s := p.diff3Files()
outputFile := d3s.noConflictPossibleOutputFile()
if outputFile != nil {
p.outputFile(outputFile)
return ConflictFree
}
d3s.performDiff3()
return AnError
}
func (p *cmdInputs) PerformMerge() CmdStatus {
d3s := p.diff3Files()
outputFile := d3s.noConflictPossibleOutputFile()
if outputFile != nil {
p.outputFile(outputFile)
return ConflictFree
}
yours, base, theirs := p.files[0], p.files[1], p.files[2]
b2yPairs, b2yStatus := p.diff2Files(base, yours)
b2tPairs, b2tStatus := p.diff2Files(base, theirs)
// len(.) == 1 expression included temporarily to supporess complaints about
// unused vars. TODO Remove.
if b2yStatus == NoDifferences && len(b2yPairs) == 1 {
// No changes in your file, so there can be no conflicts; output their file.
p.outputFile(theirs)
return ConflictFree
} else if b2tStatus == NoDifferences && len(b2tPairs) == 1 {
// No changes in their file, so there can be no conflicts; output your file.
p.outputFile(yours)
return ConflictFree
}
// Determine if there are possible conflicts. If so, then maybe do a diff of
// yours vs. theirs, which may help eliminate the diff.
// Start by sorting on the same index, base.
return AnError // TODO Replace with correct value.
}
type diff3State struct {
ci *cmdInputs
yours, base, theirs *dm.File
b2yPairs, b2tPairs, y2tPairs dm.BlockPairs
b2yStatus, b2tStatus, y2tStatus CmdStatus
diff3Triples dm.Diff3Triples
conflictsExist bool
}
// IFF at most one file is changed, return the other file that can be output.
func (p *diff3State) noConflictPossibleOutputFile() *dm.File {
if p.b2yStatus == NoDifferences {
// No changes in file p.yours, so there can be no conflicts.
return p.theirs
} else if p.b2tStatus == NoDifferences {
// No changes in file p.theirs, so there can be no conflicts.
return p.yours
}
return nil
}
func (p *diff3State) performDiff3() {
p.diff3Triples, p.conflictsExist = dm.PerformDiff3(
p.yours, p.base, p.theirs, p.b2yPairs, p.b2tPairs, p.ci.diffConfig)
}
func main() {
diffConfig := &dm.DifferencerConfig{}
diffConfig.CreateFlags(flag.CommandLine)
flag.Parse() // Scan the arguments list
cmd := filepath.Base(os.Args[0])
glog.V(1).Infoln("cmd =", cmd)
nArgs := flag.NArg()
if !(2 <= nArgs && nArgs <= 4) {
FailWithMessage(true, "Wrong number of file arguments")
}
var ci cmdInputs
ci.diffConfig = *diffConfig
ci.AddInputFile(flag.Arg(0))
ci.AddInputFile(flag.Arg(1))
if nArgs > 2 {
ci.AddInputFile(flag.Arg(2))
if nArgs > 3 {
ci.outputFileName = flag.Arg(3)
}
}
var status CmdStatus
if nArgs == 2 {
status = ci.PerformDiff2()
} else if *pDiff3Flag {
status = ci.PerformDiff3()
} else {
status = ci.PerformMerge()
}
os.Exit(int(status) & 0xff)
}