1#!/usr/bin/perl
2
3sub usage {
4    print STDERR "Usage: findunusedtranslations values/strings.xml\n";
5    print STDERR "\n";
6    print STDERR "Will read values/strings.xml and rewrite\n";
7    print STDERR "values-xx/strings.xml and values-xx-rYY/strings.xml\n";
8    print STDERR "files to remove strings that no longer appear in the\n";
9    print STDERR "base strings file.\n";
10
11    exit 1;
12}
13
14if ($#ARGV != 0) {
15    usage();
16}
17
18unless ($ARGV[0] =~ /^(.*)\/values([^\/]*)\/(.*\.xml)/) {
19    print STDERR "Bad format for $ARGV[0]\n";
20    usage();
21}
22
23unless (-f $ARGV[0]) {
24    print STDERR "$0: $ARGV[0]: No such file\n";
25}
26
27$prefix = $1;
28$values = $2;
29$suffix = $3;
30
31if ($values =~ /^(-mcc[^-]*)*(-mnc[^-]*)*(.*)$/) {
32    $pattern1 = "$prefix/values$1$2-??$3/$suffix";
33    $pattern2 = "$prefix/values$1$2-??-r??$3/$suffix";
34} else {
35    $pattern1 = "$prefix/values-??$values/$suffix";
36    $pattern2 = "$prefix/values-??-r??$values/$suffix";
37}
38
39@matches = (glob($pattern1), glob($pattern2));
40
41open(IN, "<$ARGV[0]");
42while (<IN>) {
43    if (/<string [^>]*name="([^"]*)"/) {
44        $string{$1} = 1;
45    }
46    if (/<string-array [^>]*name="([^"]*)"/) {
47        $stringarray{$1} = 1;
48    }
49    if (/<plurals [^>]*name="([^"]*)"/) {
50        $plurals{$1} = 1;
51    }
52}
53close(IN);
54
55for $match (@matches) {
56    print "Rewriting $match\n";
57    $suppress = 0;
58    $text = "";
59    $changes = 0;
60
61    open(IN, "<$match");
62    while (<IN>) {
63        if (/<string [^>]*name="([^"]*)"/) {
64            if ($string{$1} == 0) {
65                $suppress = 1;
66                $changes = 1;
67            }
68        }
69        if (/<string-array [^>]*name="([^"]*)"/) {
70            if ($stringarray{$1} == 0) {
71                $suppress = 1;
72                $changes = 1;
73            }
74        }
75        if (/<plurals [^>]*name="([^"]*)"/) {
76            if ($plurals{$1} == 0) {
77                $suppress = 1;
78                $changes = 1;
79            }
80        }
81
82        $text .= $_ unless ($suppress);
83
84        if (/<\/string/) {
85            $suppress = 0;
86        }
87        if (/<\/string-array/) {
88            $suppress = 0;
89        }
90        if (/<\/plurals/) {
91            $suppress = 0;
92        }
93    }
94    close(IN);
95
96    if ($changes) {
97        open(OUT, ">$match");
98        print OUT $text;
99        close(OUT);
100    } else {
101        print "(no changes)\n";
102    }
103}
104