Class: Pod::LocalBuilder

Inherits:
Object
  • Object
show all
Includes:
Config::Mixin, DirUtil, PodUtil
Defined in:
lib/cocoapods-xcframework/local_build.rb

Instance Method Summary collapse

Methods included from DirUtil

#create_target_directory_path_by_name, #create_target_directory_path_by_spec, #create_working_directory_by_name, #create_working_directory_by_spec

Methods included from PodUtil

#build_static_sandbox, #fix_bundle_file, #fix_header_file, #generic_new_podspec_hash, #installation_root, #installation_root_muti, #muti_config_with_file, #podfile_from_muti_configs, #podfile_from_spec, #spec_with_name, #spec_with_path, #to_native_platform

Constructor Details

#initialize(name, source, spec_sources, subspecs, configuration, force, use_modular_headers = true, enable_bitcode = false, symbols = true, support_maccatalyst = true, support_macos = false, support_dynamic = false, source_dir = Dir.pwd, workspace = nil) ⇒ LocalBuilder

Returns a new instance of LocalBuilder.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/cocoapods-xcframework/local_build.rb', line 6

def initialize(name, source, spec_sources, subspecs, configuration, force, use_modular_headers=true, enable_bitcode=false, symbols=true, support_maccatalyst=true, support_macos=false, support_dynamic=false, source_dir=Dir.pwd, workspace=nil)
  @name = name
  @source = source
  @spec_sources = spec_sources
  @subspecs = subspecs
  @configuration = configuration
  @force = force
  @use_modular_headers = use_modular_headers
  @enable_bitcode = enable_bitcode
  @symbols = symbols
  @support_maccatalyst = support_maccatalyst
  @support_dynamic = support_dynamic
  @support_macos = support_macos
  @spec = spec_with_path @name
  @source_dir = source_dir
  @outputs = Hash.new
  @workspace = workspace
end

Instance Method Details

#buildObject



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 'lib/cocoapods-xcframework/local_build.rb', line 28

def build
  spec = spec_with_path @name
  UI.puts "正在生成Local XCFramework #{spec.name}(#{spec.version}) with configuration #{@configuration} isSymbols:#{@symbols}".yellow
  @is_spec_from_path = true if spec
  spec ||= spec_with_name @name
  target_dir, work_dir = create_working_directory_by_spec spec, @force
  build_dir = "#{work_dir}/build"
  archive_path = "#{build_dir}/archives"
  defines = ""
  if @configuration == 'Debug'
    defines << 'GCC_GENERATE_DEBUGGING_SYMBOLS=YES ONLY_ACTIVE_ARCH=NO'
  else
    if @symbols
      defines << "GCC_GENERATE_DEBUGGING_SYMBOLS=YES" # Release模式需要符号表应于问题排查(二进制切源码操作) by hm 21/10/13
    else
      defines << "GCC_GENERATE_DEBUGGING_SYMBOLS=NO" # 去除符号表
    end
  end
  FileUtils.rm_rf(build_dir)

  build_all_device(defines, build_dir, archive_path)
  makeXCFramework(archive_path, build_dir)
  exportdSYMs(archive_path, build_dir)
  outputs(target_dir)
end

#build_all_device(defines, build_dir, archive_path) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/cocoapods-xcframework/local_build.rb', line 152

def build_all_device(defines, build_dir, archive_path)
  # build general first because simulator will exchange SDKROOT to simulat sdk
  build_general_device defines, build_dir, archive_path
  build_simulator_device defines, build_dir, archive_path
  # macos\MacCatalyst互斥
  if @support_macos
    build_mac_device defines, build_dir, archive_path 
  else
    build_MacCatalyst_device defines, build_dir, archive_path if @support_maccatalyst
  end
end

#build_general_device(defines, build_dir, archive_path) ⇒ Object



171
172
173
174
175
176
# File 'lib/cocoapods-xcframework/local_build.rb', line 171

def build_general_device defines, build_dir, archive_path
    UI.puts("--- Building framework #{@spec} with general device")
    destination = 'generic/platform=iOS'
    archs = 'arm64'
    xcode_xbuild(destination, archs, "iOS", defines, build_dir, archive_path)
end

#build_mac_device(defines, build_dir, archive_path) ⇒ Object



164
165
166
167
168
169
# File 'lib/cocoapods-xcframework/local_build.rb', line 164

def build_mac_device defines, build_dir, archive_path
    UI.puts("--- Building framework #{@spec} with general device")
    destination = 'generic/platform=macOS'
    archs = 'arm64'
    xcode_xbuild(destination, archs, "macOS", defines, build_dir, archive_path)
end

#build_MacCatalyst_device(defines, build_dir, archive_path) ⇒ Object



