Class: Fastlane::SwiftFastlaneAPIGenerator

Inherits:
Object
  • Object
show all
Defined in:
fastlane/lib/fastlane/swift_fastlane_api_generator.rb

Constant Summary collapse

DEFAULT_API_VERSION_STRING =
"0.9.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target_output_path: "swift") ⇒ SwiftFastlaneAPIGenerator

Returns a new instance of SwiftFastlaneAPIGenerator.


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 24

def initialize(target_output_path: "swift")
  @target_output_path = File.expand_path(target_output_path)
  @generated_paths = []
  require 'fastlane'
  require 'fastlane/documentation/actions_list'
  Fastlane.load_actions
  # Tools that can be used with <Toolname>file, like Deliverfile, Screengrabfile
  # this is important because we need to generate the proper api for these by creating a protocol
  # with default implementation we can use in the Fastlane.swift API if people want to use
  # <Toolname>file.swift files.
  self.tools_option_files = TOOL_CONFIG_FILES.map { |config_file| config_file.downcase.chomp("file") }.to_set

  self.actions_not_supported = ["import", "import_from_git"].to_set

  self.action_options_to_ignore = {

    "precheck" => [
      "negative_apple_sentiment",
      "placeholder_text",
      "other_platforms",
      "future_functionality",
      "test_words",
      "curse_words",
      "custom_text",
      "copyright_date",
      "unreachable_urls"
    ].to_set
  }
end

Instance Attribute Details

#action_options_to_ignoreObject

Returns the value of attribute action_options_to_ignore


20
21
22
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 20

def action_options_to_ignore
  @action_options_to_ignore
end

#actions_not_supportedObject

Returns the value of attribute actions_not_supported


19
20
21
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 19

def actions_not_supported
  @actions_not_supported
end

#generated_pathsObject

stores all file names of generated files (as they are generated)


22
23
24
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 22

def generated_paths
  @generated_paths
end

#target_output_pathObject

Returns the value of attribute target_output_path


21
22
23
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 21

def target_output_path
  @target_output_path
end

#tools_option_filesObject

Returns the value of attribute tools_option_files


18
19
20
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 18

def tools_option_files
  @tools_option_files
end

Instance Method Details

#autogen_version_warning_text(api_version: nil) ⇒ Object


212
213
214
215
216
217
218
219
220
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 212

def autogen_version_warning_text(api_version: nil)
  warning_text_array = []
  warning_text_array << ""
  warning_text_array << "// Please don't remove the lines below"
  warning_text_array << "// They are used to detect outdated files"
  warning_text_array << "// FastlaneRunnerAPIVersion [#{api_version}]"
  warning_text_array << ""
  return warning_text_array.join("\n")
end

#determine_api_version(new_file_content: nil, old_file_content: nil) ⇒ Object

compares the new file content to the old and figures out what api_version the new content should be


223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 223

def determine_api_version(new_file_content: nil, old_file_content: nil)
  # we know 100% there is a difference, so no need to compare
  unless old_file_content.length >= new_file_content.length
    old_api_version = find_api_version_string(content: old_file_content)

    return DEFAULT_API_VERSION_STRING if old_api_version.nil?

    return increment_api_version_string(api_version_string: old_api_version)
  end

  relevant_old_file_content = old_file_content[0..(new_file_content.length - 1)]

  if relevant_old_file_content == new_file_content
    # no changes at all, just return the same old api version string
    return find_api_version_string(content: old_file_content)
  else
    # there are differences, so calculate a new api_version_string
    old_api_version = find_api_version_string(content: old_file_content)

    return DEFAULT_API_VERSION_STRING if old_api_version.nil?

    return increment_api_version_string(api_version_string: old_api_version)
  end
end

#find_api_version_string(content: nil) ⇒ Object


271
272
273
274
275
276
277
278
279
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 271

def find_api_version_string(content: nil)
  regex = SwiftRunnerUpgrader::API_VERSION_REGEX
  matches = content.match(regex)
  if matches.length > 0
    return matches[1]
  else
    return nil
  end
end

#generate_default_implementations(tool_details: nil) ⇒ Object


135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 135

def generate_default_implementations(tool_details: nil)
  files_generated = []
  tool_details.each do |tool_detail|
    header = []
    header << "//"
    header << "//  ** NOTE **"
    header << "//  This file is provided by fastlane and WILL be overwritten in future updates"
    header << "//  If you want to add extra functionality to this project, create a new file in a"
    header << "//  new group so that it won't be marked for upgrade"
    header << "//"
    header << ""
    header << "class #{tool_detail.swift_class}: #{tool_detail.swift_protocol} {"
    lanefile_implementation_opening = header.join("\n")

    files_generated << write_lanefile(
      lanefile_implementation_opening: lanefile_implementation_opening,
      class_name: tool_detail.swift_class,
      tool_name: tool_detail.command_line_tool_name
    )
  end
  return files_generated
