]> git.draconx.ca Git - mpdhacks.git/blobdiff - MPDHacks.pm
Fix quoting of single quotes in MPD protocol.
[mpdhacks.git] / MPDHacks.pm
diff --git a/MPDHacks.pm b/MPDHacks.pm
new file mode 100644 (file)
index 0000000..2c76c2f
--- /dev/null
@@ -0,0 +1,39 @@
+#!/usr/bin/perl
+#
+# Copyright © 2008,2010,2012,2019-2020 Nick Bowler
+#
+# License GPLv3+: GNU General Public License version 3 or any later version.
+# This is free software: you are free to change and redistribute it.
+# There is NO WARRANTY, to the extent permitted by law.
+
+package MPD;
+
+use strict;
+
+use Exporter;
+our ($VERSION, @ISA, @EXPORT);
+
+$VERSION = 0;
+@ISA = qw(Exporter);
+@EXPORT = qw();
+
+# Returns the argument (or $_ if no arguments are supplied) quoted so that it
+# can be presented as a single command argument to MPD at the protocol level.
+sub escape {
+       my $s = @_[0] // $_;
+
+       # No way to encode literal newlines in the protocol, so we convert
+       # any newlines in the arguments into a space, which can help with
+       # shell quoting.
+       $s =~ s/\n/ /g;
+
+       if ($s =~ /[ \t\\"']/) {
+               $s =~ s/[\\"]/\\$&/g;
+               return "\"$s\"";
+       }
+
+       $s =~ s/^\s*$/"$&"/;
+       return $s;
+}
+
+1;