]> www.fi.muni.cz Git - aoc.git/blob - lib/Y/AoC/Task.pm
Infrastructure mods
[aoc.git] / lib / Y / AoC / Task.pm
1 package Y::AoC::Task;
2
3 use v5.36;
4
5 use Exporter ('import');
6 use IO::Handle;
7
8 our @EXPORT = qw(t asay bsay);
9 use Y::AoC qw(red white grey yellow day year);
10
11 our $printed_err;
12 $SIG{__DIE__} = sub($msg) {
13         $msg =~ s/\A(.*?)( at \S+ )(line \d+)/red($1).$2.white($3)/e
14                 if -t STDERR && !$printed_err++;
15         say STDERR $msg;
16         die "\n";
17 };
18
19 $SIG{__WARN__} = sub($msg) {
20         $msg =~ s/\A(.*?)( at \S+ )(line \d+)/red($1).$2.white($3)/e
21                 if -t STDERR && !$printed_err++;
22         say STDERR $msg;
23 };
24
25 STDOUT->autoflush(1);
26 STDERR->autoflush(1);
27
28 our $in_test;
29 sub t($subtest = ()) {
30         $subtest //= '';
31         $ARGV[0] =~ s/in\.txt/test$subtest.txt/ if defined $ARGV[0];
32         $in_test = 1;
33 }
34
35 sub asay(@msg) {
36         try_submit(1, @msg);
37 }
38
39 sub bsay(@msg) {
40         try_submit(2, @msg);
41 }
42
43 sub try_submit($part, @msg) {
44         my $msg = join($, // '', @msg);
45         my $ans;
46         $msg =~ s/(\w+)\z/white($ans = $1)/e;
47
48         say $msg;
49
50         return if $in_test;
51
52         my $day = day;
53         my $year = year;
54
55         my $url = "https://adventofcode.com/$year/day/$day/answer";
56         my $cachefile = "ans-$year-$day-$part-$ans.html";
57         local $| = 1;
58         print "\nSubmit $url\nlevel=", white($part), ' answer=',
59                 white($ans), ' ? [Enter]/[Ctrl-C]: ';
60         
61         scalar <STDIN>;
62         eval '{
63                 local $SIG{__DIE__};
64                 require Y::AoC::UA;
65         }';
66         my $res = Y::AoC::UA::request($url, {
67                 form => {
68                         answer => $ans,
69                         level  => $part,
70                 },
71                 cache_to => $cachefile,
72         });
73
74         my $art = $res->find('main > article > p')->join("\n");
75         if (!$art) {
76                 say $res->to_string;
77                 return;
78         }
79
80         $art =~ s/&#39;/'/g;
81         $art =~ s/(?<=That's )not(?= the right answer)/red($&)/e;
82         my $ok = $art =~ s/(?<=That's the )(right answer)/yellow($&)/e;
83         $art =~ s/(gold stars?)/yellow($&)/e;
84         $art =~ s/(silver star)/grey($&)/e;
85         Y::AoC::UA::cache_del($cachefile)
86                 if $msg =~ s/(?<=Please wait ).*?(?= before trying again)/white($&)/e;
87         $art =~ s/(?<=your answer is )([^\.;]+)/red($&)/e;
88         $art =~ s/<code>([^<]+)<\/code>/white($1)/e;
89         $art =~ s/<[^>]+>//g;
90
91         if ($ok) {
92                 system "cp $0 backup/$0-ok-$ans-$part";
93         }
94
95         say $art;
96 }
97
98 1;