Class: Lhj::Command::Init

Inherits:
Lhj::Command show all
Defined in:
lib/lhj/command/init.rb

Overview

sync config

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Lhj::Command

#auto_spin, #begin_title, #run, #stop

Constructor Details

#initialize(argv) ⇒ Init

Returns a new instance of Init.



26
27
28
29
30
31
# File 'lib/lhj/command/init.rb', line 26

def initialize(argv)
  @url = argv.option('url')
  @key = argv.option('key')
  @url = Lhj::CipherHelper.strict_decode64_encode(@key) if @key
  super
end

Class Method Details

.optionsObject



20
21
22
23
24
# File 'lib/lhj/command/init.rb', line 20

def self.options
  [
    %w[--url 配置文件的url]
  ]
end

Instance Method Details

#download_file(urls) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/lhj/command/init.rb', line 62

def download_file(urls)
  urls.each do |url|
    file_path = file_name_from_url(url)
    save_url_to_file(url, file_path)
  end
  puts "工具初始化完成 \n"
end

#file_name_from_url(url) ⇒ Object



74
75
76
77
# File 'lib/lhj/command/init.rb', line 74

def file_name_from_url(url)
  file_name = file_name_with_url(url)
  File.join(target_folder, file_name)
end

#file_name_with_url(url) ⇒ Object



58
59
60
# File 'lib/lhj/command/init.rb', line 58

def file_name_with_url(url)
  url.scan(%r{/([^/]+)}).flatten.last
end

#handleObject



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/lhj/command/init.rb', line 33

def handle
  FileUtils.mkdir_p(target_folder) unless File.exist?(target_folder)
  if @url
    file_path = file_name_from_url(@url)
    File.delete(file_path) if File.exist?(file_path)
    save_url_to_file(@url, file_path)
  else
    file_path = File.join(target_folder, 'config_file.yml')
  end
  content = YAML.load_file(file_path)
  download_file(content) if content.is_a?(Array)
end

#save_file(url, target) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/lhj/command/init.rb', line 50

def save_file(url, target)
  http_client = Faraday.new do |c|
    c.adapter Faraday.default_adapter
  end
  response = http_client.get(url)
  File.open(target, 'wb') { |fp| fp.write(response.body) }
end

#save_url_to_file(url, file_path) ⇒ Object



70
71
72
# File 'lib/lhj/command/init.rb', line 70

def save_url_to_file(url, file_path)
  save_file(url, file_path) unless File.exist?(file_path)
end

#target_folderObject



46
47
48
# File 'lib/lhj/command/init.rb', line 46

def target_folder
  Lhj::Config.instance.home_dir
end