Class: Pindo::AndroidConfigHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/pindo/module/android/android_config_helper.rb

Class Method Summary collapse

Class Method Details

.add_application_id_based_scheme(project_dir: nil) ⇒ Boolean

添加基于 Application ID 的 Scheme 读取当前项目的 Application ID 并添加对应的 Scheme

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

Returns:

  • (Boolean)

    是否成功添加



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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'lib/pindo/module/android/android_config_helper.rb', line 717

def self.add_application_id_based_scheme(project_dir: nil)
    # 参数验证
    if project_dir.nil? || !File.directory?(project_dir)
        Funlog.instance.fancyinfo_error("项目路径无效: #{project_dir}")
        return false
    end

    begin
        # 获取主模块
        main_module = Pindo::AndroidProjectHelper.get_main_module(project_dir)

        # 支持多种项目结构
        module_paths = []
        module_paths << File.join(project_dir, main_module) if main_module
        module_paths << File.join(project_dir, "app")
        module_paths << File.join(project_dir, "unityLibrary/launcher")
        module_paths << File.join(project_dir, "launcher")

        gradle_file = nil
        module_paths.each do |module_path|
            next unless File.exist?(module_path)

            if File.exist?(File.join(module_path, "build.gradle"))
                gradle_file = File.join(module_path, "build.gradle")
                break
            elsif File.exist?(File.join(module_path, "build.gradle.kts"))
                gradle_file = File.join(module_path, "build.gradle.kts")
                break
            end
        end

        if gradle_file.nil?
            Funlog.instance.fancyinfo_error("未找到build.gradle文件,无法读取 Application ID")
            return false
        end

        # 读取gradle文件,提取当前的 Application ID
        content = File.read(gradle_file)
        application_id = nil

        # 匹配各种 applicationId 格式
        if content =~ /applicationId\s+["']([^"']+)["']/
            application_id = $1
        elsif content =~ /applicationId\s*=\s*["']([^"']+)["']/
            application_id = $1
        end

        if application_id.nil?
            Funlog.instance.fancyinfo_error("无法从 gradle 文件中读取 Application ID")
            return false
        end

        # 将 Application ID 转换为合法的 scheme 名称(只保留字母和数字)
        bundle_scheme = application_id.gsub(/[^a-zA-Z0-9]/, '').downcase

        # 添加 Scheme
        success_scheme = add_test_scheme(
            project_dir: project_dir,
            scheme_name: bundle_scheme
        )

        if success_scheme
            puts "  ✓ 已添加Scheme: #{bundle_scheme} (基于 Application ID: #{application_id})"
            return true
        else
            Funlog.instance.fancyinfo_error("添加 Scheme 失败: #{bundle_scheme}")
            return false
        end

    rescue StandardError => e
        Funlog.instance.fancyinfo_error("添加基于 Application ID 的 Scheme 失败: #{e.message}")
        return false
    end
end

.add_scheme_with_text_replace(manifest_path, scheme_name, activity_name: nil) ⇒ Object

使用文本替换添加scheme



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# File 'lib/pindo/module/android/android_config_helper.rb', line 957

def self.add_scheme_with_text_replace(manifest_path, scheme_name, activity_name: nil)
    begin
        # 读取原始内容
        xml_content = File.read(manifest_path)

        modified_xml = insert_scheme_intent_filter_before_activity_close(xml_content, scheme_name, activity_name: activity_name)
        return false unless modified_xml

        File.write(manifest_path, modified_xml)
        return true

        return false
    rescue => e
        return false
    end
end

.add_test_scheme(project_dir: nil, scheme_name: nil) ⇒ Boolean

添加测试scheme到Android工程

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • scheme_name (String) (defaults to: nil)

    要添加的scheme名称

Returns:

  • (Boolean)

    是否成功添加



796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/pindo/module/android/android_config_helper.rb', line 796

def self.add_test_scheme(project_dir: nil, scheme_name: nil)
    # 参数验证
    if scheme_name.nil?
        Funlog.instance.fancyinfo_error("需要提供scheme名称")
        return false
    end

    if project_dir.nil? || !File.directory?(project_dir)
        Funlog.instance.fancyinfo_error("项目路径无效: #{project_dir}")
        return false
    end

    scheme_name = scheme_name.to_s.gsub(/[^a-zA-Z0-9]/, '').downcase

    # 查找所有可能的模块(添加 launcher 支持 Unity 项目)
    main_module = Pindo::AndroidProjectHelper.get_main_module(project_dir)
    search_modules = ["launcher", "app", "unityLibrary"]
    search_modules << main_module if main_module
    search_modules = search_modules.compact.uniq

    # 查找所有可能的AndroidManifest.xml文件
    manifest_candidates = find_manifests(project_dir, search_modules)

    if manifest_candidates.empty?
        Funlog.instance.fancyinfo_error("未找到任何AndroidManifest.xml文件")
        return false
    end

    # 寻找最佳的AndroidManifest.xml和Activity
    manifest_path, main_activity, android_prefix = find_best_activity(manifest_candidates)

    if manifest_path.nil? || main_activity.nil?
        Funlog.instance.fancyinfo_error("无法找到合适的Activity")
        return false
    end

    # 检查scheme是否已存在
    scheme_exists, existing_scheme = check_scheme_exists(main_activity, android_prefix, scheme_name)

    # 如果scheme已存在,检查是否需要更新格式
    if scheme_exists
        activity_name = main_activity["#{android_prefix}:name"] || "主Activity"
        if existing_scheme != scheme_name
            # 格式不同,需要更新
            if update_existing_scheme(manifest_path, main_activity, android_prefix, existing_scheme, scheme_name)
                Funlog.instance.fancyinfo_update("已将scheme从'#{existing_scheme}'更新为'#{scheme_name}'")
            else
                Funlog.instance.fancyinfo_update("scheme已存在: #{existing_scheme}")
            end
        end
        return true
    end

    # 为了避免 Nokogiri 重新序列化导致整体格式变化,优先使用文本方式局部插入。
    activity_name = main_activity["name"] || main_activity["android:name"] || main_activity["#{android_prefix}:name"]
    success = add_scheme_with_text_replace(manifest_path, scheme_name, activity_name: activity_name)

    unless success
        Funlog.instance.fancyinfo_error("无法添加scheme: #{scheme_name}")
    end

    return success
