Wrangler/FileSystem/Linux.pm untested

filter: Statementstmt 0.0% 0 / 222 Branchbran 0.0% 0 / 116 Conditioncond 0.0% 0 / 44 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 448 CC 59 SCAR 43.5
CC
59
Cov
0%
properties
240.0
type_from_ext
156.0
inode_type_from_mode
110.0
CRAP 77.8
1 package Wrangler::FileSystem::Linux;
2  
3 # similar to the Filesys::Virtual API but with some additionas/ optimisations:
4 # list() returns an array-ref, and all dots
5 # xattr methods
6 # trash()
7  
8 use strict;
9 use warnings;
10  
11 use Carp;
12 use Cwd ();
13 use File::ExtAttr ();
14 use File::Path ();
15 use File::Basename ();
16 use File::Spec ();
17 use MIME::Types ();
18 use Encode;
19  
20 sub new {
21 my $class = shift;
22
23 my $self = bless({ @_ }, $class);
24
25 return $self;
26 }
27  
28 ##
29  
30 sub cwd {
31 return Cwd::cwd();
32 }
33  
34 # for now, we even want to keep path translation tools in the FileSystem:: modules,
35 # that's why we have these additional two helpers here
36 sub fileparse {
37 shift(@_);
38 return File::Basename::fileparse(@_);
39 }
40 sub catfile {
41 shift(@_);
42 return File::Spec->catfile(@_);
43 }
44  
45 sub available_properties {
46 my ($self, $path, $args) = @_;
47  
48 my @keys;
49 if($path){
50 my %properties;
51 for(@{ $self->list($path) }){
52 for my $key (keys %$_ ){
53 $properties{ $key } = 1;
54 }
55 }
56 @keys = keys %properties;
57  
58 return \@keys;
59 }
60  
61 return [
62 'MIME::mediaType',
63 'MIME::subType',
64 'MIME::Type',
65 'MIME::Description',
66 'Filesystem::dev',
67 'Filesystem::inode',
68 'Filesystem::mode',
69 'Filesystem::nlink',
70 'Filesystem::uid',
71 'Filesystem::gid',
72 'Filesystem::rdef',
73 'Filesystem::Size',
74 'Filesystem::Accessed',
75 'Filesystem::Modified',
76 'Filesystem::Changed',
77 'Filesystem::Blocksize',
78 'Filesystem::Blocks',
79 'Filesystem::Type',
80 'Filesystem::Directory',
81 'Filesystem::Path',
82 'Filesystem::Filename',
83 'Filesystem::Basename',
84 'Filesystem::Suffix',
85 'Filesystem::Hidden',
86 'Filesystem::Xattr', # numeric value; how many xattr keys are set; this should probably only be offered when xattr are set in a dir
87 ];
88 }
89  
90 # my $regex_xattr = qr/xattr/i;
91 my $regex_dotfile = qr/^\./; # on Linux, the convention is .dotfiles are "hidden"
92 my $regex_updir = qr/\/\.\.$/;
93 my $regex_filesystem = qr/^Filesystem::/;
94 my $regex_filesystem_contains = qr/\bFilesystem::/;
95 my $regex_mime_contains = qr/\bMIME::/;
96 my $regex_xattr = qr/^Extended Attributes::/;
97 my $regex_xattr_contains = qr/\bExtended Attributes::/;
98 sub properties {
99 my ($self, $path, $wishlist) = @_;
100  
101 $wishlist = undef if $wishlist && @$wishlist == 0;
102  
103 my (@filesystem,@stat,@fileparse,$type,$type_human);
104 if(!$wishlist || 'Filesystem' ~~ @$wishlist || "@$wishlist" =~ $regex_filesystem_contains || 'MIME' ~~ @$wishlist){
105 # print STDOUT " ** properties: -asks for Filesystem\n";
106 # 0$dev,1$ino,2$mode,3$nlink,4$uid,5$gid,6$rdev,7$size,8$atime,9$mtime,10$chtime,11$blksize,12$blocks)
107 @stat = CORE::lstat($path);
108  
109 if(-l _){
110 @filesystem = (
111 'Filesystem::Link' => 'Symlink',
112 'Filesystem::LinkTarget' => CORE::readlink($path),
113 );
114 @stat = CORE::stat($path);
115 }
116  
117 ($type,$type_human) = inode_type_from_mode($stat[2]);
118 @fileparse = File::Basename::fileparse($path,qr/\.[^.]*/);
119 my $filename = ($fileparse[2] ? $fileparse[0].$fileparse[2] : $fileparse[0]);
120  
121 @filesystem = (
122 'Filesystem::dev' => $stat[0],
123 'Filesystem::inode' => $stat[1],
124 'Filesystem::mode' => $stat[2],
125 'Filesystem::nlink' => $stat[3],
126 'Filesystem::uid' => $stat[4],
127 'Filesystem::gid' => $stat[5],
128 'Filesystem::rdef' => $stat[6],
129 'Filesystem::Size' => $stat[7],
130 'Filesystem::Accessed' => $stat[8],
131 'Filesystem::Modified' => $stat[9],
132 'Filesystem::Changed' => $stat[10],
133 'Filesystem::Blocksize' => $stat[11],
134 'Filesystem::Blocks' => $stat[12],
135 'Filesystem::Type' => $type_human,
136 'Filesystem::Path' => $path,
137 'Filesystem::Directory' => $fileparse[1],
138 'Filesystem::Filename' => $filename,
139 'Filesystem::Basename' => $fileparse[0],
140 'Filesystem::Suffix' => ($fileparse[2] ? substr($fileparse[2],1) : ''),
141 'Filesystem::Hidden' => $filename ne '..' && $filename =~ $regex_dotfile ? 1 : 0,
142 @filesystem
143 );
144 }
145  
146 my @mime;
147 if(!$wishlist || 'MIME' ~~ @$wishlist || "@$wishlist" =~ $regex_mime_contains){
148 # print STDOUT " ** properties: -asks for MIME\n";
149 if($type eq '-' && $fileparse[2] && $stat[7] != 0){
150 my ($mediaType,$subType,$mimeDesc) = type_from_ext($fileparse[2]);
151 @mime = (
152 'MIME::mediaType' => $mediaType,
153 'MIME::subType' => $subType,
154 'MIME::Type' => $mediaType.'/'.$subType
155 );
156 push(@mime, 'MIME::Description' => $mimeDesc || 'File');
157 }elsif($type eq 'd'){
158 @mime = (
159 'MIME::mediaType' => 'inode', # this is not a standard!
160 'MIME::subType' => 'directory',
161 'MIME::Type' => 'inode/directory',
162 'MIME::Description' => 'Directory'
163 );
164 }
165 }
166  
167 ## are xattr part of Filesystem or not: that's tricky: they come from Filesys
168 # and yet, they usually end up in a separate namespace, as they are not part
169 # of traditional stat() return-values; here, we could treat them in a separate
170 # driver, but on the other side, the get/set/list xattr calls are part of the
171 # FUSE and POSIX filesystem-methods sets; so for now, we combine them in this
172 # Filesystem::Linux properties() method, which is able to return both namespaces
173 my (@xattr,@xattr_summary);
174 # only poll xattr when no $wishlist is given (so getting xattr is the default), or in case $wishlist is given, skip when xattr is omitted
175 if(!$wishlist || 'Extended Attributes' ~~ @$wishlist || 'Filesystem::Xattr' ~~ @$wishlist){
176 my @keys = $self->listfattr($path);
177 # print STDOUT " ** properties: -asks for all XATTR \n";
178 for my $key ( @keys ){
179 next unless $key;
180 push(@xattr, 'Extended Attributes::'.$key => $self->getfattr($path, $key) );
181 }
182 @xattr_summary = ( 'Filesystem::Xattr' => scalar(@keys) );
183 }elsif("@$wishlist" =~ $regex_xattr_contains){
184 # print STDOUT " ** properties: -asks for selected XATTR \n";
185 my @keys = grep { /$regex_xattr/ } @$wishlist;
186 s/$regex_xattr// for @keys;
187 for ( @keys ){
188 next unless $_;
189 my $value = $self->getfattr($path, $_) or next; # getting undef means this attrib is not there, at all
190 push(@xattr, 'Extended Attributes::'.$_ => $value );
191 }
192 }
193  
194 $path = $self->parent($path) if $path =~ $regex_updir; # at this point it's safe to clean up the path of the parent-dir
195  
196 my %properties = (
197 @filesystem,
198 @xattr_summary,
199 @mime,
200 @xattr
201 );
202  
203 return \%properties;
204 }
205  
206 sub list {
207 my ($self, $path, $wishlist) = @_;
208  
209 $wishlist = undef if $wishlist && @$wishlist == 0;
210  
211 my $ok = opendir(my $dh, Cwd::abs_path($path) ); # not perfect, see http://www.perlmonks.org/?node_id=655134
212 return bless([], 'error') unless $ok;
213 my @items = readdir($dh);
214 closedir($dh);
215  
216 # strings coming from filesystem are probably utf8,
217 # transfer them to perl-internal
218 for(@items){
219 $_ = decode_utf8($_);
220 }
221  
222 my @richlist;
223 if($wishlist && "@$wishlist" eq 'Plain'){ # we'll see what the final name for "only dir contents, no stats, nothing" will be
224 for(@items){
225 # not optimal: we're doing partly the same as in properties here; what we should do
226 # is distinguish in properties() between Filesystem:: metadata that requires us to do
227 # a stat() and metadata that can be derived simply from the dir-item name, without IO.
228 # For that, we probably have to rethink our vocabulary - if we need to add a special
229 # "fast-track" $wishlist keyword or if we separate Filesystem:: by adding Filesystem::Stat::
230 # or something like that. Until then (as these sceleton dir-listings are used so seldomly):
231 my @fileparse = File::Basename::fileparse($path,qr/\.[^.]*/);
232 my $filename = ($fileparse[2] ? $fileparse[0].$fileparse[2] : $fileparse[0]);
233 push(@richlist, {
234 'Filesystem::Type' => 'inode',
235 'Filesystem::Path' => File::Spec->catfile($path, $_),
236 'Filesystem::Directory' => $fileparse[1],
237 'Filesystem::Filename' => $filename,
238 'Filesystem::Basename' => $fileparse[0],
239 'Filesystem::Suffix' => ($fileparse[2] ? substr($fileparse[2],1) : ''),
240 'Filesystem::Hidden' => $filename ne '..' && $filename =~ $regex_dotfile ? 1 : 0,
241 });
242 }
243 }else{
244 for(@items){
245 push(@richlist, $self->properties( File::Spec->catfile($path, $_), $wishlist ) );
246 }
247 }
248  
249 return \@richlist;
250 }
251  
252 sub inode_type_from_mode {
253 my $mode = shift;
254  
255 my @ftype = qw(. p c ? d ? b ? - ? l ? s ? ? ?); # learn about ftypes for example from File-Stat-ModeString
256 $ftype[0] = '';
257  
258 if(wantarray){
259 my $type = $ftype[($mode & 0170000)>>12];
260 my $type_human;
261 if($type eq '-'){ # first few ordered by probability
262 $type_human = 'File';
263 }elsif($type eq 'd'){
264 $type_human = 'Directory';
265 }elsif($type eq 'l'){
266 $type_human = 'Link';
267 }elsif($type eq 'p'){
268 $type_human = 'FIFO';
269 }elsif($type eq 'l'){
270 $type_human = 'Character Device';
271 }elsif($type eq 'b'){
272 $type_human = 'Block Device';
273 }elsif($type eq '-'){
274 $type_human = 'File';
275 }elsif($type eq 's'){
276 $type_human = 'Socket';
277 }else{
278 $type_human = '?';
279 }
280 return ($type, $type_human);
281 }else{
282 return $ftype[($mode & 0170000)>>12];
283 }
284 }
285  
286 ## currently uses MIME::Types, alt:
287 ## - File::Type, nice but would need tweaks to handle filehandles (which we need for remote objects etc)
288 ## - Media::Type::Simple allows an extension of the internal db
289 my $videosuffixes = qr/\.avi$|\.mpeg$|\.mpg$|\.m2v$|\.asf$|\.wmv$|\.mov$|\.rm$|\.flv$|\.ogg$|\.mkv$|\.mp4$|\.h264|\.webm|\.on2|\.3gp$|\.3g2$|\.mxf$|\.m2t$|\.vob$/i;
290 my $imagesuffixes = qr/\.ani$|\.cr2$|\.gif$|\.jls$|\.jpeg$|\.jpg$|\.thm$|\.jp2$|\.jpe$|\.jpx$|\.png$|\.pcx$|\.pnm$|\.tif$|\.pbm$|\.pgm$|\.pnm$|\.psd$|\.ppd$|\.ppm$|\.bmp$|\.xbm$|\.xpm$|\.rle$|\.tga$|\.tif$|\.iff$|\.ico$|\.cur$|\.raw$|\.dcr$/i;
291 my $audiosuffixes = qr/\.wav$|\.aiff$|\.mp3$|\.ogg$|\.mka$|\.flac$|\.aac$|\.mid$|\.mpa$|\.au$|\.ram$|\.smp$|\.ape$|\.gsm$/i;
292 my $textsuffixes = qr/\.txt$|\.py$|\.pl$|\.mk$|\.pod$/i;
293 my $mt = MIME::Types->new;
294 my $regex_dot_first = qr/^\./;
295 sub type_from_ext {
296 my $suffix = shift;
297 my $ext = $suffix =~ $regex_dot_first ? substr($suffix,1) : $suffix;
298  
299 my ($mediaType,$subType,$mimeDesc) = ('unknown','unknown','');
300  
301 if($mediaType = $mt->mimeTypeOf($suffix)){
302 ($mediaType,$subType) = split(/\//,$mediaType,2);
303 }else{
304 if($suffix =~ $videosuffixes){
305 $mediaType = 'video';
306 }elsif($suffix =~ $imagesuffixes){
307 $mediaType = 'image';
308 }elsif($suffix =~ $audiosuffixes){
309 $mediaType = 'audio';
310 }elsif($suffix =~ $textsuffixes){
311 $mediaType = 'text';
312 }else{
313 $mediaType = 'unknown'; # mediaType might have been reset by mimeTypeOf call above
314 }
315 }
316  
317 $ext = lc($ext);
318 if(defined($Wrangler::FileSystem::Layers::exts{$ext})){
319 if( ref($Wrangler::FileSystem::Layers::exts{$ext}) ){
320 $mimeDesc = $Wrangler::FileSystem::Layers::exts{$ext}->[0];
321 ($mediaType,$subType) = split(/\//,$Wrangler::FileSystem::Layers::exts{$ext}->[1],2);
322 }else{
323 $mimeDesc = $Wrangler::FileSystem::Layers::exts{$ext};
324 }
325 }else{
326 if($mediaType eq 'audio'){
327 $mimeDesc = uc($ext) .'-'.'Audiofile';
328 }elsif($mediaType eq 'image'){
329 $mimeDesc = uc($ext) .'-'.'Imagefile';
330 }elsif($mediaType eq 'video'){
331 $mimeDesc = uc($ext) .'-'.'Videofile';
332 }else{
333 $mimeDesc = uc($ext) .'-'. 'File';
334 }
335 }
336  
337 return ($mediaType,$subType,$mimeDesc);
338 }
339  
340 ##
341  
342 sub mount {
343 my ($self, %cfg) = @_;
344  
345 $self->{driveletter} = undef; # nothing as a driveletter on *nix
346 $self->{username} = $cfg{username};
347 $self->{password} = $cfg{password};
348 }
349  
350 sub parent {
351 shift(@_);
352 return Cwd::abs_path( $_[0] ) if $_[0] =~ $regex_updir;
353 return Cwd::abs_path( File::Spec->catfile($_[0],'..') ); # see note on abs_path in list()
354 }
355  
356 ## these low level tests should probably all return a warning: "use 'properties()' instead!"
357 sub test {
358 my ($self, $test, $path) = @_;
359  
360 # $path =~ s/'/\\'/g;
361 # $test =~ s/^(.)/$1/;
362  
363 my $ret = eval("-$test '$path'");
364 return ($@) ? undef : $ret;
365 }
366 sub stat {
367 my ($self, $path) = @_;
368
369 # $path =~ s/\s+/ /g;
370 # $path = $self->_path_from_root($path);
371  
372 return CORE::stat($path);
373 }
374 sub lstat {
375 my ($self, $path) = @_;
376
377 # $path =~ s/\s+/ /g;
378 # $path = $self->_path_from_root($path);
379  
380 return CORE::lstat($path);
381 }
382  
383 sub symlink {
384 my ($self, $old, $new) = @_;
385 # $dir = $self->_path_from_root($dir);
386 # print STDOUT " Linux::symlink(@_) \n";
387  
388 return CORE::symlink($old, $new);
389 }
390  
391 sub mknod {
392 # note: could be replace with Unix::Mknod
393 # todo: does not use mode/dev
394 # my $result = open(my $fh,'>', $_[0]);
395 # close($fh);
396 my $self = shift;
397 # print "mknod(@_)\n";
398 return 0 if -e $_[0];
399 my $result = system('touch',@_); # return 0 on success, -1 or similar on error
400 return $result == 0 ? 1 : 0; # mknod returns 1 on success
401 }
402  
403 sub delete {
404 my ($self, $path) = @_;
405 # $path = $self->_path_from_root($path);
406 # print "mknod(@_)\n";
407 return ((-e $path) && (!-d $path) && (CORE::unlink($path))) ? 1 : 0;
408 }
409  
410 sub mkdir {
411 my ($self, $dir) = @_;
412 # $dir = $self->_path_from_root($dir);
413  
414 return 2 if (-d $dir);
415
416 return CORE::mkdir($dir);
417 }
418  
419 sub rmdir {
420 my ($self, $path, $recursive) = @_;
421  
422 if (-e $path) {
423 if (-d $path) {
424 if($recursive){
425 # todo: support for recycle bin!
426 return 1 if (File::Path::rmtree($path));
427 }else{
428 return 1 if (CORE::rmdir($path));
429 }
430 }
431 ## Filesys::Virtual optionally does a file unlink, we won't
432 }
433  
434 return 0;
435 }
436  
437 # move a file/dir to undo'able trash can
438 # see also: File::Trash::FreeDesktop, File::Trash::Undoable, File::Remove
439 sub trash {
440 my $self = shift;
441  
442 # don't allow empty values in list of supplied paths, because gvfs-trash would accept that as "current dir"
443 for(@_){ return 0 if $_ eq ''; }
444  
445 my $result = system('gvfs-trash', @_); # return 0 on success, -1 or similar on error
446 # print "trash(@_): $result\n";
447 return $result == 0 ? 1 : 0; # mknod returns 1 on success
448 }
449  
450 sub rename {
451 my ($self, $path, $new) = @_;
452 # print "rename(@_)\n";
453 ## todo: check if this is a 'rename' or a 'move' across filesystem boundaries
454 return CORE::rename($path,$new);
455 }
456  
457 sub move {
458 my $self = shift;
459 # print "move(@_)\n";
460 return 0 if !-e $_[0];
461 my $result = system('mv',@_); # return 0 on success, -1 or similar on error
462 return $result == 0 ? 1 : 0; # move returns 1 on success
463 }
464  
465 sub copy {
466 my $self = shift;
467 # print "copy(@_)\n";
468 return 0 if !-e $_[0];
469 my $result = system('cp','-R',@_); # return 0 on success, -1 or similar on error
470 return $result == 0 ? 1 : 0; # copy returns 1 on success
471 }
472  
473 sub utime {
474 my ($self, $atime, $mtime, @path) = @_;
475  
476 # foreach my $i ( 0 .. $#path ) {
477 # $path[$i] = $self->_path_from_root($path[$i]);
478 # }
479
480 return CORE::utime($atime, $mtime, @path);
481 }
482  
483 sub listfattr {
484 my ($self, $path) = @_;
485  
486 File::ExtAttr::listfattr($path);
487 }
488  
489 sub getfattr {
490 my ($self, $path, $key) = @_;
491  
492 # we return values from the 'user.' namespace only, for now (and we omit the 'user.' prefix in keys)
493 File::ExtAttr::getfattr($path, $key, { namespace => 'user' });
494 }
495  
496 sub setfattr {
497 my ($self, $path, $key, $value) = @_;
498  
499 File::ExtAttr::setfattr($path, $key, $value, { namespace => 'user' });
500 }
501  
502 sub delfattr {
503 my ($self, $path, $key) = @_;
504  
505 File::ExtAttr::delfattr($path, $key, { namespace => 'user' });
506 }
507  
508 1;