Class: BBItools::DocCGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/cocoapods-bb-PodAssistant/tools/docc_generator.rb

Constant Summary collapse

PODSPEC_REPO =
"babybus-babybus-ios-specs-babybus-specs"
DESTINATION =
"generic/platform=iOS Simulator"
CONFIGURATION =
"Debug"
KEYCHAIN_HOST =
"git.babybus.co"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ DocCGenerator

Returns a new instance of DocCGenerator.



17
18
19
20
21
22
23
24
25
26
# File 'lib/cocoapods-bb-PodAssistant/tools/docc_generator.rb', line 17

def initialize(options)
  @options = options
  @podspec = options[:podspec]
  @workdir = options[:workdir]
  @output = options[:output]
  @logs = options[:logs]
  @derived_data = options[:derived_data]
  @lint_root = options[:lint_root]
  @hosting_base_path = options[:hosting_base_path]
end

Class Method Details

.generate(options) ⇒ Object



13
14
15
# File 'lib/cocoapods-bb-PodAssistant/tools/docc_generator.rb', line 13

def self.generate(options)
  new(options).run
end

Instance Method Details

#runObject



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
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
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
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
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
249
250
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
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
321
322
323
324
325
326
327
328
329
330
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
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
418
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# File 'lib/cocoapods-bb-PodAssistant/tools/docc_generator.rb', line 28