end

.apply_config_from_repo(config_repo_dir: nil, project_dir: nil) ⇒ Boolean

从配置仓库应用配置(拷贝 config.json)

Parameters:

  • config_repo_dir (String) (defaults to: nil)

    配置仓库的路径

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

Returns:

  • (Boolean)

    是否成功应用



688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/pindo/module/android/android_config_helper.rb', line 688

def self.apply_config_from_repo(config_repo_dir: nil, project_dir: nil)
    # 参数验证
    if config_repo_dir.nil? || !File.directory?(config_repo_dir)
        Funlog.instance.fancyinfo_error("配置仓库路径无效: #{config_repo_dir}")
        return false
    end

    if project_dir.nil? || !File.directory?(project_dir)
        Funlog.instance.fancyinfo_error("项目路径无效: #{project_dir}")
        return false
    end

    # 拷贝 config.json 到项目目录
    config_source = File.join(config_repo_dir, 'config.json')
    if File.exist?(config_source)
        config_target = File.join(project_dir, 'config.json')
        FileUtils.cp(config_source, config_target)
        puts "  ✓ config.json 已拷贝到项目目录"
        return true
    else
        puts "  ⚠ 配置仓库中未找到 config.json"
        return false
    end
end

.check_scheme_exists(activity, android_prefix, scheme_name) ⇒ Object

检查scheme是否已存在



928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
# File 'lib/pindo/module/android/android_config_helper.rb', line 928

def self.check_scheme_exists(activity, android_prefix, scheme_name)
    scheme_exists = false
    existing_scheme = nil

    # 首先检查完全一致的scheme(修复:移除命名空间后使用 @scheme)
    activity.xpath("intent-filter/data[@scheme='#{scheme_name}']").each do |node|
        scheme_exists = true
        existing_scheme = scheme_name
        break
    end

    # 如果没有找到完全一致的,检查可能格式不同的scheme
    if !scheme_exists
        activity.xpath("intent-filter/data[@scheme]").each do |node|
            current_scheme = node["scheme"]
            normalized_current = current_scheme.to_s.downcase.strip.gsub(/[\s\-_]/, '')

            if normalized_current == scheme_name
                scheme_exists = true
                existing_scheme = current_scheme
                break
            end
        end
    end

    [scheme_exists, existing_scheme]
end

.copy_google_services_from_config_repo(config_repo_dir: nil, project_dir: nil) ⇒ Boolean

从配置仓库拷贝 google-services.json 到项目的 launcher 目录

Parameters:

  • config_repo_dir (String) (defaults to: nil)

    配置仓库的路径

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

Returns:

  • (Boolean)

    是否成功拷贝



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
# File 'lib/pindo/module/android/android_config_helper.rb', line 538

def self.copy_google_services_from_config_repo(config_repo_dir: nil, project_dir: nil)
    # 参数验证
    if config_repo_dir.nil? || !File.directory?(config_repo_dir)
        Funlog.instance.fancyinfo_error("配置仓库路径无效: #{config_repo_dir}")
        return false
    end

    if project_dir.nil? || !File.directory?(project_dir)
        Funlog.instance.fancyinfo_error("项目路径无效: #{project_dir}")
        return false
    end

    # 查找配置仓库中的 google-services.json
    source_file = File.join(config_repo_dir, 'google-services.json')
    unless File.exist?(source_file)
        Funlog.instance.fancyinfo_warning("配置仓库中未找到 google-services.json")
        return false
    end

    puts "正在拷贝 google-services.json..."

    # 优先拷贝到 launcher 目录
    launcher_dirs = [
        File.join(project_dir, 'unityLibrary', 'launcher'),  # Unity 项目的 launcher
        File.join(project_dir, 'launcher'),                  # 独立的 launcher
        File.join(project_dir, 'app')                        # 原生 Android 项目
    ]

    copied = false
    launcher_dirs.each do |launcher_dir|
        if File.exist?(launcher_dir) && File.directory?(launcher_dir)
            target_file = File.join(launcher_dir, 'google-services.json')
            FileUtils.cp(source_file, target_file)
            puts "  ✓ google-services.json 已拷贝到: #{launcher_dir}"
            copied = true

            # Unity 项目也拷贝到 unityLibrary 根目录
            if launcher_dir.include?('unityLibrary/launcher')
                unity_root = File.join(project_dir, 'unityLibrary')
                if File.exist?(unity_root) && File.directory?(unity_root)
                    unity_target = File.join(unity_root, 'google-services.json')
                    FileUtils.cp(source_file, unity_target)
                    puts "  ✓ google-services.json 也已拷贝到: unityLibrary/"
                end
            end

            break # 找到第一个有效目录后停止
        end
    end

    unless copied
        # 如果没找到合适的目录,至少拷贝到项目根目录
        target_file = File.join(project_dir, 'google-services.json')
        FileUtils.cp(source_file, target_file)
        puts "  ✓ google-services.json 已拷贝到项目根目录"
        puts "  ⚠ 请确认文件位置是否正确"
    end

    # Unity Editor(Firebase.Editor)也会读取 Assets/Scripts/Firebase/google-services.json
    unity_root = infer_unity_project_root_from_export_dir(project_dir)
    if unity_root && File.directory?(File.join(unity_root, 'Assets'))
        assets_firebase_dir = File.join(unity_root, 'Assets', 'Scripts', 'Firebase')
        FileUtils.mkdir_p(assets_firebase_dir)
        unity_gs = File.join(assets_firebase_dir, 'google-services.json')
        FileUtils.cp(source_file, unity_gs)
        puts "  ✓ google-services.json 已拷贝到: #{unity_gs}"
    end

    return true
end

.create_android_icons(icon_path: nil, output_dir: nil) ⇒ Hash

创建Android各种密度的icon(委托给 AndroidResHelper)

Parameters:

  • icon_path (String) (defaults to: nil)

    原始icon路径(建议1024x1024或512x512)

  • output_dir (String) (defaults to: nil)

    输出目录

Returns:

  • (Hash)

    各密度icon路径



1104
1105
1106
# File 'lib/pindo/module/android/android_config_helper.rb', line 1104

def self.create_android_icons(icon_path: nil, output_dir: nil)
    AndroidResHelper.create_icons(icon_name: icon_path, new_icon_dir: output_dir)
