# escape.rb - escape/unescape library for several formats # # Copyright (C) 2006,2007 Tanaka Akira # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING # IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY # OF SUCH DAMAGE. # Escape module provides several escape functions. # * shell command # modified to work only with shell module ShellEscape module_function # Escape.shell_command composes # a sequence of words to # a single shell command line. # All shell meta characters are quoted and # the words are concatenated with interleaving space. def command(*args) args.map{ |arg| word(arg) } * ' ' end # Escape.shell_single_word quotes shell meta characters. # # The result string is always single shell word, even if # the argument is "". def word(word) word = word.to_s if word.empty? "''" elsif %r{\A[0-9A-Za-z+,./:=@_-]+\z} =~ word word else result = '' word.scan(/('+)|[^']+/) { if $1 result << %q{\'} * $1.length else result << "'#{$&}'" end } result end end end