9d258db6791ee73737f820ecf8319e2d9b16693b
[p5sagit/Distar.git] / helpers / add-changelog-heading
1 #!/usr/bin/env perl
2 use strict;
3 use warnings FATAL => 'all';
4 use Getopt::Long qw(:config gnu_getopt);
5 GetOptions(
6   "git"     => \my $git,
7 ) or die("Error in command line arguments\n");
8
9 my $version = shift;
10 my @ymd = (gmtime)[5,4,3];
11 $ymd[0] += 1900;
12 $ymd[1] += 1;
13 my $changes_line = sprintf "%s - %i-%02i-%02i", $version, @ymd;
14
15 foreach my $changes (@ARGV) {
16     print "Adding $version heading to $changes.\n";
17     open my $fh, '+<:raw', $changes
18       or die "Can't open $changes: $!";
19
20     my $content = '';
21     my $context;
22
23     while (<$fh>) {
24         if (defined $context) {
25             if (/^\S/) {
26                 local $/;
27                 $content .= $_ . <$fh>;
28                 last;
29             }
30             $context++;
31         }
32         elsif (/^v?(\d+(?:\.\d+)*)(\s+|$)/) {
33             if ($1 eq $version) {
34                 die "$changes already has an entry for $version!\n";
35             }
36             else {
37                 die "No changelog entries found before $1!\n";
38             }
39         }
40         elsif (/^\s+[-*+#]/) {
41             $content .= $changes_line;
42             $content .= (/(\r?\n)/ || $content =~ /(\r?\n)/) ? $1 : "\n";
43             $context = 1;
44         }
45         $content .= $_;
46     }
47
48     seek $fh, 0, 0;
49     truncate $fh, 0;
50     print { $fh } $content;
51     close $fh;
52
53     if ($git) {
54         local $ENV{GIT_DIFF_OPTS} = "-u$context";
55         system qw(git add -p), $changes;
56     }
57 }