lhj-tools 0.1.8 → 0.1.12

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2ccdf622ec71e3f0f9b8c090e0587ecde300a61d05cccde837d3730b9b0fdebe
4
- data.tar.gz: 92d0a661cf877bce61751e137f764155244cc3c8f629c910556c342b0766ae6d
3
+ metadata.gz: d53d84a79a0bde89e0f6f4299cd74bec6f34b50bb4ae9534047a1981e8ecf481
4
+ data.tar.gz: 5c11e01ef959b491a5bd03e8f737de5a68cd0b6dffba586015291717c71a1b39
5
5
  SHA512:
6
- metadata.gz: 6fd7f9f518499f766beb7afd778e1542d61c40522958ff02ffdf5f3d167ed1260ea5e915de33848e0b2fbfc042313bfd96920f5436c72648e5222eddeda76d6b
7
- data.tar.gz: b9df71c7bb5d7cdb63e18319fe23278d08d13d9a39d94133be4cf99cb8e3cc4f7f04f4f4cce73f528dbe88f757dcd5c0e87fb04a302cd2dd56939a78d89fcd75
6
+ metadata.gz: 60619bab6cafe45d4717c97d70fba34921dd79f2e21327bcfcdc155a76cc86a2341cef50c7506ed65980c610a2d97eb1b8d79c82641dd01faf077f581ac2d2e5
7
+ data.tar.gz: 95b1acbb95b7342da7bb4c946b7506c7572d619374f39906b0c6804e691f38e2388ed567c37b06b4c451e4aeb382d48fd13c5a90ae1fa6bcde9253104b092e94
@@ -3,43 +3,94 @@ require 'lhj/config'
3
3
 
4
4
  module Lhj
5
5
  class Command
6
+ # config
6
7
  class Config < Command
8
+ def initialize(argv)
9
+ @cli = HighLine.new
10
+ super
11
+ end
12
+
13
+ def show_config
14
+ config_arr = Dir.glob("#{config_dir}/**/*.yml")
15
+ config_arr.each_index { |i| puts "#{i}.#{File.basename(config_arr[i])}".yellow }
16
+ idx = ask_which_one
17
+ config_file = config_arr[idx]
18
+ handle_yaml(config_file)
19
+ end
20
+
21
+ def handle_yaml(file)
22
+ '子类实现'
23
+ end
24
+
25
+ def handle
26
+ show_config
27
+ end
28
+
29
+ def config_dir
30
+ Lhj::Config.instance.home_dir
31
+ end
32
+
33
+ def print_table(title, table_rows)
34
+ table = Terminal::Table.new title: title, headings: %w[键 值], rows: table_rows
35
+ puts table
36
+ end
37
+
7
38
  # show config info
8
39
  class Info < Config
9
40
  self.summary = '查看配置信息'
10
41
 
11
- def initialize(argv)
12
- @cli = HighLine.new
13
- super
14
- end
15
42
 
16
- def handle
17
- show_config
18
- end
43
+ def handle_yaml(file)
44
+ table_rows = []
45
+ content = YAML.load_file(file)
19
46
 
20
- def show_config
21
- config_arr = Dir.glob("#{config_dir}/**/*.yml")
22
- config_arr.each_index { |i| puts "#{i}.#{File.basename(config_arr[i])}".yellow }
23
- idx = ask_which_one
24
- config_file = config_arr[idx]
25
- show_yaml(config_file)
26
- end
47
+ case content
48
+ when Array
49
+ content.each do |row|
50
+ next unless row.is_a?(Hash)
51
+
52
+ row.each do |key, value|
53
+ table_rows << [key, value]
54
+ end
55
+ table_rows << :separator
56
+ end
57
+ when Hash
58
+ content.each do |key, value|
59
+ table_rows << [key, value]
60
+ end
61
+ end
27
62
 
28
- def show_yaml(file)
29
- table_rows = []
30
- yaml = YAML.load_file(file)
31
- yaml.each { |key, value| table_rows << [key, value] }
32
63
  title = File.basename(file).to_s
33
- table = Terminal::Table.new title: title, headings: %w[键 值], rows: table_rows
34
- puts table
64
+ print_table(title, table_rows) if table_rows.count.positive?
35
65
  end
36
66
 
37
67
  def ask_which_one
38
68
  @cli.ask('查看哪个配置: '.green).strip.to_i
39
69
  end
70
+ end
71
+
72
+ class Update < Config
73
+
74
+ def ask_which_one
75
+ @cli.ask('更新哪个配置: '.green).strip.to_i
76
+ end
77
+
78
+ def handle_yaml(file)
79
+ table_rows = []
80
+ content = YAML.load_file(file)
81
+
82
+ if content.is_a?(Hash)
83
+ content.each do |key, value|
84
+ table_rows << [key, value]
85
+ end
86
+ end
87
+
88
+ title = File.basename(file).to_s
89
+ print_table(title, table_rows) if table_rows.count.positive?
40
90
 
41
- def config_dir
42
- Lhj::Config.instance.home_dir
91
+ cmd = ['open']
92
+ cmd << file
93
+ Actions.sh(cmd.join(' '))
43
94
  end
