tests: improve perl-based tempdir handling
authorJim Meyering <meyering@redhat.com>
Fri, 25 Apr 2008 08:41:42 +0000 (10:41 +0200)
committerJim Meyering <meyering@redhat.com>
Sun, 27 Apr 2008 19:31:32 +0000 (21:31 +0200)
Before, upon interrupt, directories would be left behind.
* tests/CuTmpdir.pm: Remove temporary directory on interrupt.

tests/CuTmpdir.pm

index 60eec90..f9d2c00 100644 (file)
@@ -1,7 +1,7 @@
 package CuTmpdir;
 # create, then chdir into a temporary sub-directory
 
-# Copyright (C) 2007 Free Software Foundation, Inc.
+# Copyright (C) 2007-2008 Free Software Foundation, Inc.
 
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -26,12 +26,44 @@ our $ME = $0 || "<???>";
 
 my $dir;
 
-sub skip_test
+sub skip_test($)
 {
-  warn "$ME: skipping test: unsafe working directory name\n";
+  warn "$ME: skipping test: unsafe working directory name: `$_[0]'\n";
   exit 77;
 }
 
+sub chmod_1
+{
+  my $name = $_;
+
+  # Skip symlinks and non-directories.
+  -l $name || !-d _
+    and return;
+
+  chmod 0700, $name;
+}
+
+sub chmod_tree
+{
+  chdir $dir
+    or warn "$ME: failed to chdir to $dir: $!\n";
+  # Perform the equivalent of find . -type d -print0|xargs -0 chmod -R 700.
+  my $options = {untaint => 1, wanted => \&chmod_1};
+  find ($options, '.');
+}
+
+sub on_sig_remove_tmpdir
+{
+  my ($sig) = @_;
+  if (defined $dir)
+    {
+      chmod_tree;
+      File::Temp::cleanup;
+    }
+  $SIG{$sig} = 'DEFAULT';
+  kill $sig, $$;
+}
+
 sub import {
   my $prefix = $_[1];
 
@@ -47,35 +79,22 @@ sub import {
 
   # Untaint for the upcoming mkdir.
   $prefix =~ m!^([-+\@\w./]+)$!
-    or skip_test;
+    or skip_test $prefix;
   $prefix = $1;
 
+  foreach my $sig (qw (INT TERM HUP))
+    {
+      $SIG{$sig} = \&on_sig_remove_tmpdir;
+    }
+
   $dir = File::Temp::tempdir("$prefix.tmp-XXXX", CLEANUP => 1 );
   chdir $dir
     or warn "$ME: failed to chdir to $dir: $!\n";
 }
 
-sub wanted
-{
-  my $name = $_;
-
-  # Skip symlinks and non-directories.
-  -l $name || !-d _
-    and return;
-
-  chmod 0700, $name;
-}
-
 END {
   my $saved_errno = $?;
-  if (defined $dir)
-    {
-      chdir $dir
-       or warn "$ME: failed to chdir to $dir: $!\n";
-      # Perform the equivalent of find . -type d -print0|xargs -0 chmod -R 700.
-      my $options = {untaint => 1, wanted => \&wanted};
-      find ($options, '.');
-    }
+  chmod_tree;
   $? = $saved_errno;
 }