home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl_ste.zip / File / Listing.pm < prev   
Text File  |  1996-11-14  |  9KB  |  328 lines

  1. #
  2. # $Id: Listing.pm,v 1.8 1996/11/14 13:08:58 aas Exp $
  3.  
  4. package File::Listing;
  5.  
  6. sub Version { $VERSION; }
  7. $VERSION = sprintf("%d.%02d", q$Revision: 1.8 $ =~ /(\d+)\.(\d+)/);
  8.  
  9. =head1 NAME
  10.  
  11. parse_dir - parse directory listing
  12.  
  13. =head1 SYNOPSIS
  14.  
  15.  use File::Listing;
  16.  for (parse_dir(`ls -l`)) {
  17.      ($name, $type, $size, $mtime, $mode) = @$_;
  18.      next if $type ne 'f'; # plain file
  19.      #...
  20.  }
  21.  
  22.  # directory listing can also be read from a file
  23.  open(LISTING, "zcat ls-lR.gz|");
  24.  $dir = parse_dir(\*LISTING, '+0000');
  25.  
  26. =head1 DESCRIPTION
  27.  
  28. The parse_dir() routine can be used to parse directory
  29. listings. Currently it only understand Unix C<'ls -l'> and C<'ls -lR'>
  30. format.  It should eventually be able to most things you might get
  31. back from a ftp server file listing (LIST command), i.e. VMS listings,
  32. NT listings, DOS listings,...
  33.  
  34. The first parameter to parse_dir() is the directory listing to parse.
  35. It can be a scalar, a reference to an array of directory lines or a
  36. glob representing a filehandle to read the directory listing from.
  37.  
  38. The second parameter is the time zone to use when parsing time stamps
  39. in the listing. If this value is undefined, then the local time zone is
  40. assumed.
  41.  
  42. The third parameter is the type of listing to assume.  The values will
  43. be strings like 'unix', 'vms', 'dos'.  Currently only 'unix' is
  44. implemented and this is also the default value.  Ideally, the listing
  45. type should be determined automatically.
  46.  
  47. The fourth parameter specify how unparseable lines should be treated.
  48. Values can be 'ignore', 'warn' or a code reference.  Warn means that
  49. the perl warn() function will be called.  If a code reference is
  50. passed, then this routine will be called and the return value from it
  51. will be incorporated in the listing.  The default is 'ignore'.
  52.  
  53. Only the first parameter is mandatory.  The parse_dir() prototype is
  54. ($;$$$).
  55.  
  56. The return value from parse_dir() is a list of directory entries.  In
  57. scalar context the return value is a reference to the list.  The
  58. directory entries are represented by an array consisting of [
  59. $filename, $filetype, $filesize, $filetime, $filemode ].  The
  60. $filetype value is one of the letters 'f', 'd', 'l' or '?'.  The
  61. $filetime value is converted to seconds since Jan 1, 1970.  The
  62. $filemode is a bitmask like the mode returned by stat().
  63.  
  64. =head1 CREDITS
  65.  
  66. Based on lsparse.pl (from Lee McLoughlin's ftp mirror package) and
  67. Net::FTP's parse_dir (Graham Barr).
  68.  
  69. =cut
  70.  
  71. require Exporter;
  72. @ISA = qw(Exporter);
  73.  
  74. @EXPORT = qw(parse_dir);
  75.  
  76. use strict;
  77.  
  78. use Carp ();
  79. use HTTP::Date qw(str2time);
  80.  
  81. sub parse_dir ($;$$$)
  82. {
  83.    my($dir, $tz, $fstype, $error) = @_;
  84.  
  85.    $fstype ||= 'unix';
  86.    $fstype = "File::Listing::" . lc $fstype;
  87.  
  88.    my @args = $_[0];
  89.    push(@args, $tz) if(@_ >= 2);
  90.    push(@args, $error) if(@_ >= 4);
  91.  
  92.    $fstype->parse(@args);
  93. }
  94.  
  95. sub line { Carp::croak("Not implemented yet"); }
  96. sub init { } # Dummy sub
  97.  
  98. sub file_mode ($)
  99. {
  100.     # This routine was originally borrowed from Graham Barr's
  101.     # Net::FTP package.
  102.  
  103.     local $_ = shift;
  104.     my $mode = 0;
  105.     my($type,$ch);
  106.  
  107.     s/^(.)// and $type = $1;
  108.  
  109.     while (/(.)/g) {
  110.     $mode <<= 1;
  111.     $mode |= 1 if $1 ne "-" &&
  112.               $1 ne 'S' &&
  113.               $1 ne 't' &&
  114.               $1 ne 'T';
  115.     }
  116.  
  117.     $type eq "d" and $mode |= 0040000 or    # Directory
  118.       $type eq "l" and $mode |= 0120000 or    # Symbolic Link
  119.     $mode |= 0100000;            # Regular File
  120.  
  121.     $mode |= 0004000 if /^...s....../i;
  122.     $mode |= 0002000 if /^......s.../i;
  123.     $mode |= 0001000 if /^.........t/i;
  124.  
  125.     $mode;
  126. }
  127.  
  128. sub parse
  129. {
  130.    my($pkg, $dir, $tz, $error) = @_;
  131.  
  132.    # First let's try to determine what kind of dir parameter we have
  133.    # received.  We allow both listings, reference to arrays and
  134.    # file handles to read from.
  135.  
  136.    if (ref($dir) eq 'ARRAY') {
  137.        # Already splitted up
  138.    } elsif (ref($dir) eq 'GLOB') {
  139.        # A file handle
  140.    } elsif (ref($dir)) {
  141.       Carp::croak("Illegal argument to parse_dir()");
  142.    } elsif ($dir =~ /^\*\w+(::\w+)+$/) {
  143.       # This scalar looks like a file handle, so we assume it is
  144.    } else {
  145.       # A normal scalar listing
  146.       $dir = [ split(/\n/, $dir) ];
  147.    }
  148.  
  149.    # Let's convert the tz to an offset in seconds
  150.    if (defined $tz) {
  151.        if ($tz =~ /^([-+])?(\d{1,2})(\d{2})?$/) {
  152.        $tz = 3600 * $2;
  153.        $tz +=  60 * $3 if $3;
  154.        $tz *= -1 if $1 ne '-';
  155.        } elsif ($tz eq 'GMT') {
  156.        $tz = 0;
  157.        } else {
  158.        Carp::croak("Illegal timezone argument (format is +0100)");
  159.        }
  160.    }
  161.  
  162.    $pkg->init();
  163.  
  164.    my @files = ();
  165.    if (ref($dir) eq 'ARRAY') {
  166.        for (@$dir) {
  167.        push(@files, $pkg->line($_, $tz, $error));
  168.        }
  169.    } else {
  170.        local($_);
  171.        while (<$dir>) {
  172.        chomp;
  173.        push(@files, $pkg->line($_, $tz, $error));
  174.        }
  175.    }
  176.    wantarray ? @files : \@files;
  177. }
  178.  
  179.  
  180. package File::Listing::unix;
  181.  
  182. use HTTP::Date qw(str2time);
  183.  
  184. # A place to remember current directory from last line parsed.
  185. use vars qw($curdir);
  186. no strict qw(vars);
  187.  
  188. @ISA = qw(File::Listing);
  189.  
  190.  
  191. sub init
  192. {
  193.     $curdir = '';
  194. }
  195.  
  196. sub line
  197. {
  198.     shift; # package name
  199.     local($_) = shift;
  200.     my($tz, $error) = @_;
  201.  
  202.     s/\015//g;
  203.     #study;
  204.  
  205.     my ($kind, $size, $date, $name);
  206.     if (($kind, $size, $date, $name) =
  207.     /^([\-FlrwxsStTdD]{10})                   # Type and permission bits
  208.      .*                                       # Graps
  209.      \D(\d+)                                  # File size
  210.      \s+                                      # Some space
  211.      (\w{3}\s+\d+\s+(?:\d{1,2}:\d{2}|\d{4}))  # Date
  212.      \s+                                      # Some more space
  213.      (.*)$                                    # File name
  214.     /x )
  215.  
  216.     {
  217.     return if $name eq '.' || $name eq '..';
  218.     $name = "$curdir/$name" if length $curdir;
  219.     my $type = '?';
  220.     if ($kind =~ /^l/ && $name =~ /(.*) -> (.*)/ ) {
  221.         $name = $1;
  222.         $type = "l $2";
  223.     } elsif ($kind =~ /^[\-F]/) { # (hopefully) a regular file
  224.         $type = 'f';
  225.     } elsif ($kind =~ /^[dD]/) {
  226.         $type = 'd';
  227.         $size = undef;  # Don't believe the reported size
  228.     }
  229.     return [$name, $type, $size, str2time($date, $tz), 
  230.               File::Listing::file_mode($kind)];
  231.  
  232.     } elsif (/^(.+):$/ && !/^[dcbsp].*\s.*\s.*:$/ ) {
  233.     my $dir = $1;
  234.     next if $dir eq '.';
  235.     $curdir = $dir;
  236.     return ();
  237.     } elsif (/^[Tt]otal\s+(\d+)$/ || /^\s*$/) {
  238.     return ();
  239.     } elsif (/not found/    || # OSF1, HPUX, and SunOS return
  240.              # "$file not found"
  241.              /No such file/ || # IRIX returns
  242.              # "UX:ls: ERROR: Cannot access $file: No such file or directory"
  243.                                # Solaris returns
  244.              # "$file: No such file or directory"
  245.              /cannot find/     # Windows NT returns
  246.              # "The system cannot find the path specified."
  247.              ) {
  248.     return () unless defined $error;
  249.     &$error($_) if ref($error) eq 'CODE';
  250.     warn "Error: $_\n" if $error eq 'warn';
  251.     return ();
  252.     } elsif ($_ eq '') {       # AIX, and Linux return nothing
  253.     return () unless defined $error;
  254.     &$error("No such file or directory") if ref($error) eq 'CODE';
  255.     warn "Warning: No such file or directory\n" if $error eq 'warn';
  256.     return ();
  257.     } else {
  258.         # parse failed, check if the dosftp parse understands it
  259.         return(File::Listing::dosftp->line($_,$tz,$error));
  260.     }
  261.  
  262. }
  263.  
  264. package File::Listing::dosftp;
  265.  
  266. use HTTP::Date qw(str2time);
  267.  
  268. # A place to remember current directory from last line parsed.
  269. use vars qw($curdir);
  270. no strict qw(vars);
  271.  
  272. @ISA = qw(File::Listing);
  273.  
  274. sub init
  275. {
  276.     $curdir = '';
  277. }
  278.  
  279. sub line
  280. {
  281.     shift; # package name
  282.     local($_) = shift;
  283.     my($tz, $error) = @_;
  284.  
  285.     s/\015//g;
  286.  
  287.     my ($kind, $size, $date, $name);
  288.  
  289.     # 02-05-96  10:48AM                 1415 src.slf
  290.     # 09-10-96  09:18AM       <DIR>          sl_util
  291.     if (($date,$size_or_dir,$name) =
  292.         /^(\d\d-\d\d-\d\d\s+\d\d:\d\d\wM)         # Date and time info
  293.          \s+                                      # Some space
  294.          (<\w{3}>|\d+)                            # Dir or Size
  295.          \s+                                      # Some more space
  296.          (.+)$                                    # File name
  297.         /x )
  298.     {
  299.     return if $name eq '.' || $name eq '..';
  300.     $name = "$curdir/$name" if length $curdir;
  301.     my $type = '?';
  302.     if ($size_or_dir eq '<DIR>') {
  303.         $type = "d";
  304.             $size = ""; # directories have no size in the pc listing
  305.         } else {
  306.         $type = 'f';
  307.             $size = $size_or_dir;
  308.     }
  309.     return [$name, $type, $size, str2time($date, $tz),
  310.               File::Listing::file_mode($kind)];
  311.  
  312.     } else {
  313.     return () unless defined $error;
  314.     &$error($_) if ref($error) eq 'CODE';
  315.     warn "Can't parse: $_\n" if $error eq 'warn';
  316.     return ();
  317.     }
  318.  
  319. }
  320.  
  321. package File::Listing::vms;
  322. @File::Listing::unix::ISA = qw(File::Listing);
  323.  
  324. package File::Listing::netware;
  325. @File::Listing::unix::ISA = qw(File::Listing);
  326.  
  327. 1;
  328.