44
95
  end
45
96
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  require 'faraday'
2
3
  require 'faraday_middleware'
3
4
  require 'net/http'
@@ -9,18 +10,41 @@ module Lhj
9
10
  # sync config
10
11
  class Init < Command
11
12
  self.summary = '初始化控件'
12
- self.description = '使用工具前先执行`lhj init`'
13
+ self.description = '使用工具前先执行`lhj init --url=http://xxx`'
13
14
 
14
- def handle
15
- FileUtils.mkdir_p(target_folder) unless File.exist?(target_folder)
16
- download_file
15
+ self.arguments = [
16
+ CLAide::Argument.new('url', true)
17
+ ]
18
+
19
+ def self.options
20
+ [
21
+ %w[--url 配置文件的url]
22
+ ]
23
+ end
24
+
25
+ def validate!
26
+ super
27
+ unless @url
28
+ path = File.join(target_folder, 'config_file.yml')
29
+ help! '配置url必须输入' unless File.exist?(path)
30
+ end
17
31
  end
18
32
 
19
- def down_load_urls
20
- %w[http://aomi-ios-repo.oss-cn-shenzhen.aliyuncs.com/localizable_config.yml
21
- http://aomi-ios-repo.oss-cn-shenzhen.aliyuncs.com/oss_config.yml
22
- http://aomi-ios-repo.oss-cn-shenzhen.aliyuncs.com/yapi.yml
23
- http://aomi-ios-repo.oss-cn-shenzhen.aliyuncs.com/zh2hant.yml]
33
+ def initialize(argv)
34
+ @url = argv.option('url')
35
+ super
36
+ end
37
+
38
+ def handle
39
+ FileUtils.mkdir_p(target_folder) unless File.exist?(target_folder)
40
+ if @url
41
+ file_path = file_name_from_url(@url)
42
+ save_url_to_file(@url, file_path)
43
+ else
44
+ file_path = File.join(target_folder, 'config_file.yml')
45
+ end
46
+ content = YAML.load_file(file_path)
47
+ download_file(content) if content.is_a?(Array)
24
48
  end
25
49
 
26
50
  def target_folder
@@ -39,14 +63,22 @@ module Lhj
39
63
  url.scan(%r{/([^/]+)}).flatten.last
40
64
  end
41
65
 
42
- def download_file
43
- down_load_urls.each do |url|
44
- file_name = file_name_with_url(url)
45
- file_path = File.join(target_folder, file_name)
46
- save_file(url, file_path) unless File.exist?(file_path)
66
+ def download_file(urls)
67
+ urls.each do |url|
68
+ file_path = file_name_from_url(url)
69
+ save_url_to_file(url, file_path)
47
70
  end
48
71
  puts "工具初始化完成 \n"
49
72
  end
73
+
74
+ def save_url_to_file(url, file_path)
75
+ save_file(url, file_path) unless File.exist?(file_path)
76
+ end
77
+
78
+ def file_name_from_url(url)
79
+ file_name = file_name_with_url(url)
80
+ File.join(target_folder, file_name)
81
+ end
50
82
  end
51
83
  end
52
84
  end
@@ -12,6 +12,10 @@ module Lhj
12
12
  super
13
13
  end
14
14
 
15
+ def begin_title
16
+ '读取映射文件~/.lhj/pod_config.yml'
17
+ end
18
+
15
19
  def handle
16
20
  sync
17
21
  end
@@ -39,7 +43,7 @@ module Lhj
39
43
  Actions.sh('git add .')
40
44
  puts '3.git add成功'.green
41
45
 
42
- Actions.sh("git commit -m '同步主工程代码by fastlane'")
46
+ Actions.sh("git commit -m '使用工具同步主工程代码'")
43
47
  puts '4.git 提交成功'.green
44
48
 
45
49
  Actions.sh('git push')
@@ -100,13 +104,11 @@ module Lhj
100
104
  cmd = ['git tag']
101
105
  cmd << '--force'
102
106
  cmd << tag
103
- UI.message("Adding git tag '#{tag}' 🎯.")
104
107
  Actions.sh(cmd.join(' '))
105
108
  end
106
109
 
107
110
  def push_tag
108
111
  cmd = ['git push --tags']
109
- UI.message('git push --tags 🎯.')
110
112
  Actions.sh(cmd.join(' '))
111
113
  end
112
114
 
@@ -47,102 +47,118 @@ module Lhj
47
47
  print_value
48
48
  end
49
49
 
50
+ def puts_d(str)
51
+ puts str.blue
52
+ end
53
+
54
+ def puts_i(str)
55
+ puts str.blue
56
+ end
57
+
58
+ def puts_l(str)
59
+ puts str.blue
60
+ end
61
+
62
+ def puts_v(str)
63
+ puts str.blue
64
+ end
65
+
50
66
  def print_declare
51
67
  names.each do |name|
52
- puts '///'
53
- puts "@property (nonatomic, strong) #{type} *#{name};"
68
+ puts_d '///'
69
+ puts_d "@property (nonatomic, strong) #{type} *#{name};"
54
70
  end
55
71
  end
56
72
 
57
73
  def print_instance
58
74
  names.each do |name|
59
- puts "-(#{type} *)#{name}"
60
- puts '{'
61
- puts " if(!_#{name}){"
75
+ puts_i "-(#{type} *)#{name}"
76
+ puts_i '{'
77
+ puts_i " if(!_#{name}){"
62
78
  print_alloc(name)
63
- puts " _#{name}.translatesAutoresizingMaskIntoConstraints = NO;"
79
+ puts_i " _#{name}.translatesAutoresizingMaskIntoConstraints = NO;"
64
80
  print_property(name)
65
- puts ' }'
66
- puts " return _#{name};"
67
- puts '}'
68
- puts "\n"
81
+ puts_i ' }'
82
+ puts_i " return _#{name};"
83
+ puts_i '}'
84
+ puts_i "\n"
69
85
  end
70
86
  end
71
87
 
72
88
  def print_alloc(name)
73
89
  case type
74
90
  when 'UIImageView'
75
- puts " _#{name} = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"xxxx\"]];"
91
+ puts_i " _#{name} = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"xxxx\"]];"
76
92
  when 'UIButton'
77
- puts " _#{name} = [UIButton buttonWithType:UIButtonTypeCustom];"
93
+ puts_i " _#{name} = [UIButton buttonWithType:UIButtonTypeCustom];"
78
94
  when 'UITableView'
79
- puts " _#{name} = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];"
95
+ puts_i " _#{name} = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];"
80
96
  else
81
- puts " _#{name} = [[#{type} alloc] init];"
97
+ puts_i " _#{name} = [[#{type} alloc] init];"
82
98
  end
83
99
  end
84
100
 
85
101
  def print_property(name)
86
102
  case type
87
103
  when 'UILabel'
88
- puts " _#{name}.textColor = kSetCOLOR(0x333333);"
89
- puts " _#{name}.text = @\"xxxxxxxx\";"
90
- puts " _#{name}.font = [UIFont systemFontOfSize:12.0 weight:UIFontWeightRegular];"
91
- puts " _#{name}.textAlignment = NSTextAlignmentCenter;"
104
+ puts_i " _#{name}.textColor = kSetCOLOR(0x333333);"
105
+ puts_i " _#{name}.text = @\"xxxxxxxx\";"
106
+ puts_i " _#{name}.font = [UIFont systemFontOfSize:12.0 weight:UIFontWeightRegular];"
107
+ puts_i " _#{name}.textAlignment = NSTextAlignmentCenter;"
92
108
  when 'UIImageView'
93
- puts " _#{name}.backgroundColor = kBackgroundColor;"
94
- puts " _#{name}.contentMode = UIViewContentModeScaleAspectFit;"
95
- puts " _#{name}.clipsToBounds = YES;"
96
- puts " _#{name}.layer.cornerRadius = 6.0f;"
97
- puts " _#{name}.layer.borderColor = kLineColor.CGColor;"
98
- puts " _#{name}.layer.borderWidth = 0.5;"
109
+ puts_i " _#{name}.backgroundColor = kBackgroundColor;"
110
+ puts_i " _#{name}.contentMode = UIViewContentModeScaleAspectFit;"
111
+ puts_i " _#{name}.clipsToBounds = YES;"
112
+ puts_i " _#{name}.layer.cornerRadius = 6.0f;"
113
+ puts_i " _#{name}.layer.borderColor = kLineColor.CGColor;"
114
+ puts_i " _#{name}.layer.borderWidth = 0.5;"
99
115
  when 'UITextField'
100
- puts " _#{name}.textColor = kSetCOLOR(0x333333);"
101
- puts " _#{name}.font = [UIFont systemFontOfSize:12.0 weight:UIFontWeightRegular];"
116
+ puts_i " _#{name}.textColor = kSetCOLOR(0x333333);"
117
+ puts_i " _#{name}.font = [UIFont systemFontOfSize:12.0 weight:UIFontWeightRegular];"
102
118
  when 'UIView'
103
- puts " _#{name}.backgroundColor = kBackgroundColor;"
119
+ puts_i " _#{name}.backgroundColor = kBackgroundColor;"
104
120
  when 'UIStackView'
105
- puts " _#{name}.axis = UILayoutConstraintAxisHorizontal;"
106
- puts " _#{name}.distribution = UIStackViewDistributionFillEqually;"
121
+ puts_i " _#{name}.axis = UILayoutConstraintAxisHorizontal;"
122
+ puts_i " _#{name}.distribution = UIStackViewDistributionFillEqually;"
107
123
  when 'UITableView'
108
- puts " _#{name}.backgroundColor = kBackgroundColor;"
109
- puts " _#{name}.delegate = self;"
110
- puts " _#{name}.delegate = self;"
111
- puts " _#{name}.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];"
112
- puts " _#{name}.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];"
113
- puts " _#{name}.separatorStyle = UITableViewCellSeparatorStyleNone;"
124
+ puts_i " _#{name}.backgroundColor = kBackgroundColor;"
125
+ puts_i " _#{name}.delegate = self;"
126
+ puts_i " _#{name}.delegate = self;"
127
+ puts_i " _#{name}.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];"
128
+ puts_i " _#{name}.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];"
129
+ puts_i " _#{name}.separatorStyle = UITableViewCellSeparatorStyleNone;"
114
130
  when 'UIButton'
115
- puts " _#{name}.backgroundColor = kBackgroundColor;"
116
- puts " [_#{name} setTitle:@\"xxx\" forState:UIControlStateNormal];"
117
- puts " [_#{name} setTitleColor:kSetCOLOR(0x999999) forState:UIControlStateNormal];"
118
- puts " _#{name}.titleLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightRegular];"
119
- puts " [_#{name} setImage:[UIImage imageNamed:@\"xx\"] forState:UIControlStateNormal];"
120
- puts " [_#{name} setImage:[UIImage imageNamed:@\"xx\"] forState:UIControlStateSelected];"
121
- puts " [_#{name} addTarget:self action:@selector(actionHandler:) forControlEvents:UIControlEventTouchUpInside];"
131
+ puts_i " _#{name}.backgroundColor = kBackgroundColor;"
132
+ puts_i " [_#{name} setTitle:@\"xxx\" forState:UIControlStateNormal];"
133
+ puts_i " [_#{name} setTitleColor:kSetCOLOR(0x999999) forState:UIControlStateNormal];"
134
+ puts_i " _#{name}.titleLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightRegular];"
135
+ puts_i " [_#{name} setImage:[UIImage imageNamed:@\"xx\"] forState:UIControlStateNormal];"
136
+ puts_i " [_#{name} setImage:[UIImage imageNamed:@\"xx\"] forState:UIControlStateSelected];"
137
+ puts_i " [_#{name} addTarget:self action:@selector(actionHandler:) forControlEvents:UIControlEventTouchUpInside];"
122
138
  end
123
139
  end
124
140
 
125
141
  def print_layout
126
142
  names.each do |name|
127
- puts "[contentView addSubview:self.#{name}];"
128
- puts "[self.#{name}.leadingAnchor constraintEqualToAnchor:contentView.leadingAnchor constant:0].active = YES;"
129
- puts "[self.#{name}.trailingAnchor constraintEqualToAnchor:contentView.trailingAnchor constant:0].active = YES;"
130
- puts "[self.#{name}.topAnchor constraintEqualToAnchor:contentView.topAnchor].active = YES;"
131
- puts "[self.#{name}.bottomAnchor constraintEqualToAnchor:contentView.bottomAnchor].active = YES;"
132
- puts "[self.#{name}.widthAnchor constraintEqualToConstant:80].active = YES;"
133
- puts "[self.#{name}.heightAnchor constraintEqualToConstant:80].active = YES;"
143
+ puts_l "[contentView addSubview:self.#{name}];"
144
+ puts_l "[self.#{name}.leadingAnchor constraintEqualToAnchor:contentView.leadingAnchor constant:0].active = YES;"
145
+ puts_l "[self.#{name}.trailingAnchor constraintEqualToAnchor:contentView.trailingAnchor constant:0].active = YES;"
146
+ puts_l "[self.#{name}.topAnchor constraintEqualToAnchor:contentView.topAnchor].active = YES;"
147
+ puts_l "[self.#{name}.bottomAnchor constraintEqualToAnchor:contentView.bottomAnchor].active = YES;"
148
+ puts_l "[self.#{name}.widthAnchor constraintEqualToConstant:80].active = YES;"
149
+ puts_l "[self.#{name}.heightAnchor constraintEqualToConstant:80].active = YES;"
134
150
  if type.eql?('UILabel')
135
- puts "[self.#{name} setContentHuggingPriority:300 forAxis:UILayoutConstraintAxisHorizontal];"
136
- puts "[self.#{name} setContentCompressionResistancePriority:300 forAxis:UILayoutConstraintAxisHorizontal];"
151
+ puts_l "[self.#{name} setContentHuggingPriority:300 forAxis:UILayoutConstraintAxisHorizontal];"
152
+ puts_l "[self.#{name} setContentCompressionResistancePriority:300 forAxis:UILayoutConstraintAxisHorizontal];"
137
153
  end
138
- puts "\n\n"
154
+ puts_l "\n\n"
139
155
  end
140
156
  end
141
157
 
142
158
  def print_value
143
159
  names.each do |name|
144
160
  if type.eql?('UILabel')
145
- puts "self.#{name}.text = @\"xxxxx\";"
161
+ puts_v "self.#{name}.text = @\"xxxxx\";"
146
162
  end
147
163
  end
148
164
  end
@@ -0,0 +1,15 @@
1
+ module Lhj
2
+ # format
3
+ module ErbFormatter
4
+ # base
5
+ class Base
6
+ def initialize(runner)
7
+ @runner = runner
8
+ end
9
+
10
+ def render
11
+ 'Implement global help here'
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lhj
4
+ module ErbFormatter
5
+ # context
6
+ class Context
7
+ def initialize(target)
8
+ @target = target
9
+ end
10
+
11
+ def fetch_binding
12
+ @target.instance_eval { binding }.tap do |bind|
13
+ decorate_binding(bind)
14
+ end
15
+ end
16
+
17
+ # 空方法
18
+ def decorate_binding(bind)
19
+ bind.eval('save = 1')
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,23 @@
1
+ require 'erb'
2
+ require_relative 'base'
3
+ require_relative 'command_context'
4
+
5
+ module Lhj
6
+ module ErbFormatter
7
+ # service
8
+ class Service < Base
9
+ # @param [String] name
10
+ def render(name = 'yapi')
11
+ template(name).result(Context.new(@runner).fetch_binding)
12
+ end
13
+
14
+ def template(name)
15
+ if RUBY_VERSION < '2.6'
16
+ ERB.new(File.read(File.join(File.dirname(__FILE__), 'template', "#{name}.erb")), nil, '-')
17
+ else
18
+ ERB.new(File.read(File.join(File.dirname(__FILE__), 'template', "#{name}.erb")), trim_mode: '-')
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,10 @@
1
+ <% if @result_model_name %>
2
+ if (responseMessage.resultCode == 0 && responseMessage.error == nil) {
3
+ if ([responseMessage.detailMsg isKindOfClass:[NSDictionary class]]) {
4
+ <%= @result_model_name %> *info = <%= @result_model_name %> yy_modelWithDictionary:responseMessage.detailMsg];
5
+ callback(info,responseMessage);
6
+ }
7
+ } else {
8
+ callback(nil,responseMessage);
9
+ }
10
+ <% end %>
@@ -0,0 +1,28 @@
1
+ /**
2
+ * <%= @title %> -- <%= @username %>
3
+ * <%= @desc %>
4
+ */
5
+ static NSString * const <%= @path_key %> = @"<%= @path %>";
6
+
7
+ <% if @method == 'GET' -%>
8
+ +(void)get<%= @path_name %>:(<%= @param_model_name %> *)param callback:(void (^)(<% unless @result_model_name.empty? -%><%= @result_model_name %> *model, <% end -%>MLResponseMessage *response))callback
9
+ {
10
+ [MLNetworkingManager getWithUrl:<%= @path_key %> params:params response:^(MLResponseMessage *responseMessage) {
11
+ <%= @model_template %>
12
+ }];
13
+ }
14
+ <% elsif @method == 'JSON' -%>
15
+ +(void)postJson<%= @path_name %>:(<%= @param_model_name %> *)param callback:(void (^)(<% unless @result_model_name.empty? -%><%= @result_model_name %> *model, <% end -%>MLResponseMessage *response))callback
16
+ {
17
+ [MLNetworkingManager requestJsonWithUrl:<%= @path_key %> httpMedth:kRequestMethodPOST params:param response:^(MLResponseMessage *responseMessage) {
18
+ <%= @model_template %>
19
+ }];
20
+ }
21
+ <% else -%>
22
+ +(void)post<%= @path_name %>:(<%= @param_model_name %> *)param callback:(void (^)(<% unless @result_model_name.empty? -%><%= @result_model_name %> *model, <% end -%>MLResponseMessage *response))callback
23
+ {
24
+ [MLNetworkingManager postWithUrl:<%= @path_key %> params:params response:^(MLResponseMessage *response) {
25
+ <%= @model_template %>
26
+ }];
27
+ }
28
+ <% end -%>
@@ -2,6 +2,7 @@ require 'net/https'
2
2
  require 'uri'