end

#generate_lanefile_parsing_functionsObject


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 158

def generate_lanefile_parsing_functions
  parsing_functions = 'func parseArray(fromString: String, function: String = #function) -> [String] {
  verbose(message: "parsing an Array from data: \(fromString), from function: \(function)")
  let potentialArray: String
  if fromString.count < 2 {
potentialArray = "[\(fromString)]"
  } else {
potentialArray = fromString
  }
  let array: [String] = try! JSONSerialization.jsonObject(with: potentialArray.data(using: .utf8)!, options: []) as! [String]
  return array
}

func parseDictionary(fromString: String, function: String = #function) -> [String : String] {
return parseDictionaryHelper(fromString: fromString, function: function) as! [String: String]
}

func parseDictionary(fromString: String, function: String = #function) -> [String : Any] {
return parseDictionaryHelper(fromString: fromString, function: function)
}

func parseDictionaryHelper(fromString: String, function: String = #function) -> [String : Any] {
  verbose(message: "parsing an Array from data: \(fromString), from function: \(function)")
  let potentialDictionary: String
  if fromString.count < 2 {
verbose(message: "Dictionary value too small: \(fromString), from function: \(function)")
potentialDictionary = "{}"
  } else {
  potentialDictionary = fromString
  }
  let dictionary: [String : Any] = try! JSONSerialization.jsonObject(with: potentialDictionary.data(using: .utf8)!, options: []) as! [String : Any]
  return dictionary
}

func parseBool(fromString: String, function: String = #function) -> Bool {
  verbose(message: "parsing a Bool from data: \(fromString), from function: \(function)")
  return NSString(string: fromString.trimmingCharacters(in: .punctuationCharacters)).boolValue
}

func parseInt(fromString: String, function: String = #function) -> Int {
  verbose(message: "parsing an Int from data: \(fromString), from function: \(function)")
  return NSString(string: fromString.trimmingCharacters(in: .punctuationCharacters)).integerValue
}
  '
  return parsing_functions
end

#generate_lanefile_tool_objects(classes: nil) ⇒ Object


205
206
207
208
209
210
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 205

def generate_lanefile_tool_objects(classes: nil)
  objects = classes.map do |filename|
    "let #{filename.downcase}: #{filename} = #{filename}()"
  end
  return objects
end

#generate_swiftObject


54
55
56
57
58
59
60
61
62
63
64
65
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
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 54

def generate_swift
  self.generated_paths = [] # reset generated paths in case we're called multiple times
  file_content = []
  file_content << "import Foundation"

  tool_details = []
  ActionsList.all_actions do |action|
    next if self.actions_not_supported.include?(action.action_name)

    swift_function = process_action(action: action)
    if defined?(swift_function.class_name)
      tool_details << SwiftToolDetail.new(
        command_line_tool_name: action.action_name,
        swift_class: swift_function.class_name,
        swift_protocol: swift_function.protocol_name
      )
    end
    unless swift_function
      next
    end

    file_content << swift_function.swift_code
  end
  file_content << "" # newline because we're adding an extension
  file_content << "// These are all the parsing functions needed to transform our data into the expected types"
  file_content << generate_lanefile_parsing_functions

  tool_objects = generate_lanefile_tool_objects(classes: tool_details.map(&:swift_class))
  file_content << tool_objects
  new_file_content = file_content.join("\n")

  fastlane_swift_api_path = File.join(@target_output_path, "Fastlane.swift")
  old_file_content = File.read(fastlane_swift_api_path)

  # compare old file content to potential new file content
  api_version = determine_api_version(new_file_content: new_file_content, old_file_content: old_file_content)
  old_api_version = find_api_version_string(content: old_file_content)

  # if there is a change, we need to write out the new file
  if api_version != old_api_version
    new_file_content.concat(autogen_version_warning_text(api_version: api_version))

    File.write(fastlane_swift_api_path, new_file_content)
    UI.success(fastlane_swift_api_path)
    self.generated_paths << fastlane_swift_api_path
  end

  default_implementations_path = generate_default_implementations(tool_details: tool_details)

  # we might not have any changes, like if it's a hotpatch
  self.generated_paths += default_implementations_path if default_implementations_path.length > 0

  return self.generated_paths
end

#generate_tool_protocol(tool_swift_function: nil) ⇒ Object


281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 281

