@@ -2,6 +2,7 @@ package gitdiff
2
2
3
3
import (
4
4
"bufio"
5
+ "encoding/json"
5
6
"io"
6
7
"os"
7
8
"reflect"
@@ -223,6 +224,98 @@ a wild fragment appears?
223
224
}
224
225
}
225
226
227
+ func TestParse (t * testing.T ) {
228
+ tests := map [string ]struct {
229
+ InputFile string
230
+ Output []* File
231
+ Err bool
232
+ }{
233
+ "singleFile" : {
234
+ InputFile : "testdata/single_file.patch" ,
235
+ Output : []* File {
236
+ {
237
+ OldName : "dir/file.txt" ,
238
+ NewName : "dir/file.txt" ,
239
+ OldMode : os .FileMode (0100644 ),
240
+ OldOIDPrefix : "ebe9fa54" ,
241
+ NewOIDPrefix : "fe103e1d" ,
242
+ Fragments : []* Fragment {
243
+ {
244
+ OldPosition : 3 ,
245
+ OldLines : 6 ,
246
+ NewPosition : 3 ,
247
+ NewLines : 8 ,
248
+ Comment : "fragment 1" ,
249
+ Lines : []FragmentLine {
250
+ {OpContext , "context line\n " },
251
+ {OpDelete , "old line 1\n " },
252
+ {OpDelete , "old line 2\n " },
253
+ {OpContext , "context line\n " },
254
+ {OpAdd , "new line 1\n " },
255
+ {OpAdd , "new line 2\n " },
256
+ {OpAdd , "new line 3\n " },
257
+ {OpContext , "context line\n " },
258
+ {OpDelete , "old line 3\n " },
259
+ {OpAdd , "new line 4\n " },
260
+ {OpAdd , "new line 5\n " },
261
+ },
262
+ LinesAdded : 5 ,
263
+ LinesDeleted : 3 ,
264
+ LeadingContext : 1 ,
265
+ },
266
+ {
267
+ OldPosition : 31 ,
268
+ OldLines : 2 ,
269
+ NewPosition : 33 ,
270
+ NewLines : 2 ,
271
+ Comment : "fragment 2" ,
272
+ Lines : []FragmentLine {
273
+ {OpContext , "context line\n " },
274
+ {OpDelete , "old line 4\n " },
275
+ {OpAdd , "new line 6\n " },
276
+ },
277
+ LinesAdded : 1 ,
278
+ LinesDeleted : 1 ,
279
+ LeadingContext : 1 ,
280
+ },
281
+ },
282
+ },
283
+ },
284
+ },
285
+ }
286
+
287
+ for name , test := range tests {
288
+ t .Run (name , func (t * testing.T ) {
289
+ f , err := os .Open (test .InputFile )
290
+ if err != nil {
291
+ t .Fatalf ("unexpected error opening input file: %v" , err )
292
+ }
293
+
294
+ files , err := Parse (f )
295
+ if test .Err {
296
+ if err == nil || err == io .EOF {
297
+ t .Fatalf ("expected error parsing patch, but got %v" , err )
298
+ }
299
+ return
300
+ }
301
+ if err != nil {
302
+ t .Fatalf ("unexpected error parsing patch: %v" , err )
303
+ }
304
+
305
+ if len (test .Output ) != len (files ) {
306
+ t .Fatalf ("incorrect number of parsed files: expected %d, actual %d" , len (test .Output ), len (files ))
307
+ }
308
+ for i := range test .Output {
309
+ if ! reflect .DeepEqual (test .Output [i ], files [i ]) {
310
+ exp , _ := json .MarshalIndent (test .Output [i ], "" , " " )
311
+ act , _ := json .MarshalIndent (files [i ], "" , " " )
312
+ t .Errorf ("incorrect file at position %d\n expected: %s\n actual: %s" , i , exp , act )
313
+ }
314
+ }
315
+ })
316
+ }
317
+ }
318
+
226
319
func newTestParser (input string , init bool ) * parser {
227
320
p := & parser {r : bufio .NewReader (strings .NewReader (input ))}
228
321
if init {
0 commit comments