3
3
  require 'json'
4
4
  require 'yaml'
5
+ require 'lhj/command/yapi/formatters/service'
5
6
 
6
7
  module Lhj
7
8
  class Command
@@ -22,23 +23,57 @@ module Lhj
22
23
  @id = argv.option('id')
23
24
  @model_pre_name = argv.option('model-pre')
24
25
  @save = argv.flag?('save', false)
26
+ @debug = argv.flag?('debug', false)
25
27
  @http_url = ''
26
28
  @http_headers = []
27
- @data_json = {}
28
- @models = []
29
29
  @config_id = ''
30
30
  @config_model_pre = 'ML'
31
31
  @model_default_suffix = 'Model'
32
32
  @type_trans = {}
33
33
  @config_model_names = []
34
34
  @model_names = []
35
+ # <<<===== model for template
36
+ @result_model_name = ''
37
+ @param_model_name = ''
38
+ @model_template = ''
39
+ @desc = ''
40
+ @path = ''
41
+ @path_name = ''
42
+ @path_key = ''
43
+ @method = 'GET'
44
+ @title = ''
45
+ @username = ''
46
+ @req_body_is_json_schema = false
47
+ # =====>>>
35
48
  super
36
49
  end
37
50
 
51
+ def begin_title
52
+ '读取配置文件~/.lhj/yapi.yml'
53
+ end
54
+
38
55
  def handle