185
186
187
188
189
190
# File 'lib/cocoapods-xcframework/local_build.rb', line 185

def build_MacCatalyst_device defines, build_dir, archive_path
    UI.puts("--- Building framework #{@spec} with MacCatalyst device")
    destination = 'generic/platform=macOS,variant=Mac Catalyst,name=Any Mac'
    archs = 'x86_64 arm64'
    xcode_xbuild(destination, archs, "MacCatalyst", defines, build_dir, archive_path)
end

#build_simulator_device(defines, build_dir, archive_path) ⇒ Object



178
179
180
181
182
183
# File 'lib/cocoapods-xcframework/local_build.rb', line 178

def build_simulator_device defines, build_dir, archive_path
    UI.puts("--- Building framework #{@spec} with simulator device")
    destination = 'generic/platform=iOS Simulator'
    archs = 'x86_64 arm64'
    xcode_xbuild(destination, archs, "Simulator", defines, build_dir, archive_path)
end

#exportdSYMs(archive_path, build_dir) ⇒ Object

导出符号表



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/cocoapods-xcframework/local_build.rb', line 251

def exportdSYMs(archive_path, build_dir)
  spec = spec_with_path @name
  spec ||= spec_with_name @name
  framework_name = spec.name

  dsym_output_dir = File.join(build_dir, 'dSYMs')
  FileUtils.mkdir_p(dsym_output_dir)

  archives = Dir.glob(File.join(archive_path, '*.xcarchive'))
  if archives.empty?
    UI.puts("⚠️ 未在 #{archive_path} 下找到 xcarchive,跳过 dSYM 导出").yellow
    return
  end

  exported = false

  archives.each do |archive|
    dsym_path = File.join(
      archive,
      'dSYMs',
      "#{framework_name}.framework.dSYM"
    )

    if File.exist?(dsym_path)
      archive_name = File.basename(archive, '.xcarchive')
      target_path = File.join(dsym_output_dir, "#{archive_name}.framework.dSYM")
      FileUtils.rm_rf(target_path)
      FileUtils.cp_r(dsym_path, target_path)
      UI.puts "� Exported dSYM: #{target_path}".green
      exported = true
    else
      UI.puts "⚠️ 未在 #{archive} 中找到 dSYM,已跳过".yellow
    end
  end

  unless exported
    UI.puts("⚠️ 未导出任何 dSYM,请确认 DEBUG_INFORMATION_FORMAT=dwarf-with-dsym").yellow
  else
    UI.puts "✅ dSYM 导出完成,目录:#{dsym_output_dir}".green
  end
end

#find_bundles(target_dir) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/cocoapods-xcframework/local_build.rb', line 353

def find_bundles target_dir
  bundle_root = "#{target_dir}/bundle/"
  pattern = "#{bundle_root}*"
  result = {}
  Pathname.glob(pattern).each do |bundle|
    bundle_relative_path = bundle.to_s.gsub(bundle_root, "")
    plat = bundle_relative_path
    result[plat] = {
      "#{@spec.name}" => "bundle/" + bundle_relative_path + "/*"
    }
  end
  result
end

#fix_xcframework_error(target_dir, name) ⇒ Object

解决项目是Swift和Objc混合开发,有一个Swift类名和ModuleName相同,当打包成xcframework引入到项目时, 会报错… is not a member type of …



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/cocoapods-xcframework/local_build.rb', line 328

def fix_xcframework_error target_dir, name
  # 全量替换代价:Swift module identity 被抹掉,--- 调试时能看不清来自哪个组件
  # command = "find #{target_dir} -name '*.swiftinterface' -exec sed -i -e 's/#{name}\\.//g' {} \\; && find #{target_dir} -name '*.swiftinterface-e' | xargs rm -rf" 
  # UI.puts "fix swift error command :#{command}"
  
  # 安全版修复: by hm 26/1/30
  # 仅修复 Swift 类名 == ModuleName 时产生的 `ModuleName.ModuleName` 冲突,
  # 避免全量移除 ModuleName. 造成 Swift module identity 丢失。
  UI.puts "fix xcframework-is-not-a-member-type-of-error (safe mode): #{target_dir}"
  # 只替换 `ModuleName.ModuleName` -> `ModuleName`
  pattern = "s/#{name}\\.#{name}/#{name}/g"
  # command = <<~CMD
  #   find #{target_dir} -name '*.swiftinterface' \
  #   -exec sed -i -e '#{pattern}' {} \; \
  #   && find #{target_dir} -name '*.swiftinterface-e' | xargs rm -rf
  # CMD
  command = "find #{target_dir} -name '*.swiftinterface' -exec sed -i -e 's/#{name}\\.#{name}/#{name}//g' {} \\; && find #{target_dir} -name '*.swiftinterface-e' | xargs rm -rf" 
  UI.puts "fix swift error command (safe): #{command}"
  output = `#{command}`.lines.to_a
  if $?.exitstatus != 0
    Pod::ErrorUtil.error_report command, output
    Process.exit -1
  end