end

.download_and_replace_icon_from_url(project_dir: nil, icon_url: nil) ⇒ Boolean

从URL下载Icon并替换Android工程的Icon

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • icon_url (String) (defaults to: nil)

    Icon的下载URL地址

Returns:

  • (Boolean)

    是否成功下载并替换Icon



1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'lib/pindo/module/android/android_config_helper.rb', line 1120

def self.download_and_replace_icon_from_url(project_dir: nil, icon_url: nil)
    # 参数校验 - 不抛出异常,返回 false
    if project_dir.nil?
        Funlog.instance.fancyinfo_error("Icon 替换失败: 项目目录不能为空")
        return false
    end

    if icon_url.nil? || icon_url.empty?
        Funlog.instance.fancyinfo_error("Icon 替换失败: Icon URL不能为空")
        return false
    end

    puts "\n检测到项目 Icon URL: #{icon_url}"

    # 创建临时目录(所有 icon 处理都在此目录进行)
    temp_icon_dir = File.join(project_dir, ".pindo_temp_android_icon")
    icon_download_path = nil
    replace_success = false

    begin
        # 先清理旧的临时目录,确保干净的环境
        FileUtils.rm_rf(temp_icon_dir) if File.exist?(temp_icon_dir)
        FileUtils.mkdir_p(temp_icon_dir)
        icon_download_path = File.join(temp_icon_dir, "android_downloaded_icon.png")

        # 使用带重试机制的下载
        Funlog.instance.fancyinfo_start("正在下载项目 Icon...")
        unless Pindo::FileDownloader.download(url: icon_url, dest_path: icon_download_path, max_retries: 3)
            Funlog.instance.fancyinfo_error("Icon 下载失败")
            return false
        end
        Funlog.instance.fancyinfo_success("Icon 下载成功!")

        # 生成 icon 目录(在临时目录内部),先清理确保干净环境
        new_icon_dir = File.join(temp_icon_dir, "android_generated_icons")
        FileUtils.rm_rf(new_icon_dir) if File.exist?(new_icon_dir)
        FileUtils.mkdir_p(new_icon_dir)

        # 创建各种密度的 icon
        Funlog.instance.fancyinfo_start("正在创建 Android icon...")
        create_android_icons(
            icon_path: icon_download_path,
            output_dir: new_icon_dir
        )
        Funlog.instance.fancyinfo_success("创建 icon 完成!")

        # 替换工程中的 icon
        Funlog.instance.fancyinfo_start("正在替换 icon...")
        install_android_icon(
            project_dir: project_dir,
            icon_dir: new_icon_dir
        )
        Funlog.instance.fancyinfo_success("替换 icon 完成!")
        replace_success = true

    rescue => e
        Funlog.instance.fancyinfo_error("Icon 处理失败: #{e.message}")
        puts e.backtrace.join("\n") if ENV['PINDO_DEBUG']
        replace_success = false
    ensure
        # 清理临时文件(无论成功失败都清理)
        FileUtils.rm_rf(temp_icon_dir) if temp_icon_dir && File.exist?(temp_icon_dir)
    end

    return replace_success
end

.existing_google_services_json_paths(project_dir) ⇒ Array<String>

Returns 项目内已存在的 google-services.json 绝对路径.

Parameters:

  • project_dir (String)

Returns:

  • (Array<String>)

    项目内已存在的 google-services.json 绝对路径

Raises:

  • (ArgumentError)


628
629
630
631
632
633
# File 'lib/pindo/module/android/android_config_helper.rb', line 628

def self.existing_google_services_json_paths(project_dir)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "项目路径无效: #{project_dir}" unless File.directory?(project_dir)

    google_services_json_candidate_paths(project_dir).select { |p| File.exist?(p) }
end

.find_best_activity(manifest_candidates) ⇒ Object

查找最佳的Activity



886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/pindo/module/android/android_config_helper.rb', line 886

def self.find_best_activity(manifest_candidates)
    require 'nokogiri'

    best_manifest = nil
    best_activity = nil
    android_prefix = nil

    manifest_candidates.each do |manifest_path|
        begin
            doc = Nokogiri::XML(File.read(manifest_path))
            doc.remove_namespaces!

            # 查找包含MAIN和LAUNCHER的Activity
            activities = doc.xpath("//activity")
            activities.each do |activity|
                intent_filters = activity.xpath("intent-filter")
                intent_filters.each do |intent_filter|
                    # 修复:移除命名空间后,应该使用 @name 而不是 @android:name
                    has_main = intent_filter.xpath("action[@name='android.intent.action.MAIN']").any?
                    has_launcher = intent_filter.xpath("category[@name='android.intent.category.LAUNCHER']").any?

                    if has_main && has_launcher
                        best_manifest = manifest_path
                        best_activity = activity
                        android_prefix = "android"
                        break
                    end
                end
                break if best_activity
            end
        rescue => e
            # 静默处理解析错误,继续尝试下一个文件
            puts "解析 #{manifest_path} 时出错: #{e.message}" if ENV['PINDO_DEBUG']
        end

        break if best_activity
    end

    [best_manifest, best_activity, android_prefix]
end

.find_manifests(project_dir, modules) ⇒ Object

查找所有可能的AndroidManifest.xml文件



863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'lib/pindo/module/android/android_config_helper.rb', line 863

def self.find_manifests(project_dir, modules)
    manifest_candidates = []

    modules.each do |mod|
        mod_path = mod.is_a?(String) && !mod.start_with?(project_dir) ? File.join(project_dir, mod) : mod
        next unless File.directory?(mod_path)

        manifest_paths = [
            File.join(mod_path, "src", "main", "AndroidManifest.xml"),
            File.join(mod_path, "AndroidManifest.xml")
        ]

        manifest_paths.each do |path|
            if File.exist?(path)
                manifest_candidates << path
            end
        end
    end

    manifest_candidates
end

.google_services_first_android_client(clients) ⇒ Hash?

取首个含 android_client_info.package_name 的 client,作为追加新包名时的模板

Parameters:

  • clients (Array)

Returns:

  • (Hash, nil)


494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/pindo/module/android/android_config_helper.rb', line 494

