PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Directory/Scratch.pm

https://github.com/gitpan/Directory-Scratch
Perl | 788 lines | 694 code | 81 blank | 13 comment | 33 complexity | 7debee15d8e1e9d64c9c523d18167ddb MD5 | raw file
Possible License(s): AGPL-1.0
  1. package Directory::Scratch; # git description: v0.15-1-g5e2e598
  2. $Directory::Scratch::VERSION = '0.16';
  3. # see POD after __END__.
  4. use warnings;
  5. use strict;
  6. use Carp;
  7. use File::Temp;
  8. use File::Copy;
  9. use Path::Class qw(dir file);
  10. use Path::Tiny;
  11. use File::Spec;
  12. use File::stat (); # no imports
  13. my ($OUR_PLATFORM) = $File::Spec::ISA[0] =~ /::(\w+)$/;
  14. my $PLATFORM = 'Unix';
  15. use Scalar::Util qw(blessed);
  16. use overload q{""} => \&base,
  17. fallback => "yes, fallback";
  18. # allow the user to specify which OS's semantics he wants to use
  19. # if platform is undef, then we won't do any translation at all
  20. sub import {
  21. my $class = shift;
  22. return unless @_;
  23. $PLATFORM = shift;
  24. eval("require File::Spec::$PLATFORM");
  25. croak "Don't know how to deal with platform '$PLATFORM'" if $@;
  26. return $PLATFORM;
  27. }
  28. # create an instance
  29. sub new {
  30. my $class = shift;
  31. my $self = {};
  32. my %args;
  33. eval { %args = @_ };
  34. croak 'Invalid number of arguments to Directory::Scratch->new' if $@;
  35. my $platform = $PLATFORM;
  36. $platform = $args{platform} if defined $args{platform};
  37. # explicitly default CLEANUP to 1
  38. $args{CLEANUP} = 1 unless exists $args{CLEANUP};
  39. # don't clean up if environment variable is set
  40. $args{CLEANUP} = 0
  41. if(defined $ENV{PERL_DIRECTORYSCRATCH_CLEANUP} &&
  42. $ENV{PERL_DIRECTORYSCRATCH_CLEANUP} == 0);
  43. # TEMPLATE is a special case, since it's positional in File::Temp
  44. my @file_temp_args;
  45. # convert DIR from their format to a Path::Class
  46. $args{DIR} = Path::Class::foreign_dir($platform, $args{DIR}) if $args{DIR};
  47. # change our arg format to one that File::Temp::tempdir understands
  48. for(qw(CLEANUP DIR)){
  49. push @file_temp_args, ($_ => $args{$_}) if $args{$_};
  50. }
  51. # this is a positional argument, not a named argument
  52. unshift @file_temp_args, $args{TEMPLATE} if $args{TEMPLATE};
  53. # fix TEMPLATE to do what we mean; if TEMPLATE is set then TMPDIR
  54. # needs to be set also
  55. push @file_temp_args, (TMPDIR => 1) if($args{TEMPLATE} && !$args{DIR});
  56. # keep this around for C<child>
  57. $self->{args} = \%args;
  58. # create the directory!
  59. my $base = dir(File::Temp::tempdir(@file_temp_args));
  60. croak "Couldn't create a tempdir: $!" unless -d $base;
  61. $self->{base} = $base;
  62. bless $self, $class;
  63. $self->platform($platform); # set platform for this instance
  64. return $self;
  65. }
  66. sub child {
  67. my $self = shift;
  68. my %args;
  69. croak 'Invalid reference passed to Directory::Scratch->child'
  70. if !blessed $self || !$self->isa(__PACKAGE__);
  71. # copy args from parent object
  72. %args = %{$self->{_args}} if exists $self->{_args};
  73. # force the directory end up as a child of the parent, though
  74. $args{DIR} = $self->base->stringify;
  75. return Directory::Scratch->new(%args);
  76. }
  77. sub base {
  78. my $self = shift;
  79. return $self->{base};#->stringify;
  80. }
  81. sub platform {
  82. my $self = shift;
  83. my $desired = shift;
  84. if($desired){
  85. eval "require File::Spec::$desired";
  86. croak "Unknown platform '$desired'" if $@;
  87. $self->{platform} = $desired;
  88. }
  89. return $self->{platform};
  90. }
  91. # make Path::Class's foreign_* respect the instance's desired platform
  92. sub _foreign_file {
  93. my $self = shift;
  94. my $platform = $self->platform;
  95. if($platform){
  96. my $file = Path::Class::foreign_file($platform, @_);
  97. return $file->as_foreign($OUR_PLATFORM);
  98. }
  99. else {
  100. return Path::Class::file(@_);
  101. }
  102. }
  103. sub _foreign_dir {
  104. my $self = shift;
  105. my $platform = $self->platform;
  106. if($platform){
  107. my $dir = Path::Class::foreign_dir($platform, @_);
  108. return $dir->as_foreign($OUR_PLATFORM);
  109. }
  110. else {
  111. return Path::Class::dir(@_);
  112. }
  113. }
  114. sub exists {
  115. my $self = shift;
  116. my $file = shift;
  117. my $base = $self->base;
  118. my $path = $self->_foreign_file($base, $file);
  119. return dir($path) if -d $path;
  120. return $path if -e $path;
  121. return; # undef otherwise
  122. }
  123. sub stat {
  124. my $self = shift;
  125. my $file = shift;
  126. my $path = $self->_foreign_file($self->base, $file);
  127. if(wantarray){
  128. return stat $path; # core stat, returns a list
  129. }
  130. return File::stat::stat($path); # returns an object
  131. }
  132. sub mkdir {
  133. my $self = shift;
  134. my $dir = shift;
  135. my $base = $self->base;
  136. $dir = $self->_foreign_dir($base, $dir);
  137. $dir->mkpath;
  138. return $dir if (-e $dir && -d $dir);
  139. croak "Error creating $dir: $!";
  140. }
  141. sub link {
  142. my $self = shift;
  143. my $from = shift;
  144. my $to = shift;
  145. my $base = $self->base;
  146. croak "Symlinks are not supported on MSWin32"
  147. if $^O eq 'MSWin32';
  148. $from = $self->_foreign_file($base, $from);
  149. $to = $self->_foreign_file($base, $to);
  150. symlink($from, $to)
  151. or croak "Couldn't link $from to $to: $!";
  152. return $to;
  153. }
  154. sub chmod {
  155. my $self = shift;
  156. my $mode = shift;
  157. my @paths = @_;
  158. my @translated = map { $self->_foreign_file($self->base, $_) } @paths;
  159. return chmod $mode, @translated;
  160. }
  161. sub read {
  162. my $self = shift;
  163. my $file = shift;
  164. my $base = $self->base;
  165. $file = $self->_foreign_file($base, $file);
  166. croak "Cannot read $file: is a directory" if -d $file;
  167. if(wantarray){
  168. my @lines = path($file->stringify)->lines;
  169. chomp @lines;
  170. return @lines;
  171. }
  172. else {
  173. my $scalar = path($file->stringify)->slurp;
  174. chomp $scalar;
  175. return $scalar;
  176. }
  177. }
  178. sub write {
  179. my $self = shift;
  180. my $file = shift;
  181. my $base = $self->base;
  182. my $path = $self->_foreign_file($base, $file);
  183. $path->parent->mkpath;
  184. croak "Couldn't create parent dir ". $path->parent. ": $!"
  185. unless -e $path->parent;
  186. # figure out if we're "write" or "append"
  187. my (undef, undef, undef, $method) = caller(1);
  188. my $args;
  189. if(defined $method && $method eq 'Directory::Scratch::append'){
  190. local $, = $, || "\n";
  191. path($path->stringify)->append(@_, '')
  192. or croak "Error writing file: $!";
  193. }
  194. else { # (cut'n'paste)++
  195. local $, = $, || "\n";
  196. path($path->stringify)->spew(@_, '')
  197. or croak "Error writing file: $!";
  198. }
  199. return 1;
  200. }
  201. sub append {
  202. return &write(@_); # magic!
  203. }
  204. sub tempfile {
  205. my $self = shift;
  206. my $path = shift;
  207. if(!defined $path){
  208. $path = $self->base;
  209. }
  210. else {
  211. $path = $self->_foreign_dir($self->base, $path);
  212. }
  213. my ($fh, $filename) = File::Temp::tempfile( DIR => $path );
  214. $filename = file($filename); # "class"ify the file
  215. if(wantarray){
  216. return ($fh, $filename);
  217. }
  218. # XXX: I don't know why you would want to do this...
  219. return $fh;
  220. }
  221. sub openfile {
  222. my $self = shift;
  223. my $file = shift;
  224. my $base = $self->base;
  225. my $path = $self->_foreign_file($base, $file);
  226. $path->dir->mkpath;
  227. croak 'Parent directory '. $path->dir.
  228. ' does not exist, and could not be created'
  229. unless -d $path->dir;
  230. open(my $fh, '+>', $path) or croak "Failed to open $path: $!";
  231. return ($fh, $path) if(wantarray);
  232. return $fh;
  233. }
  234. sub touch {
  235. my $self = shift;
  236. my $file = shift;
  237. my ($fh, $path) = $self->openfile($file);
  238. $self->write($file, @_) || croak 'failed to write file: $!';
  239. return $path;
  240. }
  241. sub ls {
  242. my $self = shift;
  243. my $dir = shift;
  244. my $base = $self->base;
  245. my $path = dir($base);
  246. my @result;
  247. if($dir){
  248. $dir = $self->_foreign_dir($dir);
  249. $path = $self->exists($dir);
  250. croak "No path `$dir' in temporary directory" if !$path;
  251. return (file($dir)) if !-d $path;
  252. $path = dir($base, $dir);
  253. }
  254. $path->recurse( callback =>
  255. sub {
  256. my $file = shift;
  257. return if $file eq $path;
  258. push @result, $file->relative($base);
  259. }
  260. );
  261. return @result;
  262. }
  263. sub create_tree {
  264. my $self = shift;
  265. my %tree = %{shift()||{}};
  266. foreach my $element (keys %tree){
  267. my $value = $tree{$element};
  268. if('SCALAR' eq ref $value){
  269. $self->mkdir($element);
  270. }
  271. else {
  272. my @lines = ($value);
  273. @lines = @$value if 'ARRAY' eq ref $value;
  274. $self->touch($element, @lines);
  275. }
  276. }
  277. }
  278. sub delete {
  279. my $self = shift;
  280. my $path = shift;
  281. my $base = $self->base;
  282. $path = $self->_foreign_file($base, $path);
  283. croak "No such file or directory '$path'" if !-e $path;
  284. if(-d _){ # reuse stat() from -e test
  285. return (scalar rmdir $path or croak "Couldn't remove directory $path: $!");
  286. }
  287. else {
  288. return (scalar unlink $path or croak "Couldn't unlink $path: $!");
  289. }
  290. }
  291. sub cleanup {
  292. my $self = shift;
  293. my $base = $self->base;
  294. # capture warnings
  295. my @errors;
  296. local $SIG{__WARN__} = sub {
  297. push @errors, @_;
  298. };
  299. File::Path::rmtree( $base->stringify );
  300. if ( @errors > 0 ) {
  301. croak "cleanup() method failed: $!\n@errors";
  302. }
  303. $self->{args}->{CLEANUP} = 1; # it happened, so update this
  304. return 1;
  305. }
  306. sub randfile {
  307. my $self = shift;
  308. # make sure we can do this
  309. eval {
  310. require String::Random;
  311. };
  312. croak 'randfile: String::Random is required' if $@;
  313. # setup some defaults
  314. my( $min, $max ) = ( 1024, 131072 );
  315. if ( @_ == 2 ) {
  316. ($min, $max) = @_;
  317. }
  318. elsif ( @_ == 1 ) {
  319. $max = $_[0];
  320. $min = int(rand($max)) if ( $min > $max );
  321. }
  322. confess "randfile: Cannot request a maximum length < 1"
  323. if ( $max < 1 );
  324. my ($fh, $name) = $self->tempfile;
  325. croak "Could not open $name: $!" if !$fh;
  326. my $rand = String::Random->new();
  327. path($name)->spew($rand->randregex(".{$min,$max}"));
  328. return file($name);
  329. }
  330. # throw a warning if CLEANUP is off and cleanup hasn't been called
  331. sub DESTROY {
  332. my $self = shift;
  333. carp "Warning: not cleaning up files in ". $self->base
  334. if !$self->{args}->{CLEANUP};
  335. }
  336. 1;
  337. __END__
  338. =head1 NAME
  339. Directory::Scratch - (DEPRECATED) Easy-to-use self-cleaning scratch space.
  340. =head1 VERSION
  341. version 0.16
  342. =head1 DEPRECATION NOTICE
  343. This module has not been maintained in quite some time, and now there are
  344. other options available, which are much more actively maintained. Please
  345. use L<Test::TempDir::Tiny> instead of this module.
  346. =head1 SYNOPSIS
  347. When writing test suites for modules that operate on files, it's often
  348. inconvenient to correctly create a platform-independent temporary
  349. storage space, manipulate files inside it, then clean it up when the
  350. test exits. The inconvenience usually results in tests that don't work
  351. everywhere, or worse, no tests at all.
  352. This module aims to eliminate that problem by making it easy to do
  353. things right.
  354. Example:
  355. use Directory::Scratch;
  356. my $temp = Directory::Scratch->new();
  357. my $dir = $temp->mkdir('foo/bar');
  358. my @lines= qw(This is a file with lots of lines);
  359. my $file = $temp->touch('foo/bar/baz', @lines);
  360. my $fh = openfile($file);
  361. print {$fh} "Here is another line.\n";
  362. close $fh;
  363. $temp->delete('foo/bar/baz');
  364. undef $temp; # everything else is removed
  365. # Directory::Scratch objects stringify to base
  366. $temp->touch('foo');
  367. ok(-e "$temp/foo"); # /tmp/xYz837/foo should exist
  368. =head1 EXPORT
  369. The first argument to the module is optional, but if specified, it's
  370. interpreted as the name of the OS whose file naming semantics you want
  371. to use with Directory::Scratch. For example, if you choose "Unix",
  372. then you can provide paths to Directory::Scratch in UNIX-form
  373. ('foo/bar/baz') on any platform. Unix is the default if you don't
  374. choose anything explicitly.
  375. If you want to use the local platform's flavor (not recommended),
  376. specify an empty import list:
  377. use Directory::Scratch ''; # use local path flavor
  378. Recognized platforms (from L<File::Spec|File::Spec>):
  379. =over 4
  380. =item Mac
  381. =item UNIX
  382. =item Win32
  383. =item VMS
  384. =item OS2
  385. =back
  386. The names are case sensitive, since they simply specify which
  387. C<File::Spec::> module to use when splitting the path.
  388. =head2 EXAMPLE
  389. use Directory::Scratch 'Win32';
  390. my $tmp = Directory::Scratch->new();
  391. $tmp->touch("foo\\bar\\baz"); # and so on
  392. =head1 METHODS
  393. The file arguments to these methods are always relative to the
  394. temporary directory. If you specify C<touch('/etc/passwd')>, then a
  395. file called C</tmp/whatever/etc/passwd> will be created instead.
  396. This means that the program's PWD is ignored (for these methods), and
  397. that a leading C</> on the filename is meaningless (and will cause
  398. portability problems).
  399. Finally, whenever a filename or path is returned, it is a
  400. L<Path::Class|Path::Class> object rather than a string containing the
  401. filename. Usually, this object will act just like the string, but to
  402. be extra-safe, call C<< $path->stringify >> to ensure that you're
  403. really getting a string. (Some clever modules try to determine
  404. whether a variable is a filename or a filehandle; these modules
  405. usually guess wrong when confronted with a C<Path::Class> object.)
  406. =head2 new
  407. Creates a new temporary directory (via File::Temp and its defaults).
  408. When the object returned by this method goes out of scope, the
  409. directory and its contents are removed.
  410. my $temp = Directory::Scratch->new;
  411. my $another = $temp->new(); # will be under $temp
  412. # some File::Temp arguments get passed through (may be less portable)
  413. my $temp = Directory::Scratch->new(
  414. DIR => '/var/tmp', # be specific about where your files go
  415. CLEANUP => 0, # turn off automatic cleanup
  416. TEMPLATE => 'ScratchDirXXXX', # specify a template for the dirname
  417. );
  418. If C<DIR>, C<CLEANUP>, or C<TEMPLATE> are omitted, reasonable defaults
  419. are selected. C<CLEANUP> is on by default, and C<DIR> is set to C<< File::Spec->tmpdir >>;
  420. =head2 child
  421. Creates a new C<Directory::Scratch> directory inside the current
  422. C<base>, copying TEMPLATE and CLEANUP options from the current
  423. instance. Returns a C<Directory::Scratch> object.
  424. =head2 base
  425. Returns the full path of the temporary directory, as a Path::Class
  426. object.
  427. =head2 platform([$platform])
  428. Returns the name of the platform that the filenames are being
  429. interpreted as (i.e., "Win32" means that this module expects paths
  430. like C<\foo\bar>, whereas "UNIX" means it expects C</foo/bar>).
  431. If $platform is sepcified, the platform is changed to the passed
  432. value. (Overrides the platform specified at module C<use> time, for
  433. I<this instance> only, not every C<Directory::Scratch> object.)
  434. =head2 touch($filename, [@lines])
  435. Creates a file named C<$filename>, optionally containing the elements
  436. of C<@lines> separated by the output record separator C<$\>.
  437. The Path::Class object representing the new file is returned if the
  438. operation is successful, an exception is thrown otherwise.
  439. =head2 create_tree(\%tree)
  440. Creates a file for every key/value pair if the hash, using the key as
  441. the filename and the value as the contents. If the value is an
  442. arrayref, the array is used as the optional @lines argument to
  443. C<touch>. If the value is a reference to C<undef>, then a directory
  444. is created instead of a file.
  445. Example:
  446. %tree = ( 'foo' => 'this is foo',
  447. 'bar/baz' => 'this is baz inside bar',
  448. 'lines' => [qw|this file contains 5 lines|],
  449. 'dir' => \undef,
  450. );
  451. $tmp->create_tree(\%tree);
  452. In this case, two directories are created, C<dir> and C<bar>; and
  453. three files are created, C<foo>, C<baz> (inside C<bar>), and
  454. C<lines>. C<foo> and C<baz> contain a single line, while C<lines>
  455. contains 5 lines.
  456. =head2 openfile($filename)
  457. Opens $filename for writing and reading (C<< +> >>), and returns the
  458. filehandle. If $filename already exists, it will be truncated. It's
  459. up to you to take care of flushing/closing.
  460. In list context, returns both the filehandle and the filename C<($fh,
  461. $path)>.
  462. =head2 mkdir($directory)
  463. Creates a directory (and its parents, if necessary) inside the
  464. temporary directory and returns its name. Any leading C</> on the
  465. directory name is ignored; all directories are created inside the
  466. C<base>.
  467. The full path of this directory is returned if the operation is
  468. successful, otherwise an exception is thrown.
  469. =head2 tempfile([$path])
  470. Returns an empty filehandle + filename in $path. If $path is omitted,
  471. the base directory is assumed.
  472. See L<File::Temp::tempfile|File::Temp/FUNCTIONS/tempfile>.
  473. my($fh,$name) = $scratch->tempfile;
  474. =head2 exists($file)
  475. Returns the file's real (system) path if $file exists, undefined
  476. otherwise.
  477. Example:
  478. my $path = $tmp->exists($file);
  479. if(defined $path){
  480. say "Looks like you have a file at $path!";
  481. open(my $fh, '>>', $path) or die $!;
  482. print {$fh} "add another line\n";
  483. close $fh or die $!;
  484. }
  485. else {
  486. say "No file called $file."
  487. }
  488. =head2 stat($file)
  489. Stats C<$file>. In list context, returns the list returned by the
  490. C<stat> builtin. In scalar context, returns a C<File::stat> object.
  491. =head2 read($file)
  492. Returns the contents of $file. In array context, returns a list of
  493. chompped lines. In scalar context, returns the raw octets of the
  494. file (with any trailing newline removed).
  495. If you wrote the file with C<$,> set, you'll want to set C<$/> to
  496. C<$,> when reading the file back in:
  497. local $, = '!';
  498. $tmp->touch('foo', qw{foo bar baz}); # writes "foo!bar!baz!" to disk
  499. scalar $tmp->read('foo') # returns "foo!bar!baz!"
  500. $tmp->read('foo') # returns ("foo!bar!baz!")
  501. local $/ = '!';
  502. $tmp->read('foo') # returns ("foo", "bar", "baz")
  503. =head2 write($file, @lines)
  504. Replaces the contents of file with @lines. Each line will be ended
  505. with a C<\n>, or C<$,> if it is defined. The file will be created if
  506. necessary.
  507. =head2 append($file, @lines)
  508. Appends @lines to $file, as per C<write>.
  509. =head2 randfile()
  510. Generates a file with random string data in it. If String::Random is
  511. available, it will be used to generate the file's data. Takes 0,
  512. 1, or 2 arguments - default size, max size, or size range.
  513. A max size of 0 will cause an exception to be thrown.
  514. Examples:
  515. my $file = $temp->randfile(); # size is between 1024 and 131072
  516. my $file = $temp->randfile( 4192 ); # size is below 4129
  517. my $file = $temp->randfile( 1000000, 4000000 );
  518. =head2 link($from, $to)
  519. Symlinks a file in the temporary directory to another file in the
  520. temporary directory.
  521. Note: symlinks are not supported on Win32. Portable code must not use
  522. this method. (The method will C<croak> if it won't work.)
  523. =head2 ls([$path])
  524. Returns a list (in no particular order) of all files below C<$path>.
  525. If C<$path> is omitted, the root is assumed. Note that directories
  526. are not returned.
  527. If C<$path> does not exist, an exception is thrown.
  528. =head2 delete($path)
  529. Deletes the named file or directory at $path.
  530. If the path is removed successfully, the method returns true.
  531. Otherwise, an exception is thrown.
  532. (Note: delete means C<unlink> for a file and C<rmdir> for a directory.
  533. C<delete>-ing an unempty directory is an error.)
  534. =head2 chmod($octal_permissions, @files)
  535. Sets the permissions C<$octal_permissions> on C<@files>, returning the
  536. number of files successfully changed. Note that C<'0644'> is
  537. C<--w----r-T>, not C<-rw-r--r-->. You need to pass in C<oct('0644')>
  538. or a literal C<0644> for this method to DWIM. The method is just a
  539. passthru to perl's built-in C<chmod> function, so see C<perldoc -f
  540. chmod> for full details.
  541. =head2 cleanup
  542. Forces an immediate cleanup of the current object's directory. See
  543. File::Path's rmtree(). It is not safe to use the object after this
  544. method is called.
  545. =head1 ENVIRONMENT
  546. If the C<PERL_DIRECTORYSCRATCH_CLEANUP> variable is set to 0, automatic
  547. cleanup will be suppressed.
  548. =head1 PATCHES
  549. Commentary, patches, etc. are most welcome. If you send a patch,
  550. try patching the git version available from:
  551. L<git://git.jrock.us/Directory-Scratch>.
  552. You can check out a copy by running:
  553. git clone git://git.jrock.us/Directory-Scratch
  554. Then you can use git to commit changes and then e-mail me a patch, or
  555. you can publish the repository and ask me to pull the changes. More
  556. information about git is available from
  557. L<http://git.or.cz/>
  558. =head1 SEE ALSO
  559. L<File::Temp>
  560. L<File::Path>
  561. L<File::Spec>
  562. L<Path::Class>
  563. =head1 BUGS
  564. Please report any bugs or feature through the web interface at
  565. L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Directory-Scratch>.
  566. =head1 ACKNOWLEDGEMENTS
  567. Thanks to Al Tobey (TOBEYA) for some excellent patches, notably:
  568. =over 4
  569. =item C<child>
  570. =item Random Files (C<randfile>)
  571. =item C<tempfile>
  572. =item C<openfile>
  573. =back
  574. =head1 COPYRIGHT & LICENSE
  575. Copyright 2006 Jonathan Rockway, all rights reserved.
  576. This program is free software; you can redistribute it and/or modify it
  577. under the same terms as Perl itself.
  578. =cut