# frozen_string_literal: true module Howzit # Command line prompt utils module Prompt class << self ## ## Display and read a Yes/No prompt ## ## @param prompt [String] The prompt string ## @param default [Boolean] default value if ## return is pressed or prompt is ## skipped ## ## @return [Boolean] result ## def yn(prompt, default: true) return default unless $stdout.isatty return true if Howzit.options[:yes] return false if Howzit.options[:no] return default if Howzit.options[:default] tty_state = `stty -g` system 'stty raw -echo cbreak isig' yn = color_single_options(default ? %w[Y n] : %w[y N]) $stdout.syswrite "\e[1;37m#{prompt} #{yn}\e[1;37m? \e[0m" res = $stdin.sysread 1 res.chomp! puts system 'stty cooked' system "stty #{tty_state}" res.empty? ? default : res =~ /y/i end ## ## Helper function to colorize the Y/N prompt ## ## @param choices [Array] The choices with ## default capitalized ## ## @return [String] colorized string ## def color_single_options(choices = %w[y n]) out = [] choices.each do |choice| case choice when /[A-Z]/ out.push(Color.template("{bw}#{choice}{x}")) else out.push(Color.template("{dw}#{choice}{xg}")) end end Color.template("{xg}[#{out.join('/')}{xg}]{x}") end ## ## Create a numbered list of options. Outputs directly ## to console, returns nothing ## ## @param matches [Array] The list items ## def options_list(matches) counter = 1 puts matches.each do |match| printf("%2d ) %