Class: PodBuilder::Podfile

Inherits:
Object
  • Object
show all
Defined in:
lib/pod_builder/podfile.rb,
lib/pod_builder/podfile/post_actions.rb

Constant Summary collapse

PODBUILDER_LOCK_ACTION =
["raise \"\\n🚨  Do not launch 'pod install' manually, use `pod_builder` instead!\\n\" if !File.exist?('pod_builder.lock')"].freeze
POST_INSTALL_ACTIONS =
["require 'pod_builder/podfile/post_actions'", "PodBuilder::Podfile::remove_target_support_duplicate_entries", "PodBuilder::Podfile::check_target_support_resource_collisions"].freeze

Class Method Summary collapse

Class Method Details

.add(entries, marker, podfile_path) ⇒ Object



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
# File 'lib/pod_builder/podfile.rb', line 354

def self.add(entries, marker, podfile_path)
  podfile_content = File.read(podfile_path)

  file_indentation = indentation_from_file(podfile_path)

  entries = entries.map { |x| "#{file_indentation}#{x}\n"}

  marker_found = false
  podfile_lines = []
  podfile_content.each_line do |line|
    stripped_line = strip_line(line)

    podfile_lines.push(line)
    if stripped_line.start_with?("#{marker}do|")
      marker_found = true
      podfile_lines.push(entries)
    end
  end

  if !marker_found
    podfile_lines.push("\n#{marker} do |installer|\n")
    podfile_lines.push(entries)
    podfile_lines.push("end\n")
  end

  File.write(podfile_path, podfile_lines.join)
end

.add_install_block(podfile_path) ⇒ Object



193
194
195
# File 'lib/pod_builder/podfile.rb', line 193

def self.add_install_block(podfile_path)
  add(PODBUILDER_LOCK_ACTION, "pre_install", podfile_path)
end

.add_post_install_checks(podfile_path) ⇒ Object



350
351
352
# File 'lib/pod_builder/podfile.rb', line 350

def self.add_post_install_checks(podfile_path)
  add(POST_INSTALL_ACTIONS + [" "], "post_install", podfile_path)
end

.add_pre_install_actions(podfile_path) ⇒ Object



346
347
348
# File 'lib/pod_builder/podfile.rb', line 346

def self.add_pre_install_actions(podfile_path)
  add(PRE_INSTALL_ACTIONS + [" "], "pre_install", podfile_path)
end

.check_for_colliding_resources(path, target_name, targets) ⇒ Object



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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/pod_builder/podfile/post_actions.rb', line 63

def self.check_for_colliding_resources(path, target_name, targets)
  if !File.file?(path)
    return
  end

  if target = targets.detect { |x| x.name == target_name }
    resource_files = target.resources_build_phase.files.map { |i| i.file_ref.real_path.to_s }.to_set
    resource_files = resource_files.map { |i| File.basename(i) }
    resource_files = resource_files.map { |i| i.gsub(".xib", ".nib") }
  else
    raise "#{target} not found!".red
  end
  
  # Check that Pods-TARGET-resources.sh doesn't contain colliding entries (Cocoapods 1.4.0)
  in_section_to_update = false
  processed_entries = []
  File.read(path).each_line do |line|
    stripped_line = line.strip()
    next if stripped_line.empty?
    
    if stripped_line.include?("if [[ \"$CONFIGURATION\" == ")
      in_section_to_update = true
      next
    elsif stripped_line == "fi"
      in_section_to_update = false
      
      processed_entries.each do |entry|
        matches_other_framework = processed_entries.select { |t| t[0] == entry[0] }
        
        # Check for static framework cross-collisions
        if matches_other_framework.count > 1
          error = "\n\nCross-framework resource collision detected:\n"
          error += "#{entry[0]} found in\n"
          error += matches_other_framework.map { |x| "- #{x[1]}" }.join("\n")
          error += "\n\n"
          
          raise error.red
        end
        
        # Check for collisions with app's resources
        matches_app_resources = resource_files.select { |t| t == entry[0] }
        if matches_app_resources.count > 0
          error = "\n\nResource collision with app file detected:\n"
          error += "#{entry[0]} found in app but also in\n"
          error += matches_app_resources.map { |x| "- #{x[1]}" }.join("\n")
          error += "\n\n"
          
          raise error.red
        end
      end
      
      processed_entries = []
    end
    
    next if stripped_line.start_with?("#") # skip commented lines
    next if stripped_line.count("/..") > 2 # skip development pods
    
    line.gsub!("\"", "")
    line.gsub!("install_resource", "")
    line.strip!()
    
    if in_section_to_update
      filename = File.basename(line)
      processed_entries.push([filename, line])
    end
  end
