]> git.draconx.ca Git - mpdhacks.git/blob - MPDHacks.pm
Fix quoting of single quotes in MPD protocol.
[mpdhacks.git] / MPDHacks.pm
1 #!/usr/bin/perl
2 #
3 # Copyright © 2008,2010,2012,2019-2020 Nick Bowler
4 #
5 # License GPLv3+: GNU General Public License version 3 or any later version.
6 # This is free software: you are free to change and redistribute it.
7 # There is NO WARRANTY, to the extent permitted by law.
8
9 package MPD;
10
11 use strict;
12
13 use Exporter;
14 our ($VERSION, @ISA, @EXPORT);
15
16 $VERSION = 0;
17 @ISA = qw(Exporter);
18 @EXPORT = qw();
19
20 # Returns the argument (or $_ if no arguments are supplied) quoted so that it
21 # can be presented as a single command argument to MPD at the protocol level.
22 sub escape {
23         my $s = @_[0] // $_;
24
25         # No way to encode literal newlines in the protocol, so we convert
26         # any newlines in the arguments into a space, which can help with
27         # shell quoting.
28         $s =~ s/\n/ /g;
29
30         if ($s =~ /[ \t\\"']/) {
31                 $s =~ s/[\\"]/\\$&/g;
32                 return "\"$s\"";
33         }
34
35         $s =~ s/^\s*$/"$&"/;
36         return $s;
37 }
38
39 1;