]> nmode's Git Repositories - Fey/blob - lib/App/Fey.pm
Allow specifying multiple files/URIs
[Fey] / lib / App / Fey.pm
1 package App::Fey;
2
3 use strict;
4 use warnings;
5 use Exporter 'import';
6
7 our @EXPORT_OK = qw(fey);
8 our $version = '0.01';
9
10 sub new {
11 my ($class, $args) = @_;
12 my $config = do ($ENV{XDG_CONFIG_HOME} // "$ENV{HOME}/.config") . '/fey/config.pl';
13
14 my $self = {
15 mime_query => $args->{mime_query} // $config->{mime_query} // sub { `file --brief --mime-type "$_[0]"` },
16 contexts => $args->{contexts} // $config->{contexts} // { default => sub { 1 } },
17 targets => $args->{targets} // $config->{targets} // {}
18 };
19
20 bless $self, $class;
21 }
22
23 sub launch {
24 my $self = shift;
25
26 ARG: for my $file_or_uri (@_) {
27 if ($file_or_uri =~ m|^file://(.+)|) {
28 $file_or_uri = $1;
29 }
30
31 my ($mime_or_uri, $targets);
32 if (-e $file_or_uri) {
33 $mime_or_uri = $self->{mime_query}->($file_or_uri)
34 } else {
35 $mime_or_uri = $file_or_uri;
36 }
37
38 for my $target (@{ $self->{targets} }) {
39 for my $pattern (@{ $target->{patterns} }) {
40 if ($mime_or_uri =~ /$pattern/) {
41 my $associations = $target->{associations};
42 for my $context (keys %{ $associations }) {
43 if ($self->{contexts}->{$context}->()) {
44 $associations->{$context}->($file_or_uri);
45 next ARG;
46 }
47 }
48 }
49 }
50 }
51 }
52 }
53
54 sub fey {
55 App::Fey->new(ref $_[0] ? shift : {})->launch(@_ ? @_ : die 'Error: No files or URIs specified.');
56 }