Module: AnnFlavorCocoapods::PodfileHelper

Defined in:
lib/ann_flavor_cocoapods/podfile_helper.rb

Class Method Summary collapse

Class Method Details

.assert_icon_generated!(user_project, flavor_key, icon_name) ⇒ Object

Fails pod install loudly for a flavor whose .appiconset directory hasn't been generated yet, instead of silently shipping a build with no app icon. ASSETCATALOG_COMPILER_APPICON_NAME is set unconditionally by sync (ios_generator.dart) before "Generate App Icons" has necessarily ever run for that flavor — without this check, Xcode just can't find the named appiconset at build time and ships a blank/default icon with no error anywhere in the pipeline. project_dir is the .xcodeproj's own containing directory (ios/), matching the SRCROOT-relative paths used everywhere else in this method's caller.



546
547
548
549
550
551
552
553
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 546

def self.assert_icon_generated!(user_project, flavor_key, icon_name)
  appiconset_dir = File.join(user_project.project_dir.to_s, 'ann', 'Assets.xcassets', "#{icon_name}.appiconset")
  return if Dir.exist?(appiconset_dir)

  raise "[ann-flavor-cocoapods] Missing app icon for flavor '#{flavor_key}': " \
    "#{appiconset_dir} does not exist. Run \"Generate App Icons\" (Studio) or " \
    "the equivalent icon-generation step for this flavor before running pod install."
end

.assert_swift_version(target, swift_version) ⇒ Object



231
232
233
234
235
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 231

def self.assert_swift_version(target, swift_version)
  target.build_configuration_list.build_configurations.each do |config|
    config.build_settings['SWIFT_VERSION'] = swift_version
  end
end

.build_type_keys(flavor) ⇒ Object

Build types to generate configurations for: always debug + release (matching ios_generator.dart's _generateXcconfigs union logic exactly, not the core's STANDARD_BUILD_TYPES, which unconditionally includes profile) plus any custom build_types configured on this flavor or the platform default.



503
504
505
506
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 503

def self.build_type_keys(flavor)
  keys = %w[debug release] + flavor.build_types.keys
  keys.uniq
end

.bundle_id_for_build_type(flavor_key, build_type, project_root: nil) ⇒ Object

Returns the bundle ID for a given flavor key and build type (e.g. "debug"), applying build_types.id_suffix from either flavor or default. An unknown flavor key falls back to the unsuffixed default id (matches pre-delegation behavior — this method never raises for a missing flavor).



309
310
311
312
313
314
315
316
317
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 309

def self.bundle_id_for_build_type(flavor_key, build_type, project_root: nil)
  project_root ||= File.dirname(SpecLoader.find_spec_file(Dir.pwd) ||
    raise("annspec.yaml not found (searched upward from #{Dir.pwd})"))
  spec = load_core_spec(project_root)
  ios  = spec.app&.ios
  return '' if ios.nil?

  AnnFlavorCore::IosResolution.bundle_id(ios, flavor_key, build_type)
end

.configure_build_configuration(target, user_project, xcode_config, xcconfig_path, info_plist_path, icon_name) ⇒ Object



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
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 589

def self.configure_build_configuration(target, user_project, xcode_config, xcconfig_path, info_plist_path, icon_name)
  config_list = target.build_configuration_list
  config = config_list[xcode_config]

  unless config
    config = user_project.new(Xcodeproj::Project::Object::XCBuildConfiguration)
    config.name = xcode_config
    # Copy an existing target-level config's settings as a starting point,
    # but strip the product-identity keys this method sets below via the
    # xcconfig include — a literal key in this configuration's OWN
    # buildSettings dict always wins over anything pulled in via
    # baseConfigurationReference, so copying Flutter's own stock
    # PRODUCT_BUNDLE_IDENTIFIER placeholder here (present on the "Debug"
    # config `flutter create` generates) would silently shadow the
    # per-flavor xcconfig value at actual `xcodebuild` time, no matter
    # what the xcconfig itself says (found via STEP-2.11 real-project
    # verification).
    source_settings = config_list.build_configurations.first&.build_settings || {}
    config.build_settings = source_settings.reject { |k, _| PROJECT_LEVEL_EXCLUDED_KEYS.include?(k) }
    config_list.build_configurations << config
  end

  xcconfig_ref = user_project.files.find { |f| f.path == xcconfig_path } ||
    user_project.main_group.new_reference(xcconfig_path)
  config.base_configuration_reference = xcconfig_ref

  config.build_settings['INFOPLIST_FILE'] = info_plist_path
  config.build_settings['ASSETCATALOG_COMPILER_APPICON_NAME'] = icon_name
  # flutter create's own stock Debug/Release configs never set
  # MARKETING_VERSION at all (confirmed against a real project) --
  # CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)" is present on the
  # stock template and so gets copied forward via source_settings above,
  # but there was never an equivalent MARKETING_VERSION bridge to copy.
  # Without this, $MARKETING_VERSION (and therefore
  # CFBundleShortVersionString, App Store Connect's displayed version,
  # and this tooling's own [ann-flavor] Print Build Info line) resolves
  # empty on every per-flavor configuration.
  config.build_settings['MARKETING_VERSION'] = '$(FLUTTER_BUILD_NAME)'

  project_config_list = user_project.root_object.build_configuration_list
  unless project_config_list[xcode_config]
    project_config = user_project.new(Xcodeproj::Project::Object::XCBuildConfiguration)
    project_config.name = xcode_config
    source_settings = project_config_list.build_configurations.first&.build_settings || {}
    project_config.build_settings = source_settings.reject { |k, _| PROJECT_LEVEL_EXCLUDED_KEYS.include?(k) }
    project_config_list.build_configurations << project_config
  end
