require "mixlib/shellout"

module CLIHelper
  class << self
    # Public: Run a command in shell
    #
    # cmd              - The String to run in the shell.
    # fail_on_std_err  - Boolean whether to raise a Ruby StandardError on stderr, or just return stderr.
    #
    # Examples
    #
    #   On a directory NOT containing a git repo:
    #
    #   shellout!('git status', false)
    #   # => "fatal: Not a git repository (or any of the parent directories): .git\n"
    #
    #   On a directory NOT containing a git repo:
    #
    #   shellout!('git status', true)
    #   # => StandardError: fatal: Not a git repository (or any of the parent directories): .git
    #   #    <rest of stacktrace>
    #
    #   On a directory containing a git repo:
    #
    #   shellout!('git status', false)
    #   # => "On branch master\nYour branch is up-to-date with 'origin/master'."\
    #   #    "\n\nnothing to commit, working directory clean\n"
    #
    # Returns stderr or stdout as a String.
    # Raises StandardError if param fail_on_std_error is true, and the command outputs to stderr.
    def shellout!(cmd, fail_on_std_err = true)
      shellout = Mixlib::ShellOut.new(cmd)
      shellout.run_command

      return shellout.stdout unless shellout.stdout.strip.empty?

      return shellout.stderr unless fail_on_std_err
      fail StandardError, "CLI returned the following $stderr: #{shellout.stderr}"
    end
  end
end
