Method: Voog::Dtk.write_config

Defined in:
lib/voog/dtk.rb

.write_config(opts) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/voog/dtk.rb', line 66

def write_config(opts)
  block = opts.fetch(:block, '')
  host = opts.fetch(:host, '')
  api_token = opts.fetch(:api_token, '')
  silent = opts.fetch(:silent, false)
  overwrite = opts.fetch(:overwrite, '')
  protocol = opts.fetch(:protocol, '')

  @file = if config_exists?
    CONFIG_FILENAME
  elsif global_config_exists?
    [ENV['HOME'], CONFIG_FILENAME].join('/')
  else
    File.new(CONFIG_FILENAME, 'w+')
    CONFIG_FILENAME
  end

  options = ParseConfig.new(File.expand_path(@file))

  if options.params.key?(block)
    puts "Writing new configuration options to existing config block.".white unless silent
    options.params[block]['host'] = host unless host.empty?
    options.params[block]['api_token'] = api_token unless api_token.empty?
    options.params[block]['overwrite'] = overwrite if (overwrite == true || overwrite == false)
    options.params[block]['protocol'] = (protocol == 'https' ? 'https' : 'http') unless protocol.empty?
  else
    puts "Writing configuration options to new config block.".white unless silent
    options.params[block] = {
      'host' => host,
      'api_token' => api_token,
      'overwrite' => (overwrite == true ? true : false),
      'protocol' => (protocol == 'https' ? 'https' : 'http')
    }
  end

  File.open(@file, 'w+') do |file|
    file.truncate(0)
    file << "\n"
    options.params.each do |param|
      file << "[#{param[0]}]\n"
      param[1].keys.each do |key|
        file << "  #{key}=#{param[1][key]}\n"
      end
      file << "\n"
    end
  end
end