end

.check_target_support_resource_collisions ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/pod_builder/podfile/post_actions.rb', line 16

def self.check_target_support_resource_collisions
  puts "[PodBuilder] Checking target support resource collisions".yellow

  targets = find_xcodeproj_targets

  targets.map(&:name).each do |target|
    check_for_colliding_resources("Pods/Target Support Files/Pods-#{target}/Pods-#{target}-resources.sh", target, targets)
  end
end

.deintegrate_install ⇒ Object



178
179
180
181
182
183
184
185
186
# File 'lib/pod_builder/podfile.rb', line 178

def self.deintegrate_install
  puts "Running pod install".yellow

  current_dir = Dir.pwd

  Dir.chdir(PodBuilder::project_path)
  system("pod install;")
  Dir.chdir(current_dir)
end

.find_xcodeproj_targets ⇒ Object



131
132
133
134
135
# File 'lib/pod_builder/podfile/post_actions.rb', line 131

def self.find_xcodeproj_targets      
  project = Xcodeproj::Project.open(PodBuilder::find_xcodeproj)

  return project.targets
end

.from_podfile_items(items, analyzer) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
53
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
# File 'lib/pod_builder/podfile.rb', line 9

def self.from_podfile_items(items, analyzer)
  raise "no items" unless items.count > 0

  sources = analyzer.sources
  
  cwd = File.dirname(File.expand_path(__FILE__))
  podfile = File.read("#{cwd}/templates/build_podfile.template")

  platform = analyzer.result.targets.first.platform
  podfile.sub!("%%%platform_name%%%", platform.name.to_s)
  podfile.sub!("%%%deployment_version%%%", platform.deployment_target.version)

  podfile.sub!("%%%sources%%%", sources.map { |x| "source '#{x.url}'" }.join("\n"))

  build_configurations = items.map(&:build_configuration).uniq
  raise "Found different build configurations in #{items}" if build_configurations.count != 1
  podfile.sub!("%%%build_configuration%%%", build_configurations.first.capitalize)

  podfile_build_settings = ""
  
  pod_dependencies = {}

  items.each do |item|
    build_settings = Configuration.build_settings.dup

    item_build_settings = Configuration.build_settings_overrides[item.name] || {}
    
    # These settings need to be set as is to properly build frameworks
    build_settings['SWIFT_COMPILATION_MODE'] = 'wholemodule'
    build_settings['CLANG_ENABLE_MODULE_DEBUGGING'] = 'NO'
    build_settings['ONLY_ACTIVE_ARCH'] = 'NO'

    build_settings['SWIFT_VERSION'] = item_build_settings["SWIFT_VERSION"] || item.swift_version || project_swift_version(analyzer)
    if item.is_static
      # https://forums.developer.apple.com/thread/17921
      build_settings['CLANG_ENABLE_MODULE_DEBUGGING'] = "NO"
    end

    item_build_settings.each do |k, v|
      build_settings[k] = v
    end

    podfile_build_settings += "set_build_settings(\"#{item.root_name}\", #{build_settings.to_s}, installer)\n  "

    dependency_names = item.dependency_names.map { |x|
      if x.split("/").first == item.root_name
        next nil # remove dependency to parent spec
      end
      if overridded_module_name = Configuration.spec_overrides.fetch(x, {})["module_name"]
        next overridded_module_name
      end
    }.compact
  
    if dependency_names.count > 0
      pod_dependencies[item.root_name] = dependency_names
    end
  end

  podfile.sub!("%%%build_settings%%%", podfile_build_settings)

  podfile.sub!("%%%build_system%%%", Configuration.build_system)

  podfile.sub!("%%%pods%%%", "\"#{items.map(&:name).join('", "')}\"")
  
  podfile.sub!("%%%pods_dependencies%%%", pod_dependencies.to_s)
  
  podfile.sub!("%%%targets%%%", items.map(&:entry).join("\n  "))

  return podfile
end

.indentation_from_file(path) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/pod_builder/podfile.rb', line 288

def self.indentation_from_file(path)
  content = File.read(path)

  lines = content.split("\n").select { |x| !x.empty? }

  if lines.count > 2
    lines[0..-2].each_with_index do |current_line, index|
      next_line = lines[index + 1]
      next_line_first_char = next_line.chars.first
      current_doesnt_begin_with_whitespace = current_line[/\A\S*/] != nil

      if current_doesnt_begin_with_whitespace && [" ", "\t"].include?(next_line_first_char)
        return next_line[/\A\s*/]
      end          
    end
  end

  return "  "
