Created
July 10, 2017 06:16
-
-
Save nmarley/2f9cb3718dcb28b8a1a5411e659a0165 to your computer and use it in GitHub Desktop.
"Perl stat" -- really old, saving here, but removing from hard drive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/perl | |
use strict; | |
use warnings; | |
use feature qw(say); | |
use Data::Dumper; | |
use File::Slurp; | |
use Carp; | |
use Fcntl ':mode'; | |
use DateTime; | |
use DateTime::TimeZone; | |
my %filetypes = ( | |
S_IFDIR , 'd', | |
S_IFCHR , 'c', | |
S_IFBLK , 'b', | |
S_IFREG , '-', | |
S_IFIFO , 'p', | |
S_IFLNK , 'l', | |
S_IFSOCK , 's', | |
); | |
my %filedesc = ( | |
S_IFDIR , 'directory', | |
S_IFCHR , 'character special', | |
S_IFBLK , 'block special', | |
S_IFREG , 'regular file', | |
S_IFIFO , 'named pipe', | |
S_IFLNK , 'symbolic link', | |
S_IFSOCK , 'UNIX socket', | |
); | |
my %digits = ( | |
0 => '---', | |
1 => '--x', | |
2 => '-w-', | |
3 => '-wx', | |
4 => 'r--', | |
5 => 'r-x', | |
6 => 'rw-', | |
7 => 'rwx', | |
); | |
my $filename = shift; | |
Carp::croak("usage: $0 <file>") | |
unless ($filename && -f $filename); | |
my @stats = stat( $filename ); | |
Carp::croak("error: Can't stat [$0]") | |
unless (0 != scalar(@stats)); | |
my $fdesc = $filedesc{S_IFMT($stats[2])}; | |
my $ftype = $filetypes{S_IFMT($stats[2])}; | |
my $octal = S_IMODE($stats[2]); | |
my $perms = sprintf("%04o", $octal); | |
my $sperms = perms2string( $perms ); | |
$sperms = $ftype . $sperms; | |
my $user = getpwuid($stats[4]); | |
my $group = getpwuid($stats[5]); | |
my @times = map { epoch2string($_) } @stats[8,9,10]; | |
my $output = qq{ | |
File: `$filename' | |
Size: $stats[7]\t\tBlocks: $stats[12]\t\tIO Block: $stats[11]\t$fdesc | |
Device: $stats[0]\t\tInode: $stats[1]\tLinks: $stats[3] | |
Access: ($perms/$sperms)\tUid: ( $stats[4]/$user)\tGid: ( $stats[5]/$group) | |
Access: $times[0] | |
Modify: $times[1] | |
Change: $times[2] | |
Birth: - | |
}; | |
say $output; | |
sub perms2string { | |
my $perms = shift; | |
$perms =~ s{ ^0(\d{3})$ }{$1}x; | |
my $str = join('', map { $digits{$_} } (split //, $perms)); | |
return $str; | |
} | |
sub epoch2string { | |
my $epoch = shift; | |
my $local_tz = DateTime::TimeZone->new( name => 'local' )->name; | |
my $dt = DateTime->from_epoch( epoch => $epoch, time_zone => $local_tz ); | |
return $dt->strftime("%Y-%m-%d %H:%M:%S.000000000 %z"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment