blib/lib/LWP/CurlLog.pm untested

filter: Statementstmt 0.0% 0 / 76 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 112 SCAR 24.8
CC
3
Cov
0%
import
12.0
BEGIN
2.0
BEGIN
2.0
CRAP 12.0
1 package LWP::CurlLog;
2 use strict;
3 use warnings;
4 use LWP::UserAgent ();
5  
6 our $VERSION = "0.03";
7 our %opts = (
8 file => undef,
9 response => 1,
10 options => "-k",
11 timing => 0,
12 );
13  
14 sub import {
15 my ($package, %args) = @_;
16 for my $key (keys %args) {
17 $opts{$key} = $args{$key};
18 }
19  
20 if (!$opts{file}) {
21 $opts{fh} = \*STDERR;
22 }
23 else {
24 my $file2 = $opts{file};
25 if ($file2 =~ m{^~/}) {
26 my $home = $ENV{HOME} || (getpwuid($<))[7];
27 $file2 =~ s{^~/}{$home/};
28 }
29 open $opts{fh}, ">>", $file2 or die "Can't open $opts{file}: $!";
30 }
31 select($opts{fh});
32 $| = 1;
33 select(STDOUT);
34 }
35  
36 no strict "refs";
37 no warnings "redefine";
38  
39 my $orig_sub = \&LWP::UserAgent::send_request;
40 *{"LWP::UserAgent::send_request"} = sub {
41 my ($self, $request) = @_;
42  
43 my $cmd = "curl ";
44 my $url = $request->uri();
45 if ($url =~ /[=&;?]/) {
46 $cmd .= "\"$url\" ";
47 }
48 else {
49 $cmd .= "$url "
50 }
51 if ($opts{options}) {
52 $cmd .= "$opts{options} ";
53 }
54 if ($request->method() && ($request->method() ne "GET" || $request->content_length())) {
55 $cmd .= "-X " . $request->method() . " ";
56 }
57 for my $header ($request->header_field_names) {
58 if ($header =~ /^(Content-Length|User-Agent)$/i) {
59 next;
60 }
61 my $value = $request->header($header);
62 $value =~ s{([\\\$"])}{\\$1}g;
63 $cmd .= "-H \"$header: $value\" ";
64 }
65 if ($request->header("Content-Length")) {
66 my $content = $request->decoded_content();
67 $content =~ s{([\\\$"])}{\\$1}g;
68 $cmd .= "-d \"$content\" ";
69 }
70 $cmd =~ s/\s*$//;
71  
72 print {$opts{fh}} "# " . localtime() . " LWP request\n";
73 print {$opts{fh}} "$cmd\n";
74 my $time1 = time();
75 my $response = $orig_sub->(@_);
76 my $time2 = time();
77  
78 if ($opts{response}) {
79 print {$opts{fh}} "\n# " . localtime() . " LWP response\n";
80 my $response2 = $response->as_string;
81 $response2 =~ s/\s*$//g;
82 print {$opts{fh}} "$response2\n";
83 }
84 if ($opts{timing}) {
85 my $diff = $time2 - $time1;
86 print {$opts{fh}} "# ${diff}s\n";
87 }
88  
89 print {$opts{fh}} "\n";
90  
91 return $response;
92 };
93  
94 1;
95  
96 __END__