39
- load_config
40
- fetch_model
41
- print_methods
56
+ process(yml_file) if File.exist?(yml_file)
57
+ end
58
+
59
+ def process(config_file)
60
+ load_config(config_file)
61
+ res_body = req_api_model
62
+ unless res_body['errcode'].to_i.zero?
63
+ puts '请修改 ~/.lhj/yapi.yml文件的对应的__wpkreporterwid_,_yapi_token,_yapi_uid这三个值'.red
64
+ return
65
+ end
66
+ return unless res_body && !res_body.empty?
67
+
68
+ # 1.print request result
69
+ print_res_body_model(res_body)
70
+ # 2.print request json body
71
+ print_req_body_model(res_body)
72
+ # 3.print request param
73
+ print_req_query(res_body['data'])
74
+ # 4.print request method
75
+ print_http_method(res_body['data'])
76
+ # 5.save to file
42
77
  save_to_file if @save
43
78
  end
44
79
 
@@ -55,6 +90,12 @@ module Lhj
55
90
  @h_file_array << str
56
91
  end
57
92
 
93
+ def puts_h_red(str)
94
+ puts str.red
95
+ @h_file_array ||= []
96
+ @h_file_array << str
97
+ end
98
+
58
99
  def puts_m(str)
59
100
  puts str.blue