end

.configure_build_settings(installer, project_root: nil) ⇒ Object

Call inside your Podfile's post_integrate hook, alongside configure_firebase, to create/update the per-flavor Xcode build configurations, scheme, and asset-catalog wiring that the ios/ann/ generated files (xcconfig, Info.plist, Assets.xcassets) depend on. Closes the previously-silent, undocumented manual Xcode step (Project → Info → Configurations → duplicate/rename/assign xcconfig) that every prior consumer had to discover on their own — see plan 035 (docs/03-planning/features/035-ios-flavor-architecture-redesign.md).

Example Podfile usage:

post_integrate do |installer|
AnnFlavorCocoapods::PodfileHelper.configure_firebase(installer)
AnnFlavorCocoapods::PodfileHelper.configure_build_settings(installer)
end

For each flavor x release (plus any custom build_types — the same union logic ios_generator.dart uses for xcconfig file generation):

1. Find-or-create an XCBuildConfiguration named "<BuildType>-<flavor>" on
 the app target.
2. Point baseConfigurationReference at ios/ann/xcconfig/<Flavor><BuildType>.xcconfig.
3. Set INFOPLIST_FILE to ios/ann/Info/Info-<flavor>.plist.
4. Find-or-create the ios/ann/Assets.xcassets catalog reference (once,
 shared across flavors) and set ASSETCATALOG_COMPILER_APPICON_NAME.
5. Find-or-create the flavor's .xcscheme, merge-if-exists (only the
 buildConfiguration= references are touched, preserving any manually
 added scheme content).
6. Inject the "[ann-flavor] Print Build Info" pre-build phase (first in
 the build-phase list), gated by debug.print_build_and_flavor_info.

All steps are idempotent by construction (find-or-create by name) — no drift between "missing" and "wrong value" the way an additive-only patch or a blind overwrite would have.



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
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 136

