| 1 | package Evo::Path; | ||
| 2 | 1 | ▶ | use Evo -Class, 'Carp croak'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | use overload | ||
| 4 | '""' => sub { shift->to_string }, | ||
| 5 | fallback => 1; | ||
| 6 | |||
| 7 | has base => '/'; | ||
| 8 | has children => sub { [] }; | ||
| 9 | |||
| 10 | my sub _split ($safe, $path) { | ||
| 11 | return if !$path; | ||
| 12 | return grep { !!$_ } split '/', $path if !$safe; | ||
| 13 | grep { | ||
| 14 | $_ ne '..' | ||
| 15 | ? 1 | ||
| 16 | : croak qq#unsafe "$path", use "append_unsafe" instead (or \$fs->cd('..'))# | ||
| 17 | } grep { !!$_ && $_ ne '.' } split '/', $path; | ||
| 18 | } | ||
| 19 | |||
| 20 | sub append ($self, $path) { | ||
| 21 | (ref $self)->new(base => $self->base, children => [$self->children->@*, _split(1, $path)]); | ||
| 22 | } | ||
| 23 | |||
| 24 | sub append_unsafe ($self, $path) { | ||
| 25 | (ref $self)->new(base => $self->base, children => [$self->children->@*, _split(0, $path)]); | ||
| 26 | } | ||
| 27 | |||
| 28 | sub to_string($self) { | ||
| 29 | my $base = $self->base; | ||
| 30 | $base .= '/' unless $base =~ m#/$#; | ||
| 31 | $base . join '/', $self->children->@*; | ||
| 32 | } | ||
| 33 | |||
| 34 | sub from_string ($me, $path = undef, $base = '/') { | ||
| 35 | $me->new(base => $base, children => [_split(1, $path)]); | ||
| 36 | } | ||
| 37 | |||
| 38 | 1; | ||
| 39 | |||
| 40 | __END__ | ||