Wrangler/FileSystem/Linux.pm untested

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