end

#makeXCFramework(archive_path, output_dir) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/cocoapods-xcframework/local_build.rb', line 192

def makeXCFramework(archive_path, output_dir)
  spec = spec_with_path @name
  spec ||= spec_with_name @name
  framework_name = spec.name

  # scan xcarchive directories
  archives = Dir.glob(File.join(archive_path, '*.xcarchive'))
  if archives.empty?
    UI.puts("❌ 未在 #{archive_path} 下找到 xcarchive 产物,无法生成 xcframework").red
    Process.exit 1
  end

  framework_args = []

  archives.each do |archive|
    framework_path = File.join(
      archive,
      'Products',
      'Library',
      'Frameworks',
      "#{framework_name}.framework"
    )
    if File.exist?(framework_path)
      framework_args << "-framework '#{framework_path}'"
      UI.puts "� Found framework: #{framework_path}".green
    else
      UI.puts "⚠️ 未在 #{archive} 中找到 #{framework_name}.framework,已跳过".yellow
    end
  end

  if framework_args.empty?
    UI.puts "❌ 未找到任何可用 Framework,xcframework 生成失败".red
    Process.exit 1
  end

  xcframework_path = File.join(output_dir, "#{framework_name}.xcframework")
  FileUtils.rm_rf(xcframework_path)
  @outputs[:xcframework] = xcframework_path

  command = [
    'xcodebuild -create-xcframework',
    framework_args.join(' '),
    "-output '#{xcframework_path}'"
  ].join(' ')

  UI.puts "� Creating XCFramework:#{command}"
  UI.puts command.cyan

  success = system(command)
  unless success
    UI.puts("❌ xcodebuild -create-xcframework 执行失败").red
    Process.exit $?.exitstatus.nonzero? || 1
  end

  UI.puts "✅ XCFramework 生成成功:"
  UI.puts xcframework_path.green
end

#outputs(target_dir) ⇒ Object



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
321
322
323
324
325
# File 'lib/cocoapods-xcframework/local_build.rb', line 293

def outputs target_dir
  puts "outputs:#{target_dir}"
  if not File.exist? target_dir
    Pathname.new(target_dir).mkdir
  end
  outputs_xcframework target_dir
  outputs_bundle target_dir
  new_spec_hash = generic_new_podspec_hash @spec
  new_spec_hash[:vendored_frameworks] = "#{@spec.name}.xcframework"
  xcframework_path = "#{target_dir}/#{@spec.name}.xcframework"
  # new_spec_hash = fix_header_file new_spec_hash, xcframework_path
  # new_spec_hash = fix_bundle_file(@spec, new_spec_hash, @source_dir, xcframework_path)
  # find_bundles(target_dir).each do |plat, value| 
  #   if new_spec_hash[plat]
  #     new_spec_hash[plat]["resource_bundles"] = value
  #   else
  #     new_spec_hash[plat] = {
  #       "resource_bundles" => value
  #     }
  #   end
  # end
  require 'json'
  spec_json = JSON.pretty_generate(new_spec_hash) << "\n"
  File.open("#{target_dir}/#{@spec.name}.podspec.json",'wb+') do |f|
    f.write(spec_json)
  end
  # fix xcframework-is-not-a-member-type-of-error https://v3.bbcloud.babybus.com/team/184/wiki/13820
  # UI.puts "fix xcframework-is-not-a-member-type-of-error:#{target_dir}"
  # fix_xcframework_error(target_dir, @spec.name)

  UI.puts "result export at :#{target_dir} 生成成功".green
  target_dir
end

#outputs_bundle(target_dir) ⇒ Object



376
377
378
379
380
# File 'lib/cocoapods-xcframework/local_build.rb', line 376

def outputs_bundle target_dir
  if @outputs[:bundle]
    FileUtils.cp_r(Dir[@outputs[:bundle]],target_dir)
  end
end

#outputs_xcframework(target_dir) ⇒ Object



367
368
369
370
371
372
373
374
# File 'lib/cocoapods-xcframework/local_build.rb', line 367

def outputs_xcframework target_dir
  command = "cp -rp #{@outputs[:xcframework]} #{target_dir} 2>&1"
  output = `#{command}`.lines.to_a
  if $?.exitstatus != 0
    Pod::ErrorUtil.error_report command,output
    Process.exit -1
  end
end

#runObject



