@@ -7,41 +7,42 @@ export function parsePatch(uniDiff, options = {}) {
7
7
let index = { } ;
8
8
list . push ( index ) ;
9
9
10
- // Ignore any leading junk
10
+ // Parse diff metadata
11
11
while ( i < diffstr . length ) {
12
- if ( / ^ ( I n d e x : | d i f f - r | @ @ ) / . test ( diffstr [ i ] ) ) {
12
+ let line = diffstr [ i ] ;
13
+
14
+ // File header found, end parsing diff metadata
15
+ if ( / ^ ( \- \- \- | \+ \+ \+ | @ @ ) \s / . test ( line ) ) {
13
16
break ;
14
17
}
15
- i ++ ;
16
- }
17
-
18
- let header = ( / ^ (?: I n d e x : | d i f f (?: - r \w + ) + ) ( .* ) / . exec ( diffstr [ i ] ) ) ;
19
- if ( header ) {
20
- index . index = header [ 1 ] ;
21
- i ++ ;
22
18
23
- if ( / ^ = = = / . test ( diffstr [ i ] ) ) {
24
- i ++ ;
19
+ // Diff index
20
+ let header = ( / ^ (?: I n d e x : | d i f f (?: - r \w + ) + ) \s + ( .+ ?) \s * $ / ) . exec ( line ) ;
21
+ if ( header ) {
22
+ index . index = header [ 1 ] ;
25
23
}
26
24
27
- parseFileHeader ( index ) ;
28
- parseFileHeader ( index ) ;
29
- } else {
30
- // Ignore erant header components that might occur at the start of the file
31
- parseFileHeader ( { } ) ;
32
- parseFileHeader ( { } ) ;
25
+ i ++ ;
33
26
}
34
27
28
+ // Parse file headers if they are defined. Unified diff requires them, but
29
+ // there's no technical issues to have an isolated hunk without file header
30
+ parseFileHeader ( index ) ;
31
+ parseFileHeader ( index ) ;
32
+
33
+ // Parse hunks
35
34
index . hunks = [ ] ;
36
35
37
36
while ( i < diffstr . length ) {
38
- if ( / ^ ( I n d e x : | d i f f - r ) / . test ( diffstr [ i ] ) ) {
37
+ let line = diffstr [ i ] ;
38
+
39
+ if ( / ^ ( I n d e x : | d i f f | \- \- \- | \+ \+ \+ ) \s / . test ( line ) ) {
39
40
break ;
40
- } else if ( / ^ @ @ / . test ( diffstr [ i ] ) ) {
41
+ } else if ( / ^ @ @ / . test ( line ) ) {
41
42
index . hunks . push ( parseHunk ( ) ) ;
42
- } else if ( diffstr [ i ] && options . strict ) {
43
+ } else if ( line && options . strict ) {
43
44
// Ignore unexpected content unless in strict mode
44
- throw new Error ( 'Unknown line ' + ( i + 1 ) + ' ' + JSON . stringify ( diffstr [ i ] ) ) ;
45
+ throw new Error ( 'Unknown line ' + ( i + 1 ) + ' ' + JSON . stringify ( line ) ) ;
45
46
} else {
46
47
i ++ ;
47
48
}
@@ -51,7 +52,7 @@ export function parsePatch(uniDiff, options = {}) {
51
52
// Parses the --- and +++ headers, if none are found, no lines
52
53
// are consumed.
53
54
function parseFileHeader ( index ) {
54
- let fileHeader = ( / ^ ( \- \- \- | \+ \+ \+ ) \s ( \S + ) \s ? ( .* ) / . exec ( diffstr [ i ] ) ) ;
55
+ let fileHeader = ( / ^ ( \- \- \- | \+ \+ \+ ) \s + ( \S + ) \s ? ( .+ ? ) \s * $ / ) . exec ( diffstr [ i ] ) ;
55
56
if ( fileHeader ) {
56
57
let keyPrefix = fileHeader [ 1 ] === '---' ? 'old' : 'new' ;
57
58
index [ keyPrefix + 'FileName' ] = fileHeader [ 2 ] ;
0 commit comments