require 'optparse' require_relative './option_transformer' require_relative './editor_config' require_relative './file_generator' module EditorConfigGenerator # Parses the arguments passed to the Editor Configurator class ArgumentParser def self.ask_user(options) ask_file_type(options) ask_indent_style(options) ask_indent_size(options) ask_end_of_line(options) ask_charset(options) ask_trailing_whitespace(options) ask_insert_newline(options) ask_question('Would you like to add another (file specific) section (y/n) [n]', %w(y n), 'n') end def self.ask_insert_newline(options) options[:insert_final_newline] = ask_question('Would you like to insert a final newline? (y/n)', %w(y n)) end def self.ask_trailing_whitespace(options) options[:trim_trailing_whitespace] = ask_question('Would you like to trim trailing whitespace? (y/n)', %w(y n)) end def self.ask_charset(options) options[:charset] = ask_question('What is the character set of the project? (latin1/utf-8/utf-8-bom /utf-16be/utf-16le)', %w(latin utf-8 utf-8-bom utf-16be utf-16le)) end def self.ask_end_of_line(options) options[:end_of_line] = ask_question('What character would you like to use to represent the end of line? (lf/cr/ctrlf)', %w(cr lf ctrlf)) end def self.ask_indent_size(options) options[:indent_size] = ask_question('What size would you like indentations to be? ', %w(2 4)) end def self.ask_indent_style(options) options[:indent_style] = ask_question('What indent style do you use (space/tabs)', %w(space tabs)) end def self.ask_file_type(options) options[:file_type] = ask_question('What is the filetype for these rules? [*]', nil, '*') end def self.ask_question(question, valid_answers, default_value = nil) loop do print "#{question}: " answer = STDIN.gets.chomp return default_value if answer.chomp == '' return answer if !valid_answers.nil? && valid_answers.include?(answer) return answer if valid_answers.nil? end end def self.parse(args) option_parser = OptionParser.new do |options| options.banner = "Generates a .editorconfig file with settings of your choosing. \nUsage: editorconfig generate " parse_options(options) end option_parser.parse!(args) end def self.parse_options(options) option_prompt = 'Generate an editorconfig file.' options.on('-g', '--generate', option_prompt) do |_answer| configs = [] options = {} options[:root] = ask_question('Is this for the topmost .editorconfig file? (y/n) [y]', %w(y n), 'y') ask_questions(options) file_generator = FileGenerator.new(configs) file_generator.generate_config_file end end def ask_questions(options, configs) loop do add_another_config = ask_user(options) e = EditorConfig.new(options) configs.push(e) options = {} warn_user_bare_minimum(add_another_config, e) break if add_another_config == 'n' end end def warn_user_bare_minimum(add_another_config, e) return unless add_another_config == 'n' && e.minimum? puts 'Warning: you have selected the bare minimum options for the file' end end end