/
ls
executable file
·670 lines (563 loc) · 15.8 KB
/
ls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
#!/usr/bin/perl
=begin metadata
Name: ls
Description: list file/directory information
Author: Mark Leighton Fisher, fisherm@tce.com
License: perl
=end metadata
=cut
# Perl Power Tool - ls(1)
use strict;
use Config qw(%Config);
use File::Basename qw(basename);
use File::Spec::Functions;
use File::stat;
use Getopt::Std;
use File::Spec;
# ------ partial inline of Stat::lsMode v0.50 code
# (see http://www.plover.com/~mjd/perl/lsMode/
# for the complete module)
#
#
# Stat::lsMode
#
# Copyright 1998 M-J. Dominus
# (mjd-perl-lsmode@plover.com)
#
# You may distribute this module under the same terms as Perl itself.
use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;
my $Program = basename($0);
my @perms = qw(--- --x -w- -wx r-- r-x rw- rwx);
my @ftype = qw(. p c ? d ? b ? - ? l ? s ? ? ?);
$ftype[0] = '';
sub get_columns {
my @methods = qw(windows unix default);
foreach my $m ( @methods ) {
my $cols = __PACKAGE__->can($m)->();
next unless defined $cols;
return $cols;
}
}
sub windows {
return unless $^O eq 'MSWin32';
my @lines = `powershell -command "&{(get-host).ui.rawui.WindowSize;}"`;
while( my $l = shift @lines ) { last if $l =~ /\A-----/ }
return $lines[0] =~ m/\A\s*(\d+)/ ? $1 : ();
}
sub unix {
return if $^O eq 'MSWin32';
my $c = do {
if( has('tput') ) { `tput cols` }
elsif( has('ssty') ) { `stty size | cut -d' ' -f 2` }
else { undef };
};
chomp $c;
return $c;
}
sub default { 80 }
sub has {
my $program = shift;
foreach my $dir ( split /\Q$Config{path_sep}/, $ENV{PATH} ) {
next unless -x catfile( $dir, $program );
return 1;
}
return;
}
sub format_mode {
my $mode = shift;
my %opts = @_;
my $setids = ($mode & 07000)>>9;
my @permstrs = @perms[($mode&0700)>>6, ($mode&0070)>>3, $mode&0007];
my $ftype = $ftype[($mode & 0170000)>>12];
if ($setids) {
if ($setids & 01) { # Sticky bit
$permstrs[2] =~ s/([-x])$/$1 eq 'x' ? 't' : 'T'/e;
}
if ($setids & 04) { # Setuid bit
$permstrs[0] =~ s/([-x])$/$1 eq 'x' ? 's' : 'S'/e;
}
if ($setids & 02) { # Setgid bit
$permstrs[1] =~ s/([-x])$/$1 eq 'x' ? 's' : 'S'/e;
}
}
join '', $ftype, @permstrs;
}
# ------ define variables
my $Arg = ""; # file/directory name argument from @ARGV
my $ArgCount = 0; # file/directory argument count
my $Attributes = ""; # File::stat from STDOUT (isatty() kludge)
my %Attributes = (); # File::stat directory entry attributes
my %DirEntries = (); # hash of dir entries and stat attributes
my $Getgrgid = ""; # getgrgid() for this platform
my $Getpwuid = ""; # getpwuid() for this platform
my @Dirs = (); # directories in ARGV
my @Files = (); # non-directories in ARGV
my $First = 1; # first directory entry on command line
my $Maxlen = 1; # longest string we've seen
my $Now = time; # time we were invoked
my %Options = (); # option/flag arguments
my $SixMonths = # long listing time if < 6 months, else year
60*60*24*(365/2);
my $VERSION = '0.70'; # because we're V7-compatible :)
my $WinCols; # window columns of output
# ------ compensate for lack of getpwuid/getgrgid on some platforms
eval { my $dummy = ""; $dummy = (getpwuid(0))[0] };
if ($@) {
$Getpwuid = sub { return ($_[0], 0); };
$Getgrgid = sub { return ($_[0], 0); };
} else {
$Getpwuid = sub { return getpwuid($_[0]); };
$Getgrgid = sub { return getgrgid($_[0]); };
}
# ------ functions
# ------ get directory entries
sub DirEntries {
my $Options = shift; # option arguments hashref
my $dh; # directory handle
my %Attributes = (); # entry/attributes hash
my @Entries = (); # entries in original order
my $Name = ""; # entry name
if (!opendir($dh, $_[0]) || exists($Options{'d'})) {
if (-e $_[0]) {
closedir($dh) if (defined($dh));
push(@Entries, $_[0]);
$Attributes{$_[0]} = stat($_[0]);
push(@Entries, \%Attributes);
return @Entries;
}
warn "$Program: can't access '$_[0]': $!\n";
return ();
}
while ($Name = readdir($dh)) {
next if (!exists($Options->{'a'}) &&
$Name =~ m/^\./o);
push(@Entries, $Name);
$Attributes{$Name} = stat( File::Spec->catfile( $_[0], $Name ) );
}
closedir($dh);
# ------ return list with %Attributes ref at end
push(@Entries, \%Attributes);
return @Entries;
}
# ------ format directory entry
sub EntryFormat {
my $Options = shift; # ls option arguments
my $Attributes = shift; # entry attributes hashref
my $Entry = shift; # directory entry name
my $Blocks = 0; # block size when otherwise unknown
my $BlockSize = # block size in 512-byte units
exists($Options->{'k'}) ? 2 : 1;
my $DateStr = ""; # time/date string
my $Gid = -1; # group ID number
my $Mode = ""; # file mode
my @Month = ( # file time month abbrev.
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
);
my $Time = 0; # file time
my $Uid = -1; # user ID number
# ------ for localtime()
my $sec = 0;
my $min = 0;
my $hour = 0;
my $mday = 0;
my $mon = 0;
my $year = 0;
my $wday = 0;
my $yday = 0;
my $isdst = 0;
if (exists($Options->{'i'})) {
if (defined($Attributes->{$Entry})) {
# 1 2 3 4 5 6 7
#23456789*123456789*123456789*123456789*123456789*123456789*123456789*
printf("%10d ", $Attributes->{$Entry}->ino);
} else {
print "_________ ";
}
}
if (exists($Options->{'s'})) {
if (defined($Attributes->{$Entry})) {
$Blocks = $Attributes->{$Entry}->blocks;
if ($Blocks eq '') {
$Blocks = 0;
}
printf("%4d ",
$Blocks / $BlockSize +
(($Blocks % $BlockSize)
> 0));
} else {
print "____ ";
}
}
if (!exists($Options->{'l'})) {
print "$Entry\n";
} else {
if (!defined($Attributes->{$Entry})) {
print <<UNDEFSTAT;
__________ ___ ________ ________ ________ ___ __ _____
UNDEFSTAT
} else {
$Mode =
format_mode($Attributes->{$Entry}->mode);
print "$Mode ";
printf("%3d ",
$Attributes->{$Entry}->nlink);
if (exists($Options->{'n'})) {
printf("%-8d ",
$Attributes->{$Entry}->uid);
} else {
$Uid =
&$Getpwuid($Attributes->{$Entry}->uid);
if (defined($Uid)) {
printf("%-8s ", $Uid);
} else {
printf("%-8d ",
$Attributes->{$Entry}->uid);
}
}
if (exists($Options->{'n'})) {
printf("%-8d ",
$Attributes->{$Entry}->gid);
} else {
$Gid =
&$Getgrgid($Attributes->{$Entry}->gid);
if (defined($Gid)) {
printf("%-8s ", $Gid);
} else {
printf("%-8d ",
$Attributes->{$Entry}->gid);
}
}
if ($Attributes->{$Entry}->mode & 0140000) {
printf("%9d ",
$Attributes->{$Entry}->size);
} else {
printf("%4x,%4x ",
(($Attributes->{$Entry}->dev
& 0xFFFF000) > 16),
$Attributes->{$Entry}->dev
& 0xFFFF);
}
$Time = $Attributes->{$Entry}->mtime;
if (exists($Options->{'c'})) {
$Time = $Attributes->{$Entry}->ctime;
}
if (exists($Options->{'u'})) {
$Time = $Attributes->{$Entry}->atime;
}
($sec,$min,$hour,$mday,$mon,$year,
$wday,$yday,$isdst) =
localtime($Time);
print $Month[$mon];
if ($mday < 10) {
print " $mday ";
} else {
print " $mday ";
}
if ($Now - $Time <= $SixMonths) {
printf("%02d:%02d", $hour, $min);
} else {
printf(" %04d", $year + 1900);
}
}
print " $Entry\n";
}
}
# ------ list directory entries, breadth-first
sub List {
my $Name = shift; # directory name
my $Options = shift; # options/flags hashref
my $is_dir = shift;
my $Expand = shift; # do 1 level of dir expansion,
# for "ls DIRNAME"
my $Attributes = ""; # entry attributes hashref
my $BlockSize = # block size in 512-byte units
exists($Options->{'k'}) ? 2 : 1;
my $Cols = 0; # output columns for this List()
my $Entry = ""; # directory entry
my @Dirs = (); # directories from -R and DirEntries
my $Mask = ""; # sprintf() format/mask
my $Mylen = 0; # current entry length
my $Path = ""; # path for subdirectories
my $Piece = ""; # piece of entry list
my @SortedEntries = (); # sorted entry list
my $Rows = 0; # output rows for this List()
my $Target = 0; # target element index
my $TotalBlocks = 0; # total directory size in blocks
my $elt = 0; # element index
# ------ get directory entries attributes
$Attributes = pop(@_);
# ------ precompute max entry length and total size
foreach (@_) {
$TotalBlocks +=
(!defined($Attributes->{$_}) ||
($Attributes->{$_}->blocks eq '')) ?
0: $Attributes->{$_}->blocks;
$Mylen = length($_);
if ($Mylen > $Maxlen) {
$Maxlen = $Mylen;
}
}
$Maxlen += 1; # account for spaces
# ------ print directory name if -R
if (exists($Options->{'R'})) {
print "$Name:\n" if $is_dir;
}
# ----- print total in blocks if -s or -l
if (exists($Options->{'l'}) || exists($Options->{'s'})) {
print "total $TotalBlocks\n" if $is_dir;
}
# ------ sort entry list
@SortedEntries = Order(\%Options, $Attributes, @_);
# ------ user requested 1 entry/line, long, size, or inode
if (defined($Options->{'1'}) ||
exists($Options->{'l'}) ||
exists($Options->{'s'}) ||
exists($Options->{'i'})) {
for my $Entry (@SortedEntries) {
EntryFormat(\%Options,
$Attributes, $Entry);
}
# ------ multi-column output
} else {
# ------ compute rows, columns, width mask
$Cols = int($WinCols / $Maxlen) || 1;
$Rows = int(($#_+$Cols) / $Cols);
$Mask = sprintf("%%-%ds ", $Maxlen);
for ($elt = 0; $elt < $Rows * $Cols; $elt++) {
$Target = ($elt % $Cols) * $Rows +
int(($elt / $Cols));
$Piece = sprintf($Mask,
$Target < ($#SortedEntries + 1) ?
$SortedEntries[$Target] : "");
# don't blank pad to eol of line
$Piece =~ s/\s+$//
if (($elt+1) % $Cols == 0);
print $Piece;
print "\n" if (($elt+1) % $Cols == 0);
}
print "\n" if (($elt+1) % $Cols == 0);
}
# ------ print blank line if -R
if (exists($Options->{'R'})) {
print "\n";
}
# ------ list subdirectories of this directory
if (!exists($Options{'d'}) &&
($Expand || exists($Options->{'R'}))) {
for my $Entry (Order(\%Options, $Attributes, @_)) {
next if ($Entry eq "." || $Entry eq "..");
if (defined($Attributes->{$Entry}) &&
$Attributes->{$Entry}->mode & 0040000) {
$Path = File::Spec->canonpath(File::Spec->catdir($Name,$Entry));
@Dirs = DirEntries(\%Options, $Path);
List($Path, \%Options, 1, 0, @Dirs);
}
}
}
}
# ------ sort file list based on %Options
sub Order {
my $Options = shift; # parsed option/flag arguments
my $Attributes = shift; # File::stat attributes hashref
my @Entries = @_; # directory entry names
# ------ sort by size, largest first
if (exists($Options->{'S'})) {
if (exists($Options->{'r'})) {
@Entries = sort
{ $Attributes->{$a}->size <=>
$Attributes->{$b}->size }
@Entries;
} else {
@Entries = sort
{ $Attributes->{$b}->size <=>
$Attributes->{$a}->size }
@Entries;
}
# ------ sort by time, most recent first
} elsif (exists($Options->{'t'}) ||
exists($Options->{'c'}) ||
exists($Options->{'u'})) {
if (exists($Options->{'r'})) {
if (exists($Options->{'u'})) {
@Entries = sort
{ $Attributes->{$a}->atime <=>
$Attributes->{$b}->atime }
@Entries;
} elsif (exists($Options->{'c'})) {
@Entries = sort
{ $Attributes->{$a}->ctime <=>
$Attributes->{$b}->ctime }
@Entries;
} else {
@Entries = sort
{ $Attributes->{$a}->mtime <=>
$Attributes->{$b}->mtime }
@Entries;
}
} else {
if (exists($Options->{'u'})) {
@Entries = sort
{ $Attributes->{$b}->atime <=>
$Attributes->{$a}->atime }
@Entries;
} elsif (exists($Options->{'c'})) {
@Entries = sort
{ $Attributes->{$b}->ctime <=>
$Attributes->{$a}->ctime }
@Entries;
} else {
@Entries = sort
{ $Attributes->{$b}->mtime <=>
$Attributes->{$a}->mtime }
@Entries;
}
}
# ------ sort by name
} elsif (!exists($Options->{'f'})) {
if (exists($Options->{'r'})) {
@Entries = sort { $b cmp $a } @Entries;
} else {
@Entries = sort { $a cmp $b } @Entries;
}
}
# ------ return list sorted by options (or unsorted if -f)
return @Entries;
}
# ------ process arguments
unless (getopts('1ACFLRSTWacdfgiklmnopqrstux', \%Options)) {
warn "usage: $Program [-1RSacdfiklnrstu] [file ...]\n";
exit EX_FAILURE;
}
if ($Options{'f'}) {
$Options{'a'} = 1;
}
$WinCols = get_columns();
$Attributes = stat(*STDOUT);
if ($Attributes->mode & 0140000) {
$Options{'1'} = '1';
}
# ------ current directory if no arguments
if ($#ARGV < 0) {
List('.', \%Options, 1, 0, DirEntries(\%Options, "."));
# ------ named files/directories if arguments
} else {
$ArgCount = -1;
for my $Arg (@ARGV) {
if (!exists($Options{'d'}) && -d $Arg) {
$ArgCount++;
push(@Dirs, $Arg);
} else {
$ArgCount += 2;
push(@Files, $Arg);
}
}
for my $Arg (@Files) {
$Attributes{$Arg} = stat($Arg);
}
for my $Arg (Order(\%Options, \%Attributes, @Files)) {
$First = 0;
List($Arg, \%Options, 0, 0,
DirEntries(\%Options, $Arg));
}
for my $Arg (@Dirs) {
$Attributes{$Arg} = stat($Arg);
}
for my $Arg (Order(\%Options, \%Attributes, @Dirs)) {
if (!exists($Options{'R'})) {
print "\n" if (!$First);
$First = 0;
print "$Arg:\n" if ($ArgCount > 0);
}
List($Arg, \%Options, 1, 0,
DirEntries(\%Options, $Arg));
}
}
__END__
=pod
=head1 NAME
ls - list file/directory information
=head1 SYNOPSIS
ls [-1RSacdfiklnrstu] [file ...]
=head1 DESCRIPTION
This program lists information about files and directories.
If it is invoked without file/directory name arguments,
it lists the contents of the current directory.
Otherwise, B<ls> lists information about the files and
information about the contents of the directories (but
see B<-d>). Furthermore, without any option arguments
B<ls> just lists the names of files and directories.
All files are listed before all directories.
The default sort order is ascending ASCII on filename.
=head2 OPTIONS
The BSD options
'1ACFLRSTWacdfgiklmnopqrstux'
are recognized,
but only '1RSacdfiklnrstu' are implemented:
=over 4
=item -1
List entries 1 per line (default if output is not a tty).
=item -R
Recursively list the contents of all directories, breadth-first.
=item -S
Sort descending by size.
=item -a
List all files (normally files starting with '.' are ignored).
=item -c
Sort by descending last modification time of inode.
=item -d
Do not list directory contents.
=item -f
Do not sort -- list in whatever order files/directories are returned
by the directory read function. This option implies -a.
=item -i
List file inode number. (Doesn't mean much on non-inode systems.)
=item -k
When used with B<-s>, list file/directory size in 1024-byte blocks.
=item -l
Long format listing of mode -- # of links, owner name, group name,
size in bytes, time of last modification, and name.
=item -n
List numeric uid and gid (default on platforms without getpwuid()).
=item -r
Reverse sorting order.
=item -s
List file/directory size in 512-byte blocks. (May not mean much
on non-Unix systems.)
=item -t
Sort by descending last modification time.
=item -u
Sort by descending last access time.
=back
=head1 ENVIRONMENT
The working of I<ls> is not influenced by any environment variables.
=head1 BUGS
The file metadata from stat() is used, which may not necessarily
mean much on non-Unix systems. Specifically, the uid, gid, inode,
and block numbers may be meaningless (or less than meaningful
at least).
The B<-l> option does not yet list the major and minor
device numbers for special files, but it does list
the value of the 'dev' field as 2 hex 16-bit words.
Doing this properly would
probably require filesystem type probing.
=head1 AUTHOR
This Perl implementation of I<ls>
was written by Mark Leighton Fisher of Thomson Consumer Electronics,
I<fisherm@tce.com>.
=head1 COPYRIGHT and LICENSE
This program is free and open software. You may use, modify,
distribute, and sell this program (and any modified variants) in any
way you wish, provided you do not restrict others from doing the same.
=cut