patch-header (1808B)
1 #!/usr/bin/perl 2 3 use strict; 4 5 sub diff ($$) { 6 my ($a, $b) = @_; 7 8 open (my $fa, $a) or die ("Cannot read $a: $!\n"); 9 open (my $fb, $b) or die ("Cannot read $b: $!\n"); 10 11 while (1) { 12 my $la = <$fa>; 13 my $lb = <$fb>; 14 15 if (defined ($la)) { 16 return (1) 17 if ( (defined ($lb) and $la ne $lb) or 18 (! defined ($lb)) ); 19 } else { 20 return (1) 21 if (defined ($lb)); 22 return (0); 23 } 24 } 25 } 26 27 die ("Usage: patch-header header-template version file(s)\n") 28 if ($#ARGV < 2); 29 my $hdrfile = shift (@ARGV); 30 my $ver = shift (@ARGV); 31 my ($header, $firstline, $lastline); 32 open (my $if, $hdrfile) 33 or die ("Can't read header file $hdrfile: $!\n"); 34 while (my $line = <$if>) { 35 chomp ($line); 36 37 $line =~ s/__VER__/$ver/g; 38 $header .= "$line\n"; 39 40 $firstline = $line if ($firstline eq ''); 41 $lastline = $line if ($line ne ''); 42 } 43 close ($if); 44 45 for my $src (@ARGV) { 46 my $dst = "$src.new"; 47 open (my $of, ">$dst") 48 or die ("Can't write $dst: $!\n"); 49 print $of ($header); 50 51 open (my $if, $src) 52 or die ("Can't read $src: $!\n"); 53 my $state = 0; 54 while (my $line = <$if>) { 55 chomp ($line); 56 # print ("Line: [$line], first: [$firstline], state: [$state]\n"); 57 if ($state == 2) { 58 print $of ("$line\n"); 59 next; 60 } 61 if ($state == 0 and $line eq $firstline) { 62 $state = 1; 63 next; 64 } 65 if ($state == 1 and $line eq $lastline) { 66 $state = 2; 67 next; 68 } 69 if ($state == 0) { 70 print $of ("$line\n"); 71 next; 72 } 73 } 74 close ($of); 75 close ($if); 76 77 if (diff ($src, $dst)) { 78 unlink ($src) 79 or die ("Cannot unlink $src: $!\n"); 80 rename ($dst, $src) 81 or die ("Cannot rename $dst to $src: $!\n"); 82 print ("patch-header: $ver $src\n"); 83 } else { 84 unlink ($dst) 85 or die ("Cannot unlink $dst: $!\n"); 86 } 87 }