addXcodeReference function

Future<void> addXcodeReference({
  1. required String projectPath,
  2. required String xcstringsPath,
})

Adds a reference to the xcstrings file in the Xcode project.

Implementation

Future<void> addXcodeReference({
  required String projectPath,
  required String xcstringsPath,
}) async {
  final fileName = p.basename(xcstringsPath);
  // Ruby script to add the file
  final rubyScript =
      '''
require "xcodeproj"

project_path = "$projectPath"
full_file_path = "$xcstringsPath"
file_name = "$fileName"

begin
  project = Xcodeproj::Project.open(project_path)
  target = project.targets.first

  # Check if file already exists (check by filename)
  existing = project.files.find { |f| f.path == file_name || f.path == full_file_path }

  if existing.nil?
    # Find or create the Runner group (where other app files live)
    runner_group = project.main_group.groups.find { |g| g.display_name == "Runner" }

    if runner_group.nil?
      # If no Runner group, use main group
      runner_group = project.main_group
    end

    # Add file reference to Runner group with just the filename
    # This makes it relative to the Runner group location
    file_ref = runner_group.new_reference(file_name)

    # Set the source tree to group-relative
    file_ref.source_tree = "<group>"

    # Add to resources build phase
    target.resources_build_phase.add_file_reference(file_ref)

    # Save
    project.save

  else
    puts "\\#{file_name} already exists in project"
  end
rescue => e
  puts "Error: \\#{e.message}"
  exit 1
end
''';

  // Run the Ruby script
  final result = await Process.run('ruby', ['-e', rubyScript]);

  if (result.exitCode != 0) {
    Logger.error('Error adding to Xcode project');
    Logger.error(result.stderr);
    exit(1);
  }
}