]> git.vpit.fr Git - perl/modules/Test-Valgrind.git/blob - t/lib/Test/Valgrind/FakeValgrind.pm
Make sure File::Temp is recent enough for ->newdir
[perl/modules/Test-Valgrind.git] / t / lib / Test / Valgrind / FakeValgrind.pm
1 package Test::Valgrind::FakeValgrind;
2
3 use strict;
4 use warnings;
5
6 use Config ();
7 use File::Spec;
8 use File::Temp;
9
10 sub _dummy_valgrind_code {
11  my ($version, $body) = @_;
12
13  my $perl = $^X;
14  unless (-e $perl and -x $perl) {
15   $perl = $Config::Config{perlpath};
16   unless (-e $perl and -x $perl) {
17    return undef;
18   }
19  }
20
21  if (defined $body) {
22   $body = "\n$body";
23  } else {
24   $body = '';
25  }
26
27  return <<" FAKE_VG";
28 #!$perl
29 if (\@ARGV == 1 && \$ARGV[0] eq '--version') {
30  print "valgrind-$version\n";
31  exit 0;
32 }$body
33  FAKE_VG
34 }
35
36 my $good_enough_file_temp;
37 BEGIN {
38  $good_enough_file_temp = do {
39   no warnings;
40   local $@;
41   eval { File::Temp->VERSION('0.19'); 1 }
42  }
43 }
44
45 sub new {
46  my ($class, %args) = @_;
47
48  my $exe_name = $args{exe_name};
49  my $version  = $args{version} || '3.1.0';
50  my $body     = $args{body};
51
52  my $self = { };
53
54  if (defined $exe_name) {
55   return 'File::Temp 0.19 is required to make a proper temporary directory'
56          unless $good_enough_file_temp;
57   $self->{tmp_dir_obj}  = File::Temp->newdir(CLEANUP => 1);
58   $self->{tmp_dir}      = $self->{tmp_dir_obj}->dirname;
59   $self->{tmp_file}     = File::Spec->catfile($self->{tmp_dir}, $exe_name);
60  } else {
61   # Can't use the OO interface if we don't wan't the file to be opened by
62   # default, but then we have to deal with cleanup ourselves.
63   local $^W = 0;
64   (undef, my $tmp_file) = File::Temp::tempfile(
65    TEMPLATE => 'fakevgXXXX',
66    TMPDIR   => 1,
67    CLEANUP  => 0,
68    OPEN     => 0,
69   );
70   $self->{tmp_file}     = $tmp_file;
71   my ($vol, $dir)       = File::Spec->splitpath($self->{tmp_file});
72   $self->{tmp_dir}      = File::Spec->catpath($vol, $dir, '');
73  }
74
75  my $code = _dummy_valgrind_code($version, $body);
76  return 'Could not generate the dummy valgrind executable' unless $code;
77
78  return 'Temporary file already exists' if -s $self->{tmp_file};
79
80  {
81   open my $vg_fh, '>', $self->{tmp_file};
82   print $vg_fh $code;
83   close $vg_fh;
84   chmod 0755, $self->{tmp_file};
85  }
86
87  bless $self, $class;
88 }
89
90 sub path    { $_[0]->{tmp_file} }
91
92 sub dir     { $_[0]->{tmp_dir} }
93
94 sub DESTROY { 1 while unlink $_[0]->{tmp_file} }
95
96 1;