Module: AnnFlavorCocoapods::PodfileHelper

Defined in:
lib/ann_flavor_cocoapods/podfile_helper.rb

Class Method Summary collapse

Class Method Details

.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.



324
325
326
327
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 324

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).



188
189
190
191
192
193
194
195
196
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 188

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



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

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

  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.



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

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

  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|
      next unless 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"

          configure_build_configuration(
            target, user_project, xcode_config, xcconfig_path, info_plist_path,
            "#{flavor_key.capitalize}AppIcon"
          )
        end

        configure_scheme(target, user_project, flavor_key)
      end

      if print_build_info
        inject_build_info_phase(target)
      end

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

  touched_projects.each(&:save)
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 two build phases 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):

- A pre-build shell script that copies the correct plist to
${SRCROOT}/Runner/GoogleService-Info.plist at build time.
- A post-build shell script that removes the copied file so the workspace
stays clean and a mis-matched plist cannot accidentally survive.

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



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

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.

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.



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 429

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"

  scheme = File.exist?(scheme_path.to_s) ? Xcodeproj::XCScheme.new(scheme_path.to_s) : Xcodeproj::XCScheme.new
  scheme.configure_with_targets(target, nil, launch_target: true)

  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}"

  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).



82
83
84
85
86
87
88
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 82

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

.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).



334
335
336
337
338
339
340
341
342
343
344
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 334

def self.find_or_create_icon_catalog(target, user_project)
  group = user_project.main_group.find_subpath('ann', true)
  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.



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 455

def self.inject_build_info_phase(target)
  target.build_phases.reject! { |p| p.respond_to?(:name) && p.name == '[ann-flavor] Print Build Info' }

  script = <<~SHELL
    # Injected by ann-flavor-cocoapods: print build info
    echo "🛠 Build Information 🛠"
    echo "\t🔹 Build Type:    $CONFIGURATION"
    echo "\t🔹 App Name:      $APP_NAME"
    echo "\t🔹 App ID:        $PRODUCT_BUNDLE_IDENTIFIER"
    echo "\t🔹 Version Name:  $MARKETING_VERSION"
    echo "\t🔹 Version Code:  $CURRENT_PROJECT_VERSION"
  SHELL

  phase = 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'
  target.build_phases.unshift(phase)
end

.inject_build_phases(installer, project_root, config_map) ⇒ Object

Injects pre-build and post-build shell script phases 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).



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

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
      echo "ann-flavor-cocoapods ERROR: Firebase plist not found: $SRC_PLIST"
      exit 1
    fi
    cp "$SRC_PLIST" "$DEST"
    echo "ann-flavor-cocoapods: copied $SRC_PLIST -> $DEST"
  SHELL

  post_build_script = <<~SHELL
    # Injected by ann-flavor-cocoapods: remove copied GoogleService-Info.plist after build
    DEST="${SRCROOT}/Runner/GoogleService-Info.plist"
    rm -f "$DEST"
    echo "ann-flavor-cocoapods: removed $DEST"
  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.
      target.build_phases.reject! do |p|
        p.respond_to?(:name) && ['[ann-flavor] Copy Firebase plist', '[ann-flavor] Remove Firebase plist'].include?(p.name)
      end

      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)

      post = target.project.new(Xcodeproj::Project::Object::PBXShellScriptBuildPhase)
      post.name            = '[ann-flavor] Remove Firebase plist'
      post.shell_path      = '/bin/sh'
      post.shell_script    = post_build_script
      post.show_env_vars_in_log = '0'
      post.input_paths     = ['$(SRCROOT)/Runner/GoogleService-Info.plist']
      target.build_phases << post

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

      puts "ann-flavor-cocoapods: injected Firebase build phases 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(&:save)
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.



200
201
202
203
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 200

def self.load_core_spec(project_root)
  path = File.join(project_root, SpecLoader::SPEC_FILE)
  AnnFlavorCore::Parser.parse_file(path)
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.



209
210
211
212
213
214
215
216
217
# File 'lib/ann_flavor_cocoapods/podfile_helper.rb', line 209

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