def self.configure_build_settings(installer, project_root: nil)
  project_root ||= File.dirname(SpecLoader.find_spec_file(Dir.pwd) ||
    raise("annspec.yaml not found (searched upward from #{Dir.pwd})"))
  spec = load_core_spec(project_root)

  ios = spec.app&.ios
  return if ios.nil?
  return if ios.flavors.empty?
  return if installer.nil?

  print_build_info = spec.debug_config.nil? || spec.debug_config.print_build_and_flavor_info != false
  swift_version = ios.default.sdk&.swift_version

  touched_projects = []

  installer.aggregate_targets.each do |aggregate_target|
    user_project = aggregate_target.user_project
    next if user_project.nil?

    user_project.native_targets.each do |target|
      if target.symbol_type == :application
        find_or_create_icon_catalog(target, user_project)

        ios.flavors.each_key do |flavor_key|
          flavor = ios.flavors[flavor_key]

          build_type_keys(flavor).each do |bt|
            xcode_config = "#{bt.capitalize}-#{flavor_key}"
            # Relative to SRCROOT/PROJECT_DIR, which xcodebuild resolves as
            # the .xcodeproj's own containing directory (ios/), NOT the
            # Flutter project root -- confirmed via `xcodebuild
            # -showBuildSettings`'s own SRCROOT value (found via STEP-2.11
            # real-project verification: with a leading "ios/" prefix here,
            # both paths silently resolved to the doubled, nonexistent
            # ios/ios/ann/... and Xcode read neither the xcconfig's values
            # nor the per-flavor Info.plist, with no error at pod install
            # OR build time -- showBuildSettings even echoes the literal
            # unresolved INFOPLIST_FILE string back, so it looked correct
            # until checked against what the xcconfig #include actually
            # applied).
            xcconfig_path = "ann/xcconfig/#{flavor_key}#{bt.capitalize}.xcconfig"
            info_plist_path = "ann/Info/Info-#{flavor_key}.plist"
            icon_name = "#{flavor_key.capitalize}AppIcon"

            assert_icon_generated!(user_project, flavor_key, icon_name)

            configure_build_configuration(
              target, user_project, xcode_config, xcconfig_path, info_plist_path,
              icon_name
            )
          end

          configure_scheme(target, user_project, flavor_key)
        end

        if print_build_info
          inject_build_info_phase(target)
        end
      end

      # Fixes a real pod-install failure: PBXNativeTarget#resolved_build_setting
      # checks a target against EVERY configuration name that exists
      # anywhere in the project (its own configs AND every project-level
      # config name), not just the target's own list -- a name the target
      # has no configuration for resolves to nil rather than being
      # skipped. Runner gets Debug-<flavor>/Release-<flavor> configs (via
      # configure_build_configuration above and the project-level mirror
      # it creates), but this plugin never gave RunnerTests (or any other
      # non-application target) equivalent per-flavor configs -- so for
      # every flavor name, RunnerTests resolves SWIFT_VERSION to nil while
      # Runner resolves to a real value, and CocoaPods rejects the project
      # ("There may only be up to 1 unique SWIFT_VERSION per target").
      # Confirmed directly against a real project: `target
      # .resolved_build_setting('SWIFT_VERSION', true)` returned
      # {"Debug"=>"5.0", ..., "Debug-ledger_in"=>nil, ...} for RunnerTests,
      # even though its own Debug/Release/Profile configs already had an
      # explicit, consistent SWIFT_VERSION.
      #
      # The fix mirrors every project-level configuration name onto this
      # target too (not just :application), each an explicit-SWIFT_VERSION
      # config with no other build settings and no xcconfig -- these
      # names only need to exist and resolve consistently, not carry any
      # of Runner's per-flavor app-identity settings.
      if swift_version
        assert_swift_version(target, swift_version)
        mirror_project_configuration_names(target, user_project, swift_version)
      end

      touched_projects << user_project unless touched_projects.include?(user_project)
    end
  end

  touched_projects.each { |p| save_if_changed(p) }
end

.configure_firebase(installer, project_root: nil) ⇒ Object

Call inside your Podfile's post_integrate hook to wire per-flavor Firebase GoogleService-Info.plist into the Xcode build. Must be post_integrate, not post_install (DEF-061, #61): post_install fires before CocoaPods has integrated/saved the user's app project, so build phases injected there never reach the real app target's build graph — only post_integrate runs after the app project has been integrated and saved.

Example Podfile usage:

require 'ann_flavor_cocoapods'
post_integrate do |installer|
AnnFlavorCocoapods::PodfileHelper.configure_firebase(installer)
end