def run
  $stdout.sync = true
  $stderr.sync = true

  fail!("必须传入 podspec") if @podspec.to_s.strip.empty?

  base_dir = Dir.pwd
  podspec_path_abs = abs_path(@podspec.to_s.strip, base_dir: base_dir)
  fail!("podspec 不存在: #{@podspec}") unless File.file?(podspec_path_abs)
  podspec_path_rel = rel_path(podspec_path_abs, base_dir: base_dir)

  podspec_basename = File.basename(podspec_path_abs)
  workdir_opt = @workdir.to_s.strip
  podspec_dir_abs =
    if workdir_opt.empty?
      File.dirname(podspec_path_abs)
    else
      abs_path(workdir_opt, base_dir: base_dir)
    end
  fail!("workdir 不存在: #{rel_path(podspec_dir_abs, base_dir: base_dir)}") unless File.directory?(podspec_dir_abs)
  
  # 如果指定了 workdir,且 podspec 不在其中,则复制过去
  podspec_in_workdir = File.join(podspec_dir_abs, podspec_basename)
  if File.expand_path(podspec_in_workdir) != File.expand_path(podspec_path_abs)
    FileUtils.cp(podspec_path_abs, podspec_in_workdir)
  end

  zip_push_repo = ENV["BB_DOCC_ZIP_PUSH_REPO"].to_s.strip
  zip_push_repo = "https://git.babybus.co/babybus/ios/CommonBusiness/Tools/iOSWeb" if zip_push_repo.empty?
  zip_push_branch = ENV["BB_DOCC_ZIP_PUSH_BRANCH"].to_s.strip
  zip_push_branch = "main" if zip_push_branch.empty?
  zip_push_subdir = ENV["BB_DOCC_ZIP_PUSH_SUBDIR"].to_s.strip
  zip_push_subdir = "docc_zips" if zip_push_subdir.empty?

  final_destination_root = nil
  real_home = ENV["HOME"].to_s
  scheme = extract_name_from_podspec(podspec_path_abs)
  deployment_target = extract_ios_deployment_target_from_podspec(podspec_path_abs)
  
  # ---------------------------------------------------------
  # 2. 所有操作都在脚本同级目录下的 _docc_temp 中进行
  # ---------------------------------------------------------
  # 脚本所在目录 (Gem 安装位置可能只读,所以使用当前运行目录 Dir.pwd)
  local_work_root = File.join(Dir.pwd, "_docc_temp", scheme)
  FileUtils.rm_rf(local_work_root) # 清理旧的
  FileUtils.mkdir_p(local_work_root)
  
  log "🔨 本地工作区 (生成中): file://#{local_work_root}"

  # 各个子目录都在本地工作区内
  logs_dir = File.join(local_work_root, "logs")
  FileUtils.mkdir_p(logs_dir)
  
  derived_data_root = File.join(local_work_root, "DerivedData")
  FileUtils.mkdir_p(derived_data_root)
  
  lint_root = File.join(local_work_root, "Lint")
  FileUtils.mkdir_p(lint_root)
  lint_root_rel = lint_root

  # 最终生成的站点先放在本地
  local_site_output = File.join(local_work_root, "site_output")
  FileUtils.mkdir_p(local_site_output)

  # 模拟 component_dir_abs 供后续逻辑使用 (指向本地)
  component_dir_abs = local_site_output
  component_dir_rel = component_dir_abs

  hosting_base_path = @options[:hosting_base_path].to_s.strip
  if hosting_base_path.empty?
    hosting_base_path = "Docs/#{scheme}"
  end
  hosting_base_path = hosting_base_path.sub(%r{\A/+}, "")

  status_md = File.join(logs_dir, "status.md")
  File.open(status_md, "w") do |f|
    f.puts "# #{scheme}"
    f.puts
    f.puts "- 时间: #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
    f.puts "- podspec: #{podspec_path_rel}"
    f.puts "- workdir: #{rel_path(podspec_dir_abs, base_dir: base_dir)}" unless workdir_opt.empty?
    f.puts "- local_work_root: #{local_work_root}"
    f.puts "- zip_push_repo: #{redact_git_url(zip_push_repo)}"
    f.puts "- zip_push_branch: #{zip_push_branch}"
    f.puts "- zip_push_subdir: #{zip_push_subdir}"
    f.puts "- home: ~"
    f.puts "- deployment_target: #{deployment_target}" unless deployment_target.to_s.strip.empty?
    f.puts "- hosting_base_path: #{hosting_base_path}"
    f.puts "- sources: #{PODSPEC_REPO}"
  end

  exported_source_root = File.join(component_dir_abs, "exported-source")
  export_staging_dir = ""
  cleanup_written = false
  is_success = false

  # Cleanup hook
  at_exit_block = proc do
    next if cleanup_written
    cleanup_written = true

    exit_code = $!.is_a?(SystemExit) ? $!.status : 0
    
    # ---------------------------------------------------------
    # 3. 任务结束:移动产物到 SMB 并清理本地
    # ---------------------------------------------------------
    if final_destination_root
      # 只有明确标记成功 (is_success = true) 才执行同步
      if is_success && exit_code.zero? && File.directory?(local_site_output)
        # 关键校验:检查目标目录下是否存在 server.js
        server_js_path = File.join(final_destination_root, "server.js")
        
        if File.file?(server_js_path)
          log "✅ 校验通过:发现 server.js"
          
          # ---------------------------------------------------------
          # 压缩 -> 移动 -> 删除旧版 -> 解压 -> 删除压缩包
          # ---------------------------------------------------------
          
          # 1. 准备压缩:将 site_output 重命名为 #{scheme},这样解压后直接就是正确的目录名
          staging_dir = File.join(local_work_root, scheme)
          FileUtils.rm_rf(staging_dir)
          FileUtils.mv(local_site_output, staging_dir)
          
          zip_name = "#{scheme}.zip"
          local_zip_path = File.join(local_work_root, zip_name)

          remote_zip_name = "#{scheme}_#{Time.now.strftime("%Y%m%d_%H%M%S")}_#{Process.pid}.zip"

          zip_log = File.join(logs_dir, "zip.log")
          zip_timeout_sec = (ENV["BB_DOCC_ZIP_TIMEOUT_SEC"].to_s.strip.empty? ? 1800 : ENV["BB_DOCC_ZIP_TIMEOUT_SEC"].to_i)

          log "📦 正在压缩产物 (zip)... (timeout=#{zip_timeout_sec}s)"
          log "📄 zip 日志: #{rel_path(zip_log, base_dir: base_dir)}"

          zip_exit = nil
          FileUtils.mkdir_p(File.dirname(zip_log))
          File.open(zip_log, "w") do |f|
            Dir.chdir(local_work_root) do
              pid = Process.spawn({ "HOME" => real_home }, "zip", "-r", "-q", zip_name, scheme, out: f, err: f)
              begin
                Timeout.timeout(zip_timeout_sec) do
                  _pid, status = Process.wait2(pid)
                  zip_exit = status.exitstatus
                end
              rescue Timeout::Error
                begin
                  Process.kill("TERM", pid)
                rescue StandardError
                end
                sleep 2
                begin
                  Process.kill("KILL", pid)
                rescue StandardError
                end
                zip_exit = 124
              end
            end
          end

          log "📦 压缩结束 (exit=#{zip_exit})"

          if zip_exit == 0 && File.exist?(local_zip_path)
            lock_dir = File.join(final_destination_root, ".docc_deploy_lock_#{scheme}")
            lock_timeout_sec = (ENV["BB_DOCC_DEPLOY_LOCK_TIMEOUT_SEC"].to_s.strip.empty? ? 600 : ENV["BB_DOCC_DEPLOY_LOCK_TIMEOUT_SEC"].to_i)
            lock_stale_sec = (ENV["BB_DOCC_DEPLOY_LOCK_STALE_SEC"].to_s.strip.empty? ? 21600 : ENV["BB_DOCC_DEPLOY_LOCK_STALE_SEC"].to_i)

            lock_start = Time.now
            acquired_lock = false

            until acquired_lock
              begin
                Dir.mkdir(lock_dir)
                acquired_lock = true
              rescue Errno::EEXIST
                begin
                  if File.exist?(lock_dir) && (Time.now - File.mtime(lock_dir)) > lock_stale_sec
                    FileUtils.rm_rf(lock_dir)
                    next
                  end
                rescue StandardError
                end

                if (Time.now - lock_start) > lock_timeout_sec
                  log "❌ 获取部署锁超时 (timeout=#{lock_timeout_sec}s):#{lock_dir}"
                  break
                end
                sleep 2
              end
            end

            begin
              if acquired_lock
                log "🚚 正在将压缩包移动到 SMB..."
                target_zip_path = File.join(final_destination_root, remote_zip_name)

                copy_log = File.join(logs_dir, "copy.log")
                copy_timeout_sec = (ENV["BB_DOCC_COPY_TIMEOUT_SEC"].to_s.strip.empty? ? 600 : ENV["BB_DOCC_COPY_TIMEOUT_SEC"].to_i)

                log "🚚 正在复制到 SMB... (timeout=#{copy_timeout_sec}s)"
                log "📄 copy 日志: #{rel_path(copy_log, base_dir: base_dir)}"

                copy_exit = nil
                File.open(copy_log, "w") do |f|
                  pid = Process.spawn({ "HOME" => real_home }, "cp", "-f", local_zip_path, target_zip_path, out: f, err: f)
                  begin
                    Timeout.timeout(copy_timeout_sec) do
                      _pid, status = Process.wait2(pid)
                      copy_exit = status.exitstatus
                    end
                  rescue Timeout::Error
                    begin
                      Process.kill("TERM", pid)
                    rescue StandardError
                    end
                    sleep 2
                    begin
                      Process.kill("KILL", pid)
                    rescue StandardError
                    end
                    copy_exit = 124
                  end
                end

                if copy_exit != 0
                  log "❌ 复制到 SMB 失败 (exit=#{copy_exit}):#{target_zip_path}"
                else
                  target_dir = File.join(final_destination_root, scheme)

                  if File.exist?(target_dir)
                    log "🗑️ 发现旧版本,正在删除..."
                    FileUtils.rm_rf(target_dir)
                  end

                  unzip_log = File.join(logs_dir, "unzip.log")
                  unzip_timeout_sec = (ENV["BB_DOCC_UNZIP_TIMEOUT_SEC"].to_s.strip.empty? ? 600 : ENV["BB_DOCC_UNZIP_TIMEOUT_SEC"].to_i)

                  log "📦 正在解压并部署... (timeout=#{unzip_timeout_sec}s)"
                  log "📄 unzip 日志: #{rel_path(unzip_log, base_dir: base_dir)}"

                  unzip_exit = nil
                  File.open(unzip_log, "w") do |f|
                    Dir.chdir(final_destination_root) do
                      pid = Process.spawn({ "HOME" => real_home }, "unzip", "-q", "-o", remote_zip_name, out: f, err: f)
                      begin
                        Timeout.timeout(unzip_timeout_sec) do
                          _pid, status = Process.wait2(pid)
                          unzip_exit = status.exitstatus
                        end
                      rescue Timeout::Error
                        begin
                          Process.kill("TERM", pid)
                        rescue StandardError
                        end
                        sleep 2
                        begin
                          Process.kill("KILL", pid)
                        rescue StandardError
                        end
                        unzip_exit = 124
                      end
                    end
                  end

                  log "📦 解压结束 (exit=#{unzip_exit})"

                  FileUtils.rm_f(target_zip_path)

                  if unzip_exit == 0
                    target_logs = File.join(target_dir, "docc-logs")
                    FileUtils.mkdir_p(target_logs)
                    sync_dir_contents(logs_dir, target_logs)

                    log "✅ 部署完成: file://#{target_dir.gsub(' ', '%20')}"
                  else
                    log "❌ 解压失败 (exit=#{unzip_exit})"
                  end
                end
              end
            ensure
              FileUtils.rm_rf(lock_dir) if acquired_lock && File.exist?(lock_dir)
            end
          else
            log "❌ 压缩失败,未找到 zip 文件"
          end
        else
          log "❌ 校验失败:在目标目录未找到 server.js"
          log "❌ 目标路径: #{final_destination_root}"
          log "⚠️ 取消同步,生成的静态站点将被删除"
        end
      else
        # ---------------------------------------------------------
        # 失败处理:将日志同步到 Docs/log 目录
        # ---------------------------------------------------------
        log "⚠️ 任务失败或被中断,正在保存错误日志..."
        
        # 确保 log 根目录存在
        global_log_root = File.join(final_destination_root, "log")
        if File.directory?(final_destination_root)
          FileUtils.mkdir_p(global_log_root)
          
          # 创建带时间戳的日志目录: Docs/log/Scheme_20230101_120000
          timestamp = Time.now.strftime("%Y%m%d_%H%M%S")
          fail_log_dir = File.join(global_log_root, "#{scheme}_#{timestamp}")
          FileUtils.mkdir_p(fail_log_dir)
          
          # 同步日志文件
          if File.directory?(logs_dir)
            sync_dir_contents(logs_dir, fail_log_dir)
            log "📄 错误日志已保存至: file://#{fail_log_dir.gsub(' ', '%20')}"
          else
            log "❌ 无法保存日志:本地日志目录不存在"
          end
        else
          log "❌ 无法保存日志:SMB 目标目录不可访问"
        end
      end
    end

    # 强制删除本地临时目录 (_docc_temp)
    # local_work_root 是 _docc_temp/scheme
    # 我们要删除的是 _docc_temp
    temp_root = File.dirname(local_work_root)
    
    if File.exist?(temp_root)
      log "正在清理本地临时目录: file://#{temp_root}"
      FileUtils.rm_rf(temp_root)
      
      if File.exist?(temp_root)
         log "⚠️ 清理失败,目录仍存在: file://#{temp_root}"
      else
         log "🗑️ 已清理本地临时目录"
      end
    end
  end
  
  # 注意:at_exit 是全局的,这里直接调用可能不太合适,最好是 ensure 块
  # 但为了保持逻辑,我们使用 ensure

  begin
    require_cmd!("pod")
    require_cmd!("xcodebuild")
    require_cmd!("xcrun")
    require_cmd!("git")

    lint_log = File.join(logs_dir, "pod-lib-lint.log")
    lint_log_rel = rel_path(lint_log, base_dir: base_dir)
    lint_cmd = [
      "pod", "lib", "lint", podspec_basename,
      "--verbose", "--no-clean", "--skip-tests", "--skip-import-validation",
      "--use-modular-headers", "--use-static-frameworks",
      "--allow-warnings",
      "--sources=#{PODSPEC_REPO}"
    ]

    File.open(status_md, "a") { |f| f.puts "- lint: #{lint_cmd.join(" ")}" }

    log "执行 lint: #{podspec_basename}(cwd=#{rel_path(podspec_dir_abs, base_dir: base_dir)})"
    lint_env = {
      "HOME" => real_home,
      "TMPDIR" => lint_root
    }

    # 移除所有手动注入的 GIT_CONFIG_ 配置,完全依赖用户本地环境的 Git 配置。
    # 仅保留 GIT_TERMINAL_PROMPT=0 以防止在日志重定向模式下进程卡死。
    # 如果用户本地 Keychain 配置正确,Git 会自动读取,无需我们干预。
    
    if ENV["BB_DOCC_ALLOW_PROMPT"] != "1"
      lint_env["GIT_TERMINAL_PROMPT"] = "0"
    end

    lint_exit = run_to_file(lint_cmd, cwd: podspec_dir_abs, env: lint_env, log_path: lint_log)

    File.open(status_md, "a") do |f|
      if lint_exit.zero?
        f.puts "- lint: 成功"
      else
        f.puts "- lint: 失败(exit=#{lint_exit})"
      end
      f.puts
      f.puts "**pod lib lint 日志(尾部)**"
      f.puts "```"
      tail_lines(lint_log, 200).each { |line| f.puts line }
      f.puts "```"
    end

    unless lint_exit.zero?
      File.open(status_md, "a") do |f|
        f.puts "- docbuild: 跳过(lint 失败)"
        f.puts "- export: 跳过(lint 失败)"
      end

      log "lint 失败,跳过 docbuild 与导出"
      log "失败日志: #{lint_log_rel}"
      log "状态汇总: #{rel_path(status_md, base_dir: base_dir)}"

      puts "[docc] -------- pod lib lint 日志(尾部 200 行)--------"
      puts tail_lines(lint_log, 200).join("\n")
      puts "[docc] -------- 关键错误/失败行(尾部 400 行过滤)--------"

      tail_lines(lint_log, 400).each_with_index do |line, idx|
        next unless line.match?(/^\[!\]| error: | ERROR | fatal: |Undefined symbols|Ld /)
        puts "#{idx + 1}:#{line}"
      end

      if safe_read_text(lint_log).include?("Authentication failed for 'https://#{KEYCHAIN_HOST}/")
        puts "[docc] 提示: 检测到 git clone 认证失败(#{KEYCHAIN_HOST})"
        puts "[docc] 处理方式: 确保系统 git 能在终端里无交互 clone 私有仓库(一般用 Token)"
      end

      # Early return instead of exit
      return
    end

    workspace_path_abs = find_workspace_from_lint_log(lint_log, lint_root)
    
    if workspace_path_abs.to_s.strip.empty?
      fail!("未找到 *.xcworkspace(lint_root=#{lint_root_rel})")
    end
    
    workspace_path_rel = rel_path(workspace_path_abs.to_s, base_dir: base_dir)
    fail!("workspace 不存在: #{workspace_path_rel}") unless File.directory?(workspace_path_abs)

    validation_dir_abs = File.dirname(workspace_path_abs)
    File.open(status_md, "a") do |f|
      f.puts "- validation_dir: #{rel_path(validation_dir_abs, base_dir: base_dir)}"
      f.puts "- workspace: #{workspace_path_rel}"
    end

    if deployment_target && !deployment_target.strip.empty?
      changed = bump_deployment_targets_in_validation_dir(validation_dir_abs, deployment_target)
      File.open(status_md, "a") { |f| f.puts "- bumped_deployment_target: #{deployment_target} (changed=#{changed})" }
    end

    exported_source = ""
    dev_pod_dir = File.join(validation_dir_abs, "Pods", "Development Pods", scheme)
    if File.directory?(dev_pod_dir)
      FileUtils.rm_rf(exported_source_root)
      FileUtils.mkdir_p(exported_source_root)
      FileUtils.cp_r(dev_pod_dir, exported_source_root)
      exported_source = File.join(exported_source_root, scheme)
    end

    File.open(status_md, "a") do |f|
      if exported_source.empty?
        f.puts "- exported_source: 未找到(跳过)"
      else
        f.puts "- exported_source: #{rel_path(exported_source, base_dir: base_dir)}"
      end
    end

    derived_dir = File.join(derived_data_root, scheme)
    FileUtils.mkdir_p(derived_dir)
    derived_dir_rel = rel_path(derived_dir, base_dir: base_dir)

    docbuild_log = File.join(logs_dir, "xcodebuild-docbuild.log")

    workspace_for_docbuild = rel_path(workspace_path_abs, base_dir: podspec_dir_abs)
    derived_dir_for_docbuild = rel_path(derived_dir, base_dir: podspec_dir_abs)
    docbuild_cmd = [
      "xcodebuild", "docbuild",
      "-workspace", workspace_for_docbuild,
      "-scheme", scheme,
      "-destination", DESTINATION,
      "-configuration", CONFIGURATION,
      "-derivedDataPath", derived_dir_for_docbuild
    ]
    if deployment_target && !deployment_target.strip.empty?
      docbuild_cmd << "IPHONEOS_DEPLOYMENT_TARGET=#{deployment_target}"
      docbuild_cmd << "SWIFT_VERSION=5.0"
    end
    docbuild_cmd += ["CODE_SIGNING_ALLOWED=NO", "CODE_SIGNING_REQUIRED=NO", "CODE_SIGN_IDENTITY="]

    docbuild_cmd_report = docbuild_cmd.dup
    docbuild_cmd_report[docbuild_cmd_report.index(workspace_for_docbuild) || 0] = workspace_path_rel
    docbuild_cmd_report[docbuild_cmd_report.index(derived_dir_for_docbuild) || 0] = derived_dir_rel
    File.open(status_md, "a") { |f| f.puts "- docbuild: #{docbuild_cmd_report.join(" ")}" }

    log "执行 docbuild: #{scheme}"
    docbuild_exit = run_to_file(docbuild_cmd, cwd: podspec_dir_abs, env: { "HOME" => real_home }, log_path: docbuild_log)

    unless docbuild_exit.zero?
      File.open(status_md, "a") do |f|
        f.puts "- docbuild: 失败(exit=#{docbuild_exit})"
        f.puts
        f.puts "**xcodebuild 日志(尾部)**"
        f.puts "```"
        tail_lines(docbuild_log, 200).each { |line| f.puts line }
        f.puts "```"
      end
      fail!("docbuild 失败")
    end

    File.open(status_md, "a") { |f| f.puts "- docbuild: 成功" }

    archives = []
    Find.find(derived_dir) do |p|
      next unless File.directory?(p)
      next unless p.end_with?(".doccarchive")
      archives << p
      Find.prune
    end

    doccarchive_path =
      archives
        .select { |p| File.directory?(p) }
        .sort_by { |p| File.mtime(p) }
        .reverse
        .find { |p| File.basename(p) == "#{scheme}.doccarchive" } || archives.max_by { |p| File.mtime(p) }

    fail!("未找到 .doccarchive(derivedData=#{derived_dir_rel})") if doccarchive_path.to_s.strip.empty?

    doccarchive_rel = rel_path(doccarchive_path, base_dir: base_dir)
    File.open(status_md, "a") { |f| f.puts "- doccarchive: #{doccarchive_rel}" }

    site_out = component_dir_abs
    FileUtils.mkdir_p(site_out)

    export_log = File.join(logs_dir, "docc-transform.log")

    doccarchive_for_export = rel_path(doccarchive_path, base_dir: podspec_dir_abs)
    export_staging_dir = File.join(derived_data_root, ".docc-site", scheme)
    FileUtils.rm_rf(export_staging_dir)
    FileUtils.mkdir_p(export_staging_dir)
    site_out_for_export = rel_path(export_staging_dir, base_dir: podspec_dir_abs)
    export_cmd = [
      "xcrun", "docc", "process-archive", "transform-for-static-hosting",
      doccarchive_for_export,
      "--output-path", site_out_for_export,
      "--hosting-base-path", hosting_base_path
    ]

    export_cmd_report = export_cmd.dup
    export_cmd_report[export_cmd_report.index(doccarchive_for_export) || 0] = doccarchive_rel
    export_cmd_report[export_cmd_report.index(site_out_for_export) || 0] = rel_path(site_out, base_dir: base_dir)
    File.open(status_md, "a") { |f| f.puts "- export: #{export_cmd_report.join(" ")}" }

    log "导出静态站点: #{component_dir_rel}"
    export_exit = run_to_file(export_cmd, cwd: podspec_dir_abs, env: { "HOME" => real_home }, log_path: export_log)
    unless export_exit.zero?
      warn tail_lines(export_log, 200).join("\n")
      fail!("docc 导出失败")
    end

    sync_dir_contents(export_staging_dir, site_out)

    log "本地生成完成: file://#{component_dir_abs.gsub(' ', '%20')}"
    is_success = true

    staging_dir = File.join(local_work_root, scheme)
    FileUtils.rm_rf(staging_dir)
    FileUtils.mv(local_site_output, staging_dir)

    zip_name = "#{scheme}_#{Time.now.strftime("%Y%m%d_%H%M%S")}_#{Process.pid}.zip"
    local_zip_path = File.join(local_work_root, zip_name)

    zip_log = File.join(logs_dir, "zip.log")
    zip_timeout_sec = (ENV["BB_DOCC_ZIP_TIMEOUT_SEC"].to_s.strip.empty? ? 1800 : ENV["BB_DOCC_ZIP_TIMEOUT_SEC"].to_i)

    log "📦 正在压缩产物 (zip)... (timeout=#{zip_timeout_sec}s)"
    log "📄 zip 日志: #{rel_path(zip_log, base_dir: base_dir)}"

    zip_exit = nil
    FileUtils.mkdir_p(File.dirname(zip_log))
    File.open(zip_log, "w") do |f|
      Dir.chdir(local_work_root) do
        pid = Process.spawn({ "HOME" => real_home }, "zip", "-r", "-q", zip_name, scheme, out: f, err: f)
        begin
          Timeout.timeout(zip_timeout_sec) do
            _pid, status = Process.wait2(pid)
            zip_exit = status.exitstatus
          end
        rescue Timeout::Error
          begin
            Process.kill("TERM", pid)
          rescue StandardError
          end
          sleep 2
          begin
            Process.kill("KILL", pid)
          rescue StandardError
          end
          zip_exit = 124
        end
      end
    end

    log "📦 压缩结束 (exit=#{zip_exit})"
    fail!("压缩失败,未找到 zip 文件") unless zip_exit == 0 && File.exist?(local_zip_path)

    zip_rel_path_in_repo = File.join(zip_push_subdir, scheme, zip_name)
    git_log = File.join(logs_dir, "git-push.log")
    git_timeout_sec = (ENV["BB_DOCC_GIT_TIMEOUT_SEC"].to_s.strip.empty? ? 600 : ENV["BB_DOCC_GIT_TIMEOUT_SEC"].to_i)

    git_env = { "HOME" => real_home }
    git_env["GIT_TERMINAL_PROMPT"] = "0" if ENV["BB_DOCC_ALLOW_PROMPT"].to_s.strip != "1"

    log "🚚 正在推送 zip 到 Git: #{redact_git_url(zip_push_repo)} (branch=#{zip_push_branch})"
    log "📄 git 日志: #{rel_path(git_log, base_dir: base_dir)}"

    git_exit = push_zip_to_git(
      repo_url: zip_push_repo,
      branch: zip_push_branch,
      scheme: scheme,
      zip_path: local_zip_path,
      zip_rel_path_in_repo: zip_rel_path_in_repo,
      log_path: git_log,
      env: git_env,
      timeout_sec: git_timeout_sec
    )
    fail!("推送 zip 失败(exit=#{git_exit})") unless git_exit.zero?

  ensure
    at_exit_block.call
  end
end