def self.google_services_first_android_client(clients)
    return nil unless clients.is_a?(Array)

    clients.each do |c|
        next unless c.is_a?(Hash)
        ci = c['client_info']
        next unless ci.is_a?(Hash)
        aci = ci['android_client_info']
        if aci.is_a?(Hash) && aci['package_name'].is_a?(String) && !aci['package_name'].empty?
            return c
        end
    end
    nil
end

.google_services_has_android_package?(clients, package_name) ⇒ Boolean

Parameters:

  • clients (Array)
  • package_name (String)

Returns:

  • (Boolean)


479
480
481
482
483
484
485
486
487
488
489
# File 'lib/pindo/module/android/android_config_helper.rb', line 479

def self.google_services_has_android_package?(clients, package_name)
    return false unless clients.is_a?(Array)

    clients.any? do |c|
        next false unless c.is_a?(Hash)
        ci = c['client_info']
        next false unless ci.is_a?(Hash)
        aci = ci['android_client_info']
        aci.is_a?(Hash) && aci['package_name'] == package_name
    end
end

.google_services_json_candidate_paths(project_dir) ⇒ Object

与 update_google_services_package_name 相同的候选路径(不一定存在)



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/pindo/module/android/android_config_helper.rb', line 610

def self.google_services_json_candidate_paths(project_dir)
    candidates = [
        File.join(project_dir, 'unityLibrary', 'launcher', 'google-services.json'),
        File.join(project_dir, 'unityLibrary', 'google-services.json'),
        File.join(project_dir, 'launcher', 'google-services.json'),
        File.join(project_dir, 'app', 'google-services.json'),
        File.join(project_dir, 'google-services.json')
    ]
    unity_root = infer_unity_project_root_from_export_dir(project_dir)
    if unity_root
        candidates << unity_assets_firebase_google_services_path(unity_root)
        candidates << unity_streaming_assets_google_services_desktop_path(unity_root)
    end
    candidates.uniq
end

.google_services_merge_android_package!(json, package_name) ⇒ Boolean

不修改已有 client;若尚无目标 package_name,则深拷贝模板 client 并追加

Parameters:

  • json (Hash)
  • package_name (String)

Returns:

  • (Boolean)

    是否追加了新 client



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/pindo/module/android/android_config_helper.rb', line 513

def self.google_services_merge_android_package!(json, package_name)
    return false unless json.is_a?(Hash)

    clients = json['client']
    return false unless clients.is_a?(Array) && !clients.empty?

    return false if google_services_has_android_package?(clients, package_name)

    template = google_services_first_android_client(clients)
    unless template
        return false
    end

    new_client = JSON.parse(JSON.generate(template))
    new_client['client_info'] ||= {}
    new_client['client_info']['android_client_info'] ||= {}
    new_client['client_info']['android_client_info']['package_name'] = package_name
    clients << new_client
    true
end

.infer_unity_project_root_from_export_dir(export_project_dir) ⇒ String?

从 Android 导出工程路径推断 Unity 工程根目录(GoodPlatform/BaseAndroid 布局)

Parameters:

  • export_project_dir (String)

    例如 GoodPlatform/BaseAndroid

Returns:

  • (String, nil)

    Unity 根目录绝对路径,无法推断时返回 nil



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/pindo/module/android/android_config_helper.rb', line 438

def self.infer_unity_project_root_from_export_dir(export_project_dir)
    return nil if export_project_dir.nil? || !File.directory?(export_project_dir)

    abs = File.expand_path(export_project_dir)
    base = File.basename(abs)
    parent = File.basename(File.dirname(abs))
    if base == 'BaseAndroid' && parent == 'GoodPlatform'
        return File.expand_path('../..', abs)
    end

    dir = abs
    8.times do
        if File.directory?(File.join(dir, 'Assets')) &&
           File.directory?(File.join(dir, 'ProjectSettings'))
            return dir
        end
        parent_dir = File.dirname(dir)
        break if parent_dir == dir

        dir = parent_dir
    end
    nil
end

.insert_scheme_intent_filter_before_activity_close(xml_content, scheme_name, activity_name: nil) ⇒ Object



1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
# File 'lib/pindo/module/android/android_config_helper.rb', line 1005