25
26
# File 'lib/cocoapods-xcframework/local_build.rb', line 25

def run
end

#xcode_xbuild(destination, archs, platform, defines, build_dir, archive_path) ⇒ Object



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
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
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/cocoapods-xcframework/local_build.rb', line 54

def xcode_xbuild(destination, archs, platform, defines, build_dir, archive_path)
    # xcodebuild archive requires -scheme when -archivePath is specified
    spec = spec_with_path @name
    spec ||= spec_with_name @name
    
    workspace_path = @workspace
    scheme_name = @spec&.name
    configuration = @configuration
    skip_install = 'NO'
    plat_name   = platform.to_s.gsub(/\s+/, '_')
    target_name = "#{scheme_name}-#{plat_name}"
    archivePath = "#{archive_path}/#{target_name}.xcarchive"
    UI.puts "scheme_name=#{scheme_name} plat_name=#{plat_name} destination=#{destination} archs=#{archs} workspace_path=#{workspace_path}"
    if scheme_name.nil?
      UI.puts("❌ archive 构建缺少 scheme,请在调用 xcode_xbuild 时显式传入 scheme").red
      Process.exit 1
    end

    workspace_arg = if workspace_path && !workspace_path.to_s.strip.empty?
                      "-workspace '#{workspace_path}' "
                    else
                      ""
                    end

    scheme_arg = if workspace_path && !workspace_path.to_s.strip.empty?
                    if platform == "iOS" or platform == "Simulator" or platform == "MacCatalyst"
                      "#{scheme_name}-iOS"
                    else
                      "#{scheme_name}-macOS"
                    end
                 else
                   scheme_name
                 end

    command = "xcodebuild archive " \
              "#{workspace_arg}" \
              "-scheme '#{scheme_arg}' " \
              "-archivePath '#{archivePath}' " \
              "-destination '#{destination}' " \
              "-configuration #{configuration} " \
              "ARCHS='#{archs}' " \
              "SKIP_INSTALL=#{skip_install} " \
              "#{defines} " \
              "SWIFT_OPTIMIZATION_LEVEL=-Onone DEBUG_INFORMATION_FORMAT=dwarf-with-dsym " \
              "BUILD_LIBRARY_FOR_DISTRIBUTION=YES clean build "
        
    # command = "xcodebuild archive #{workspace_arg} -scheme '#{scheme_arg}' -archivePath '#{archivePath}' #{defines} BUILD_LIBRARY_FOR_DISTRIBUTION=YES clean build -configuration #{configuration} -destination '#{destination}' ARCHS='#{archs}' SKIP_INSTALL=#{skip_install}"

    # --- enhanced logging & reliable failure surfacing ---
    log_dir  = File.join(archivePath, 'logs')
    FileUtils.mkdir_p(log_dir)
    log_raw = File.join(log_dir, "xcodebuild-#{scheme_name}-#{plat_name}-#{configuration}.raw.log")

    # Allow disabling xcpretty via env
    use_pretty = ENV['XBUILDER_NOPRETTY'] != '1'
    wrapped = if use_pretty
      "set -o pipefail; #{command} 2>&1 | tee '#{log_raw}' | xcpretty"
      # "set -o pipefail; #{command} | tee '#{log_raw}' | xcpretty"
    else
      # no pretty: just tee to log and console
      "set -o pipefail; #{command} | tee '#{log_raw}'"
    end
    # UI.puts "XBuilder command wrapped: #{wrapped}"
    UI.puts "XBuilder command: #{command}"
    UI.puts "Available schemes:"
    schemes = `xcodebuild -list 2>/dev/null`
    UI.puts schemes

    success = system('bash', '-lc', wrapped)
    unless success
      UI.puts ""
      UI.puts "========== XCODEBUILD FAILED =========="
      UI.puts "platform=#{platform}"
      UI.puts "scheme=#{scheme_name}"
      UI.puts "destination=#{destination}"
      UI.puts "log=#{log_raw}"
      if platform == 'macOS'
        UI.puts "Available schemes:"
        schemes = `xcodebuild -list 2>/dev/null`
        UI.puts schemes
      end
      if File.exist?(log_raw)
        UI.puts ""
        UI.puts "===== LAST 300 LINES ====="
        tail = `tail -n 300 "#{log_raw}"`
        UI.puts tail
        UI.puts ""
        UI.puts "===== ERROR LINES ====="
        errors = `grep -nE "error:|fatal error:|Undefined symbols|Command Compile|Command SwiftCompile|Command Ld" "#{log_raw}"`
        UI.puts(errors.empty? ? "No error lines found." : errors)
      else
        UI.puts "raw log not found"
      end
      raise Informative,
            "xcodebuild failed. see log: #{log_raw}"
    end
end