end

.pod_definition_in(line, include_commented) ⇒ Object



197
198
199
200
201
202
203
204
205
206
# File 'lib/pod_builder/podfile.rb', line 197

def self.pod_definition_in(line, include_commented)
  stripped_line = strip_line(line)
  matches = stripped_line.match(/(^pod')(.*?)(')/)
  
  if matches&.size == 4 && (include_commented || !stripped_line.start_with?("#"))
    return matches[2]
  else
    return nil
  end
end

.podfile_items_at(podfile_path, include_prebuilt = false) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/pod_builder/podfile.rb', line 316

def self.podfile_items_at(podfile_path, include_prebuilt = false)
  raise "Expecting basepath folder!" if !File.exist?(PodBuilder::basepath("Podfile"))

  if File.basename(podfile_path) != "Podfile"
    File.rename(PodBuilder::basepath("Podfile"), PodBuilder::basepath("Podfile.tmp"))
    FileUtils.cp(podfile_path, PodBuilder::basepath("Podfile"))
  end

  current_dir = Dir.pwd
  Dir.chdir(File.dirname(podfile_path))

  buildable_items = []
  begin
    installer, analyzer = Analyze.installer_at(PodBuilder::basepath)
  
    podfile_items = Analyze.podfile_items(installer, analyzer)
    buildable_items = podfile_items.select { |item| include_prebuilt || !item.is_prebuilt }   
  rescue Exception => e
    raise e
  ensure
    Dir.chdir(current_dir)
  
    if File.basename(podfile_path) != "Podfile"
      File.rename(PodBuilder::basepath("Podfile.tmp"), PodBuilder::basepath("Podfile"))
    end  
  end

  return buildable_items
end

.project_swift_version(analyzer) ⇒ Object



308
309
310
311
312
313
314
# File 'lib/pod_builder/podfile.rb', line 308

def self.project_swift_version(analyzer)
  swift_versions = analyzer.result.target_inspections.values.map { |x| x.target_definition.swift_version }.compact.uniq

  raise "Found different Swift versions in targets. Expecting one, got `#{swift_versions}`" if swift_versions.count != 1

  return swift_versions.first
end

.remove_duplicate_entries(path) ⇒ Object



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
53
54
55
56
57
58
59
60
61
# File 'lib/pod_builder/podfile/post_actions.rb', line 28

def self.remove_duplicate_entries(path)
  if !File.file?(path)
    return
  end
  
  # Adding the same pod to multiple targets results in duplicate entries in Pods-TARGET-frameworks.sh and Pods-TARGET-resources.sh (Cocoapods 1.4.0)
  # To avoid conflicts during parallel codesign we manually remove duplicates
  in_section_to_update = false
  processed_entries = []
  lines = []
  File.read(path).each_line do |line|
    stripped_line = line.strip()
    next if stripped_line.empty?

    if stripped_line.include?("if [[ \"$CONFIGURATION\" == ")
      in_section_to_update = true
    elsif stripped_line == "fi"
      in_section_to_update = false
      processed_entries = []
    end
    if in_section_to_update
      if processed_entries.include?(stripped_line)
        if !line.include?("#")
          line = "# #{line}"
        end
      end
      processed_entries.push(stripped_line)
    end
    
    lines.push(line)
  end
  
  File.write(path, lines.join)
end

.remove_target_support_duplicate_entries ⇒ Object



7
8
9
10
11
12
13
14
# File 'lib/pod_builder/podfile/post_actions.rb', line 7

def self.remove_target_support_duplicate_entries
  puts "[PodBuilder] Removing target support duplicated entries".yellow
  # Frameworks and resources
  find_xcodeproj_targets.map(&:name).each do |target|
    remove_duplicate_entries("Pods/Target Support Files/Pods-#{target}/Pods-#{target}-frameworks.sh")
    remove_duplicate_entries("Pods/Target Support Files/Pods-#{target}/Pods-#{target}-resources.sh")
  end
end

.restore_file_sanity_check ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/pod_builder/podfile.rb', line 235