def self.insert_scheme_intent_filter_before_activity_close(xml_content, scheme_name, activity_name: nil)
    return nil if xml_content.to_s.empty?

    newline = xml_content.include?("\r\n") ? "\r\n" : "\n"

    activity_block = nil
    if activity_name && !activity_name.to_s.empty?
        name = Regexp.escape(activity_name.to_s)
        # 锁定到目标 activity(兼容 android:name / name)
        activity_block = xml_content.match(
            /(?<open><activity\b[^>]*(?:\bandroid:name|\bname)\s*=\s*["']#{name}["'][^>]*>)(?<inner>.*?)(?<close><\/activity>)/m
        )
    end

    # 找不到目标 activity 时,再退化为第一个 </activity>(保持向后兼容)
    if activity_block
        open_tag = activity_block[:open]
        inner = activity_block[:inner]
        # close 缩进必须与原文件一致(避免 </activity> 顶格)
        close_line_indent =
            activity_block[0].match(/^(?<indent>[ \t]*)<\/activity>\s*$/m)&.[](:indent) ||
            activity_block[0].match(/^(?<indent>[ \t]*)<activity\b/m)&.[](:indent) ||
            ""
        close_line = "#{close_line_indent}</activity>"

        # 复用该 activity 内已存在 intent-filter 的缩进(取最短的,避免被历史插歪的块污染)
        intent_filter_indents = inner.scan(/^(?<indent>[ \t]*)<intent-filter\b/m).flatten
        child_indent = intent_filter_indents.reject(&:empty?).min_by(&:length)

        # 如果没有 intent-filter,则尝试复用其它子元素缩进
        child_indent ||= inner.scan(/^(?<indent>[ \t]*)<(?:action|category|data)\b/m).flatten.reject(&:empty?).min_by(&:length)

        # 如果 activity 内部完全没有子元素,则用 close_tag 行缩进推导
        unless child_indent
            # 默认与现有 AndroidManifest 常见风格对齐:activity 内缩进步长通常为 4
            child_indent = close_line_indent + "    "
        end

        # 推导 intent-filter 内部子元素的缩进步长(2/4/tab 都兼容)
        existing_grandchild = inner.match(/^(?<indent>[ \t]*)<(?:action|category|data)\b/m)&.[](:indent)
        indent_step = nil
        if existing_grandchild && existing_grandchild.start_with?(child_indent)
            step = existing_grandchild.delete_prefix(child_indent)
            indent_step = step unless step.empty?
        end
        indent_step ||= "    "
        grandchild_indent = child_indent + indent_step

        block = [
            "#{child_indent}<intent-filter>",
            "#{grandchild_indent}<action android:name=\"android.intent.action.VIEW\" />",
            "#{grandchild_indent}<category android:name=\"android.intent.category.DEFAULT\" />",
            "#{grandchild_indent}<category android:name=\"android.intent.category.BROWSABLE\" />",
            "#{grandchild_indent}<data android:scheme=\"#{scheme_name}\" />",
            "#{child_indent}</intent-filter>",
        ].join(newline)

        # 规范化:块与块之间留 1 个空行;保持 </activity> 缩进对齐
        normalized_inner = inner.sub(/(?:#{Regexp.escape(newline)}[ \t]*)*\z/, "")
        replaced = [
            open_tag,
            normalized_inner,
            newline,
            newline,
            block,
            newline,
            close_line
        ].join
        return xml_content.sub(activity_block[0], replaced)
    end

    m = xml_content.match(/^(?<indent>[ \t]*)<\/activity>\s*$/m)
    return nil unless m

    close_indent = m[:indent] || ""
    # 默认与现有 AndroidManifest 常见风格对齐:activity 内缩进步长通常为 4
    child_indent = close_indent + "    "
    grandchild_indent = child_indent + "    "

    block = [
        "#{child_indent}<intent-filter>",
        "#{grandchild_indent}<action android:name=\"android.intent.action.VIEW\" />",
        "#{grandchild_indent}<category android:name=\"android.intent.category.DEFAULT\" />",
        "#{grandchild_indent}<category android:name=\"android.intent.category.BROWSABLE\" />",
        "#{grandchild_indent}<data android:scheme=\"#{scheme_name}\" />",
        "#{child_indent}</intent-filter>",
    ].join(newline)

    xml_content.sub(/^(?<indent>[ \t]*)<\/activity>\s*$/m) do |match|
        "#{newline}#{block}#{newline}#{newline}#{match}"
    end
end

.install_android_icon(project_dir: nil, icon_dir: nil) ⇒ Boolean

安装Android icon到项目中(委托给 AndroidResHelper)

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录

  • icon_dir (String) (defaults to: nil)

    icon文件目录(包含各密度文件夹)

Returns:

  • (Boolean)

    是否成功安装



1112
1113
1114
# File 'lib/pindo/module/android/android_config_helper.rb', line 1112

def self.install_android_icon(project_dir: nil, icon_dir: nil)
    AndroidResHelper.install_icon(proj_dir: project_dir, new_icon_dir: icon_dir)
end

.unity_assets_firebase_google_services_path(unity_root) ⇒ String

Unity 工程中 Firebase Android 配置(Editor 与 Gradle 均可能读取)

Parameters:

  • unity_root (String)

    Unity 工程根目录

Returns:

  • (String)


465
466
467
# File 'lib/pindo/module/android/android_config_helper.rb', line 465

def self.unity_assets_firebase_google_services_path(unity_root)
    File.join(unity_root, 'Assets', 'Scripts', 'Firebase', 'google-services.json')
end

.unity_streaming_assets_google_services_desktop_path(unity_root) ⇒ String

Unity Editor 侧 Firebase 可能读取的桌面配置(与 Assets/Firebase 下 json 宜保持一致)

Parameters:

  • unity_root (String)

    Unity 工程根目录

Returns:

  • (String)


472
473
474
# File 'lib/pindo/module/android/android_config_helper.rb', line 472

def self.unity_streaming_assets_google_services_desktop_path(unity_root)
    File.join(unity_root, 'Assets', 'StreamingAssets', 'google-services-desktop.json')
end

.update_android_project_version(project_dir: nil, version_name: nil, version_code: nil) ⇒ Boolean

更新Android工程版本号

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • version_name (String) (defaults to: nil)

    版本名

  • version_code (Integer) (defaults to: nil)

    版本号

Returns:

  • (Boolean)

    是否成功更新

Raises:

  • (ArgumentError)


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
# File 'lib/pindo/module/android/android_config_helper.rb', line 63

def self.update_android_project_version(project_dir: nil, version_name: nil, version_code: nil)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "版本名不能为空" if version_name.nil?
    raise ArgumentError, "版本号不能为空" if version_code.nil?

    # 验证version_code的有效性
    unless Pindo::GitRepoHelper.share_instance.valid_build_number?(version_code)
        Funlog.instance.fancyinfo_error("Android versionCode必须在1到#{2**31-1}之间,当前值:#{version_code}")
        return false
    end

    Funlog.instance.fancyinfo_start("正在更新Android工程版本信息...")

    begin
        # 获取主模块路径
        main_module = Pindo::AndroidProjectHelper.get_main_module(project_dir)

        if main_module.nil?
            # 如果无法获取主模块,尝试常见的模块名(优先 launcher,支持 Unity 项目)
            ["launcher", "app", "application", "main"].each do |module_name|
                module_path = File.join(project_dir, module_name)
                if File.exist?(File.join(module_path, "build.gradle")) ||
                   File.exist?(File.join(module_path, "build.gradle.kts"))
                    main_module = module_path
                    break
                end
            end
        end

        if main_module.nil?
            Funlog.instance.fancyinfo_error("未找到Android主模块")
            return false
        end

        # 查找build.gradle或build.gradle.kts文件
        gradle_file = nil
        if File.exist?(File.join(main_module, "build.gradle"))
            gradle_file = File.join(main_module, "build.gradle")
        elsif File.exist?(File.join(main_module, "build.gradle.kts"))
            gradle_file = File.join(main_module, "build.gradle.kts")
        end

        if gradle_file.nil?
            Funlog.instance.fancyinfo_error("未找到build.gradle文件")
            return false
        end

        # 读取并更新gradle文件
        content = File.read(gradle_file)

        # 第一步:清理所有现有的版本信息(无论在什么位置)
        # 直接赋值格式
        content.gsub!(/^\s*versionCode\s+\d+\s*$/, '')
        content.gsub!(/^\s*versionCode\s*=\s*\d+\s*$/, '')
        content.gsub!(/^\s*versionName\s+["'][^"']*["']\s*$/, '')
        content.gsub!(/^\s*versionName\s*=\s*["'][^"']*["']\s*$/, '')

        # 外部变量引用格式
        content.gsub!(/^\s*versionCode\s+rootProject\.ext\.\w+\s*$/, '')
        content.gsub!(/^\s*versionCode\s+project\.ext\.\w+\s*$/, '')
        content.gsub!(/^\s*versionCode\s+ext\.\w+\s*$/, '')
        content.gsub!(/^\s*versionName\s+["']?\$\{rootProject\.ext\.\w+\}["']?\s*$/, '')
        content.gsub!(/^\s*versionName\s+["']?\$\{project\.ext\.\w+\}["']?\s*$/, '')
        content.gsub!(/^\s*versionName\s+["']?\$\{ext\.\w+\}["']?\s*$/, '')
        content.gsub!(/^\s*versionName\s+rootProject\.ext\.\w+\s*$/, '')
        content.gsub!(/^\s*versionName\s+project\.ext\.\w+\s*$/, '')
        content.gsub!(/^\s*versionName\s+ext\.\w+\s*$/, '')

        # 清理多余的空行
        content.gsub!(/\n\n+/, "\n\n")

        # 第二步:在 defaultConfig 块的正确位置添加版本信息
        if content =~ /defaultConfig\s*\{/
            # 找到 defaultConfig 的起始位置
            start_pos = $~.end(0)

            # 从起始位置开始,找到匹配的 }
            brace_count = 1
            end_pos = start_pos

            while end_pos < content.length && brace_count > 0
                if content[end_pos] == '{'
                    brace_count += 1
                elsif content[end_pos] == '}'
                    brace_count -= 1
                end
                end_pos += 1
            end

            if brace_count == 0
                # 成功找到匹配的 }
                # 在 defaultConfig 块的末尾(但在最后的 } 之前)添加版本信息
                insert_pos = end_pos - 1

                version_lines = [
                    "        versionCode #{version_code}",
                    "        versionName \"#{version_name}\""
                ]

                content.insert(insert_pos, "\n" + version_lines.join("\n") + "\n    ")
                File.write(gradle_file, content)

                Funlog.instance.fancyinfo_success("Android版本更新完成!")
                puts "  ✓ 版本号已更新: #{version_name}"
                puts "  ✓ Build号已更新: #{version_code}"
                return true
            end
        end

        Funlog.instance.fancyinfo_error("无法在gradle文件中找到或添加版本信息")
        return false

    rescue StandardError => e
        Funlog.instance.fancyinfo_error("更新Android版本失败: #{e.message}")
        return false
    end
end

.update_app_name_with_packagename(project_dir: nil, package_name: nil) ⇒ Boolean

使用package_name更新Android应用名称(strings.xml中的app_name)

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • package_name (String) (defaults to: nil)

    工作流的package_name(如:“Test Demo”)

Returns:

  • (Boolean)

    是否成功更新

Raises:

  • (ArgumentError)


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
# File 'lib/pindo/module/android/android_config_helper.rb', line 185

def self.update_app_name_with_packagename(project_dir: nil, package_name: nil)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "Package Name不能为空" if package_name.nil?

    # 生成应用名称(去除特殊字符和空格)
    app_name = package_name.gsub(/[^a-zA-Z0-9\s]/, '').gsub(/\s+/, '')

    begin
        main_module = Pindo::AndroidProjectHelper.get_main_module(project_dir)

        if main_module.nil?
            # 尝试常见的模块名(优先 launcher,支持 Unity 项目)
            ["launcher", "app", "application", "main"].each do |module_name|
                module_path = File.join(project_dir, module_name)
                if File.directory?(module_path)
                    main_module = module_path
                    break
                end
            end
        end

        return false if main_module.nil?

        # 1. 先删除 build.gradle 中的 resValue("string", "app_name", ...)
        build_gradle_path = File.join(main_module, "build.gradle")
        build_gradle_kts_path = File.join(main_module, "build.gradle.kts")

        gradle_file = nil
        if File.exist?(build_gradle_kts_path)
            gradle_file = build_gradle_kts_path
        elsif File.exist?(build_gradle_path)
            gradle_file = build_gradle_path
        end

        if gradle_file
            gradle_content = File.read(gradle_file)
            original_content = gradle_content.dup

            # 删除 resValue("string", "app_name", ...) 这一行
            # 支持多种格式:
            # resValue("string", "app_name", "xxx")
            # resValue("string", "app_name", "${rootProject.ext.app_name}")
            # resValue "string", "app_name", "xxx"
            gradle_content.gsub!(/^\s*resValue\s*\(?\s*["']string["']\s*,\s*["']app_name["'].*?\)?\s*$\n?/, '')

            if gradle_content != original_content
                File.write(gradle_file, gradle_content)
                puts "  ✓ 已删除 build.gradle 中的 resValue(\"string\", \"app_name\", ...)"
            end
        end

        # 2. 更新 strings.xml
        # 查找strings.xml文件
        strings_xml_path = File.join(main_module, "src", "main", "res", "values", "strings.xml")

        unless File.exist?(strings_xml_path)
            Funlog.instance.fancyinfo_error("未找到strings.xml文件")
            return false
        end

        # 读取并更新strings.xml
        content = File.read(strings_xml_path)

        # 检查是否存在 app_name
        if content =~ /<string\s+name="app_name">.*?<\/string>/
            # 存在,直接更新
            content.gsub!(/<string\s+name="app_name">.*?<\/string>/, "<string name=\"app_name\">#{app_name}</string>")
            File.write(strings_xml_path, content)
            puts "  ✓ App Name 已更新为: #{app_name} (来自: #{package_name})"
            return true
        else
            # 不存在,自动添加
            if content =~ /<resources>(.*?)<\/resources>/m
                # 在 <resources> 标签内添加 app_name
                new_string_entry = "\n  <string name=\"app_name\">#{app_name}</string>"
                content.sub!(/<resources>/, "<resources>#{new_string_entry}")
                File.write(strings_xml_path, content)
                puts "  ✓ App Name 已添加: #{app_name} (来自: #{package_name})"
                return true
            else
                Funlog.instance.fancyinfo_error("strings.xml格式异常,无法添加app_name")
                return false
            end
        end

    rescue StandardError => e
        Funlog.instance.fancyinfo_error("更新App Name失败: #{e.message}")
        return false
    end
end

.update_application_id(project_dir: nil, application_id: nil) ⇒ Boolean

直接更新Application ID(不依赖package_name生成)

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • application_id (String) (defaults to: nil)

    要设置的Application ID(如 com.example.app)

Returns:

  • (Boolean)

    是否成功更新



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
# File 'lib/pindo/module/android/android_config_helper.rb', line 362

def self.update_application_id(project_dir: nil, application_id: nil)
    # 参数验证
    if application_id.nil? || application_id.empty?
        Funlog.instance.fancyinfo_error("Application ID不能为空")
        return false
    end

    if project_dir.nil? || !File.directory?(project_dir)
        Funlog.instance.fancyinfo_error("项目路径无效: #{project_dir}")
        return false
    end

    begin
        puts "正在设置 Application ID: #{application_id}"

        # 获取主模块
        main_module = Pindo::AndroidProjectHelper.get_main_module(project_dir)

        # 支持多种项目结构
        module_paths = []
        module_paths << File.join(project_dir, main_module) if main_module
        module_paths << File.join(project_dir, "app")
        module_paths << File.join(project_dir, "unityLibrary/launcher")
        module_paths << File.join(project_dir, "launcher")

        gradle_file = nil
        module_paths.each do |module_path|
            next unless File.exist?(module_path)

            if File.exist?(File.join(module_path, "build.gradle"))
                gradle_file = File.join(module_path, "build.gradle")
                break
            elsif File.exist?(File.join(module_path, "build.gradle.kts"))
                gradle_file = File.join(module_path, "build.gradle.kts")
                break
            end
        end

        if gradle_file.nil?
            Funlog.instance.fancyinfo_error("未找到build.gradle文件")
            return false
        end

        # 读取并更新gradle文件
        content = File.read(gradle_file)
        updated = false

        # 更新applicationId(支持多种格式)
        # 格式1: applicationId "com.example.app"
        if content =~ /applicationId\s+["'][^"']*["']/
            content.gsub!(/applicationId\s+["'][^"']*["']/, "applicationId \"#{application_id}\"")
            updated = true
        # 格式2: applicationId = "com.example.app"
        elsif content =~ /applicationId\s*=\s*["'][^"']*["']/
            content.gsub!(/applicationId\s*=\s*["'][^"']*["']/, "applicationId = \"#{application_id}\"")
            updated = true
        end

        unless updated
            Funlog.instance.fancyinfo_error("gradle文件中未找到applicationId配置")
            return false
        end

        File.write(gradle_file, content)
        puts "  ✓ 更新 #{File.basename(gradle_file)} 中的 applicationId"
        return true

    rescue StandardError => e
        Funlog.instance.fancyinfo_error("更新Application ID失败: #{e.message}")
        return false
    end
end

.update_applicationid_with_workflowname(project_dir: nil, package_name: nil) ⇒ Boolean

使用工作流名称生成并更新Android Application ID(build.gradle中的applicationId)

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • package_name (String) (defaults to: nil)

    工作流的名称(如:“Test Demo”),将被转换为application ID格式

Returns:

  • (Boolean)

    是否成功更新

Raises:

  • (ArgumentError)


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
# File 'lib/pindo/module/android/android_config_helper.rb', line 280

def self.update_applicationid_with_workflowname(project_dir: nil, package_name: nil)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "Package Name不能为空" if package_name.nil?

    # 生成 Application ID
    app_id_suffix = package_name.gsub(/[^a-zA-Z0-9]/, '').downcase
    application_id = "com.heroneverdie101.#{app_id_suffix}"

    begin
        main_module = Pindo::AndroidProjectHelper.get_main_module(project_dir)

        if main_module.nil?
            # 尝试常见的模块名(优先 launcher,支持 Unity 项目)
            ["launcher", "app", "application", "main"].each do |module_name|
                module_path = File.join(project_dir, module_name)
                if File.exist?(File.join(module_path, "build.gradle")) ||
                   File.exist?(File.join(module_path, "build.gradle.kts"))
                    main_module = module_path
                    break
                end
            end
        end

        return false if main_module.nil?

        # 查找build.gradle或build.gradle.kts文件
        gradle_file = nil
        if File.exist?(File.join(main_module, "build.gradle"))
            gradle_file = File.join(main_module, "build.gradle")
        elsif File.exist?(File.join(main_module, "build.gradle.kts"))
            gradle_file = File.join(main_module, "build.gradle.kts")
        end

        return false if gradle_file.nil?

        # 读取并更新gradle文件
        content = File.read(gradle_file)

        # 更新applicationId(支持多种格式)
        updated = false

        # 格式1: applicationId "com.example.app"
        if content =~ /applicationId\s+["'][^"']*["']/
            content.gsub!(/applicationId\s+["'][^"']*["']/, "applicationId \"#{application_id}\"")
            updated = true
        # 格式2: applicationId = "com.example.app"
        elsif content =~ /applicationId\s*=\s*["'][^"']*["']/
            content.gsub!(/applicationId\s*=\s*["'][^"']*["']/, "applicationId = \"#{application_id}\"")
            updated = true
        # 格式3: applicationId rootProject.ext.application_id (外部变量引用)
        elsif content =~ /applicationId\s+rootProject\.ext\.\w+/
            content.gsub!(/applicationId\s+rootProject\.ext\.\w+/, "applicationId \"#{application_id}\"")
            updated = true
        # 格式4: applicationId project.ext.application_id
        elsif content =~ /applicationId\s+project\.ext\.\w+/
            content.gsub!(/applicationId\s+project\.ext\.\w+/, "applicationId \"#{application_id}\"")
            updated = true
        # 格式5: applicationId ext.application_id
        elsif content =~ /applicationId\s+ext\.\w+/
            content.gsub!(/applicationId\s+ext\.\w+/, "applicationId \"#{application_id}\"")
            updated = true
        end

        unless updated
            Funlog.instance.fancyinfo_error("gradle文件中未找到applicationId字段")
            return false
        end

        File.write(gradle_file, content)
        puts "  ✓ Application ID 已更新为: #{application_id} (来自: #{package_name})"
        return true

    rescue StandardError => e
        Funlog.instance.fancyinfo_error("更新Application ID失败: #{e.message}")
        return false
    end
end

.update_existing_scheme(manifest_path, activity, android_prefix, existing_scheme, scheme_name) ⇒ Object



974
975
976
977
978
979
980
981
982
983
984
985
# File 'lib/pindo/module/android/android_config_helper.rb', line 974

def self.update_existing_scheme(manifest_path, activity, android_prefix, existing_scheme, scheme_name)
    begin
        xml_content = File.read(manifest_path)
        modified = update_scheme_value_in_place(xml_content, existing_scheme, scheme_name)
        return false unless modified

        File.write(manifest_path, modified)
        true
    rescue => e
        return false
    end
end

.update_google_services_package_name(project_dir: nil, package_name: nil) ⇒ Boolean

在 google-services.json 的 client 数组中确保存在目标 Android package_name:不改写已有 client,仅当尚不存在时深拷贝模板 client 并追加,避免切换 bundle id / applicationId 时 Firebase Unity SDK 反复弹窗。

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • package_name (String) (defaults to: nil)

    目标 applicationId(例如: com.heroneverdie101.fancyapptest)

Returns:

  • (Boolean)

    是否至少在一个文件中新追加了 client(已存在目标包名则视为无需写入)

Raises:

  • (ArgumentError)


640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# File 'lib/pindo/module/android/android_config_helper.rb', line 640

def self.update_google_services_package_name(project_dir: nil, package_name: nil)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "Package Name不能为空" if package_name.nil? || package_name.empty?
    raise ArgumentError, "项目路径无效: #{project_dir}" unless File.directory?(project_dir)

    target_files = existing_google_services_json_paths(project_dir)
    if target_files.empty?
        Funlog.instance.fancyinfo_warning("未找到 google-services.json,无法合并 package_name: #{package_name}")
        return false
    end

    updated_any = false

    target_files.each do |target_file|
        begin
            raw = File.read(target_file)
            json = JSON.parse(raw)

            unless json.is_a?(Hash) && json['client'].is_a?(Array) && !json['client'].empty?
                Funlog.instance.fancyinfo_warning("google-services.json 缺少有效 client 数组,跳过: #{target_file}")
                next
            end

            unless google_services_first_android_client(json['client'])
                Funlog.instance.fancyinfo_warning("google-services.json 中无可用 Android client 模板,跳过: #{target_file}")
                next
            end

            merged = google_services_merge_android_package!(json, package_name)
            if merged
                File.write(target_file, JSON.pretty_generate(json) + "\n")
                puts "  ✓ 已合并 #{File.basename(target_file)}:新增 client package_name #{package_name}(保留原有条目)"
                updated_any = true
            end
        rescue JSON::ParserError
            Funlog.instance.fancyinfo_warning("google-services.json 不是合法 JSON,跳过更新: #{target_file}")
        rescue StandardError => e
            Funlog.instance.fancyinfo_warning("更新 google-services.json 失败: #{e.message} (#{target_file})")
        end
    end

    updated_any
end

.update_project_with_workflow(project_dir: nil, workflow_packname: nil) ⇒ Boolean

使用工作流配置一次性更新App Name、Application ID和URL Schemes 优化版本:提高性能,减少代码重复

Parameters:

  • project_dir (String) (defaults to: nil)

    Android项目目录路径

  • workflow_packname (String) (defaults to: nil)

    工作流的名称(如:“Test Demo”)

Returns:

  • (Boolean)

    是否成功更新

Raises:

  • (ArgumentError)


20
21
22
23
24
25
26
27
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
# File 'lib/pindo/module/android/android_config_helper.rb', line 20

def self.update_project_with_workflow(project_dir: nil, workflow_packname: nil)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "Workflow Package Name不能为空" if workflow_packname.nil?

    # 生成各种值
    app_name = workflow_packname.gsub(/[^a-zA-Z0-9\s]/, '').gsub(/\s+/, '')
    app_id_suffix = workflow_packname.gsub(/[^a-zA-Z0-9]/, '').downcase
    application_id = "com.heroneverdie101.#{app_id_suffix}"
    package_scheme = workflow_packname.gsub(/[^a-zA-Z0-9]/, '').downcase
    # bundle_scheme 现在在 update_application_id 中处理

    # 1. 更新 App Name
    success_app_name = update_app_name_with_packagename(
        project_dir: project_dir,
        package_name: workflow_packname
    )

    # 2. 更新 Application ID
    success_app_id = update_applicationid_with_workflowname(
        project_dir: project_dir,
        package_name: workflow_packname
    )

    # 3. 添加基于 package_name 的 Scheme
    success_package_scheme = add_test_scheme(
        project_dir: project_dir,
        scheme_name: package_scheme
    )
    if success_package_scheme
        puts "  ✓ 已添加Scheme: #{package_scheme} (基于 Package Name)"
    end

    # 注意:基于 Application ID 的 Scheme 将在 update_application_id 方法中添加
    # 因为 Application ID 可能在后续流程中被覆盖

    return success_app_name && success_app_id && success_package_scheme
end

.update_scheme_value_in_place(xml_content, existing_scheme, scheme_name) ⇒ Object



987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
# File 'lib/pindo/module/android/android_config_helper.rb', line 987

def self.update_scheme_value_in_place(xml_content, existing_scheme, scheme_name)
    return nil if xml_content.to_s.empty?
    return nil if existing_scheme.to_s.empty? || scheme_name.to_s.empty?

    # 尽量局部替换 data 的 android:scheme / scheme 属性值,避免重排整个 XML。
    patterns = [
        /(?<attr>\bandroid:scheme)\s*=\s*(?<q>["'])#{Regexp.escape(existing_scheme)}\k<q>/,
        /(?<attr>\bscheme)\s*=\s*(?<q>["'])#{Regexp.escape(existing_scheme)}\k<q>/
    ]

    patterns.each do |pat|
        next unless xml_content.match?(pat)
        return xml_content.gsub(pat) { |m| %(#{$~[:attr]}="#{scheme_name}") }
    end

    nil
end