Module: Squared::Common::Shell

Defined in:
lib/squared/common/shell.rb

Class Method Summary collapse

Class Method Details

.double_quote(val) ⇒ Object



62
63
64
# File 'lib/squared/common/shell.rb', line 62

def double_quote(val)
  val.gsub(/(?<!\\)"/, '\\"')
end

.fill_option(val) ⇒ Object



52
53
54
55
56
# File 'lib/squared/common/shell.rb', line 52

def fill_option(val)
  return "-#{val}" if val =~ /\A[a-z](?:\d*)\z/i

  shell_escape(val.start_with?('-') ? val : "--#{val}")
end

.shell_escape(val, quote: false, force: false) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/squared/common/shell.rb', line 11

def shell_escape(val, quote: false, force: false)
  if (data = /\A(--?[^= ]+)((=|\s+)(["'])?(.+?)(["'])?)?\z/m.match(val = val.to_s))
    return val unless data[2]

    join = ->(opt) { data[1] + data[3] + shell_quote(opt) }
    if data[4] == data[6]
      data[4] ? val : join.(data[5])
    else
      join.("#{data[4]}#{data[5]}#{data[6]}")
    end
  elsif Rake::Win32.windows?
    quote ? shell_quote(val, force: force) : val
  else
    Shellwords.escape(val)
  end
end

.shell_option(flag, val = nil, quote: false, escape: true) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/squared/common/shell.rb', line 42

def shell_option(flag, val = nil, quote: false, escape: true)
  "--#{flag}#{if val
                "=#{if escape
                      shell_escape(val, quote: quote)
                    else
                      quote ? shell_quote(val) : val
                    end}"
              end}"
end

.shell_quote(val, force: true) ⇒ Object



28
29
30
31
32
33
# File 'lib/squared/common/shell.rb', line 28

def shell_quote(val, force: true)
  val = val.to_s
  return val if (!force && !val.include?(' ')) || val =~ /(?:^|\S=|[^=]\s+)(["']).+\1\z/m

  Rake::Win32.windows? ? "\"#{double_quote(val)}\"" : "'#{single_quote(val)}'"
end

.shell_split(val, quote: false, join: nil) ⇒ Object



35
36
37
38
39
40
# File 'lib/squared/common/shell.rb', line 35

def shell_split(val, quote: false, join: nil)
  val = Shellwords.split(val).map { |opt| shell_escape(opt, quote: quote) }
  return val unless join

  val.join(join.is_a?(::String) ? join : ' ')
end

.single_quote(val) ⇒ Object



58
59
60
# File 'lib/squared/common/shell.rb', line 58

def single_quote(val)
  val.gsub("'", "'\\\\''")
end

.split_escape(val, char: ',') ⇒ Object



66
67
68
# File 'lib/squared/common/shell.rb', line 66

def split_escape(val, char: ',')
  val.split(/\s*(?<!\\)#{char}\s*/o)
end