3 # Clean a patch file -- or directory of patch files -- of stealth whitespace.
4 # WARNING: this can be a highly destructive operation. Use with caution.
11 # Clean up space-tab sequences, either by removing spaces or
12 # replacing them with tabs.
13 sub clean_space_tabs
($)
15 no bytes
; # Tab alignment depends on characters
23 for ($i = 0; $i < length($li); $i++) {
24 $c = substr($li, $i, 1);
26 my $npos = ($pos+$nsp+8) & ~7;
27 my $ntab = ($npos >> 3) - ($pos >> 3);
31 } elsif ($c eq "\n" || $c eq "\r") {
53 foreach $f ( @ARGV ) {
54 print STDERR
"$name: $f\n";
57 print STDERR
"$f: not a file\n";
61 if (!open(FILE
, '+<', $f)) {
62 print STDERR
"$name: Cannot open file: $f: $!\n";
68 # First, verify that it is not a binary file; consider any file
69 # with a zero byte to be a binary file. Is there any better, or
70 # additional, heuristic that should be applied?
73 while (read(FILE
, $data, 65536) > 0) {
81 print STDERR
"$name: $f: binary file\n";
95 while ( defined($line = <FILE
>) ) {
96 $in_bytes += length($line);
99 if ($line =~ /^\@\@\s+\-([0-9]+),([0-9]+)\s+\+([0-9]+),([0-9]+)\s\@\@/) {
102 if ($minus_lines || $plus_lines) {
104 @hunk_lines = ($line);
108 $out_bytes += length($line);
113 if ($line =~ /^\+/) {
116 $text = substr($line, 1);
117 $text =~ s/[ \t\r]*$//; # Remove trailing spaces
118 $text = clean_space_tabs
($text);
120 push(@hunk_lines, '+'.$text);
121 } elsif ($line =~ /^\-/) {
123 push(@hunk_lines, $line);
124 } elsif ($line =~ /^ /) {
127 push(@hunk_lines, $line);
129 print STDERR
"$name: $f: malformed patch\n";
134 if ($plus_lines < 0 || $minus_lines < 0) {
135 print STDERR
"$name: $f: malformed patch\n";
138 } elsif ($plus_lines == 0 && $minus_lines == 0) {
139 # End of a hunk. Process this hunk.
146 for ($i = scalar(@hunk_lines)-1; $i > 0; $i--) {
147 $l = $hunk_lines[$i];
148 if (!$done && $l eq "+\n") {
149 $adj++; # Skip this line
150 } elsif ($l =~ /^[ +]/) {
158 $l = $hunk_lines[0]; # Hunk header
159 undef @hunk_lines; # Free memory
163 ($l =~ /^\@\@\s+\-([0-9]+),([0-9]+)\s+\+([0-9]+),([0-9]+)\s\@\@(.*)$/);
168 my $tail = $5; # doesn't include the final newline
170 $l = sprintf("@@ -%d,%d +%d,%d @@%s\n",
171 $mstart, $mlin, $pstart, $plin-$adj,
176 # Transfer to the output array
178 $out_bytes += length($l);
188 print STDERR
"$name: $f: malformed patch\n";
193 if ($in_bytes != $out_bytes) {
194 # Only write to the file if changed
198 if ( !defined($where = tell(FILE
)) ||
199 !truncate(FILE
, $where) ) {
200 die "$name: Failed to truncate modified file: $f: $!\n";