Teach 'git-apply --whitespace=strip' to remove empty lines at the end of file
[jc: with an obvious microfix to avoid doing this unless --whitespace=strip] Signed-off-by: Marco Costalba <mcostalba@gmail.com> Signed-off-by: Junio C Hamano <junkio@cox.net>
Marco Costalba committed
May 20, 2007 at 14:45 UTC
efe7f3586156bff4d29c347a1c41f93627c9f3e3
1 file changed
+40
-3
builtin-apply.c
+40
-3
@@ -1671,6 +1671,7 @@ static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, i
1671
char *new = xmalloc(size);
1672
const char *oldlines, *newlines;
1673
int oldsize = 0, newsize = 0;
1674
+ int trailing_added_lines = 0;
1675
unsigned long leading, trailing;
1676
int pos, lines;
1677
@@ -1699,6 +1700,17 @@ static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, i
1700
else if (first == '+')
1701
first = '-';
1702
}
1703
+ /*
1704
+ * Count lines added at the end of the file.
1705
+ * This is not enough to get things right in case of
1706
+ * patches generated with --unified=0, but it's a
1707
+ * useful upper bound.
1708
+ */
1709
+ if (first == '+')
1710
+ trailing_added_lines++;
1711
+ else
1712
+ trailing_added_lines = 0;
1713
+
1714
switch (first) {
1715
case '\n':
1716
/* Newer GNU diff, empty context line */
@@ -1738,6 +1750,24 @@ static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, i
1750
newsize--;
1751
}
1752
1753
+ if (new_whitespace == strip_whitespace) {
1754
+ /* Any added empty lines is already cleaned-up here
1755
+ * becuase of 'strip_whitespace' flag, so just count '\n'
1756
+ */
1757
+ int empty = 0;
1758
+ while ( empty < trailing_added_lines
1759
+ && newsize - empty > 0
1760
+ && new[newsize - empty - 1] == '\n')
1761
+ empty++;
1762
+
1763
+ if (empty < trailing_added_lines)
1764
+ empty--;
1765
+
1766
+ /* these are the empty lines added at
1767
+ * the end of the file, modulo u0 patches.
1768
+ */
1769
+ trailing_added_lines = empty;
1770
+ }
1771
oldlines = old;
1772
newlines = new;
1773
leading = frag->leading;
@@ -1770,9 +1800,16 @@ static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, i
1800
if (match_beginning && offset)
1801
offset = -1;
1802
if (offset >= 0) {
1773
- int diff = newsize - oldsize;
1774
- unsigned long size = desc->size + diff;
1775
- unsigned long alloc = desc->alloc;
1803
+ int diff;
1804
+ unsigned long size, alloc;
1805
+
1806
+ if (new_whitespace == strip_whitespace &&
1807
+ (desc->size - oldsize - offset == 0)) /* end of file? */
1808
+ newsize -= trailing_added_lines;
1809
+
1810
+ diff = newsize - oldsize;
1811
+ size = desc->size + diff;
1812
+ alloc = desc->alloc;
1813
1814
/* Warn if it was necessary to reduce the number
1815
* of context lines.