def self.restore_file_sanity_check
  unless Configuration.restore_enabled
    return nil
  end

  podfile_restore_path = PodBuilder::basepath("Podfile.restore")
  unless File.exist?(podfile_restore_path)
    return
  end

  error = nil

  begin
    File.rename(PodBuilder::basepath("Podfile"), PodBuilder::basepath("Podfile.tmp2"))
    File.rename(podfile_restore_path, PodBuilder::basepath("Podfile"))

    Analyze.installer_at(PodBuilder::basepath, false)
  rescue Exception => e
    error = e.to_s
  ensure
    File.rename(PodBuilder::basepath("Podfile"), podfile_restore_path)
    File.rename(PodBuilder::basepath("Podfile.tmp2"), PodBuilder::basepath("Podfile"))
  end

  if !error.nil?
    FileUtils.rm(podfile_restore_path)
  end

  return error
end

.restore_podfile_clean(pod_items) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/pod_builder/podfile.rb', line 208

def self.restore_podfile_clean(pod_items)
  unless Configuration.restore_enabled
    return
  end

  # remove pods that are no longer listed in pod_items
  podfile_restore_path = PodBuilder::basepath("Podfile.restore")
  unless File.exist?(podfile_restore_path)
    return
  end

  restore_content = File.read(podfile_restore_path)

  cleaned_lines = []
  restore_content.each_line do |line|
    if pod_name = pod_definition_in(line, false)
      if pod_items.map(&:name).include?(pod_name)
        cleaned_lines.push(line)      
      end
    else
      cleaned_lines.push(line)
    end
  end

  File.write(podfile_restore_path, cleaned_lines.join)
end

.sanity_check ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/pod_builder/podfile.rb', line 266

def self.sanity_check
  podfile_path = PodBuilder::basepath("Podfile")
  unless File.exist?(podfile_path)
    return
  end

  lines = File.read(podfile_path).split("\n")
  lines.each do |line|
    stripped_line = strip_line(line)
    unless !stripped_line.start_with?("#")
      next
    end

    if stripped_line.match(/(pod')(.*?)(')/) != nil
      starting_def_found = stripped_line.start_with?("def") && (line.match("\s*def\s") != nil)
      raise "Unsupported single line def/pod. `def` and `pod` shouldn't be on the same line, please modify the following line:\n#{line}" if starting_def_found
    end
  end
end

.strip_line(line) ⇒ Object



188
189
190
191
# File 'lib/pod_builder/podfile.rb', line 188

def self.strip_line(line)
  stripped_line = line.strip
  return stripped_line.gsub("\"", "'").gsub(" ", "").gsub("\t", "").gsub("\n", "")
end

.update_path_entires(podfile_path, use_absolute_paths = false, path_base = PodBuilder::basepath("")) ⇒ Object



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/pod_builder/podfile.rb', line 382

