Class: Scallop

Inherits:
Object
  • Object
show all
Defined in:
lib/scallop.rb,
lib/scallop/version.rb

Defined Under Namespace

Modules: Errors Classes: Param, Result

Constant Summary collapse

DSL_METHODS =
%i{ cmd run run! sudo }
VERSION =
"0.3.2"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeScallop

Returns a new instance of Scallop.



59
60
61
# File 'lib/scallop.rb', line 59

def initialize
  @params = {}
end

Class Method Details

.param(key) ⇒ Object



54
55
56
# File 'lib/scallop.rb', line 54

def param(key)
  Param.new(key: key)
end

Instance Method Details

#cmd(*cmd) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/scallop.rb', line 71

def cmd(*cmd)
  dup
    .tap do |instance|
      instance.instance_eval { @cmd = cmd }
    end
    .freeze
end

#runObject



118
119
120
121
122
# File 'lib/scallop.rb', line 118

def run
  to_command
    .yield_self(&Open3.method(:capture3))
    .yield_self(&Result.method(:from_capture3))
end

#run!Object



124
125
126
127
128
# File 'lib/scallop.rb', line 124

def run!
  run.tap do |result|
    raise Errors::CommandFailed.new(result.stderr, result) unless result.success?
  end
end

#set(params) ⇒ Object



79
80
81
82
83
84
85
86
87
# File 'lib/scallop.rb', line 79

def set(params)
  new_params = @params.merge(params)

  dup
    .tap do |instance|
      instance.instance_eval { @params = new_params }
    end
    .freeze
end

#sudo(sudo = true) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/scallop.rb', line 63

def sudo(sudo = true)
  dup
    .tap do |instance|
      instance.instance_eval { @sudo = sudo }
    end
    .freeze
end

#to_commandObject



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/scallop.rb', line 89

def to_command
  raise Errors::ValidationFailed.new("cmd missing") if @cmd.nil?

  prefix =
    case @sudo
    when true then "sudo"
    when String, Symbol then "sudo -u #{@sudo}"
    else nil
    end

  cmd =
    [*@cmd]
      .flatten
      .map do |cmd_part|
        case cmd_part
        when Param
          @params[cmd_part.key].tap do |value|
            raise Errors::ValidationFailed.new("value for param '#{cmd_part.key}' not set") if value.nil?
          end
        else
          cmd_part.to_s
        end
      end
      .map(&Shellwords.method(:escape))
      .join(" ")

  [prefix, cmd].compact.join(" ")
end