class EcoRake module Shell module Command include Rake::DSL # It double quotes a string (escapes the double quotes) # @param str [String] # @return [String] def double_quote(str) "\"#{str}\"" if str end # Helper to build command line # @note it excludes `nil` values. # @return [String, Array] def array_cmd(base, *opts) base = [base] unless base.is_a?(Array) base.tap do |out| opts.each {|opt| out << opt unless opt.nil?} yield(out) if block_given? end end # @see #array_cmd it the same but it returns a `String` # @return [String] def string_cmd(base, *options, join: ' ') array_cmd(base, *options).join(join) end # @param continue [Boolean] whether it should continue when one failed. # @param arr [Array] array of commands to be run def sh_chain(cmds, continue: false, &block) cmds.each do |cmd| next sh(cmd, &block) unless continue ch_continue(cmd, &block) end end # It **continues** even if there was an error or `exit(1)` during the execution # @param comm [String] the command line def sh_continue(comm, &block) sh(comm, &sh_default_block(comm, &block)) end # It exits if there is an error # @note if doesn't raise (prevents) a RuntimeError # @param comm [String] the command line def sh_exit_on_fail(comm) callback = middlewared_callback(sh_default_block(comm)) do |ok, res| next if ok exit(1) end sh(comm, &callback) end # Returns the default block for `sh` native method. # @note it wraps `block` if given # @return [Proc] def sh_default_block(comm) proc do |ok, res| yield(ok, res) if block_given? unless ok msg = "Command failed (status = #{res.exitstatus})" puts "#{msg}\n • #{comm}" end res.exitstatus end end def middlewared_callback(original) proc do |*args, **kargs| yield(*args, **kargs) ensure original.call(*args, **kargs) end end end end end