* gnulib: Update submodule to latest.
[coreutils.git] / tests / CuTmpdir.pm
blob166e50bd83a3f52b0cc362b7a385123aa46b670c
1 package CuTmpdir;
2 # create, then chdir into a temporary sub-directory
4 # Copyright (C) 2007-2008 Free Software Foundation, Inc.
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.
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.
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/>.
19 use strict;
20 use warnings;
22 use File::Temp;
23 use File::Find;
25 our $ME = $0 || "<???>";
27 my $dir;
29 sub skip_test($)
31 warn "$ME: skipping test: unsafe working directory name: `$_[0]'\n";
32 exit 77;
35 sub chmod_1
37 my $name = $_;
39 # Skip symlinks and non-directories.
40 -l $name || !-d _
41 and return;
43 chmod 0700, $name;
46 sub chmod_tree
48 if (defined $dir && chdir $dir)
50 # Perform the equivalent of find . -type d -print0|xargs -0 chmod -R 700.
51 my $options = {untaint => 1, wanted => \&chmod_1};
52 find ($options, '.');
54 else
56 warn "$ME: failed to chdir to $dir: $!\n";
60 sub import {
61 my $prefix = $_[1];
63 $ME eq '-' && defined $prefix
64 and $ME = $prefix;
66 if ($prefix !~ /^\//)
68 eval 'use Cwd';
69 my $cwd = $@ ? '.' : Cwd::getcwd();
70 $prefix = "$cwd/$prefix";
73 # Untaint for the upcoming mkdir.
74 $prefix =~ m!^([-+\@\w./]+)$!
75 or skip_test $prefix;
76 $prefix = $1;
78 my $original_pid = $$;
80 my $on_sig_remove_tmpdir = sub {
81 my ($sig) = @_;
82 if ($$ == $original_pid and defined $dir)
84 chmod_tree;
85 # Older versions of File::Temp lack this method.
86 exists &File::Temp::cleanup
87 and &File::Temp::cleanup;
89 $SIG{$sig} = 'DEFAULT';
90 kill $sig, $$;
93 foreach my $sig (qw (INT TERM HUP))
95 $SIG{$sig} = $on_sig_remove_tmpdir;
98 $dir = File::Temp::tempdir("$prefix.tmp-XXXX", CLEANUP => 1 );
99 chdir $dir
100 or warn "$ME: failed to chdir to $dir: $!\n";
103 END {
104 my $saved_errno = $?;
105 chmod_tree;
106 $? = $saved_errno;