Class: Pindo::GitHandler

Inherits:
Object
  • Object
show all
Extended by:
Executable
Defined in:
lib/pindo/base/git_handler.rb

Overview

Git 操作处理类 提供所有 Git 相关的静态方法,方便其他模块直接调用

Class Method Summary collapse

Methods included from Executable

capture_command, executable, execute_command, popen3, reader, which, which!

Class Method Details

.add_branch(local_repo_dir: nil, branch: nil) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/pindo/base/git_handler.rb', line 88

def add_branch(local_repo_dir: nil, branch: nil)
    # 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
    result = false

    if !local_branch_exists?(local_repo_dir: local_repo_dir, branch: branch)
      git!(%W(-C #{local_repo_dir} checkout -b #{branch}))
      result = true
    end

    git_remote!(local_repo_dir, %W(-C #{local_repo_dir} push origin #{branch}:#{branch}))

    return result
end

.add_tag(local_repo_dir: nil, tag_name: nil) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/pindo/base/git_handler.rb', line 210

def add_tag(local_repo_dir: nil, tag_name: nil)
    # 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
    result = false
    if File.exist?(local_repo_dir)
      if !local_tag_exists?(local_repo_dir: local_repo_dir, tag_name: tag_name)
          git!(%W(-C #{local_repo_dir} tag #{tag_name}))
          result = true
      end
      git_remote!(local_repo_dir, %W(-C #{local_repo_dir} push origin #{tag_name}))
    else
      result = false
    end
    return result
end

.add_tag_with_check(local_repo_dir: nil, tag_name: nil, check: true) ⇒ Object



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
# File 'lib/pindo/base/git_handler.rb', line 225

def add_tag_with_check(local_repo_dir:nil, tag_name:nil, check: true)

    if remote_tag_exists?(local_repo_dir: local_repo_dir, tag_name: tag_name)
        puts
        puts "路径: #{local_repo_dir}"
        puts "Tag: #{tag_name}"
        puts
        puts "仓库已经存在同样tag:#{tag_name} !!!"

        if check
          answer = agree("确定删除远程仓库的tag, 重新添加tag:#{tag_name}吗(Y/n)?:")
          unless answer
              raise Informative, "添加tag异常!!!"
          end
        end

        if local_tag_exists?(local_repo_dir: local_repo_dir, tag_name: tag_name)
            git!(%W(-C #{local_repo_dir} tag -d #{tag_name}))
        end
        git_remote!(local_repo_dir, %W(-C #{local_repo_dir} push origin :#{tag_name}))
        add_tag(local_repo_dir:local_repo_dir, tag_name:tag_name)
    else
        if local_tag_exists?(local_repo_dir: local_repo_dir, tag_name: tag_name)
            git!(%W(-C #{local_repo_dir} tag -d #{tag_name}))
        end
        add_tag(local_repo_dir:local_repo_dir, tag_name:tag_name)
    end
end

.borrow_conventional_desc(git_root) ⇒ String?

从最近 15 条非 merge 提交中找一条符合 Conventional Commits 规范的描述 仅供 get_latest_conventional_commit 内部使用(本文件的类方法均为 public, 加 private 会影响同块内其它对外方法,故以注释标注)

Parameters:

  • git_root (String)

    git 根目录

Returns:

  • (String, nil)

    提交描述;找不到时返回 nil



840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/pindo/base/git_handler.rb', line 840

def borrow_conventional_desc(git_root)
    output = git!(%W(-C #{git_root} log -15 --no-merges --format=%s)).strip
    return nil if output.empty?

    descs = output.split("\n").map { |line| line&.force_encoding('UTF-8')&.scrub('') }

    # 符合规范的提交类型(Conventional Commits 规范),支持 type: 与 type(scope): 两种格式
    valid_types = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert']
    conventional = descs.find do |desc|
      normalized = desc.to_s.strip.downcase
      valid_types.any? { |type| normalized.start_with?("#{type}:") || normalized.start_with?("#{type}(") }
    end

    return conventional if conventional

    Funlog.instance.warning("在最近15个提交中未找到符合规范的提交(feat:, fix: 等开头),保留 merge commit 描述")
    nil
end

.check_submodule_dirty_state(git_root, gitmodules_path) ⇒ Object

检查子模块是否有未提交的内容(脏数据)

Parameters:

  • git_root (String)

    Git 根目录

  • gitmodules_path (String)

    .gitmodules 文件路径



1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
# File 'lib/pindo/base/git_handler.rb', line 1399

def check_submodule_dirty_state(git_root, gitmodules_path)
  submodule_paths = parse_submodule_paths(gitmodules_path)
  dirty_submodules = []

  submodule_paths.each do |path|
    full_path = File.join(git_root, path)
    next unless File.exist?(full_path)

    begin
      # 使用 git status --porcelain 检查是否有修改
      status = git!(%W(-C #{full_path} status --porcelain))

      unless status.nil? || status.strip.empty?
        # 统计修改类型
        lines = status.strip.split("\n")
        untracked = lines.count { |line| line.start_with?('??') }
        modified = lines.count { |line| line.start_with?(' M', 'M ', 'MM') }
        added = lines.count { |line| line.start_with?('A ') }
        deleted = lines.count { |line| line.start_with?(' D', 'D ') }

        dirty_submodules << {
          path: path,
          untracked: untracked,
          modified: modified,
          added: added,
          deleted: deleted,
          total: lines.size
        }
      end
    rescue => e
      # 忽略错误,继续检查其他子模块
    end
  end

  # 如果有脏数据,显示警告
  unless dirty_submodules.empty?
    puts "\n"
    Funlog.instance.fancyinfo_warning("⚠️  检测到 #{dirty_submodules.size} 个子模块包含未提交的内容")
    puts "\n以下子模块有未提交的修改:\n".yellow

    dirty_submodules.each do |submodule|
      puts "#{submodule[:path]}:".yellow
      puts "    - 未跟踪文件: #{submodule[:untracked]}".yellow if submodule[:untracked] > 0
      puts "    - 已修改文件: #{submodule[:modified]}".yellow if submodule[:modified] > 0
      puts "    - 已添加文件: #{submodule[:added]}".yellow if submodule[:added] > 0
      puts "    - 已删除文件: #{submodule[:deleted]}".yellow if submodule[:deleted] > 0
    end

    puts "\n建议处理方式:".yellow
    puts "  1. 进入子模块目录处理这些修改:cd #{dirty_submodules.first[:path]}".yellow
    puts "  2. 在子模块中提交修改:git add . && git commit -m 'message'".yellow
    puts "  3. 或者丢弃修改:git clean -fd && git reset --hard\n".yellow
  end
end

.check_submodule_path_conflicts(git_root, gitmodules_path) ⇒ Array<Hash>

检查子模块路径冲突

Parameters:

  • git_root (String)

    Git 根目录

  • gitmodules_path (String)

    .gitmodules 文件路径

Returns:

  • (Array<Hash>)

    冲突列表,每个元素包含 :path, :full_path, :files



1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
# File 'lib/pindo/base/git_handler.rb', line 1369

def check_submodule_path_conflicts(git_root, gitmodules_path)
  submodule_paths = parse_submodule_paths(gitmodules_path)
  conflicts = []

  submodule_paths.each do |path|
    full_path = File.join(git_root, path)

    # 检查:路径存在 && 不是 git 仓库 && 不为空
    if File.exist?(full_path) && File.directory?(full_path)
      git_dir = File.join(full_path, '.git')

      unless File.exist?(git_dir)
        # 检查目录是否为空
        unless Dir.empty?(full_path)
          conflicts << {
            path: path,
            full_path: full_path,
            files: Dir.children(full_path).size
          }
        end
      end
    end
  end

  conflicts
end

.check_unpushed_commits(project_dir:, branch:) ⇒ void

This method returns an undefined value.

检查并推送未推送的本地提交,确保本地和远程分支完全同步

Parameters:

  • project_dir (String)

    项目目录路径

  • branch (String)

    分支名称



1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/pindo/base/git_handler.rb', line 1178

def check_unpushed_commits(project_dir:, branch:)
  remote_branch = "origin/#{branch}"

  # 1. 检查远程分支是否存在
  remote_exists = false
  begin
    git!(%W(-C #{project_dir} rev-parse --verify #{remote_branch}))
    remote_exists = true
  rescue => e
    # 远程分支不存在
    remote_exists = false
  end

  # 2. 如果远程分支不存在,直接推送创建远程分支
  unless remote_exists
    Funlog.instance.fancyinfo_warning("远程分支 #{remote_branch} 不存在,需要创建")
    Funlog.instance.fancyinfo_start("正在推送并创建远程分支...")
    git_remote!(project_dir, %W(-C #{project_dir} push -u origin #{branch}))
    Funlog.instance.fancyinfo_success("远程分支创建成功!")
    return
  end

  # 3. 先 fetch 获取最新的远程状态
  git_remote!(project_dir, %W(-C #{project_dir} fetch origin #{branch}))

  # 4. 检查本地分支是否领先远程分支
  ahead_count = git!(%W(-C #{project_dir} rev-list --count #{remote_branch}..#{branch})).strip.to_i

  # 5. 检查远程分支是否领先本地分支
  behind_count = git!(%W(-C #{project_dir} rev-list --count #{branch}..#{remote_branch})).strip.to_i

  # 6. 根据同步状态执行相应操作
  if ahead_count == 0 && behind_count == 0
    Funlog.instance.fancyinfo_success("本地分支 #{branch} 与远程分支完全同步")
    return
  elsif ahead_count > 0 && behind_count == 0
    # 仅本地领先:直接推送
    Funlog.instance.fancyinfo_warning("检测到 #{ahead_count} 个本地提交尚未推送")
    Funlog.instance.fancyinfo_start("正在推送到远程分支 #{remote_branch}...")
    git_remote!(project_dir, %W(-C #{project_dir} push origin #{branch}))
    Funlog.instance.fancyinfo_success("推送成功!")
  elsif ahead_count == 0 && behind_count > 0
    # 仅远程领先:重置本地到远程位置
    Funlog.instance.fancyinfo_warning("远程分支领先本地 #{behind_count} 个提交")

    # 检查工作目录是否干净
    status = git!(%W(-C #{project_dir} status --porcelain)).strip
    unless status.empty?
      raise Informative, "工作目录有未提交的修改,无法同步远程更新。请先提交或 stash 修改。"
    end

    # 工作目录干净,安全地重置到远程位置
    Funlog.instance.fancyinfo_start("正在重置本地分支到远程位置...")
    git!(%W(-C #{project_dir} reset --hard #{remote_branch}))
    Funlog.instance.fancyinfo_success("已同步到远程分支!")
  else
    # 分叉:需要合并
    Funlog.instance.fancyinfo_warning("本地和远程分支已分叉:本地领先 #{ahead_count} 个提交,远程领先 #{behind_count} 个提交")
    raise Informative, "本地分支和远程分支已分叉,请手动合并或变基后再继续!"
  end
end

.clone_clang_repoObject



494
495
496
497
498
499
500
501
502
503
504
# File 'lib/pindo/base/git_handler.rb', line 494

def clone_clang_repo
  pindo_dir = File::expand_path(Pindoconfig.instance.pindo_dir)
  if !File.exist?(pindo_dir)
    FileUtils.mkdir(pindo_dir)
  end

  getcode_to_dir(reponame:"deployclang", remote_url:Pindoconfig.instance.deploy_clang_giturl, path:pindo_dir)

  config_repo_dir = File.join(pindo_dir, "deployclang")
  return config_repo_dir
end

.clone_devclang_repoObject



482
483
484
485
486
487
488
489
490
491
492
# File 'lib/pindo/base/git_handler.rb', line 482

def clone_devclang_repo
  pindo_dir = File::expand_path(Pindoconfig.instance.pindo_dir)
  if !File.exist?(pindo_dir)
    FileUtils.mkdir(pindo_dir)
  end

  getcode_to_dir(reponame:"confuseclang", remote_url:Pindoconfig.instance.dev_clang_giturl, path:pindo_dir)

  config_repo_dir = File.join(pindo_dir, "confuseclang")
  return config_repo_dir
end

.clone_pindo_common_config_repo(force_delete: false) ⇒ Object



447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/pindo/base/git_handler.rb', line 447

def clone_pindo_common_config_repo(force_delete:false)
  pindo_dir = File::expand_path(Pindoconfig.instance.pindo_dir)
  if !File.exist?(pindo_dir)
    FileUtils.mkdir(pindo_dir)
  end

  common_config_dir_basename = get_repo_base_name(repo_url:Pindoconfig.instance.pindo_common_config_giturl)
  config_repo_dir = File.join(pindo_dir, common_config_dir_basename)
  if force_delete
    if File.exist?(config_repo_dir)
      FileUtils.rm_rf(config_repo_dir)
    end
  end
  getcode_to_dir(reponame:common_config_dir_basename, remote_url:Pindoconfig.instance.pindo_common_config_giturl, path:pindo_dir)

  return config_repo_dir
end

.clone_pindo_env_config_repo(force_delete: false) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/pindo/base/git_handler.rb', line 465

def clone_pindo_env_config_repo(force_delete:false)
  pindo_dir = File::expand_path(Pindoconfig.instance.pindo_dir)
  if !File.exist?(pindo_dir)
    FileUtils.mkdir(pindo_dir)
  end

  env_config_dir_basename = get_repo_base_name(repo_url:Pindoconfig.instance.pindo_env_config_giturl)
  config_repo_dir = File.join(pindo_dir, env_config_dir_basename)
  if force_delete
    if File.exist?(config_repo_dir)
      FileUtils.rm_rf(config_repo_dir)
    end
  end
  getcode_to_dir(reponame:env_config_dir_basename, remote_url:Pindoconfig.instance.pindo_env_config_giturl, path:pindo_dir)
  return config_repo_dir
end

.clong_buildconfig_repo(repo_name: nil) ⇒ Object



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
# File 'lib/pindo/base/git_handler.rb', line 419

def clong_buildconfig_repo(repo_name:nil)


  pindo_dir = File::expand_path(Pindoconfig.instance.pindo_dir)
  if !File.exist?(pindo_dir)
    FileUtils.mkdir(pindo_dir)
  end

  # 通配符 bundle id (如 com.eyesofstorms.*) 对应的仓库名去掉 .* 后缀
  actual_repo_name = repo_name&.gsub(".*", "") || repo_name

  repo_org_name = Pindoconfig.instance.build_deploy_org

  git_repo_file = File.join(Pindoconfig.instance.pindo_env_configdir,  "git_base_url.json")
  git_repo_json = JSON.parse(File.read(git_repo_file))
  if actual_repo_name && git_repo_json && git_repo_json[actual_repo_name]
    repo_org_name = git_repo_json[actual_repo_name]
  end

  url = File.join("https://gitee.com", repo_org_name, actual_repo_name + ".git")
  getcode_to_dir(reponame:actual_repo_name, remote_url: url, path:pindo_dir)
  config_repo_dir = File.join(pindo_dir, actual_repo_name)



  return config_repo_dir
end

.create_next_version_tag(project_dir: nil, tag_prefix: "v", increment_mode: "minor", force_retag: false) ⇒ String

创建新的版本标签

Parameters:

  • project_dir (String) (defaults to: nil)

    项目目录路径

  • tag_prefix (String) (defaults to: "v")

    标签前缀

  • increment_mode (String) (defaults to: "minor")

    版本号增加模式 ("major", "minor", "patch")

  • force_retag (Boolean) (defaults to: false)

    是否强制重新打最新的tag

Returns:

  • (String)

    返回新创建的版本标签或已存在的标签

Raises:

  • (ArgumentError)

    当项目目录不存在时抛出



866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
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
# File 'lib/pindo/base/git_handler.rb', line 866

def create_next_version_tag(project_dir:nil, tag_prefix:"v", increment_mode:"minor", force_retag:false)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?

    latest_tag = get_latest_version_tag(project_dir: project_dir, tag_prefix: tag_prefix)
    if latest_tag.nil?
        latest_tag = get_latest_version_tag(project_dir: project_dir, tag_prefix: "")
    end
    # 如果没有任何tag,创建初始版本
    if latest_tag.nil?
        new_tag = tag_prefix + "1.0.0"
        add_tag_with_check(local_repo_dir: project_dir, tag_name: new_tag, check: false)
        Funlog.instance.fancyinfo_success("创建新tag完成!")
        return new_tag
    end

    if is_tag_at_head?(git_root_dir: project_dir, tag_name: latest_tag)
        return latest_tag
    end

    if force_retag && latest_tag
        # 删除并重新打tag
        Funlog.instance.fancyinfo_update("正在重新打tag: #{latest_tag}")
        remove_tag(local_repo_dir: project_dir, tag_name: latest_tag)
        add_tag_with_check(local_repo_dir: project_dir, tag_name: latest_tag)
        Funlog.instance.fancyinfo_success("重新打tag完成!")
        return latest_tag
    end

    # 解析当前版本号
    version_numbers = latest_tag.gsub(tag_prefix, '').split('.').map(&:to_i)
    major, minor, patch = version_numbers

    # 根据increment_mode增加版本号
    case increment_mode
    when "major"
        major += 1
        minor = 0
        patch = 0
    when "minor"
        minor += 1
        patch = 0
    when "patch"
        patch += 1
    end

    new_tag = tag_prefix + "#{major}.#{minor}.#{patch}"
    add_tag_with_check(local_repo_dir: project_dir, tag_name: new_tag, check: false)
    Funlog.instance.fancyinfo_success("创建新tag完成!")
    new_tag
end

.current_branch_name(local_repo_dir: nil) ⇒ String?

获取仓库当前所在分支名

Parameters:

  • local_repo_dir (String) (defaults to: nil)

    仓库目录

Returns:

  • (String, nil)

    分支名;detached HEAD、非仓库或读取失败时返回 nil



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/pindo/base/git_handler.rb', line 155

def current_branch_name(local_repo_dir: nil)
    return nil if local_repo_dir.nil?

    branch = git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip
    # detached HEAD 时 git 返回字面量 "HEAD",不是分支名
    return nil if branch.empty? || branch == 'HEAD'

    branch
rescue StandardError
    nil
end

.display_file_status(branch, files) ⇒ Object

显示未提交的文件状态

Parameters:

  • branch (String)

    当前分支名

  • files (Array<String>, String)

    文件列表



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/pindo/base/git_handler.rb', line 656

def display_file_status(branch, files)
    puts "" * 60
    puts "⚠️  警告:检测到未提交的文件".red
    puts "" * 60
    puts
    puts "当前所在分支: #{branch}".red
    puts "以下文件尚未提交到 Git:".red
    puts

    # 将文件列表分行并用红色显示
    # 防御性编码归一化:git! 返回的是 ASCII-8BIT,与 UTF-8 字面量 "  • " 拼接会抛
    # Encoding::CompatibilityError;此处再兜一层,避免其它调用方传入 BINARY 字符串时崩溃
    file_lines = files.is_a?(String) ? files.split("\n") : Array(files)
    file_lines.each do |file|
        next if file.nil? || file.empty?
        safe_file = file.dup.force_encoding('UTF-8').scrub
        puts "#{safe_file}".red
    end

    puts
    puts "" * 60
end

.display_submodules_status(git_root) ⇒ Object

显示子模块状态信息

Parameters:

  • git_root (String)

    Git 根目录



1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
# File 'lib/pindo/base/git_handler.rb', line 1332

def display_submodules_status(git_root)
  begin
    status_output = git!(%W(-C #{git_root} submodule status --recursive))

    unless status_output.nil? || status_output.strip.empty?
      puts "\n" + "" * 60
      puts "子模块状态".center(60)
      puts "" * 60
      puts status_output
      puts "" * 60 + "\n"
    end
  rescue StandardError => e
    Funlog.instance.warning("无法获取子模块状态: #{e.message}")
  end
end

.get_latest_conventional_commit(project_dir: nil, tag_prefix: 'v') ⇒ Hash

获取本次构建对应的 commit commit_id 与 commit_time 恒为 HEAD:调用方(包绑定、媒体上传、工作流消息) 要的是「本次构建所在的节点」,提交信息是否符合 Conventional Commits、 是不是 merge commit,都不改变这一点——沿历史回溯只会关联到与本次构建无关的祖先提交。

只有 commit_desc 会被替换:HEAD 是 merge commit 时其描述通常是无信息量的 "Merge branch ...",此时从最近 15 条非 merge 提交中借用一条规范提交的描述。

Parameters:

  • project_dir (String) (defaults to: nil)

    项目目录路径

  • tag_prefix (String) (defaults to: 'v')

    tag前缀,用于识别 HEAD 上的版本 tag,默认 'v'

Returns:

  • (Hash)

    包含 :commit_id, :commit_time, :commit_desc



786
787
788
789
790
791
792
793
794
795
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
# File 'lib/pindo/base/git_handler.rb', line 786

def get_latest_conventional_commit(project_dir:nil, tag_prefix: 'v')
    result = {
      commit_id: nil,
      commit_time: nil,
      commit_desc: nil
    }

    return result if project_dir.nil? || !File.exist?(project_dir)

    # 获取 git 根目录
    git_root = git_root_directory(local_repo_dir: project_dir)
    return result unless git_root

    begin
      # 1. 取 HEAD 的 commit 信息(commit_id / commit_time 以此为准)
      head_info = git!(%W(-C #{git_root} log -1 --format=%H|%ci|%s HEAD)).strip
      if head_info.empty?
        Funlog.instance.warning("未找到 git commit 历史")
        return result
      end

      parts = head_info.split('|', 3)
      result[:commit_id] = parts[0]
      result[:commit_time] = parts[1]
      result[:commit_desc] = parts[2]&.force_encoding('UTF-8')&.scrub('')

      if head_has_version_tag?(project_dir: git_root, tag_prefix: tag_prefix)
        puts "  HEAD 存在版本 tag,使用 HEAD commit: #{result[:commit_desc]}"
        return result
      end

      # 2. HEAD 不是 merge commit:描述本身有效,直接返回
      head_parents = git!(%W(-C #{git_root} rev-list --parents -1 HEAD)).strip.split(/\s+/)
      unless head_parents.size > 2
        puts "  使用 HEAD commit: #{result[:commit_desc]}"
        return result
      end

      # 3. HEAD 是 merge commit:commit 仍用 HEAD,只借用祖先的规范提交描述
      result[:commit_desc] = borrow_conventional_desc(git_root) || result[:commit_desc]
      puts "  HEAD 为 merge commit,使用 HEAD commit + 祖先描述: #{result[:commit_desc]}"
    rescue StandardError => e
      Funlog.instance.warning("获取 commit 信息失败: #{e.message}")
      return result
    end

    result
end

.get_latest_version_tag(project_dir: nil, tag_prefix: "v") ⇒ String?

获取最新的版本标签

Parameters:

  • project_dir (String) (defaults to: nil)

    项目目录路径

Returns:

  • (String, nil)

    返回最新的版本标签,如果没有则返回nil



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/pindo/base/git_handler.rb', line 756

def get_latest_version_tag(project_dir:nil, tag_prefix:"v")
    return nil unless project_dir && File.exist?(project_dir)

    begin
        # 获取所有以v开头的标签并按版本号排序
        tags = git!(%W(-C #{project_dir} tag -l #{tag_prefix}*)).split("\n")
        return nil if tags.empty?

        # 按版本号排序(假设格式为 v1.2.3)
        sorted_tags = tags.sort_by do |tag|
            tag.gsub(tag_prefix, '').split('.').map(&:to_i)
        end

        sorted_tags.last
    rescue StandardError => e
        nil
    end
end

.get_repo_base_name(repo_url: nil) ⇒ Object



411
412
413
414
415
416
417
# File 'lib/pindo/base/git_handler.rb', line 411

def get_repo_base_name(repo_url:nil)
  temp_url = String.new(repo_url)
  index = temp_url.rindex('/')
  temp_url = temp_url.slice(index + 1, temp_url.length)
  base_name = temp_url.gsub!(/\.git/, "")
  return base_name
end

.get_uncommitted_files(project_dir:) ⇒ Array<String>?

获取未提交的文件列表

Parameters:

  • project_dir (String)

    项目目录路径

Returns:

  • (Array<String>, nil)

    返回未提交的文件列表,如果没有则返回 nil

Raises:

  • (ArgumentError)


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
# File 'lib/pindo/base/git_handler.rb', line 562

def get_uncommitted_files(project_dir:)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?

    begin
        # 1. 检查是否是 Git 仓库,并获取 Git 根目录
        git_root = git_root_directory(local_repo_dir: project_dir)

        # 2. 如果不是 Git 仓库,返回 nil
        unless git_root
            Funlog.instance.fancyinfo_warning("当前目录不是Git仓库,跳过Git操作")
            return nil
        end

        # 3. 使用 Git 根目录执行 Git 命令
        # 重置暂存区
        git!(%W(-C #{git_root} restore --staged #{git_root}))

        # 获取未跟踪和已修改的文件
        files_list = git!(%W(-C #{git_root} ls-files --other --modified --exclude-standard)) || []

        # 返回文件列表(如果为空则返回 nil)
        if files_list.nil? || files_list.empty?
            return nil
        end

        # git!/IO#readpartial 返回的是 ASCII-8BIT 字符串,含非 ASCII 字节(如中文路径、
        # core.quotePath=false 时的原始多字节)会与下游 UTF-8 字面量拼接失败,这里统一
        # 标成 UTF-8 并 scrub 无效字节,避免上层 `puts "...#{file}"` 抛 Encoding::CompatibilityError
        raw_list = files_list.is_a?(String) ? files_list.split("\n") : Array(files_list)
        raw_list.map { |f| f.dup.force_encoding('UTF-8').scrub }.reject(&:empty?)
    rescue => e
        Funlog.instance.fancyinfo_error("获取未提交文件列表失败: #{e.message}")
        nil
    end
end

.get_uncommitted_files_process_type(project_dir:, interactive: true, default_process_type: nil) ⇒ Symbol

获取未提交文件的处理方式

Parameters:

  • project_dir (String)

    项目目录路径

  • interactive (Boolean) (defaults to: true)

    是否允许交互,默认为 true

  • default_process_type (Symbol, nil) (defaults to: nil)

    非交互模式下的默认处理方式,默认为 nil

Returns:

  • (Symbol)

    UncommittedFilesProcessType 枚举常量



972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/pindo/base/git_handler.rb', line 972

def get_uncommitted_files_process_type(project_dir:, interactive: true, default_process_type: nil)
  # 1. 检查是否有未提交的文件
  uncommitted_files = get_uncommitted_files(project_dir: project_dir)

  # 2. 如果没有未提交的文件,返回 NONE 类型
  # 未显式指定处理方式时必须返回 NONE 而不是 nil:nil 会让 GitCommitTask 兜底成
  # SKIP_WITH_TAG,导致构建阶段注入的源码修改在打 tag 时被当作"用户选择不提交"而跳过。
  if uncommitted_files.nil? || uncommitted_files.empty?
    return default_process_type || Pindo::UncommittedFilesProcessType::NONE
  end

  # 3. 如果非交互模式,使用指定的处理方式
  unless interactive
    Funlog.instance.info("当前处于非交互模式,使用指定的处理方式: #{default_process_type}")
    return default_process_type
  end

  # 4. 获取 Git 根目录并获取当前分支名
  git_root = git_root_directory(local_repo_dir: project_dir)
  unless git_root
    Funlog.instance.fancyinfo_warning("当前目录不是Git仓库")
    return Pindo::UncommittedFilesProcessType::SKIP_WITH_TAG
  end

  current_branch = git!(%W(-C #{git_root} rev-parse --abbrev-ref HEAD)).strip
  display_file_status(current_branch, uncommitted_files)

  # 5. 交互式选择
  # 危险选项在这里就地二次确认:此时未提交文件列表还在屏幕上,用户能看着清单做决定。
  # 若把确认延后到任务执行阶段,中间会隔着任务计划输出,用户看不到自己要丢弃的是哪些文件。
  cli = HighLine.new
  loop do
    choice = cli.choose do |menu|
      menu.header = "仓库有未提交的修改,请选择处理方式"
      menu.prompt = "请输入选项(1/2/3/4/5/6):"
      menu.choice("(commit) 全部提交") { Pindo::UncommittedFilesProcessType::COMMIT }
      menu.choice("(skip-with-tag) 不提交,但合并分支并打tag") { Pindo::UncommittedFilesProcessType::SKIP_WITH_TAG }
      menu.choice("(skip-without-tag) 不提交,不合并分支,不打tag") { Pindo::UncommittedFilesProcessType::SKIP_WITHOUT_TAG }
      menu.choice("(reset) 全部丢弃更改,回滚代码") { Pindo::UncommittedFilesProcessType::RESET }
      menu.choice("(stash) 保存到stash区域(该部分代码本次编译不生效)") { Pindo::UncommittedFilesProcessType::STASH }
      menu.choice("(exit) 先退出,手动来处理退出") { Pindo::UncommittedFilesProcessType::EXIT }
    end

    # reset 会 reset --hard + clean -df,改动无法恢复,必须当场确认
    if choice == Pindo::UncommittedFilesProcessType::RESET
      puts
      puts "⚠️  以上 #{Array(uncommitted_files).size} 个文件的修改将被永久丢弃,无法恢复".red
      unless cli.agree("确认删除?(y/n) ")
        puts "已取消,请重新选择处理方式".yellow
        puts
        next
      end
    end

    return choice
  end
end

.getcode_to_dir(reponame: nil, remote_url: nil, path: nil, new_branch: "master", new_tag: nil) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/pindo/base/git_handler.rb', line 318

def getcode_to_dir(reponame:nil, remote_url:nil, path: nil, new_branch:"master", new_tag: nil)

  current=Dir.pwd
  local_repo_dir = File::join(path, reponame)

  # gitee.com 仓库自动去除代理
  if remote_url && remote_url.include?("gitee.com")
    return without_proxy { getcode_to_dir_impl(reponame: reponame, remote_url: remote_url, path: path, new_branch: new_branch, new_tag: new_tag) }
  end

  getcode_to_dir_impl(reponame: reponame, remote_url: remote_url, path: path, new_branch: new_branch, new_tag: new_tag)
end

.getcode_to_dir_impl(reponame: nil, remote_url: nil, path: nil, new_branch: "master", new_tag: nil) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/pindo/base/git_handler.rb', line 331

def getcode_to_dir_impl(reponame:nil, remote_url:nil, path: nil, new_branch:"master", new_tag: nil)

  current=Dir.pwd
  local_repo_dir = File::join(path, reponame)

  Funlog.instance.fancyinfo_update("开始更新仓库:#{local_repo_dir}...")

  begin


    if !reponame.empty? && !remote_url.empty? && !path.empty?

        if File.exist?(local_repo_dir)
          Dir.chdir(local_repo_dir)

          remote_info = git!(%W(remote -v))
          if remote_info.include?("git.coding.net")
            current_branch = git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip
            git!(%W(remote remove origin))
            git!(%W(remote add origin #{remote_url}))
            args = %W(-C #{local_repo_dir} fetch origin)
            args.push('--progress')
            git_remote!(local_repo_dir, args)
            git!(%W(-C #{local_repo_dir} branch --set-upstream-to=origin/#{current_branch}  #{current_branch}))
          end

          git_remote!(local_repo_dir, %W(-C #{local_repo_dir} fetch origin --progress))
        else
          if remote_url&.include?("gitee.com")
            without_proxy { git!(['clone', remote_url, local_repo_dir]) }
          else
            git!(['clone', remote_url, local_repo_dir])
          end
        end

        Dir.chdir(local_repo_dir)
        current_branch = git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip
        if current_branch.eql?(new_branch)
            git!(%W(-C #{local_repo_dir} reset --hard origin/#{new_branch}))
            git!(%W(-C #{local_repo_dir} branch --set-upstream-to=origin/#{new_branch} #{new_branch}))
            git_remote!(local_repo_dir, %W(-C #{local_repo_dir} pull))

        else
          git!(%W(-C #{local_repo_dir} clean -fd))
          if local_branch_exists?(local_repo_dir:local_repo_dir, branch:new_branch)
            git!(%W(-C #{local_repo_dir} checkout #{new_branch}))
          else
            if !remote_branch_exists?(local_repo_dir:local_repo_dir, branch:new_branch)
                git!(%W(-C #{local_repo_dir} checkout -b #{new_branch}))
            else
                raise Informative, "仓库中的#{new_branch}分支不存在 !!!"
            end
          end
          git!(%W(-C #{local_repo_dir} branch --set-upstream-to=origin/#{new_branch} #{new_branch}))
          git_remote!(local_repo_dir, %W(-C #{local_repo_dir} pull))
        end

        if !new_tag.nil? && new_tag != ""
          if !new_tag.nil? && new_tag != "" && local_tag_exists?(local_repo_dir:local_repo_dir, tag_name:new_tag)
            puts "tag : #{new_tag} is exist !!!"
            git!(%W(-C #{local_repo_dir} checkout #{new_tag}))
          else
            raise Informative, "tag #{new_tag} is not exist !!!"
          end
        end

    end
    $stdin.flush
    Funlog.instance.fancyinfo_success("仓库#{local_repo_dir}更新完成!")
  rescue StandardError => e
    Funlog.instance.fancyinfo_error("仓库#{local_repo_dir}更新失败!")
    raise Informative, e.to_s
  ensure
    # 无论成功失败都还原 cwd,避免异常路径下污染全局工作目录
    Dir.chdir(current)
  end

  return local_repo_dir
end

.git_addpush_repo(path: nil, message: "chore(config): pindo 提交配置变更", commit_file_params: nil) ⇒ Object



506
507
508
509
510
511
512
513
# File 'lib/pindo/base/git_handler.rb', line 506

def git_addpush_repo(path:nil, message:"chore(config): pindo 提交配置变更", commit_file_params:nil)
  # gitee.com 仓库自动去除代理;is_gitee_repo? 命令已带 -C,无需 chdir
  if is_gitee_repo?(local_repo_dir: path)
    return without_proxy { git_addpush_repo_impl(path: path, message: message, commit_file_params: commit_file_params) }
  end

  git_addpush_repo_impl(path: path, message: message, commit_file_params: commit_file_params)
end

.git_addpush_repo_impl(path: nil, message: "chore(config): pindo 提交配置变更", commit_file_params: nil) ⇒ Object



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/pindo/base/git_handler.rb', line 515

def git_addpush_repo_impl(path:nil, message:"chore(config): pindo 提交配置变更", commit_file_params:nil)
  current=Dir.pwd
  Dir.chdir(path)
  begin
      if !commit_file_params.nil? && !commit_file_params.empty?
        files_list = git! ['ls-files', '--other', '--modified', '--exclude-standard'] || []

        need_commit = false
        commit_file_params.each do |file_name|
          if !files_list.nil? && files_list.size > 0 && files_list.include?(file_name)
              need_commit = true
              git! ['add', file_name]
          end
        end
        if need_commit
          git! ['commit', '-m', message]
          git! ['push']
        else
          # puts "\n#{path}\n!!!仓库中文件未发生变化,无需提交!!!\n"
        end
      else
        files_list = git! ['ls-files', '--other', '--modified', '--exclude-standard'] || []
        # puts "提交如下内容:"
        # puts files_list
        if !files_list.nil? && files_list.size > 0
            git! ['add', '-A']
            git! ['commit', '-m', message]
            git! ['push']
        else
          puts "\n#{path}\n!!!仓库中文件未发生变化,无需提交!!!\n"
        end
      end

  rescue => error
      # puts(error.to_s)
      raise Informative, "\n#{path}\n 仓库失败 !!!"
  ensure
      # 无论成功失败都还原 cwd,避免异常路径下污染全局工作目录
      Dir.chdir(current)
  end
end

.git_latest_commit_id(local_repo_dir: nil) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/pindo/base/git_handler.rb', line 302

def git_latest_commit_id(local_repo_dir:nil)
  # 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
  unless File.exist?(File::join(local_repo_dir, ".git"))
    return nil
  end

  commit_id = nil

  if File.exist?(local_repo_dir)
    current_branch = git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip
    commit_id = git!(%W(-C #{local_repo_dir} rev-parse #{current_branch})).strip
  end

  return commit_id
end

.git_remote!(project_dir, args) ⇒ Object

执行需要联网的 git 命令(fetch / push / pull) 若仓库地址包含 gitee.com,自动清除代理环境变量再执行

Parameters:

  • project_dir (String)

    仓库目录(用于判断是否 gitee)

  • args (Array)

    git 命令参数



59
60
61
62
63
64
65
# File 'lib/pindo/base/git_handler.rb', line 59

def git_remote!(project_dir, args)
  if is_gitee_repo?(local_repo_dir: project_dir)
    without_proxy { git!(args) }
  else
    git!(args)
  end
end

.git_root_directory(local_repo_dir: nil) ⇒ Object



77
78
79
80
81
82
83
84
85
86
# File 'lib/pindo/base/git_handler.rb', line 77

def git_root_directory(local_repo_dir: nil)
  return nil unless is_git_directory?(local_repo_dir: local_repo_dir)

  args = local_repo_dir ? %W(-C #{local_repo_dir} rev-parse --show-toplevel) : %w(rev-parse --show-toplevel)
  begin
    git!(args).strip
  rescue StandardError => e
    nil
  end
end

.has_uncommitted_changes?(git_root_dir: nil) ⇒ Boolean

检查仓库是否有未提交的更改(包括未暂存和已暂存的更改)

Parameters:

  • git_root_dir (String) (defaults to: nil)

    项目目录路径

Returns:

  • (Boolean)

    如果有未提交的更改返回true,否则返回false



934
935
936
937
938
939
940
941
942
943
944
945
# File 'lib/pindo/base/git_handler.rb', line 934

def has_uncommitted_changes?(git_root_dir:nil)
    return false if git_root_dir.nil?

    begin
        # 使用 git status --porcelain 检查是否有更改
        # 如果输出不为空,说明有未提交的更改
        status_output = git!(%W(-C #{git_root_dir} status --porcelain)).strip
        !status_output.empty?
    rescue StandardError => e
        false
    end
end

.head_has_version_tag?(project_dir:, tag_prefix: 'v') ⇒ Boolean

检查 HEAD 是否已有版本 tag

Parameters:

  • project_dir (String)

    项目目录

  • tag_prefix (String) (defaults to: 'v')

    tag前缀,默认 'v'

Returns:

  • (Boolean)

    HEAD 是否有版本 tag



921
922
923
924
925
926
927
928
929
# File 'lib/pindo/base/git_handler.rb', line 921

def head_has_version_tag?(project_dir:, tag_prefix: 'v')
  latest_tag = get_latest_version_tag(
    project_dir: project_dir,
    tag_prefix: tag_prefix
  )
  return false if latest_tag.nil?

  is_tag_at_head?(git_root_dir: project_dir, tag_name: latest_tag)
end

.is_git_directory?(local_repo_dir: nil) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
70
71
72
73
74
75
# File 'lib/pindo/base/git_handler.rb', line 67

def is_git_directory?(local_repo_dir: nil)
  args = local_repo_dir ? %W(-C #{local_repo_dir} rev-parse --is-inside-work-tree) : %w(rev-parse --is-inside-work-tree)
  begin
    git!(args)
    true
  rescue StandardError => e
    false
  end
end

.is_gitee_repo?(local_repo_dir: nil) ⇒ Boolean

检查指定目录的 Git 仓库是否使用 gitee.com 远程地址

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
32
# File 'lib/pindo/base/git_handler.rb', line 24

def is_gitee_repo?(local_repo_dir: nil)
  return false if local_repo_dir.nil? || !File.exist?(local_repo_dir)
  begin
    remote_url = git!(%W(-C #{local_repo_dir} remote get-url origin)).strip rescue ""
    remote_url.include?("gitee.com")
  rescue
    false
  end
end

.is_tag_at_head?(git_root_dir: nil, tag_name: nil) ⇒ Boolean

检查tag是否在指定的commit上

Parameters:

  • git_root_dir (String) (defaults to: nil)

    项目目录路径

  • tag_name (String) (defaults to: nil)

    标签名称

Returns:

  • (Boolean)

    如果tag在当前HEAD上返回true,否则返回false



951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
# File 'lib/pindo/base/git_handler.rb', line 951

def is_tag_at_head?(git_root_dir:nil, tag_name:nil)
    return false if git_root_dir.nil? || tag_name.nil?

    begin
        # 获取tag指向的commit hash(使用^{commit}解引用,支持annotated tag和lightweight tag)
        tag_commit = git!(%W(-C #{git_root_dir} rev-parse #{tag_name}^{commit})).strip
        # 获取HEAD的commit hash
        head_commit = git!(%W(-C #{git_root_dir} rev-parse HEAD)).strip

        # 比较两个commit hash是否相同
        tag_commit == head_commit
    rescue StandardError => e
        false
    end
end

.local_branch_exists?(local_repo_dir: nil, branch: nil) ⇒ Boolean

Returns:

  • (Boolean)


124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/pindo/base/git_handler.rb', line 124

def local_branch_exists?(local_repo_dir: nil, branch: nil)
    # 命令改带 -C,去掉 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
    return false unless local_repo_dir && File.exist?(local_repo_dir)
    return false if branch.nil? || branch.to_s.strip.empty?

    # 注意:capture_command(:capture => :out) 返回 [stdout, status] 数组,
    # 必须判断 stdout 内容而非整个数组(数组恒非空会误判任何分支“存在”)。
    # 用 show-ref --verify 精确校验本地分支 refs/heads/<branch>。
    res_data = Executable.capture_command('git', %W(-C #{local_repo_dir} show-ref --verify refs/heads/#{branch}), :capture => :out)
    stdout = res_data.is_a?(Array) ? res_data.first.to_s : res_data.to_s
    !stdout.strip.empty?
end

.local_tag_exists?(local_repo_dir: nil, tag_name: nil) ⇒ Boolean

Returns:

  • (Boolean)


296
297
298
299
300
# File 'lib/pindo/base/git_handler.rb', line 296

def local_tag_exists?(local_repo_dir: nil, tag_name: nil)
    return false if local_repo_dir.nil? || !File.exist?(local_repo_dir)
    res_data = git!(%W(-C #{local_repo_dir} tag --list #{tag_name}))
    !res_data.nil? && !res_data.empty?
end

.merge_branches(project_dir:, source_branch:, target_branch:, sync_branches: false) ⇒ void

This method returns an undefined value.

合并分支 将源分支合并到目标分支,支持单向或双向同步

Parameters:

  • project_dir (String)

    项目目录

  • source_branch (String)

    源分支名称(要合并的分支)

  • target_branch (String)

    目标分支名称(接收合并的分支)

  • sync_branches (Boolean) (defaults to: false)

    是否双向合并(同步两分支),默认 false

    • true: 双向合并,source → target,然后 target → source(确保两分支完全同步)
    • false: 单向合并,仅 source → target


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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
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
# File 'lib/pindo/base/git_handler.rb', line 1042

def merge_branches(project_dir:, source_branch:, target_branch:, sync_branches: false)
  current_project_dir = project_dir
  Funlog.instance.fancyinfo_start("开始合并到#{target_branch}分支")
  if !source_branch.eql?(target_branch)
    source_branch_commit_id = git!(%W(-C #{current_project_dir} rev-parse #{source_branch})).strip
    target_branch_commit_id = nil

    if remote_branch_exists?(local_repo_dir: current_project_dir, branch: target_branch)
      Funlog.instance.fancyinfo_update("存在#{target_branch}远程分支")
      if local_branch_exists?(local_repo_dir: current_project_dir, branch: target_branch)
        Funlog.instance.fancyinfo_update("存在#{target_branch}本地分支")
        git!(%W(-C #{current_project_dir} checkout #{target_branch}))
      else
        Funlog.instance.fancyinfo_update("不存在#{target_branch}本地分支")
        git!(%W(-C #{current_project_dir} checkout -b #{target_branch} origin/#{target_branch}))
      end

      git!(%W(-C #{current_project_dir} branch --set-upstream-to=origin/#{target_branch} #{target_branch}))
      git_remote!(current_project_dir, %W(-C #{current_project_dir} fetch origin #{target_branch}))
      git!(%W(-C #{current_project_dir} merge origin/#{target_branch}))

      # 执行合并操作
      Executable.capture_command('git', %W(-C #{current_project_dir} merge #{source_branch}), :capture => :out)

      # 检查是否有冲突
      conflict_filelist = git!(%W(-C #{current_project_dir} diff --name-only --diff-filter=U --relative))
      if !conflict_filelist.nil? && !conflict_filelist.strip.empty?
        raise Informative, "合并#{source_branch}#{target_branch}时产生冲突,请手动处理!"
      else
        git_remote!(current_project_dir, %W(-C #{current_project_dir} push))
        Funlog.instance.fancyinfo_success("代码已经合并到#{target_branch}分支")
        # 获取 target_branch 的 commit ID(处理空分支情况)
        begin
          target_branch_commit_id = git!(%W(-C #{current_project_dir} rev-parse #{target_branch})).strip
        rescue => e
          # 分支可能存在但没有提交(空分支),此时使用 source_branch 的 commit
          Funlog.instance.fancyinfo_update("#{target_branch}分支为空或获取commit失败,将使用当前分支commit")
          target_branch_commit_id = source_branch_commit_id
        end
      end

    else
      if local_branch_exists?(local_repo_dir: current_project_dir, branch: target_branch)
        Funlog.instance.fancyinfo_update("不存在#{target_branch}远程分支")
        Funlog.instance.fancyinfo_update("存在#{target_branch}本地分支")
        git!(%W(-C #{current_project_dir} checkout #{target_branch}))
        # 使用带时间戳的备份分支名,避免重复操作时冲突
        backup_branch = "#{target_branch}_backup_#{Time.now.strftime('%Y%m%d%H%M%S')}"
        Funlog.instance.fancyinfo_update("备份本地分支到: #{backup_branch}")
        git!(%W(-C #{current_project_dir} checkout -b #{backup_branch}))
        git!(%W(-C #{current_project_dir} checkout #{source_branch}))
        git!(%W(-C #{current_project_dir} branch -D #{target_branch}))
      else
        Funlog.instance.fancyinfo_update("不存在#{target_branch}远程分支")
        Funlog.instance.fancyinfo_update("不存在#{target_branch}本地分支")
      end

      # 基于 source_branch 创建 target_branch(明确指定起点,避免基于错误的分支创建)
      git!(%W(-C #{current_project_dir} checkout -b #{target_branch} #{source_branch}))
      git_remote!(current_project_dir, %W(-C #{current_project_dir} push origin #{target_branch}))
      git!(%W(-C #{current_project_dir} branch --set-upstream-to=origin/#{target_branch} #{target_branch}))

      Funlog.instance.fancyinfo_success("代码已经合并到#{target_branch}分支")
      # 获取 target_branch 的 commit ID(处理空分支情况)
      begin
        target_branch_commit_id = git!(%W(-C #{current_project_dir} rev-parse #{target_branch})).strip
      rescue => e
        # 新创建的分支,commit ID 应该与 source_branch 相同
        target_branch_commit_id = source_branch_commit_id
      end
    end

    # 同步分支:将 source_branch 同步到 target_branch(确保两分支在同一节点)
    git!(%W(-C #{current_project_dir} checkout #{source_branch}))
    if sync_branches
      if target_branch_commit_id && !target_branch_commit_id.eql?(source_branch_commit_id)
        # 检查是否可以 fast-forward(即 source_branch 是 target_branch 的祖先)
        is_ancestor = false
        begin
          git!(%W(-C #{current_project_dir} merge-base --is-ancestor #{source_branch} #{target_branch}))
          is_ancestor = true
        rescue => e
          # 不是祖先关系,说明 source_branch 有独立提交(理论上不应该,因为刚合并过)
          Funlog.instance.fancyinfo_warning("#{source_branch} 不是 #{target_branch} 的祖先")
        end

        if is_ancestor
          # 可以安全 fast-forward(source 的所有提交都在 target 中)
          Funlog.instance.fancyinfo_update("#{source_branch}#{target_branch}的祖先,执行 fast-forward 合并")
          begin
            # 尝试 fast-forward only merge(确保不产生新 commit)
            git!(%W(-C #{current_project_dir} merge --ff-only #{target_branch}))
            Funlog.instance.fancyinfo_success("已将#{source_branch} fast-forward 到#{target_branch},两分支现在在同一节点")

            # 推送到远程(普通 push,因为是 fast-forward)
            git_remote!(current_project_dir, %W(-C #{current_project_dir} push origin #{source_branch}))
            Funlog.instance.fancyinfo_success("已推送#{source_branch}分支到远程")
          rescue => e
            if e.message.include?("Not possible to fast-forward")
              # 理论上不应该到这里,因为前面检查过是祖先
              Funlog.instance.fancyinfo_warning("无法 fast-forward,将产生 merge commit")
              git!(%W(-C #{current_project_dir} merge #{target_branch}))
              git_remote!(current_project_dir, %W(-C #{current_project_dir} push origin #{source_branch}))
            else
              raise e
            end
          end
        else
          # 不是祖先关系,使用普通 merge(会产生新的 merge commit)
          Funlog.instance.fancyinfo_warning("#{source_branch}不是#{target_branch}的祖先,将执行普通合并(可能产生新 commit)")
          Executable.capture_command('git', %W(-C #{current_project_dir} merge #{target_branch}), :capture => :out)

          # 检查冲突
          conflict_filelist = git!(%W(-C #{current_project_dir} diff --name-only --diff-filter=U --relative))
          if !conflict_filelist.nil? && !conflict_filelist.strip.empty?
            raise Informative, "合并#{target_branch}#{source_branch}时产生冲突,请手动处理!"
          end

          git_remote!(current_project_dir, %W(-C #{current_project_dir} push origin #{source_branch}))
          Funlog.instance.fancyinfo_success("已将#{target_branch}合并到#{source_branch}(产生了新 merge commit)")
        end
      else
        Funlog.instance.fancyinfo_success("#{source_branch}#{target_branch}已经在同一节点,无需同步")
      end
    else
      Funlog.instance.fancyinfo_success("单向合并完成,未同步 #{target_branch}#{source_branch}")
    end
  else
    Funlog.instance.fancyinfo_success("代码处于#{source_branch}分支,无需合并")
  end
end

.parse_gitmodules_count(gitmodules_path) ⇒ Integer

解析 .gitmodules 文件,统计子模块数量

Parameters:

  • gitmodules_path (String)

    .gitmodules 文件路径

Returns:

  • (Integer)

    子模块数量



1322
1323
1324
1325
1326
1327
1328
# File 'lib/pindo/base/git_handler.rb', line 1322

def parse_gitmodules_count(gitmodules_path)
  return 0 unless File.exist?(gitmodules_path)

  content = File.read(gitmodules_path)
  # 统计 [submodule "xxx"] 的数量
  content.scan(/\[submodule\s+"[^"]+"\]/).count
end

.parse_submodule_paths(gitmodules_path) ⇒ Array<String>

解析 .gitmodules 文件,提取所有子模块路径

Parameters:

  • gitmodules_path (String)

    .gitmodules 文件路径

Returns:

  • (Array<String>)

    子模块路径列表



1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
# File 'lib/pindo/base/git_handler.rb', line 1351

def parse_submodule_paths(gitmodules_path)
  return [] unless File.exist?(gitmodules_path)

  content = File.read(gitmodules_path)
  paths = []

  # 匹配 path = xxx 行
  content.scan(/^\s*path\s*=\s*(.+)$/) do |match|
    paths << match[0].strip
  end

  paths
end

.prepare_gitenvObject



17
18
19
20
21
# File 'lib/pindo/base/git_handler.rb', line 17

def prepare_gitenv()
  usrname = Etc.getlogin
  git!(%W(config --global user.email #{usrname}@example.com))
  git!(%W(config --global user.name #{usrname}))
end

.process_need_add_files(project_dir:, process_type:, commit_message: nil) ⇒ Object

处理未提交的文件

Parameters:

  • project_dir (String)

    项目目录路径

  • process_type (String)

    处理方式: 'commit'(全部提交), 'delete'(全部删除), 'stash'(保存到stash), 'exit'(退出)

  • commit_message (String) (defaults to: nil)

    提交信息(仅在 process_type 为 'commit' 时使用)

Raises:

  • (Informative)

    当用户选择退出或需要手动处理文件时抛出



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
# File 'lib/pindo/base/git_handler.rb', line 603

def process_need_add_files(project_dir:, process_type:, commit_message: nil)
    raise ArgumentError, "项目目录不能为空" if project_dir.nil?
    raise ArgumentError, "处理方式不能为空" if process_type.nil?

    # 获取 Git 根目录
    git_root = git_root_directory(local_repo_dir: project_dir)
    unless git_root
        Funlog.instance.fancyinfo_warning("当前目录不是Git仓库,跳过处理未提交文件")
        return
    end

    current_project_dir = git_root
    origin_path = Dir.pwd

    begin
        Dir.chdir(current_project_dir)

        # 获取当前分支信息
        coding_branch = git!(%W(-C #{current_project_dir} rev-parse --abbrev-ref HEAD)).strip

        # 根据 process_type 执行对应操作
        case process_type
        when Pindo::UncommittedFilesProcessType::NONE
            # 没有未提交的文件,无需处理
            return
        when Pindo::UncommittedFilesProcessType::COMMIT
            handle_commit_all(current_project_dir, coding_branch, commit_message)
        when Pindo::UncommittedFilesProcessType::RESET
            handle_delete_all(current_project_dir, coding_branch)
        when Pindo::UncommittedFilesProcessType::STASH
            handle_stash(current_project_dir, coding_branch)
        when Pindo::UncommittedFilesProcessType::SKIP_WITH_TAG
            # 不提交,但后续会合并分支并打 tag
            Funlog.instance.warning("跳过提交,但会合并分支并打 tag")
            return
        when Pindo::UncommittedFilesProcessType::SKIP_WITHOUT_TAG
            # 不提交,不合并分支,不打 tag
            Funlog.instance.warning("跳过提交,不合并分支,不打 tag")
            return
        when Pindo::UncommittedFilesProcessType::EXIT
            raise Informative, "请手动处理未提交的文件!!!"
        else
            raise ArgumentError, "不支持的处理方式: #{process_type}"
        end

    ensure
        Dir.chdir(origin_path)
    end
end

.remote_branch_exists?(local_repo_dir: nil, branch: nil) ⇒ Boolean

Returns:

  • (Boolean)


197
198
199
200
201
202
203
204
205
206
207
# File 'lib/pindo/base/git_handler.rb', line 197

def remote_branch_exists?(local_repo_dir: nil, branch: nil)
    # 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
    result = false
    if File.exist?(local_repo_dir)
      res_data = git_remote!(local_repo_dir, %W(-C #{local_repo_dir} ls-remote --heads origin refs/heads/#{branch}))
      result = !res_data.nil? && !res_data.empty?
    else
      result = false
    end
    return result
end

.remote_branch_names(local_repo_dir: nil) ⇒ Object

列出远程分支短名(去掉 origin/ 前缀与 HEAD 指针)。使用本地 remote-tracking 引用,不触发网络。



138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/pindo/base/git_handler.rb', line 138

def remote_branch_names(local_repo_dir: nil)
    return [] unless local_repo_dir && File.exist?(local_repo_dir)
    out = git!(%W(-C #{local_repo_dir} for-each-ref --format=%(refname:short) refs/remotes/origin))
    return [] if out.nil? || out.strip.empty?
    # 仅取 "origin/<branch>";origin/HEAD 的短名会缩写为裸 "origin",需排除
    out.lines.map(&:strip)
       .select { |name| name.start_with?('origin/') }
       .map { |name| name.sub(%r{\Aorigin/}, '') }
       .reject { |name| name.empty? || name == 'HEAD' }
       .uniq
rescue => e
    []
end

.remote_tag_commit(local_repo_dir: nil, tag_name: nil) ⇒ Object

获取远程 tag 指向的 commit SHA,不存在返回 nil 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/pindo/base/git_handler.rb', line 276

def remote_tag_commit(local_repo_dir: nil, tag_name: nil)
    return nil if local_repo_dir.nil? || !File.exist?(local_repo_dir)
    tag_ref = "refs/tags/#{tag_name}"
    peeled_ref = "#{tag_ref}^{}"
    # annotated tag 需要 ^{} 解引用行才能拿到真实 commit;但只传 tag_ref 精确过滤时,
    # git ls-remote 不会附带 ^{} 行,必须显式把 peeled_ref 一起传入才能拿到它
    res_data = git_remote!(local_repo_dir, %W(-C #{local_repo_dir} ls-remote --tags origin #{tag_ref} #{peeled_ref}))
    entries = res_data.to_s.lines.map { |l| l.strip.split(/\s+/, 2) }
                      .select { |sha, ref| sha && ref }
    return nil if entries.empty?
    # 优先取 ^{} 行(annotated tag 的真实 commit);lightweight tag 只有 tag_ref 行且本身即 commit
    peeled = entries.find { |_sha, ref| ref == peeled_ref }
    plain  = entries.find { |_sha, ref| ref == tag_ref }
    (peeled || plain)&.first
end

.remote_tag_exists?(local_repo_dir: nil, tag_name: nil) ⇒ Boolean

Returns:

  • (Boolean)


292
293
294
# File 'lib/pindo/base/git_handler.rb', line 292

def remote_tag_exists?(local_repo_dir: nil, tag_name: nil)
    !remote_tag_commit(local_repo_dir: local_repo_dir, tag_name: tag_name).nil?
end

.remove_branch(local_repo_dir: nil, branch: nil) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/pindo/base/git_handler.rb', line 102

def remove_branch(local_repo_dir: nil, branch: nil)
    # 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
    result = false
    if File.exist?(local_repo_dir)
      current_branch = git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip
      if local_branch_exists?(local_repo_dir: local_repo_dir, branch: branch)
          git!(%W(-C #{local_repo_dir} branch -D #{branch}))
          result = true
      end

      if remote_branch_exists?(local_repo_dir: local_repo_dir, branch: branch)
          git_remote!(local_repo_dir, %W(-C #{local_repo_dir} push origin :#{branch}))
          result = true
      end

    else
      result = false
    end
    return result
end

.remove_tag(local_repo_dir: nil, tag_name: nil) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/pindo/base/git_handler.rb', line 254

def remove_tag(local_repo_dir: nil, tag_name: nil)
    # 命令已带 -C,无需 Dir.chdir(并发模式下 chdir 会污染全局 cwd)
    result = false
    if File.exist?(local_repo_dir)
      if local_tag_exists?(local_repo_dir: local_repo_dir, tag_name: tag_name)
          git!(%W(-C #{local_repo_dir} tag -d #{tag_name}))
          result = true
      end
      if remote_tag_exists?(local_repo_dir: local_repo_dir, tag_name: tag_name)
          git_remote!(local_repo_dir, %W(-C #{local_repo_dir} push origin :#{tag_name}))
          result = true
      end
    else
      result = false
    end
    return result

end

.resolve_release_branch(local_repo_dir: nil, preferred: nil) ⇒ String

解析发布分支(当用户未显式指定时给出合理默认):

  1. preferred(用户 --release_branch 或默认值)在远程存在 → 用它(master 仓库、显式指定均走此)
  2. 否则远程有 master → master
  3. 否则远程有 main → main
  4. 否则只有唯一远程分支 → 用它
  5. 兜底:当前分支(避免往不存在的分支同步而报错)

Parameters:

  • local_repo_dir (String) (defaults to: nil)

    仓库目录

  • preferred (String, nil) (defaults to: nil)

    期望的发布分支

Returns:

  • (String)

    解析后的发布分支名



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/pindo/base/git_handler.rb', line 176

def resolve_release_branch(local_repo_dir: nil, preferred: nil)
    current = (git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip rescue nil)
    remotes = remote_branch_names(local_repo_dir: local_repo_dir)
    pref = preferred.to_s.strip

    # 无法获取远程分支(网络异常/未 fetch)→ 退回当前分支,跳过跨分支同步,避免误操作
    if remotes.empty?
      return current unless current.nil? || current.empty?
      return pref.empty? ? 'master' : pref
    end

    return pref if !pref.empty? && remotes.include?(pref)
    return 'master' if remotes.include?('master')
    return 'main' if remotes.include?('main')
    return remotes.first if remotes.size == 1
    # 多远程分支且无 master/main/preferred:退回当前分支(coding==release,跳过跨分支同步,
    # 避免退回到可能不存在的 preferred 而在 checkout 时报错)
    return current if current && !current.strip.empty? && current != 'HEAD'
    pref.empty? ? 'master' : pref
end

.update_submodules(local_repo_dir:, force: false) ⇒ Boolean

初始化并递归更新所有 Git 子模块

Parameters:

  • local_repo_dir (String)

    Git 仓库目录路径

  • force (Boolean) (defaults to: false)

    是否强制重新初始化子模块

Returns:

  • (Boolean)

    成功返回 true,无子模块返回 false

Raises:

  • (ArgumentError)


1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
# File 'lib/pindo/base/git_handler.rb', line 1244

def update_submodules(local_repo_dir:, force: false)
  raise ArgumentError, "项目目录不能为空" if local_repo_dir.nil?

  # 验证是否是 Git 仓库
  unless is_git_directory?(local_repo_dir: local_repo_dir)
    raise Informative, "#{local_repo_dir} 不是有效的 Git 仓库!"
  end

  # 检查 .gitmodules 文件是否存在
  git_root = git_root_directory(local_repo_dir: local_repo_dir)
  gitmodules_path = File.join(git_root, '.gitmodules')

  unless File.exist?(gitmodules_path)
    Funlog.instance.fancyinfo_warning("当前仓库没有子模块配置文件 (.gitmodules)")
    return false
  end

  # 显示子模块信息
  Funlog.instance.fancyinfo_start("正在读取子模块配置...")
  submodules_count = parse_gitmodules_count(gitmodules_path)
  Funlog.instance.fancyinfo_success("检测到 #{submodules_count} 个子模块")

  # 检查子模块路径冲突
  conflicts = check_submodule_path_conflicts(git_root, gitmodules_path)
  unless conflicts.empty?
    if force
      # 使用 --force 参数,自动清理冲突路径
      Funlog.instance.fancyinfo_start("检测到 #{conflicts.size} 个路径冲突,正在清理...")
      conflicts.each do |conflict|
        begin
          FileUtils.rm_rf(conflict[:full_path])
          Funlog.instance.fancyinfo_success("已清理: #{conflict[:path]} (包含 #{conflict[:files]} 个文件)")
        rescue => e
          Funlog.instance.fancyinfo_error("清理失败: #{conflict[:path]} - #{e.message}")
          raise Informative, "无法清理路径冲突:#{conflict[:path]}\n#{e.message}"
        end
      end
    else
      # 不使用 --force,报错退出
      Funlog.instance.fancyinfo_error("检测到 #{conflicts.size} 个子模块路径冲突")
      puts "\n以下路径已存在但不是 Git 仓库,其中的文件会污染子模块:\n".yellow
      conflicts.each do |conflict|
        puts "#{conflict[:path]} (包含 #{conflict[:files]} 个文件)".yellow
      end
      puts "\n请选择处理方式:".yellow
      puts "  1. 使用 --force 参数自动清理这些目录".yellow
      puts "  2. 手动删除或备份这些目录后重新执行\n".yellow
      raise Informative, "子模块路径冲突!请处理后重试。"
    end
  end

  # 构建 git submodule update 命令
  args = %W(-C #{git_root} submodule update --init --recursive)
  args << '--force' if force
  args << '--progress'

  # 执行子模块更新
  begin
    Funlog.instance.fancyinfo_start("正在初始化和更新所有子模块...")
    output = git!(args)
    Funlog.instance.fancyinfo_success("子模块更新完成!")

    # 显示子模块状态
    display_submodules_status(git_root)

    # 检查子模块是否有未提交的内容
    check_submodule_dirty_state(git_root, gitmodules_path)

    true
  rescue StandardError => e
    Funlog.instance.fancyinfo_error("子模块更新失败: #{e.message}")
    raise Informative, "子模块更新失败!\n详细错误:#{e.message}"
  end
end

.without_proxy(&block) ⇒ Object

临时去除代理环境变量执行代码块 用于 gitee.com 等不需要代理的仓库操作



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/pindo/base/git_handler.rb', line 36

def without_proxy(&block)
  saved_env = {}
  %w[http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY].each do |key|
    saved_env[key] = ENV[key]
    ENV.delete(key)
  end
  begin
    block.call
  ensure
    saved_env.each do |key, value|
      if value.nil?
        ENV.delete(key)
      else
        ENV[key] = value
      end
    end
  end
end