60
101
  @m_file_array ||= []
@@ -75,9 +116,12 @@ module Lhj
75
116
  "#{@http_url}#{api_id}"
76
117
  end
77
118
 
78
- def load_config
79
- yml = File.join(Lhj::Config.instance.home_dir, 'yapi.yml')
80
- config = YAML.load_file(yml)
119
+ def yml_file
120
+ File.join(Lhj::Config.instance.home_dir, 'yapi.yml')
121
+ end
122
+
123
+ def load_config(file)
124
+ config = YAML.load_file(file)
81
125
  config.each do |k, v|
82
126
  @http_headers << "#{k}=#{v}" if k.eql?('__wpkreporterwid_') || k.eql?('_yapi_token') || k.eql?('_yapi_uid')
83
127
  end
@@ -101,79 +145,81 @@ module Lhj
101
145
  @config_model_suffix || @model_default_suffix
102
146
  end
103
147
 
104
- def req_model
148
+ def req_api_model
105
149
  uri = URI.parse(url_str)
106
150
  req = Net::HTTP::Get.new(uri)
107
151
  req['Cookie'] = @http_headers.join('; ')
108
152
  res = Net::HTTP.start(uri.hostname, uri.port) do |http|
109
153
  http.request(req)
110
154
  end
111
- puts res.body unless res.body['errcode'].to_i.zero?
112
- JSON.parse(res.body)
155
+ res_json = JSON.parse(res.body)
156
+ puts res.body unless res_json['errcode'].to_i.zero?
157
+ puts res.body if @debug
158
+ res_json
113
159
  end