For each iOS flavor that has config_file set, this injects a pre-build shell script phase into the app target (identified by product type, not a hardcoded name) in the real user Xcode project (Runner.xcodeproj, not CocoaPods' generated Pods.xcodeproj) that copies the correct plist to $SRCROOT/Runner/GoogleService-Info.plist at build time, overwriting whatever was there before.

Deliberately does NOT delete the copied plist after the build (a prior design did, as a post-build phase) — that combination is unsafe: the pre-build phase declares GoogleService-Info.plist as its output_paths (required so Xcode's build system knows the script produces the file, rather than failing Copy Bundle Resources with "Build input file cannot be found" before any script has run), but Xcode's incremental build system can then skip re-running the pre-build script on a later build once it considers that declared output already satisfied — while a post-build phase had already deleted it at the end of the prior build, permanently leaving Runner/GoogleService-Info.plist (and therefore the shipped .app) without a Firebase config for the next incremental build. ios/Runner/GoogleService-Info.plist is gitignored, so leaving the last-built flavor's copy on disk between builds is safe — it is always overwritten fresh by the pre-build phase before the next real build.

Gate: only runs when integrations.firebase is true in annspec.yaml.



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
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 45

def self.configure_firebase(installer, project_root: nil)
  project_root ||= File.dirname(SpecLoader.find_spec_file(Dir.pwd) ||
    raise("annspec.yaml not found (searched upward from #{Dir.pwd})"))
  spec = load_core_spec(project_root)

  # integrations.firebase must be explicitly enabled (REQ-FIRE-00010).
  return unless spec.app&.integrations&.firebase == true

  ios = spec.app&.ios
  return if ios.nil?

  layout = detect_project_layout(project_root)

  # Build a map: configuration_name → config_file path.
  # Xcode configuration names are capitalized: Release-<flavor>, Debug-<flavor>.
  config_map = {}
  ios.flavors.each_key do |flavor_key|
    AnnFlavorCore::Resolver::STANDARD_BUILD_TYPES.each do |bt|
      fb_file = AnnFlavorCore::IosResolution.firebase_config_path(
        ios, flavor_key, bt, generated_dir: layout[:generated_dir]
      )
      next unless fb_file

      # Map Xcode config name (e.g. "Release-ledger_in") → plist path
      xcode_config = "#{bt.capitalize}-#{flavor_key}"
      config_map[xcode_config] = fb_file

      warn_if_static_plist(project_root, xcode_config, fb_file)
    end
  end

  return if config_map.empty?
  return if installer.nil?

  inject_build_phases(installer, project_root, config_map)
end

.configure_scheme(target, user_project, flavor_key) ⇒ Object

Find-or-create the flavor's .xcscheme at the fixed Xcode-mandated path, merge-if-exists: only the buildConfiguration= references this tooling owns are (re)set, leaving any manually-added scheme content (env vars, launch arguments, test configuration) untouched — unlike the prior Studio/Kotlin generator, which blindly overwrote the whole file on every run.

Idempotent by construction: Xcodeproj's configure_with_targets always APPENDS a fresh BuildActionEntry/testable/launch-runnable rather than checking whether an equivalent one already exists (confirmed against a real project: 16 duplicate BuildActionEntry blocks, all pointing at the same Runner target, after repeated pod install / Upgrade runs). Skip calling it at all when the scheme's build action already has an entry for this target, and skip writing the file entirely when the fully rebuilt scheme content is byte-identical to what's already on disk — so a pod install with no real change produces no file write and no git diff, not just no visible duplication.

Schemes are consulted only by Xcode's GUI scheme picker; the CLI/CI build path (flutter build ipa --flavor X) invokes xcodebuild -configuration directly and never reads scheme files at all — this step exists purely for developer ergonomics, not build correctness.



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 659

def self.configure_scheme(target, user_project, flavor_key)
  project_path = user_project.path.to_s
  scheme_path = Xcodeproj::XCScheme.shared_data_dir(project_path) + "#{flavor_key}.xcscheme"
  existing_content = File.exist?(scheme_path.to_s) ? File.read(scheme_path.to_s) : nil

  scheme = existing_content ? Xcodeproj::XCScheme.new(scheme_path.to_s) : Xcodeproj::XCScheme.new

  already_has_target = (scheme.build_action.entries || []).any? do |entry|
    entry.buildable_references.any? { |ref| ref.target_uuid == target.uuid }
  end
  scheme.configure_with_targets(target, nil, launch_target: true) unless already_has_target

  scheme.test_action.build_configuration    = "Debug-#{flavor_key}"
  scheme.launch_action.build_configuration  = "Debug-#{flavor_key}"
  scheme.profile_action.build_configuration = "Release-#{flavor_key}"
  scheme.analyze_action.build_configuration = "Debug-#{flavor_key}"
  scheme.archive_action.build_configuration = "Release-#{flavor_key}"

  return if scheme.to_s == existing_content

  scheme.save_as(project_path, flavor_key)
end

.detect_project_layout(project_root) ⇒ Object

Detects whether project_root is a Flutter project (has pubspec.yaml, so generated Firebase files live under lib/generated/firebase/) or a plain iOS-only Xcode project with no Flutter wrapper (no pubspec.yaml — ios/ itself is the effective root, so generated Firebase files live under ios/generated/firebase/ instead, since there is no lib/ to nest under). Either way, the returned generated_dir is relative to project_root, and for the real Runner target $SRCROOT is always <project_root>/ios — one level below project_root — so inject_build_phases always needs exactly one ".." hop to reach it, regardless of layout.

Resolved once here, at pod install time, rather than probed for at build time inside the generated shell script — a runtime "try here, then try one level up" fallback would mask a genuinely wrong layout instead of surfacing it, exactly the failure mode already fixed once in this file (DEF-061, #61 and the 0.1.22/0.1.23 stale-path bugs).



97
98
99
100
101
102
103
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 97

def self.detect_project_layout(project_root)
  if File.exist?(File.join(project_root, 'pubspec.yaml'))
    { generated_dir: 'lib/generated/firebase' }
  else
    { generated_dir: 'ios/generated/firebase' }
  end
end

.ensure_plist_in_resources(target, user_project) ⇒ Object

Find-or-create a file reference for Runner/GoogleService-Info.plist and add it to the target's Resources build phase (Copy Bundle Resources), so the file the pre-build script copies onto disk actually gets packaged into the built .app — a reference-only membership check (idempotent, no duplicate entries across repeated pod install runs).



488
489
490
491
492
493
494
495
496
497
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 488

def self.ensure_plist_in_resources(target, user_project)
  runner_group = user_project.main_group.find_subpath('Runner', false)
  return if runner_group.nil?

  existing = runner_group.children.find { |c| c.path == 'GoogleService-Info.plist' }
  ref = existing || runner_group.new_reference('GoogleService-Info.plist')
  ref.last_known_file_type = 'text.plist.xml'

  target.resources_build_phase.add_file_reference(ref, true)
end

.find_or_create_icon_catalog(target, user_project) ⇒ Object

Find-or-create the ios/ann/Assets.xcassets catalog's own file reference, added once to the target's Resources build phase and shared across every flavor — only the per-flavor .appiconset contents inside it vary (wired via ASSETCATALOG_COMPILER_APPICON_NAME on each build configuration, not by the file reference itself).



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 513

def self.find_or_create_icon_catalog(target, user_project)
  group = user_project.main_group.find_subpath('ann', true)
  # find_subpath('ann', true) creates the group via Xcodeproj's new_group('ann')
  # when it doesn't already exist -- that only sets the group's NAME, never its
  # PATH. A <group>-sourceTree PBXGroup with a name but no path contributes
  # nothing to its children's resolved filesystem path, so the Assets.xcassets
  # reference below silently resolved to ios/Assets.xcassets instead of
  # ios/ann/Assets.xcassets -- the actual generated catalog's real location
  # (ios_icon_generator.dart writes to ios/ann/Assets.xcassets/). Xcode then
  # can't find the per-flavor .appiconset at build time, even though the files
  # are correctly on disk. Setting the path explicitly (idempotent -- a no-op
  # once already set) fixes the resolved location without touching the group's
  # display name.
  group.set_path('ann') if group.path.nil?
  existing = group.children.find { |c| c.path == 'Assets.xcassets' }

  ref = existing || group.new_reference('Assets.xcassets')
  ref.last_known_file_type = 'folder.assetcatalog'

  target.resources_build_phase.add_file_reference(ref, true)

  ref
end

.inject_build_info_phase(target) ⇒ Object

Injects a pre-build phase that prints resolved build/flavor info before any compilation step — iOS parity with Android's PreBuildProcessingTask (plugins/ann-flavor-gradle/.../tasks/PreBuildProcessing.kt). Positioned first in the build-phase list so it fires ahead of the Firebase-copy phase too.

Unlike Android's task, which re-resolves the cascade in Kotlin at Gradle-task-execution time, this reads already-resolved Xcode build-setting environment variables — by the time this phase runs, Xcode has already selected the Debug-/Release- configuration and its xcconfig, so no re-parsing of annspec.yaml is needed here.



692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 692

def self.inject_build_info_phase(target)
  script = <<~SHELL
    # Injected by ann-flavor-cocoapods: print build info
    # $CONFIGURATION is "<BuildType>-<flavor>" (e.g. "Debug-ledger_in") for
    # a flavor build -- split it so the flavor key has its own labeled line
    # instead of only appearing embedded inside Build Type.
    #
    # Plain ASCII markers only, deliberately -- Nanaimo (Xcodeproj's
    # pbxproj serializer) has a real nondeterminism for non-ASCII bytes in
    # shell_script content: the same emoji can be written as raw UTF-8
    # bytes or as a \\u{...} escape depending on the object's history
    # (confirmed via a real byte-level diff across two otherwise-identical
    # configure_build_settings runs), which defeats save_if_changed's
    # byte comparison even though both forms are semantically identical.
    FLAVOR_NAME="${CONFIGURATION#*-}"
    if [ "$FLAVOR_NAME" = "$CONFIGURATION" ]; then
      FLAVOR_NAME="(none)"
    fi
    BUILD_INFO=$(cat <<EOF
    == Build Information ==
    \t- Build Type:    $CONFIGURATION
    \t- Flavor:        $FLAVOR_NAME
    \t- App Name:      $APP_NAME
    \t- App ID:        $PRODUCT_BUNDLE_IDENTIFIER
    \t- Version Name:  $MARKETING_VERSION
    \t- Version Code:  $CURRENT_PROJECT_VERSION
    EOF
    )
    echo "$BUILD_INFO"
    # Also written to build_info.log so it's readable without Xcode's own
    # build log or `flutter run -v` -- e.g. `tail -f ios/build_info.log`
    # in a separate terminal while `flutter run` is going. Overwritten
    # fresh on every build, one level below $SRCROOT (ios/), so it always
    # reflects the most recently built flavor.
    echo "$BUILD_INFO" > "${SRCROOT}/build_info.log"
  SHELL

  # Find-or-update in place, rather than delete+recreate: even with a
  # correct delete via ObjectList#delete (no growing orphan count), a
  # fresh PBXShellScriptBuildPhase gets a fresh UUID every time, which
  # alone makes project.pbxproj non-idempotent — every pod install would
  # still produce a different file (and git diff) despite the phase's
  # actual content never changing. Reusing the existing object when found
  # keeps its UUID stable across runs with no real change.
  existing = target.build_phases.find { |p| p.respond_to?(:name) && p.name == '[ann-flavor] Print Build Info' }
  phase = existing || target.project.new(Xcodeproj::Project::Object::PBXShellScriptBuildPhase)
  phase.name = '[ann-flavor] Print Build Info'
  phase.shell_path = '/bin/sh'
  phase.shell_script = script
  phase.show_env_vars_in_log = '0'

  unless existing
    target.build_phases.unshift(phase)
  end
end

.inject_build_phases(installer, project_root, config_map) ⇒ Object

Injects a pre-build shell script phase into the real app target (identified by product type) inside the user's own Xcode project — NOT installer.pods_project (CocoaPods' generated Pods.xcodeproj, whose Pods-Runner aggregate target only builds pod dependencies and can never satisfy the app target's own build graph — DEF-061, #61).



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
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 369

def self.inject_build_phases(installer, project_root, config_map)
  # Build the per-config shell that selects the right source file.
  # Uses a case statement keyed on $CONFIGURATION (Xcode build setting).
  # plist_path is always relative to project_root (either
  # lib/generated/firebase/... for a Flutter project, or
  # ios/generated/firebase/... for an iOS-only project — see
  # detect_project_layout); for the real Runner target (fixed by
  # DEF-061, #61) $SRCROOT is <project_root>/ios, one level below
  # project_root regardless of layout — a single ".." reaches it in both
  # cases. (The old ".." x2 was seemingly sized for Pods-Runner's
  # $SRCROOT, one level deeper still inside CocoaPods' generated
  # Pods.xcodeproj, but that build phase never actually ran there either,
  # so this was never previously exercised.)
  case_body = config_map.map do |xcode_config, plist_path|
    "  #{xcode_config}) SRC_PLIST=\"${SRCROOT}/../#{plist_path}\" ;;"
  end.join("\n")

  pre_build_script = <<~SHELL
    # Injected by ann-flavor-cocoapods: copy per-flavor GoogleService-Info.plist
    case "$CONFIGURATION" in
    #{case_body}
      *) echo "ann-flavor-cocoapods: no Firebase plist for $CONFIGURATION"; exit 0 ;;
    esac
    DEST="${SRCROOT}/Runner/GoogleService-Info.plist"
    if [ ! -f "$SRC_PLIST" ]; then
      MSG="ann-flavor-cocoapods ERROR: Firebase plist not found: $SRC_PLIST"
      echo "$MSG"
      echo "$MSG" >> "${SRCROOT}/build_info.log"
      exit 1
    fi
    cp "$SRC_PLIST" "$DEST"
    MSG="ann-flavor-cocoapods: copied $SRC_PLIST -> $DEST"
    echo "$MSG"
    # Appended (not overwritten) — [ann-flavor] Print Build Info's phase
    # overwrites build_info.log with $BUILD_INFO earlier in the same
    # build, so this line adds to that, rather than replacing it.
    echo "$MSG" >> "${SRCROOT}/build_info.log"
  SHELL

  # aggregate_targets are the Podfile's own `target 'Runner' do ... end`
  # definitions; each carries a user_project pointing at the real
  # Runner.xcodeproj (not installer.pods_project).
  touched_projects = []

  installer.aggregate_targets.each do |aggregate_target|
    user_project = aggregate_target.user_project
    next if user_project.nil?

    user_project.native_targets.each do |target|
      # Robust across differently-named projects/targets — an app target's
      # product type, not a hardcoded "Runner"/"Pods-Runner" name.
      next unless target.symbol_type == :application

      # Remove any previously-injected phases before re-adding fresh ones.
      # A presence-only check here (skip if a phase with our marker already
      # exists) would leave a stale script baked into project.pbxproj forever
      # once injected once — pod install does not re-read the gem's current
      # script content into an existing phase, so upgrading the gem alone
      # would never fix an already-injected, now-outdated shell_script.
      #
      # Real bug: Array#reject! only drops the phase from target.build_phases
      # (an ObjectList) -- the PBXShellScriptBuildPhase object itself stays
      # registered in the project's global objects table (objects_by_uuid)
      # forever unless removed via ObjectList#delete (which reference-counts
      # and fully unregisters once nothing else points to it), leaving one
      # more orphaned, unreferenced build-phase object baked into
      # project.pbxproj after every single pod install (confirmed via a
      # real object-count diff across two consecutive runs with zero
      # actual config change).
      # A stale "[ann-flavor] Remove Firebase plist" phase (injected by a
      # gem version prior to 0.1.35's fix) is always cleaned up via
      # ObjectList#delete -- see the identical note on inject_build_info_phase
      # for why plain Array#reject! alone would leave it as a permanent
      # orphan in project.pbxproj.
      target.build_phases.select do |p|
        p.respond_to?(:name) && p.name == '[ann-flavor] Remove Firebase plist'
      end.each { |p| target.build_phases.delete(p) }

      # Find-or-update the copy phase in place, rather than delete+recreate
      # -- see the identical note on inject_build_info_phase for why a
      # fresh UUID every run alone makes project.pbxproj non-idempotent.
      existing_pre = target.build_phases.find { |p| p.respond_to?(:name) && p.name == '[ann-flavor] Copy Firebase plist' }
      pre = existing_pre || target.project.new(Xcodeproj::Project::Object::PBXShellScriptBuildPhase)
      pre.name             = '[ann-flavor] Copy Firebase plist'
      pre.shell_path       = '/bin/sh'
      pre.shell_script     = pre_build_script
      pre.show_env_vars_in_log = '0'
      # Declaring the destination as an output file tells Xcode's build system
      # that this script produces the plist — suppresses the "input file not found"
      # error that fires when the plist is referenced in Copy Bundle Resources.
      pre.output_paths     = ['$(SRCROOT)/Runner/GoogleService-Info.plist']
      target.build_phases.unshift(pre) unless existing_pre

      # Real bug: the plist was copied into Runner/ on disk by the script
      # above, but never added as a Copy Bundle Resources member — nothing
      # actually packaged it into the built .app, so native Firebase found
      # no GoogleService-Info.plist in the bundle at runtime despite the
      # file existing correctly in the source tree the whole time.
      ensure_plist_in_resources(target, user_project)

      touched_projects << user_project unless touched_projects.include?(user_project)

      puts "ann-flavor-cocoapods: injected Firebase build phase into #{target.name} " \
           "(#{config_map.size} configuration(s))"
    end
  end

  # post_integrate runs after CocoaPods' own save pass for the user project
  # (UserProjectIntegrator#integrate! already saved it before this hook
  # fires) — no later save happens automatically, so these changes are
  # silently lost unless saved explicitly here.
  touched_projects.each { |p| save_if_changed(p) }
end

.load_core_spec(project_root) ⇒ Object

Parses annspec.yaml through the shared core (ADR-008) — the single source of truth for parsing, cascade merging, and resolution.



321
322
323
324
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 321

def self.load_core_spec(project_root)
  path = File.join(project_root, SpecLoader::SPEC_FILE)
  AnnFlavorCore::Parser.parse_file(path)
end

.mirror_project_configuration_names(target, user_project, swift_version) ⇒ Object

Creates a bare XCBuildConfiguration on target, named after every project-level configuration name it doesn't already have one for, with only SWIFT_VERSION set. See the call site's comment for why this is necessary -- PBXNativeTarget#resolved_build_setting resolves every target against every project-level configuration name, and a target with no configuration for a given name resolves to nil there rather than being skipped, which is indistinguishable from a real conflicting value to CocoaPods' single-unique-SWIFT_VERSION-per-target check.

Idempotent -- find-or-create by name, like configure_build_configuration.



247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 247

def self.mirror_project_configuration_names(target, user_project, swift_version)
  project_config_names = user_project.root_object.build_configuration_list
    .build_configurations.map(&:name)
  target_config_list = target.build_configuration_list

  project_config_names.each do |name|
    next if target_config_list[name]

    config = user_project.new(Xcodeproj::Project::Object::XCBuildConfiguration)
    config.name = name
    config.build_settings = { 'SWIFT_VERSION' => swift_version }
    target_config_list.build_configurations << config
  end
end

.preflight_swift_version(project_root: nil) ⇒ Object

Opens the .xcodeproj directly and applies the same SWIFT_VERSION fix as configure_build_settings' post_integrate path (assert_swift_version + mirror_project_configuration_names on every native target) -- but callable standalone, with no CocoaPods installer object needed.

This exists because pod install's own dependency-resolution/analysis phase (Pod::Installer::Analyzer::TargetInspector#compute_swift_version_from_targets) runs BEFORE any Podfile hook -- pre_install, pre_integrate, post_install, and post_integrate all fire only after analysis has already succeeded. A project whose SWIFT_VERSION is inconsistent across configuration names fails during analysis itself, so configure_build_settings never gets a chance to run and fix it -- confirmed against a real project via Pod::Installer#install!'s call order (resolve_dependencies, which calls analyze, happens before integrate, which is what runs the Podfile hooks). Calling this from sync (a separate process that runs before pod install is ever invoked) fixes the project ahead of time, so a project's very first pod install succeeds too, not just every one after the first.

No-op if sdk.swift_version isn't set, iOS isn't configured, or no .xcodeproj can be found under ios/.



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 283

def self.preflight_swift_version(project_root: nil)
  project_root ||= File.dirname(SpecLoader.find_spec_file(Dir.pwd) ||
    raise("annspec.yaml not found (searched upward from #{Dir.pwd})"))
  spec = load_core_spec(project_root)

  ios = spec.app&.ios
  return if ios.nil? || ios.flavors.empty?

  swift_version = ios.default.sdk&.swift_version
  return if swift_version.nil?

  xcodeproj_path = Dir.glob(File.join(project_root, 'ios', '*.xcodeproj')).first
  return if xcodeproj_path.nil?

  project = Xcodeproj::Project.open(xcodeproj_path)
  project.native_targets.each do |target|
    assert_swift_version(target, swift_version)
    mirror_project_configuration_names(target, project, swift_version)
  end
  save_if_changed(project)
end

.save_if_changed(project) ⇒ Object

Xcodeproj::Project#save unconditionally rewrites the entire project.pbxproj from the in-memory object graph, even when nothing actually changed -- every pod install would otherwise leave project.pbxproj showing as modified in git regardless of whether any real configuration changed (same class of bug fixed for .xcscheme files in configure_scheme, just without the duplication risk since find-by-name already prevents that here). Renders what save would write (mirroring its own to_ascii_plist + Nanaimo::Writer::PBXProjWriter pipeline exactly) and compares against the file currently on disk, skipping the actual write when identical.



336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 336

def self.save_if_changed(project)
  path = File.join(project.path.to_s, 'project.pbxproj')
  current = File.exist?(path) ? File.read(path) : nil

  rendered = StringIO.new
  Nanaimo::Writer::PBXProjWriter.new(
    project.to_ascii_plist, pretty: true, output: rendered, strict: false
  ).write

  return if rendered.string == current

  project.save
end

.warn_if_static_plist(project_root, xcode_config, config_file) ⇒ Object

Warn if a static GoogleService-Info.plist already exists in the project; a higher-priority static file would shadow the one we copy at build time.



354
355
356
357
358
359
360
361
362
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 354

def self.warn_if_static_plist(project_root, xcode_config, config_file)
  static_path = File.join(project_root, 'ios', 'Runner', 'GoogleService-Info.plist')
  if File.exist?(static_path)
    puts "ann-flavor-cocoapods WARNING: A static GoogleService-Info.plist exists at " \
         "ios/Runner/GoogleService-Info.plist. It will be overwritten at build time " \
         "for configuration '#{xcode_config}' (source: #{config_file}). " \
         "Remove the static file to silence this warning."
  end
end