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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pindo/base/git_handler.rb', line 42

def add_branch(local_repo_dir: nil, branch: nil)

    current=Dir.pwd
    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!(%W(-C #{local_repo_dir} push origin #{branch}:#{branch}))

    Dir.chdir(current)
    return result
end

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



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/pindo/base/git_handler.rb', line 116

def add_tag(local_repo_dir: nil, tag_name: nil)

    current=Dir.pwd
    result = false
    if File.exist?(local_repo_dir)
      Dir.chdir(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!(%W(-C #{local_repo_dir} push origin #{tag_name}))
    else
      result = false
    end
    Dir.chdir(current)
    return result
end

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



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

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!(%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

.check_uncommitted_files(project_dir:) ⇒ void

This method returns an undefined value.

检查并处理未提交的文件(交互式)

Parameters:

  • project_dir (String)

    项目目录路径



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

def check_uncommitted_files(project_dir:)
  # 1. 检查是否有未提交的文件
  uncommitted_files = get_uncommitted_files(project_dir: project_dir)

  # 2. 如果没有未提交的文件,直接返回
  return if uncommitted_files.nil? || uncommitted_files.empty?

  # 3. 获取当前分支名
  current_branch = git!(%W(-C #{project_dir} rev-parse --abbrev-ref HEAD)).strip

  # 4. 显示文件状态
  display_file_status(current_branch, uncommitted_files)

  # 5. 让用户选择处理方式
  cli = HighLine.new
  process_type = cli.choose do |menu|
    menu.header = "仓库有未提交的修改,请选择处理方式"
    menu.prompt = "请输入选项(1/2/3/4/5):"
    menu.choice("(commit) 全部提交") { 'commit' }
    menu.choice("(skip) 跳过并且不作任何修改,继续执行") { 'skip' }
    menu.choice("(reset) 全部丢弃更改,回滚代码") { 'reset' }
    menu.choice("(stash) 保存到stash区域(该部分代码本次不生效)") { 'stash' }
    menu.choice("(exit) 先退出,手动来处理退出") { 'exit' }
  end

  # 6. 如果用户选择跳过,输出警告信息并返回
  if process_type == 'skip'
    Funlog.instance.warning("跳过提交,可能导致 build number 与代码仓库不一致")
    return
  end

  # 7. 处理未提交的文件
  process_need_add_files(
    project_dir: project_dir,
    process_type: process_type
  )
end

.check_unpushed_commits(project_dir:, branch:) ⇒ void

This method returns an undefined value.

检查并推送未推送的本地提交

Parameters:

  • project_dir (String)

    项目目录路径

  • branch (String)

    分支名称



857
858
859
860
861
862
863
864
865
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
# File 'lib/pindo/base/git_handler.rb', line 857

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!(%W(-C #{project_dir} push -u origin #{branch}))
    Funlog.instance.fancyinfo_success("远程分支创建成功!")
    return
  end

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

  # 4. 如果没有未推送的提交,直接返回
  if ahead_count == 0
    Funlog.instance.fancyinfo_success("本地分支 #{branch} 与远程分支同步,无需推送")
    return
  end

  # 5. 有未推送的提交,直接推送(不显示内容,不询问用户)
  Funlog.instance.fancyinfo_warning("检测到 #{ahead_count} 个本地提交尚未推送")
  Funlog.instance.fancyinfo_start("正在推送到远程分支 #{remote_branch}...")
  git!(%W(-C #{project_dir} push origin #{branch}))
  Funlog.instance.fancyinfo_success("推送成功!")
end

.clone_clang_repoObject



400
401
402
403
404
405
406
407
408
409
410
# File 'lib/pindo/base/git_handler.rb', line 400

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



388
389
390
391
392
393
394
395
396
397
398
# File 'lib/pindo/base/git_handler.rb', line 388

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



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/pindo/base/git_handler.rb', line 353

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



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/pindo/base/git_handler.rb', line 371

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



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/pindo/base/git_handler.rb', line 328

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

  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 repo_name && git_repo_json && git_repo_json[repo_name]
    repo_org_name = git_repo_json[repo_name]
  end

  url = File.join("https://gitee.com", repo_org_name, repo_name + ".git")
  getcode_to_dir(reponame:repo_name, remote_url: url, path:pindo_dir)
  config_repo_dir = File.join(pindo_dir, 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)

    当项目目录不存在时抛出



634
635
636
637
638
639
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
683
# File 'lib/pindo/base/git_handler.rb', line 634

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

.display_file_status(branch, files) ⇒ Object

显示未提交的文件状态

Parameters:

  • branch (String)

    当前分支名

  • files (Array<String>, String)

    文件列表



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/pindo/base/git_handler.rb', line 522

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

    # 将文件列表分行并用红色显示
    if files.is_a?(String)
        files.split("\n").each do |file|
            puts "#{file}".red unless file.empty?
        end
    else
        files.each do |file|
            puts "#{file}".red unless file.empty?
        end
    end

    puts
    puts "" * 60
end

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

获取最新的版本标签

Parameters:

  • project_dir (String) (defaults to: nil)

    项目目录路径

Returns:

  • (String, nil)

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



608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/pindo/base/git_handler.rb', line 608

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



320
321
322
323
324
325
326
# File 'lib/pindo/base/git_handler.rb', line 320

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)


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

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

    begin
        # 重置暂存区
        git!(%W(-C #{project_dir} restore --staged #{project_dir}))

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

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

        # 将字符串转换为数组
        files_list.is_a?(String) ? files_list.split("\n").reject(&:empty?) : files_list
    rescue => e
        Funlog.instance.fancyinfo_error("获取未提交文件列表失败: #{e.message}")
        nil
    end
end

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



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/pindo/base/git_handler.rb', line 246

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)

  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!(args)
            git!(%W(-C #{local_repo_dir} branch --set-upstream-to=origin/#{current_branch}  #{current_branch}))
          end

          git!(%W(-C #{local_repo_dir} fetch origin --progress))
        else
          git! ['clone', remote_url, local_repo_dir]
        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!(%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!(%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
  end

  Dir.chdir(current)
  return local_repo_dir
end

.git_addpush_repo(path: nil, message: "res", commit_file_params: nil) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/pindo/base/git_handler.rb', line 412

def git_addpush_repo(path:nil, message:"res", 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 仓库失败 !!!"
  end


  Dir.chdir(current)
end

.git_latest_commit_id(local_repo_dir: nil) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/pindo/base/git_handler.rb', line 221

def git_latest_commit_id(local_repo_dir:nil)

  current=Dir.pwd

  unless File.exist?(File::join(local_repo_dir, ".git"))
    return nil
  end

  commit_id = nil

  if File.exist?(local_repo_dir)
    Dir.chdir(local_repo_dir)
    current_branch = git!(%W(-C #{local_repo_dir} rev-parse --abbrev-ref HEAD)).strip
    # puts "current_branch: #{current_branch}"

    # git log -n 1 --pretty=format:"commit %H"
    # format_str = "commit %H"
    # latest_log_info = git!(%W(-C #{current} log -n 1 --pretty=#{format_str} #{current_branch})).strip
    commit_id = git!(%W(-C #{local_repo_dir} rev-parse #{current_branch})).strip
  end
  Dir.chdir(current)

  return commit_id
end

.git_root_directory(local_repo_dir: nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/pindo/base/git_handler.rb', line 31

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



688
689
690
691
692
693
694
695
696
697
698
699
# File 'lib/pindo/base/git_handler.rb', line 688

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

.is_git_directory?(local_repo_dir: nil) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
29
# File 'lib/pindo/base/git_handler.rb', line 21

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



705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
# File 'lib/pindo/base/git_handler.rb', line 705

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
        tag_commit = git!(%W(-C #{git_root_dir} rev-parse #{tag_name})).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)


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/pindo/base/git_handler.rb', line 82

def local_branch_exists?(local_repo_dir: nil, branch: nil)
    current=Dir.pwd
    result = false

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

      res_data = Executable.capture_command('git', %W(rev-parse --verify #{branch}), :capture => :out)
      # puts "=====1"
      # puts res_data
      # res_data = git!(%W(-C #{local_repo_dir} --no-pager branch --list origin/#{branch} --no-color -r))
      result = !res_data.nil? && !res_data.empty?
    else
      result = false
    end
    Dir.chdir(current)
    return result
end

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

Returns:

  • (Boolean)


205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/pindo/base/git_handler.rb', line 205

def local_tag_exists?(local_repo_dir: nil, tag_name: nil)
    # tag_ref = "refs/tags/#{tag_name}"
    result = false
    current=Dir.pwd

    if File.exist? (local_repo_dir)
      Dir.chdir(local_repo_dir)
      res_data = git!(%W(-C #{local_repo_dir} tag --list #{tag_name}))
      result = !res_data.nil? && !res_data.empty?
    else
      result = false
    end
    Dir.chdir(current)
    return result
end

.merge_to_release_branch(project_dir:, release_branch:, coding_branch:) ⇒ Object

合并到发布分支

Parameters:

  • project_dir (String)

    项目目录

  • release_branch (String)

    发布分支名称

  • coding_branch (String)

    当前开发分支名称



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
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/pindo/base/git_handler.rb', line 766

def merge_to_release_branch(project_dir:, release_branch:, coding_branch:)
  current_project_dir = project_dir
  Funlog.instance.fancyinfo_start("开始合并到#{release_branch}分支")
  if !coding_branch.eql?(release_branch)
    coding_branch_commit_id = git!(%W(-C #{current_project_dir} rev-parse #{coding_branch})).strip
    release_branch_commit_id = nil

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

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

      # 执行合并操作
      Executable.capture_command('git', %W(-C #{current_project_dir} merge #{coding_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, "合并#{coding_branch}#{release_branch}时产生冲突,请手动处理!"
      else
        git!(%W(-C #{current_project_dir} push))
        Funlog.instance.fancyinfo_success("代码已经合并到#{release_branch}分支")
        # 获取 release_branch 的 commit ID(处理空分支情况)
        begin
          release_branch_commit_id = git!(%W(-C #{current_project_dir} rev-parse #{release_branch})).strip
        rescue => e
          # 分支可能存在但没有提交(空分支),此时使用 coding_branch 的 commit
          Funlog.instance.fancyinfo_update("#{release_branch}分支为空或获取commit失败,将使用当前分支commit")
          release_branch_commit_id = coding_branch_commit_id
        end
      end

    else
      if local_branch_exists?(local_repo_dir: current_project_dir, branch: release_branch)
        Funlog.instance.fancyinfo_update("不存在#{release_branch}远程分支")
        Funlog.instance.fancyinfo_update("存在#{release_branch}本地分支")
        git!(%W(-C #{current_project_dir} checkout #{release_branch}))
        # 使用带时间戳的备份分支名,避免重复操作时冲突
        backup_branch = "#{release_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 #{coding_branch}))
        git!(%W(-C #{current_project_dir} branch -D #{release_branch}))
      else
        Funlog.instance.fancyinfo_update("不存在#{release_branch}远程分支")
        Funlog.instance.fancyinfo_update("不存在#{release_branch}本地分支")
      end

      git!(%W(-C #{current_project_dir} checkout -b #{release_branch}))
      git!(%W(-C #{current_project_dir} push origin #{release_branch}))
      git!(%W(-C #{current_project_dir} branch --set-upstream-to=origin/#{release_branch} #{release_branch}))

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

    git!(%W(-C #{current_project_dir} checkout #{coding_branch}))
    if release_branch_commit_id && !release_branch_commit_id.eql?(coding_branch_commit_id)
      Executable.capture_command('git', %W(-C #{current_project_dir} merge #{release_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, "合并#{release_branch}#{coding_branch}时产生冲突,请手动处理!"
      end
      Funlog.instance.fancyinfo_success("已将#{release_branch}合并到#{coding_branch}")
    end
    git!(%W(-C #{current_project_dir} push origin #{coding_branch}))
    Funlog.instance.fancyinfo_success("已推送#{coding_branch}分支到远程")
  else
    Funlog.instance.fancyinfo_success("代码处于#{coding_branch}分支,无需合并")
  end
end

.prepare_gitenvObject



15
16
17
18
19
# File 'lib/pindo/base/git_handler.rb', line 15

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)

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



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/pindo/base/git_handler.rb', line 487

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

    current_project_dir = project_dir
    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 'commit', '全部提交'
            handle_commit_all(current_project_dir, coding_branch, commit_message)
        when 'reset', '全部丢弃更改,回滚代码', 'delete', '全部删除'
            handle_delete_all(current_project_dir, coding_branch)
        when 'stash', '保存到stash区域', '保存到stash区域(改代码本次不生效)'
            handle_stash(current_project_dir, coding_branch)
        when '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)


101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/pindo/base/git_handler.rb', line 101

def remote_branch_exists?(local_repo_dir: nil, branch: nil)
    current=Dir.pwd
    result = false
    if File.exist?(local_repo_dir)
      Dir.chdir(local_repo_dir)
      res_data = git!(%W(-C #{local_repo_dir} ls-remote --heads origin refs/heads/#{branch}))
      result = !res_data.nil? && !res_data.empty?
    else
      result = false
    end
    Dir.chdir(current)
    return result
end

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

Returns:

  • (Boolean)


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/pindo/base/git_handler.rb', line 186

def remote_tag_exists?(local_repo_dir: nil, tag_name: nil)

    result = false
    current=Dir.pwd

    if File.exist?(local_repo_dir)
      Dir.chdir(local_repo_dir)
      tag_ref = "refs/tags/#{tag_name}"
      res_data = git!(%W(-C #{local_repo_dir} ls-remote --tags origin #{tag_ref}))
      result =  !res_data.nil? && !res_data.empty?
    else
      result = false
    end
    Dir.chdir(current)
    return result


end

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



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/pindo/base/git_handler.rb', line 58

def remove_branch(local_repo_dir: nil, branch: nil)
    current=Dir.pwd

    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!(%W(-C #{local_repo_dir} push origin :#{branch}))
          result = true
      end

    else
      result = false
    end
    Dir.chdir(current)
    return result
end

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



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/pindo/base/git_handler.rb', line 163

def remove_tag(local_repo_dir: nil, tag_name: nil)

    result = false
    current=Dir.pwd
    if File.exist?(local_repo_dir)
      Dir.chdir(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!(%W(-C #{local_repo_dir} push origin :#{tag_name}))
          result = true
      end
    else
      result = false
    end
    Dir.chdir(current)
    return result

end