chiark / gitweb /
Use commas to separate islands in route database for easier editing
[ypp-sc-tools.db-live.git] / pctb / Commods.pm
1 # This is part of ypp-sc-tools, a set of third-party tools for assisting
2 # players of Yohoho Puzzle Pirates.
3 #
4 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
20 # are used without permission.  This program is not endorsed or
21 # sponsored by Three Rings.
22
23 package Commods;
24 use IO::File;
25 use HTTP::Request::Common ();
26
27 use strict;
28 use warnings;
29
30 BEGIN {
31     use Exporter ();
32     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33     $VERSION     = 1.00;
34     @ISA         = qw(Exporter);
35     @EXPORT      = qw(&parse_masters &parse_masters_ocean
36                       %oceans %commods %clients %routes %route_mysteries
37                       &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
38                       &get_our_version &check_tsv_line
39                       &pipethrough_prep &pipethrough_run
40                       &pipethrough_run_along &pipethrough_run_finish
41                       &pipethrough_run_gzip
42                       &cgipostform);
43     %EXPORT_TAGS = ( );
44
45     @EXPORT_OK   = qw();
46 }
47
48 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
49 our %commods; # eg $commods{'Fine black cloth'}= $sources;
50 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
51 our %routes; # eg $routes{'Midnight'}{'Orca'}{'Tinga'}= $sources  NB abbrevs!
52 our %route_mysteries; # eg $route_mysteries{'Midnight'}{'Norse'}= 3
53 # $sources = 's[l]b';
54 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
55
56 our (%pctb_commodmap,@pctb_commodmap);
57
58 my %colours; # eg $colours{'c'}{'black'}= $sources
59 my @rawcm; # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
60
61 sub parse_master_master1 ($$) {
62     my ($mmfn,$src)= @_;
63     my $mm= new IO::File $mmfn, 'r' or die "$mmfn $!";
64     my @ctx= ();
65     while (<$mm>) {
66         next if m/^\s*\#/;
67         next unless m/\S/;
68         s/\s+$//;
69         if (m/^\%(\w+)$/) {
70             my $colourkind= $1;
71             @ctx= (sub { $colours{$colourkind}{lc $_} .= $src; });
72         } elsif (m/^commods$/) {
73             @ctx= (sub { push @rawcm, lc $_; });
74         } elsif (m/^ocean (\w+)$/) {
75             my $ocean= $1;
76             @ctx= (sub {
77                 $ocean or die; # ref to $ocean needed to work
78                                # around a perl bug
79                 my $arch= $_;
80                 $ctx[1]= sub {
81                     $oceans{$ocean}{$arch}{$_} .= $src;
82                 };
83             });
84         } elsif (m/^routes (\w+)$/) {
85             my $ocean= $1;
86             @ctx= (sub {
87                 m/^(\S[^\t]*\S),\s*(\S[^\t]*\S),\s*([1-9][0-9]{0,2})$/ or die;
88                 $routes{$ocean}{$1}{$2}= $3;
89             });
90         } elsif (m/^client (\S+.*\S)$/) {
91             my $client= $1;
92             $clients{$client}= [ ];
93             @ctx= (sub {
94                 my $bug= $_;
95                 push @{ $clients{$client} }, $bug;
96             });
97         } elsif (s/^ +//) {
98             my $indent= length $&;
99             die "wrong indent $indent" unless defined $ctx[$indent-1];
100             &{ $ctx[$indent-1] }();
101         } else {
102             die "bad syntax";
103         }
104     }
105     $mm->error and die $!;
106     close $mm or die $!;
107
108 #print Dumper(\%oceans);
109 #print Dumper(\@rawcm);
110         
111     %commods= ();
112     my $ca;
113     $ca= sub {
114         my ($s,$ss) = @_;
115 #print "ca($s)\n";
116         if ($s !~ m/\%(\w+)/) { $commods{ucfirst $s} .= $ss; return; }
117         die "unknown $&" unless defined $colours{$1};
118         foreach my $c (keys %{ $colours{$1} }) {
119             &$ca($`.$c.$', $ss .'%'. $colours{$1}{$c});
120         }
121     };
122     foreach (@rawcm) { &$ca($_,$src); }
123
124     foreach my $on (keys %routes) {
125         my $routes= $routes{$on};
126         my $ocean= $oceans{$on};
127         die unless defined $ocean;
128         
129         my @allislands;
130         foreach my $an (sort keys %$ocean) {
131             my $arch= $ocean->{$an};
132             push @allislands, sort keys %$arch;
133         }
134         parse_master_map_route_islands($on, \@allislands, $routes);
135         foreach my $route (values %$routes) {
136             parse_master_map_route_islands($on, \@allislands, $route);
137         }
138     }
139 }
140
141 sub parse_master_map_route_islands ($$$) {
142     my ($on, $allislands, $routemap) = @_;;
143     foreach my $k (sort keys %$routemap) {
144         my @ok= grep { index($_,$k) >= 0 } @$allislands;
145         die "ambiguous $k" if @ok>1;
146         if (!@ok) {
147             $route_mysteries{$on}{$k}++;
148             delete $routemap->{$k};
149         } elsif ($ok[0] ne $k) {
150             $routemap->{$ok[0]}= $routemap->{$k};
151             delete $routemap->{$k};
152         }
153     }
154 }
155
156 sub parse_masters () {
157     parse_master_master1('master-master.txt','s');
158 }
159 sub parse_masters_ocean ($) {
160     my ($oceanname) = @_;
161     parse_master_master1('master-master.txt','s');
162     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
163     parse_master_master1("ocean-".(lc $oceanname).".txt",'s');
164 }
165
166 sub parse_pctb_commodmap () {
167     undef %pctb_commodmap;
168     foreach my $commod (keys %commods) { $commods{$commod} =~ s/b//; }
169
170     my $c= new IO::File '_commodmap.tsv' or die $!;
171     if (!$c) { $!==&ENOENT or die $!; return 0; }
172
173     while (<$c>) {
174         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
175         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
176         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
177         $commods{$1} .= 'b';
178     }
179     $c->error and die $!;
180     close $c or die $!;
181     return 1;
182 }
183
184 sub get_our_version ($$) {
185     my ($aref,$prefix) = @_;
186     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
187     $aref->{"${prefix}fixes"}= 'lastpage';
188
189     my $version= `git-describe --tags HEAD`; $? and die $?;
190     chomp($version);
191     $aref->{"${prefix}version"}= $version;
192     return $aref;
193 }
194
195 sub pipethrough_prep () {
196     my $tf= IO::File::new_tmpfile() or die $!;
197     return $tf;
198 }
199
200 sub pipethrough_run_along ($$$@) {
201     my ($tf, $childprep, $cmd, @a) = @_;
202     $tf->flush or die $!;
203     $tf->seek(0,0) or die $!;
204     my $fh= new IO::File;
205     my $child= $fh->open("-|"); defined $child or die $!;
206     if (!$child) {
207         open STDIN, "<&", $tf;
208         &$childprep() if defined $childprep;
209         exec $cmd @a; die $!;
210     }
211     return $fh;
212 }
213 sub pipethrough_run_finish ($) {
214     my ($fh)= @_;
215     $fh->error and die $!;
216     close $fh or die "$! $?";  die $? if $?;
217 }
218
219 sub pipethrough_run ($$$@) {
220     my ($tf, $childprep, $cmd, @a) = @_;
221     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
222     my $r;
223     { undef $/; $!=0; $r= <$pt>; }
224     defined $r or die $!;
225     pipethrough_run_finish($pt);
226     return $r;
227 }
228 sub pipethrough_run_gzip ($) {
229     pipethrough_run($_[0],undef,'gzip','gzip');
230 }
231
232 sub cgipostform ($$$) {
233     my ($ua, $url, $form) = @_;
234     my $req= HTTP::Request::Common::POST($url,
235                                          Content => $form,
236                                          Content_Type => 'form-data');
237     if ($url =~ m,^\.?/,) {
238         my $tf= pipethrough_prep();
239         print $tf $req->content() or die $!;
240 #print STDERR "[[[",$req->content(),"]]]";
241         my $out= pipethrough_run($tf, sub {
242             $ENV{'REQUEST_METHOD'}= 'POST';
243             $ENV{'QUERY_STRING'}= '';
244             $ENV{'PATH_TRANSLATED'}= $url;
245             $ENV{'PATH_INFO'}= '';
246             $ENV{'HTTP_HOST'}= 'localhost';
247             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
248             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
249             $ENV{'DOCUMENT_ROOT'}= '.';
250             $ENV{'SCRIPT_FILENAME'}= $url;
251             $ENV{'SCRIPT_NAME'}= $url;
252             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
253
254             foreach my $f (qw(Content_Length Content_Type)) {
255                 $ENV{uc $f}= $req->header($f);
256             }
257 #system 'printenv >&2';
258         }, "$url", "$url");
259         $out =~ s/\r\n/\n/g;
260         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
261         return $';
262     } else {
263         my $resp= $ua->request($url,$req);
264         die $resp->status_line unless $resp->is_success;
265         return $resp->content();
266     }
267 }
268
269 our %check_tsv_done;
270
271 sub check_tsv_line ($$) {
272     my ($l, $bad_data_callback) = @_;
273     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
274     
275     chomp($l) or &$bad_data('missing end-of-line');
276
277     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
278     $l !~ m/\\/ or &$bad_data('data contains backslashes');
279     my @v= split /\t/, $l, -1;
280     @v==6 or &$bad_data('wrong number of fields');
281     my ($commod,$stall) = @v;
282
283     !keys %commods or
284         defined $commods{$commod} or
285         &$bad_data("unknown commodity \`$commod'");
286     
287     $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
288     !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
289     $check_tsv_done{$commod,$stall}= 1;
290     foreach my $i (2..5) {
291         my $f= $v[$i];
292         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
293         ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
294     }
295     return @v;
296 }
297
298 1;