Sha256: 27dbe840288cf65584fea99d6e1a9a3251d2b5f263dede3254bde538bdab36f4

Contents?: true

Size: 1.96 KB

Versions: 2

Compression:

Stored size: 1.96 KB

Contents

# frozen_string_literal: true
module ZendeskAppsTools
  module Common
    module ClassMethods
      def shared_options(except: [])
        unless except.include? :path
          method_option :path,
                        type: :string,
                        default: './',
                        aliases: ['-p']
        end
        unless except.include? :clean
          method_option :clean,
                        type: :boolean,
                        default: false
        end
        unless except.include? :unattended
          method_option :unattended,
                        type: :boolean,
                        default: false,
                        desc: 'Experimental: Never prompt for input, expecting all input from the original invocation. Many '\
                              'commands invoked with this option will just crash.'
        end
      end
    end

    def self.included(base)
      base.extend(ClassMethods)
    end

    def say_error_and_exit(msg)
      say_error msg
      exit 1
    end

    def say_error(msg)
      say msg, :red
    end

    def get_value_from_stdin(prompt, opts = {})
      error_if_unattended(prompt)
      options = {
        valid_regex: opts[:allow_empty] ? /^.*$/ : /\S+/,
        error_msg: 'Invalid, try again:',
        allow_empty: false
      }.merge(opts)

      thor_options = { default: options[:default] }

      while input = ask(prompt, thor_options)
        return '' if options[:allow_empty] && input.empty?
        break if input.to_s =~ options[:valid_regex]
        say_error options[:error_msg]
      end

      input
    end

    def get_password_from_stdin(prompt)
      error_if_unattended(prompt)
      password = ask(prompt, echo: false)
      say ''
      password
    end

    private

    def error_if_unattended(prompt)
      return unless options[:unattended]
      say_error 'Would have prompted for a value interactively, but we are running unattended.'
      say_error_and_exit prompt
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
zendesk_apps_tools-1.35.6 lib/zendesk_apps_tools/common.rb
zendesk_apps_tools-1.35.4 lib/zendesk_apps_tools/common.rb