114
160
 
115
- def fetch_model
116
- res_json = req_model
117
- begin
118
- puts "\n<===============打印返回数据模型-Begin=====================>\n".green
119
- fetch_res_boy(res_json)
120
- print_models
121
- print_models_implementation
122
- puts "\n<===============打印返回数据模型-End=====================>\n".green
161
+ def print_res_body_model(res_json)
162
+ res_body = fetch_res_boy(res_json)
163
+ return unless res_body
164
+
165
+ puts "\n<===============打印返回数据模型-Begin=====================>\n".green
166
+ models = []
167
+ handle_model(res_body) do |model|
168
+ models << model
123
169
  end
124
- begin
125
- puts "\n<===============打印请求模型-Begin=====================>\n".green
126
- @models = []
127
- @model_names = []
128
- fetch_req_body(res_json)
129
- print_models
130
- print_models_implementation
131
- puts "\n<===============打印请求模型-End=====================>\n".green
170
+ print_models(models)
171
+ print_models_impl(models)
172
+ @result_model_name = models.last[:name]
173
+ puts "\n<===============打印返回数据模型-End=====================>\n".green
174
+ end
175
+
176
+ def print_req_body_model(res_json)
177
+ req_body = fetch_req_body(res_json)
178
+ return unless req_body
179
+
180
+ puts "\n<===============打印请求模型-Begin=====================>\n".green
181
+ models = []
182
+ handle_model(req_body) do |model|
183
+ models << model
132
184
  end
185
+ print_models(models)
186
+ print_models_impl(models)
187
+ @param_model_name = models.last[:name]
188
+ puts "\n<===============打印请求模型-End=====================>\n".green
133
189
  end
134
190
 
135
191
  def fetch_res_boy(res_json)
136
- if res_json && res_json['data']
137
- @data_json = res_json['data']
138
- if @data_json['res_body']
139
- begin
140
- res_body = JSON.parse(@data_json['res_body'])
141
- detail_obj = res_body['properties']['detailMsg'] || {}
142
- detail_obj['name'] = gen_model_name('')
143
- handle_model(detail_obj)
144
- rescue => ex
145
- puts ex
146
- end
147
- end
148
- end
192
+ return if !res_json || !res_json['data'] || !res_json['data']['res_body']
193
+
194
+ res_body = JSON.parse(res_json['data']['res_body'])
195
+ return if !res_body['properties'] || !res_body['properties']['detailMsg']
196
+
197
+ result = res_body['properties']['detailMsg']
198
+ return unless result['type'] == 'object' || result['type'] == 'array'
199
+
200
+ result['name'] = gen_model_name('')
201
+ result
149
202
  end
