Debian Codegraph @

change-po-charset

raw
1 #!/usr/bin/perl
2 # Changes the "charset" attribute value of the Content-Type header in a po file.
3 # Does NOT actually change the encoding of the file.
4 #
5 # Copyright 2007-2009 Marcin Owsiany
6 # This script is public domain.
7 use strict;
8 use warnings;
9
10 my $debug = 0;
11
12 my $charset = shift @ARGV;
13 die "Usage: change-po-charset <charset> [ file ] [ ... ]\n" unless defined $charset;
14
15 # States
16 my ($S_BLANK, $S_COMMENT, $S_MSGCTXT, $S_MSGID, $S_MSGSTR) = (1..10);
17
18 # Possible regexes
19 my %r = (
20 blank => qr{^\s*$}oi,
21 comment => qr{^#}oi,
22 msgctxt => qr{^msgctxt\s+"(.*)"$}oi,
23 msgid => qr{^msgid(_plural)?\s+".*"$}oi,
24 msgstr => qr{^msgstr(\[\w+\])?\s+".*"$}oi,
25 string => qr{^".*"$}oi,
26 );
27 my $subst = qr{^("Content-Type:.*charset=)(.*?)(( *;.*)?\\n")$}oi;
28
29 # Current line
30 my $l;
31 # Current line number
32 my $n = 0;
33 # Curerrent state
34 my $s = $S_BLANK;
35 # Whether we've done the job
36 my $done = 0;
37
38 while ($l = <>) {
39 chomp $l;
40 my $orig_s = $s;
41 $n++;
42
43 if ($done) {
44 print $l, "\n" or die "print failed: $!";
45 next;
46 } elsif ($s == $S_BLANK && $l =~ $r{blank}) {
47 } elsif (($s == $S_BLANK || $s == $S_COMMENT) && $l =~ $r{comment}) {
48 $s = $S_COMMENT;
49 } elsif (($s == $S_BLANK || $s == $S_COMMENT) && $l =~ $r{msgctxt}) {
50 $s = $S_MSGCTXT;
51 } elsif (($s == $S_BLANK || $s == $S_COMMENT || $s == $S_MSGCTXT) && $l =~ $r{msgid}) {
52 $s = $S_MSGID;
53 } elsif ($s == $S_MSGID && $l =~ $r{msgstr}) {
54 $s = $S_MSGSTR;
55 } elsif ($s == $S_MSGID && ($l =~ $r{string} or $l =~ $r{msgid})) {
56 } elsif ($s == $S_MSGSTR && ($l =~ $r{string} or $l =~ $r{msgstr})) {
57 } elsif ($s == $S_MSGSTR && $l =~ $r{blank}) {
58 $s = $S_BLANK;
59 } else {
60 die "Unrecognized line num. $n in state $s: [$l], exiting";
61 }
62
63 if ($s == $S_MSGSTR) {
64 $done = $l =~ s{$subst}{${1}${charset}${3}}i;
65 print STDERR "CHANGED\n" if $debug and $done;
66 }
67
68 print $l, "\n" or die "print failed: $!";
69
70 printf STDERR "%03d: %s->%s: [%s]\n", $n, $orig_s, $s, $l if $debug;
71 }
72
73 close(STDOUT) or die "close failed: $!";
74 exit($done ? 0 : 2);
75