def generate_tool_protocol(tool_swift_function: nil)
  protocol_content_array = []
  protocol_name = tool_swift_function.protocol_name

  protocol_content_array << "protocol #{protocol_name}: class {"
  protocol_content_array += tool_swift_function.swift_vars
  protocol_content_array << "}"
  protocol_content_array << ""

  protocol_content_array << "extension #{protocol_name} {"
  protocol_content_array += tool_swift_function.swift_default_implementations
  protocol_content_array << "}"
  protocol_content_array << ""
  new_file_content = protocol_content_array.join("\n")

  target_path = File.join(@target_output_path, "#{protocol_name}.swift")

  old_file_content = ""
  # we might have a new file here, unlikely, but possible
  if File.exist?(target_path)
    old_file_content = File.read(target_path)
  end

  # compare old file content to potential new file content
  api_version = determine_api_version(new_file_content: new_file_content, old_file_content: old_file_content)
  old_api_version = find_api_version_string(content: old_file_content)

  # we don't need to write this file out because the file versions are exactly the same
  return nil if api_version == old_api_version

  # use api_version to generate the disclaimer
  api_version_disclaimer = autogen_version_warning_text(api_version: api_version)
  new_file_content.concat(api_version_disclaimer)

  target_path = File.join(@target_output_path, "#{protocol_name}.swift")

  File.write(target_path, new_file_content)
  UI.success(target_path)
  return target_path
end

#ignore_param?(function_name: nil, param_name: nil) ⇒ Boolean

Returns:


322
323
324
325
326
327
328
329
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 322

def ignore_param?(function_name: nil, param_name: nil)
  option_set = @action_options_to_ignore[function_name.to_s]
  unless option_set
    return false
  end

  return option_set.include?(param_name.to_s)
end

#increment_api_version_string(api_version_string: nil, increment_by: :patch) ⇒ Object

expects format to be “X.Y.Z” where each value is a number


249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 249

def increment_api_version_string(api_version_string: nil, increment_by: :patch)
  versions = api_version_string.split(".")
  major = versions[0].to_i
  minor = versions[1].to_i
  patch = versions[2].to_i

  case increment_by
  when :patch
    patch += 1
  when :minor
    minor += 1
    patch = 0
  when :major
    major += 1
    minor = 0
    patch = 0
  end

  new_version_string = [major, minor, patch].join(".")
  return new_version_string
end

#process_action(action: nil) ⇒ Object


331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 331

def process_action(action: nil)
  options = action.available_options || []

  action_name = action.action_name
  keys = []
  key_descriptions = []
  key_default_values = []
  key_optionality_values = []
  key_type_overrides = []

  if options.kind_of?(Array)
    options.each do |current|
      next unless current.kind_of?(FastlaneCore::ConfigItem)

      if ignore_param?(function_name: action_name, param_name: current.key)
        next
      end
      keys << current.key.to_s
      key_descriptions << current.description
      key_default_values << current.code_gen_default_value
      key_optionality_values << current.optional
      key_type_overrides << current.data_type
    end
  end
  action_return_type = action.return_type

  if self.tools_option_files.include?(action_name.to_s.downcase)
    tool_swift_function = ToolSwiftFunction.new(
      action_name: action_name,
      keys: keys,
      key_descriptions: key_descriptions,
      key_default_values: key_default_values,
      key_optionality_values: key_optionality_values,
      key_type_overrides: key_type_overrides,
      return_type: action_return_type
    )
    generated_protocol_file_path = generate_tool_protocol(tool_swift_function: tool_swift_function)
    self.generated_paths << generated_protocol_file_path unless generated_protocol_file_path.nil?
    return tool_swift_function
  else
    return SwiftFunction.new(
      action_name: action_name,
      keys: keys,
      key_descriptions: key_descriptions,
      key_default_values: key_default_values,
      key_optionality_values: key_optionality_values,
      key_type_overrides: key_type_overrides,
      return_type: action_return_type
    )
  end
end

#write_lanefile(lanefile_implementation_opening: nil, class_name: nil, tool_name: nil) ⇒ Object


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'fastlane/lib/fastlane/swift_fastlane_api_generator.rb', line 109

def write_lanefile(lanefile_implementation_opening: nil, class_name: nil, tool_name: nil)
  disclaimer = []
  disclaimer << "// This class is automatically included in FastlaneRunner during build"
  disclaimer << ""
  disclaimer << "// This autogenerated file will be overwritten or replaced during build time, or when you initialize `#{tool_name}`"
  disclaimer << lanefile_implementation_opening
  disclaimer << "// If you want to enable `#{tool_name}`, run `fastlane #{tool_name} init`"
  disclaimer << "// After, this file will be replaced with a custom implementation that contains values you supplied"
  disclaimer << "// during the `init` process, and you won't see this message"
  disclaimer << "}"
  disclaimer << ""
  disclaimer << ""
  disclaimer << ""
  disclaimer << ""
  disclaimer << ""
  disclaimer << "// Generated with fastlane #{Fastlane::VERSION}"
  disclaimer << ""

  file_content = disclaimer.join("\n")

  target_path = File.join(@target_output_path, "#{class_name}.swift")
  File.write(target_path, file_content)
  UI.success(target_path)
  return target_path
end