150
203
 
151
204
  def fetch_req_body(res_json)
152
- if res_json && res_json['data']
153
- @data_json = res_json['data']
154
- if @data_json['req_body_other']
155
- begin
156
- res_body = JSON.parse(@data_json['req_body_other'])
157
- res_body['name'] = gen_model_name('')
158
- handle_model(res_body)
159
- rescue => ex
160
- puts ex
161
- end
162
- end
163
- end
205
+ return if !res_json || !res_json['data'] || !res_json['data']['req_body_other']
206
+
207
+ result = JSON.parse(res_json['data']['req_body_other'])
208
+ result['name'] = gen_model_name('')
209
+ result
164
210
  end
165
211
 
166
212
  def gen_model_name(name)
167
213
  n = name.gsub(/vo|model|list/i, '').gsub(/(.*)s$/, '\1').gsub(/^\w/) { $&.upcase }
168
214
  if n.length <= 0
169
- n = @config_model_names.detect { |c| !@model_names.any? { |n| n.gsub(/#{model_pre}(.*)Model/, '\1').eql?(c) } }
215
+ n = @config_model_names.detect { |c| @model_names.none? { |na| na.gsub(/#{model_pre}(.*)Model/, '\1').eql?(c) } }
170
216
  end
171
217
  model_name = "#{model_pre}#{n}#{model_suffix}"
172
218
  @model_names << model_name
173
219
  model_name
174
220
  end
175
221
 
176
- def handle_model(model)
222
+ def handle_model(model, &block)
177
223
  p_type = model['type']
178
224
  p_name = model['name']
179
225
  p_properties = model['properties']
@@ -192,22 +238,22 @@ module Lhj
192
238
  c_model[:type_name] = 'NSString'
193
239
  else
194
240
  c_model[:type_name] = o['name']
195
- handle_model(o)
241
+ handle_model(o, &block)
196
242
  end
197
243
  end
198
244
  properties << c_model
199
245
  end
200
246
  p_model[:properties] = properties
201
- @models << p_model
247
+ block[p_model] if block_given?
202
248
  when 'array'
203
249
  t = model['items']
204
250
  t['name'] = p_name
205
- handle_model(t)
251
+ handle_model(t, &block)
206
252
  end
207
253
  end
208
254
 
209
- def print_models
210
- @models.each do |model|
255
+ def print_models(models)
256
+ models.each do |model|
211
257
  model_name = model[:name] || ''
212
258
  model_properties = model[:properties]
213
259
  puts_h "@interface #{model_name} : NSObject"
@@ -218,8 +264,8 @@ module Lhj
218
264
  end
219
265
  end
220
266
 
221
- def print_models_implementation
222
- @models.each do |model|
267
+ def print_models_impl(models)
268
+ models.each do |model|
223
269
  puts_m "@implementation #{model[:name]}"
224
270
  str = model[:properties].filter { |p| p[:type].eql?('array') && !p[:type_name].eql?('NSString') }.map { |p| "@\"#{p[:key]}\": #{p[:type_name]}.class" }.join(', ')
225
271
  if str && str.length.positive?
@@ -243,9 +289,9 @@ module Lhj
243
289
  case type
244
290
  when 'integer'
245
291
  puts_h "@property (nonatomic, assign) NSInteger #{key};"
246
- if des.include?('分')
247
- puts_h '/////////==========删掉其中一个属性'
248
- puts_h "@property (nonatomic, strong) MLCentNumber *#{key};"
292
+ if des.include?('分') || des.include?('0.01')
293
+ puts_h_red '/////////==========删掉其中一个属性'
294
+ puts_h_red "@property (nonatomic, strong) MLCentNumber *#{key};"
249
295
  end
250
296
  when 'cent'
251
297
  puts_h "@property (nonatomic, strong) MLCentNumber *#{key};"
@@ -268,39 +314,36 @@ module Lhj
268
314
  end
269
315
  end
270
316
 
271
- def print_methods
272
- puts "\n<===============方法调用=====================>\n".green
273
- puts_m '/**'
274
- puts_m " * #{@data_json['title']} -- #{@data_json['username']}"
275
- puts_m ' */'
276
- key_str = @data_json['path'].split('/').map { |s| s.gsub(/[^A-Za-z0-9]/, '').gsub(/^\w/) { $&.upcase } }.join('')
277
- key = "k#{key_str}URL"
278
- puts_m "static NSString * const #{key} = @\"#{@data_json['path']}\";"
279
- puts_m "\n\n"
317
+ # @param [Object] data
318
+ def print_req_query(data)
319
+ return unless data && data['req_query']
320
+
280
321
  puts_h '@interface MLParamModel : NSObject'
281
- @data_json['req_query'].each do |h|
322
+ data['req_query'].each do |h|
282
323
  des = h['desc']
283
324
  puts_h "///#{des} #{h['example']}"
284
325
  puts_h "@property (nonatomic, copy) NSString *#{h['name']};"
285
326
  end
286
327
  puts_h '@end'
287
328
  puts "\n\n"
288
- model = @models.last
289
- if @data_json['method'].eql?('GET')
290
- puts_m " [MLNetworkingManager getWithUrl:#{key} params:nil response:^(MLResponseMessage *responseMessage) {"
291
- puts_m ' if (response.resultCode == 0 && !response.error){'
292
- puts_m ' NSDictionary *detailMsg = response.detailMsg'
293
- puts_m " #{model[:name]} *model = [#{model[:name]} yy_modelWithDictionary:detailMsg];" if model
294
- puts_m ' }'
295
- puts_m ' }];'
296
- else
297
- puts_m " [MLNetworkingManager postWithUrl:#{key} params:nil response:^(MLResponseMessage *responseMessage) {"
298
- puts_m ' if (response.resultCode == 0 && !response.error){'
299
- puts_m ' NSDictionary *detailMsg = response.detailMsg'
300
- puts_m " #{model[:name]} *model = [#{model[:name]} yy_modelWithDictionary:detailMsg];" if model
301
- puts_m ' }'
302
- puts_m ' }];'
303
- end
329
+
330
+ @param_model_name = 'MLParamModel' if @param_model_name.empty?
331
+ end
332
+
333
+ def print_http_method(data)
334
+ return unless data
335
+
336
+ @path = data['path']
337
+ @method = data['method']
338
+ @title = data['title']
339
+ @username = data['username']
340
+ @desc = data['desc']
341
+ @method = 'JSON' if data['req_body_is_json_schema']
342
+ @path_name = @path.split('/').map { |s| s.gsub(/[^A-Za-z0-9]/, '').gsub(/^\w/) { $&.upcase } }.join('') if @path
343
+ @path_key = "k#{@path_name}URL"
344
+ puts "\n<===============方法调用=====================>\n".green
345
+ @model_template = Lhj::ErbFormatter::Service.new(self).render('model')
346
+ puts Lhj::ErbFormatter::Service.new(self).render('yapi').blue
304
347
  end
305
348
  end
306
349
  end
data/lib/lhj/command.rb CHANGED
@@ -30,19 +30,23 @@ module Lhj
30
30
  self.abstract_command = true
31
31
  self.command = 'lhj'
32
32
 
33
+ def begin_title
34
+ '开始处理...'
35
+ end
36
+
33
37
  def auto_spin
34
- print "正在处理...\n".green
38
+ puts begin_title.green
35
39
  # @spinner.auto_spin
36
40
  end
37
41
 
38
42
  def stop
39
- print '处理完成'.green
43
+ puts '处理完成'.green
40
44
  # @spinner.success('Done!')
41
45
  end
42
46
 
43
47
  def initialize(argv)
44
48
  super(argv)
45
- @spinner = TTY::Spinner.new('...', output: $stdout, format: :dots, clear: true)
49
+ @spinner = TTY::Spinner.new('[:spinner]...', output: $stdout, format: :dots, clear: true)
46
50
  end
47
51
 
48
52
  def run
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Lhj
4
4
  module Tools
5
- VERSION = "0.1.8"
5
+ VERSION = "0.1.12"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lhj-tools
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.8
4
+ version: 0.1.12
5
5
  platform: ruby
6
6
  authors:
7
7
  - lihaijian
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2022-01-23 00:00:00.000000000 Z
11
+ date: 2022-02-03 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: claide
@@ -142,16 +142,16 @@ dependencies:
142
142
  name: colored
143
143
  requirement: !ruby/object:Gem::Requirement
144
144
  requirements:
145
- - - ">="
145
+ - - '='
146
146
  - !ruby/object:Gem::Version
147
- version: '0'
147
+ version: '1.2'
148
148
  type: :runtime
149
149
  prerelease: false
150
150
  version_requirements: !ruby/object:Gem::Requirement
151
151
  requirements:
152
- - - ">="
152
+ - - '='
153
153
  - !ruby/object:Gem::Version
154
- version: '0'
154
+ version: '1.2'
155
155
  - !ruby/object:Gem::Dependency
156
156
  name: excon
157
157
  requirement: !ruby/object:Gem::Requirement
@@ -297,6 +297,11 @@ files:
297
297
  - lib/lhj/command/trans.rb
298
298
  - lib/lhj/command/view.rb
299
299
  - lib/lhj/command/yapi.rb
300
+ - lib/lhj/command/yapi/formatters/base.rb
301
+ - lib/lhj/command/yapi/formatters/command_context.rb
302
+ - lib/lhj/command/yapi/formatters/service.rb
303
+ - lib/lhj/command/yapi/formatters/template/model.erb
304
+ - lib/lhj/command/yapi/formatters/template/yapi.erb
300
305
  - lib/lhj/config.rb
301
306
  - lib/lhj/helper/local_config.rb
302
307
  - lib/lhj/helper/oss_config.rb