def self.update_path_entires(podfile_path, use_absolute_paths = false, path_base = PodBuilder::basepath(""))
  podfile_content = File.read(podfile_path)
  
  base_path = Pathname.new(File.dirname(podfile_path))
  regex = "(\s*pod\s*['|\"])(.*?)(['|\"])(.*?)(:path\s*=>\s*['|\"])(.*?)(['|\"])"

  podfile_lines = []
  podfile_content.each_line do |line|
    stripped_line = strip_line(line)
    matches = line.match(/#{regex}/)

    if matches&.size == 8 && !stripped_line.start_with?("#")
      pod_name = matches[2]
      path = matches[6]

      is_absolute = ["~", "/"].include?(path[0])
      unless !pod_name.start_with?("PodBuilder/") && !is_absolute
        podfile_lines.push(line)
        next
      end

      original_path = Pathname.new(File.join(path_base, path))
      replace_path = original_path.relative_path_from(base_path)
      if use_absolute_paths
        replace_path = replace_path.expand_path(base_path)
      end
                
      updated_path_line = line.gsub(/#{regex}/, '\1\2\3\4\5' + replace_path.to_s + '\7\8')
      podfile_lines.push(updated_path_line)
    else
      podfile_lines.push(line)
    end
  end

  File.write(podfile_path, podfile_lines.join)
end

.update_project_entries(podfile_path, use_absolute_paths = false, path_base = PodBuilder::basepath("")) ⇒ Object



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/pod_builder/podfile.rb', line 419

def self.update_project_entries(podfile_path, use_absolute_paths = false, path_base = PodBuilder::basepath(""))
  podfile_content = File.read(podfile_path)
  
  base_path = Pathname.new(File.dirname(podfile_path))
  regex = "(\s*project\s*['|\"])(.*?)(['|\"])"

  podfile_lines = []
  podfile_content.each_line do |line|
    stripped_line = strip_line(line)
    matches = line.match(/#{regex}/)

    if matches&.size == 4 && !stripped_line.start_with?("#")
      path = matches[2]

      is_absolute = ["~", "/"].include?(path[0])
      unless !is_absolute
        podfile_lines.push(line)
        next
      end

      original_path = Pathname.new(File.join(path_base, path))
      replace_path = original_path.relative_path_from(base_path)
      if use_absolute_paths
        replace_path = replace_path.expand_path(base_path)
      end
                
      updated_path_line = line.gsub(/#{regex}/, '\1' + replace_path.to_s + '\3\4')
      podfile_lines.push(updated_path_line)
    else
      podfile_lines.push(line)
    end
  end

  File.write(podfile_path, podfile_lines.join)
end

.write_prebuilt(all_buildable_items, analyzer) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/pod_builder/podfile.rb', line 140

def self.write_prebuilt(all_buildable_items, analyzer)  
  puts "Updating Application Podfile".yellow

  podbuilder_podfile_path = PodBuilder::basepath("Podfile")
  rel_path = Pathname.new(podbuilder_podfile_path).relative_path_from(Pathname.new(PodBuilder::project_path)).to_s
    
  podfile_content = File.read(podbuilder_podfile_path)

  exclude_lines = Podfile::PODBUILDER_LOCK_ACTION.map { |x| strip_line(x) }

  prebuilt_lines = ["# Autogenerated by PodBuilder (https://github.com/Subito-it/PodBuilder)\n", "# Any change to this file should be done on #{rel_path}\n", "\n"]
  podfile_content.each_line do |line|
    stripped_line = strip_line(line)

    if pod_name = pod_definition_in(line, true)
      if podfile_item = all_buildable_items.detect { |x| x.name == pod_name }
        if Podspec.include?(podfile_item.name)
          if podfile_item.is_prebuilt == false
            line = "#{line.detect_indentation}#{podfile_item.prebuilt_entry}\n"
          end
        end
      end
    end

    if !exclude_lines.include?(stripped_line)
      prebuilt_lines.push(line)
    end
  end

  project_podfile_path = PodBuilder::project_path("Podfile")
  File.write(project_podfile_path, prebuilt_lines.join)
  Podfile.update_path_entires(project_podfile_path, false)
  Podfile.update_project_entries(project_podfile_path, false)

  add_pre_install_actions(project_podfile_path)
  add_post_install_checks(project_podfile_path)
end

.write_restorable(updated_pods, podfile_items, analyzer) ⇒ Object



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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/pod_builder/podfile.rb', line 80

def self.write_restorable(updated_pods, podfile_items, analyzer)
  unless Configuration.restore_enabled
    return
  end
  
  puts "Writing Restore Podfile".yellow

  podfile_items = podfile_items.dup
  podfile_restore_path = PodBuilder::basepath("Podfile.restore")
  podfile_path = PodBuilder::basepath("Podfile")

  if File.exist?(podfile_restore_path)
    restore_podfile_items = podfile_items_at(podfile_restore_path, include_prebuilt = true)

    podfile_items.map! { |podfile_item|
      if updated_pod = updated_pods.detect { |x| x.name == podfile_item.name } then
        updated_pod
      elsif updated_pods.any? { |x| podfile_item.root_name == x.root_name } == false && # podfile_item shouldn't be among those being updated (including root specification)
            restored_pod = restore_podfile_items.detect { |x| x.name == podfile_item.name }
        restored_pod
      else
        podfile_item
      end
    }
  end

  result_targets = analyzer.result.targets.map(&:name) 
  podfile_content = ["# Autogenerated by PodBuilder (https://github.com/Subito-it/PodBuilder)", "# Please don't modify this file", "\n"]
  podfile_content += analyzer.podfile.sources.map { |x| "source '#{x}'" }
  podfile_content += ["", "use_frameworks!", ""]

  # multiple platforms not (yet) supported
  # https://github.com/CocoaPods/Rome/issues/37
  platform = analyzer.result.targets.first.platform
  podfile_content += ["platform :#{platform.name}, '#{platform.deployment_target.version}'", ""]

  analyzer.result.specs_by_target.each do |target, specifications|
    target_name = target.name.to_s

    unless result_targets.select { |x| x.end_with?(target_name) }.count > 0
      next
    end

    podfile_content.push("target '#{target_name}' do")

    if project_path = target.user_project_path
      podfile_content.push("\tproject '#{project_path}'")
    end

    specifications.each do |spec|
      item = podfile_items.detect { |x| x.name == spec.name }
      podfile_content.push("\t#{item.entry}")
    end

    podfile_content.push("end\n")
  end

  File.write(podfile_restore_path, podfile_content.join("\n"))
end