Class: Squared::Workspace::Project::Git

Inherits:
Base
  • Object
show all
Extended by:
Rake::DSL
Defined in:
lib/squared/workspace/project/git.rb

Direct Known Subclasses

Node, Python, Ruby

Constant Summary

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary

Attributes inherited from Base

#dependfile, #exception, #group, #name, #parent, #path, #pipe, #project, #theme, #verbose, #workspace

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#add, aliasargs, #allref, #archive, #archive?, #as, as_path, bannerargs, #basepath, batchargs, #build, #build?, #clean?, #copy, #copy?, #depend?, #dependtype, #dev?, #doc, #doc?, #error, #event, #exclude?, #first, #graph, #graph?, #has?, #initialize_build, #initialize_env, #initialize_events, #initialize_logger, #initialize_ref, #inject, #inspect, #last, #lint, #lint?, #localname, #log, #prod?, ref, #ref?, #rootpath, #script?, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #variable_set, #version, #with

Methods included from Common::Format

#enable_aixterm

Constructor Details

#initializeGit

Returns a new instance of Git.



334
335
336
337
# File 'lib/squared/workspace/project/git.rb', line 334

def initialize(*, **)
  super
  initialize_ref Git.ref if gitpath.exist?
end

Class Method Details

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


306
307
308
309
310
# File 'lib/squared/workspace/project/git.rb', line 306

def config?(val)
  return false unless (val = as_path(val))

  val.join('.git').directory?
end

.populate(ws) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/squared/workspace/project/git.rb', line 277

def populate(ws, **)
  return if ws.series[:pull].empty?

  namespace(name = ws.task_name('git')) do
    all = ws.task_join(name, 'all')

    ws.format_desc(all, %w[stash|rebase depend])
    task 'all' do |_, args|
      opts = args.to_a
      cmd = if opts.include?('stash')
              [ws.task_sync('stash'), ws.task_sync('pull')]
            elsif opts.include?('rebase')
              [ws.task_sync('rebase')]
            else
              [ws.task_sync('pull')]
            end
      cmd << ws.task_sync('depend') if opts.include?('depend') && !ws.series[:depend].empty?
      cmd << ws.task_sync('build')
      Common::Utils.task_invoke(*cmd, **ws.invokeargs)
    end
    ws.series.sync << all
    ws.series.multiple << all
  end
end

.tasksObject



302
303
304
# File 'lib/squared/workspace/project/git.rb', line 302

def tasks
  %i[pull rebase fetch clone stash status branch revbuild].freeze
end

Instance Method Details

#branch(flag = nil, opts = [], refs: [], ref: nil, target: nil) ⇒ Object



1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
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
# File 'lib/squared/workspace/project/git.rb', line 1137

def branch(flag = nil, opts = [], refs: [], ref: nil, target: nil)
  cmd, opts = git_session('branch', opts: opts)
  stdout = false
  case flag
  when :create
    if (arg = option('track', ignore: false))
      cmd << case arg
             when '0'
               '--no-track'
             when 'direct', 'inherit'
               basic_option('track', arg)
             else
               '--track'
             end
    end
    cmd << '--force' if option('force')
  when :set
    return unless ref

    if ref.start_with?('^')
      cmd << '--unset-upstream' << shell_escape(ref[1..-1])
      target = nil
      stdout = true
    else
      cmd << quote_option('set-upstream-to', ref)
    end
    ref = nil
  when :delete
    force, list = refs.partition { |val| val.match?(/^[\^~]/) }
    force.each do |val|
      dr = val[0, 3]
      d = dr.include?('^') ? '-D' : '-d'
      r = dr.include?('~') ? '-r' : nil
      source git_output('branch', d, r, shell_quote(val.sub(/^[\^~]+/, '')))
    end
    return if list.empty?

    cmd << '-d'
    list.each { |val| cmd << shell_quote(val) }
  when :move, :copy
    flag = "-#{flag.to_s[0]}"
    cmd << (option('force') ? flag.upcase : flag)
    refs.compact.each { |val| cmd << shell_quote(val) }
    stdout = true
  when :edit
    cmd << '--edit-description'
  when :current
    cmd << '--show-current'
  when :list
    opts = option_sanitize(opts, OPT_GIT[:branch], no: OPT_GIT[:no][:branch], single: /^v+$/).first
    cmd << '--list'
    opts.each { |val| cmd << shell_quote(val) }
    out, banner, from = source(io: true)
    print_item banner
    ret = write_lines(out, sub: [
      { pat: /^(\*\s+)(\S+)(\s*)$/, styles: color(:green), index: 2 },
      { pat: %r{^(\s*)(remotes/\S+)(.*)$}, styles: color(:red), index: 2 }
    ])
    list_result(ret, 'branches', from: from)
    return
  else
    head = git_spawn('rev-parse --abbrev-ref HEAD').first.chomp
    if head.empty?
      ret = 0
    else
      git_spawn 'fetch --all --prune --quiet' if option('sync')
      out, banner, from = source(cmd << '-vv --no-abbrev --list', io: true)
      ret = write_lines(out, grep: /^\*\s+#{Regexp.escape(head)}\s/, banner: banner, first: true) do |line|
        next line if stdin?

        data = line.sub(/^\*\s+/, '').split(/\s+/)
        a = sub_style(data[0], styles: theme[:inline])
        b = sub_style(data[1], styles: theme[:extra])
        r = /\A(?:\[(.+?)(?=\]\s)\]\s)?(.+)\z/m.match(data[2..-1].join(' '))
        if (r1 = r[1]) && r1 =~ /^(.+):(?: ([a-z]+) (\d+),)? ([a-z]+) (\d+)$/
          write = ->(s1, s2) { "#{s1.capitalize.rjust(7)}: #{sub_style(s2, styles: theme[:warn])}" }
          r1 = $1
          r2 = $2 && write.($2, $3)
          r3 = write.($4, $5)
        end
        r1 = nil if r1 == "origin/#{data[0]}"
        [" Branch: #{a + (r1 ? " (#{r1})" : '')}", r2, r3, " Commit: #{b}", "Message: #{r[2]}"]
          .compact
          .join("\n")
      end
      on :last, from
    end
    if ret == 0
      warn log_message(Logger::WARN, name, 'no ref found', subject: 'branch', hint: 'head', pass: true)
    end
    return
  end
  cmd << shell_escape(target) if target
  cmd << shell_escape(ref) if ref
  source(stdout: stdout)
end

#checkout(flag, opts = [], branch: nil, origin: nil, create: nil, commit: nil, detach: nil) ⇒ Object



935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
# File 'lib/squared/workspace/project/git.rb', line 935

def checkout(flag, opts = [], branch: nil, origin: nil, create: nil, commit: nil, detach: nil)
  cmd, opts = git_session('checkout', opts: opts)
  append_option 'force', 'merge'
  case flag
  when :branch
    cmd << '--detach' if detach == 'd' || option('detach')
    append_option('track', equals: true)
    cmd << (create ? shell_option(create, branch) : branch) << commit
  when :track
    if branch
      if branch.start_with?('^')
        opt = 'B'
        branch = branch[1..-1]
      end
      cmd << shell_option(opt || 'b', branch)
    end
    cmd << '--track' << origin
  when :detach
    cmd << '--detach' << commit
  else
    refs = option_sanitize(opts, OPT_GIT[:checkout], no: OPT_GIT[:no][:checkout]).first
    if flag == :commit
      append_value(commit, delim: true)
      option_clear(refs, pass: false)
    else
      append_head
      append_pathspec refs
    end
  end
  source
end

#cleanObject



696
697
698
699
# File 'lib/squared/workspace/project/git.rb', line 696

def clean(*, **)
  workspace.rev_clear(name)
  super
end

#clone(sync: invoked_sync?('clone')) ⇒ Object



764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'lib/squared/workspace/project/git.rb', line 764

def clone(*, sync: invoked_sync?('clone'), **)
  return unless clone? && (data = workspace.git_repo(name))

  cmd = git_session('clone', worktree: false)
  opts = data[1].dup
  if (val = option('depth', ignore: false))
    if (n = val.to_i) > 0
      opts[:depth] = n
    else
      opts.delete(:depth)
    end
  end
  opts[:origin] = val if (val = option('origin', ignore: false))
  opts[:branch] = val if (val = option('branch', strict: true))
  opts[:local] = val != '0' if (val = option('local', strict: true))
  opts.delete(:'recurse-submodules') || opts.delete(:'no-recurse-submodules') if append_submodules(:clone)
  append_hash opts
  cmd << '--quiet' unless verbose
  append_value(data[0], path, delim: true)
  source(banner: sync && !quiet?, multiple: !sync || quiet?)
end

#clone?Boolean

Returns:

  • (Boolean)


1350
1351
1352
# File 'lib/squared/workspace/project/git.rb', line 1350

def clone?
  ref?(workspace.baseref) && workspace.git_clone?(path, name) ? 1 : false
end

#commit(flag, refs: [], message: nil, pass: false) ⇒ Object



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
# File 'lib/squared/workspace/project/git.rb', line 1053

def commit(flag, *, refs: [], message: nil, pass: false)
  message ||= option('message', 'm', prefix: 'git', ignore: false)
  amend = flag.to_s.start_with?('amend')
  if !message && !amend
    return if pass

    raise_error('missing message', hint: 'GIT_MESSAGE="description"')
  end
  pathspec = if flag == :all || (amend && refs.size == 1 && refs.first == '*')
               '--all'
             elsif (refs = projectmap(refs)).empty?
               raise_error 'no qualified pathspec'
             else
               "-- #{refs.join(' ')}"
             end
  origin = nil
  branch = nil
  upstream = nil
  git_spawn 'fetch --no-tags --quiet'
  git_spawn('branch -vv --list', stdout: false).first.each do |val|
    next unless (r = /^\*\s(\S+)\s+(\h+)(?:\s\[(.+?)(?=\]\s)\])?\s/.match(val))

    branch = r[1]
    if r[3]
      origin = r[3][%r{^(.+)/#{Regexp.escape(branch)}$}, 1]
    else
      unless (origin = option('repository', prefix: 'git', ignore: false))
        out = git_spawn('log -n1 --format=%h%d').first
        if out =~ /^#{r[2]} \(HEAD -> #{Regexp.escape(branch)}, (.+?)\)$/
          split_escape($1).each do |s|
            next unless s.end_with?("/#{branch}")

            origin = s[0, s.size - branch.size - 1]
            break
          end
        end
      end
      upstream = true if origin
    end
    break
  end
  raise_error 'work tree is not usable' unless origin && branch
  cmd = git_session('commit', option('dry-run') && '--dry-run', options: false)
  if amend
    cmd << '--amend'
  else
    cmd.delete('--amend')
  end
  if message
    append_message message
  elsif flag == :'amend-orig' || option('edit', equals: '0')
    cmd << '--no-edit'
  end
  a = git_output 'add', '--verbose'
  b = git_output 'push', upstream && '--set-upstream'
  if dryrun?
    a << '--dry-run'
    b << '--dry-run'
  end
  a << pathspec
  b << '--force-with-lease' if amend
  b << origin << branch
  puts if pass
  source a
  source cmd
  source b
end

#dependObject



691
692
693
694
# File 'lib/squared/workspace/project/git.rb', line 691

def depend(*, **)
  workspace.rev_clear(name)
  super
end

#diff(flag, opts = [], refs: [], branch: nil, range: [], index: []) ⇒ Object



1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'lib/squared/workspace/project/git.rb', line 1014

def diff(flag, opts = [], refs: [], branch: nil, range: [], index: [])
  cmd, opts = git_session('diff', opts: opts)
  files = option_sanitize(opts, collect_hash(OPT_GIT[:diff]) + OPT_GIT[:log][:diff],
                          no: OPT_GIT[:no][:log][:diff]).first
  case flag
  when :files, :view, :between, :contain
    cmd.delete('--cached')
  end
  append_nocolor
  if flag == :files
    cmd << '--no-index'
    append_pathspec(refs, parent: true)
  else
    case flag
    when :view
      cmd << '--merge-base' if option('merge-base')
      cmd << shell_quote(range.first, quote: true) << shell_quote(range.last, quote: true)
    when :between, :contain
      cmd.delete('--merge-base')
      cmd << shell_quote(range.join(flag == :between ? '..' : '...'))
    else
      cmd << '--merge-base' if option('merge-base')
      cmd << shell_quote(branch) if branch
      if !index.empty?
        if session_arg?('cached')
          raise_error("one commit only: #{index.join(', ')}", hint: '--cached') if index.size > 1
          cmd << index.first
        else
          cmd.merge(index)
        end
      elsif (n = option('index', ignore: false))
        cmd << "HEAD~#{n}"
      end
    end
    append_pathspec files
  end
  source(exception: session_arg?('exit-code'))
end

#enabled?(**kwargs) ⇒ Boolean

Returns:

  • (Boolean)


1358
1359
1360
# File 'lib/squared/workspace/project/git.rb', line 1358

def enabled?(*, **kwargs)
  super || (kwargs[:base] == false && !!clone?)
end

#fetch(flag = nil, opts = [], sync: invoked_sync?('fetch', flag), remote: nil) ⇒ Object



755
756
757
758
759
760
761
762
# File 'lib/squared/workspace/project/git.rb', line 755

def fetch(flag = nil, opts = [], sync: invoked_sync?('fetch', flag), remote: nil)
  cmd, opts = git_session('fetch', opts: opts)
  append_pull(opts, collect_hash(OPT_GIT[:fetch]), no: collect_hash(OPT_GIT[:no][:fetch]),
                                                   remote: remote, flag: flag)
  cmd << '--all' if !remote && !session_arg?('multiple') && option('all')
  cmd << '--verbose' if verbose && !session_arg('quiet')
  source(sync: sync, **threadargs)
end

#generate(keys = []) ⇒ Object



686
687
688
689
# File 'lib/squared/workspace/project/git.rb', line 686

def generate(keys = [], **)
  keys << :clone if clone?
  super
end

#git(flag, opts = []) ⇒ Object



1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
# File 'lib/squared/workspace/project/git.rb', line 1318

def git(flag, opts = [])
  cmd, opts = git_session(flag, opts: opts)
  refs = option_sanitize(opts, OPT_GIT[flag], no: OPT_GIT[:no][flag]).first
  sync = false
  stderr = true
  case flag
  when :clean
    refs = projectmap(refs)
    unless refs.empty?
      cmd << '--'
      cmd.merge(refs)
    end
    sync = true
    stderr = false
  when :revert
    if VAL_GIT[:rebase][:send].any? { |val| session_arg?(val) }
      option_clear refs
    elsif refs.empty?
      raise_error 'no commit given'
    else
      append_commit(*refs)
    end
  when :mv
    refs = projectmap(refs)
    raise_error 'no source/destination' unless refs.size > 1
    cmd.merge(refs)
  when :rm
    append_pathspec(refs, expect: true)
  end
  source(sync: sync, stderr: stderr)
end

#logx(flag, opts = [], range: [], index: []) ⇒ Object



1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
# File 'lib/squared/workspace/project/git.rb', line 1000

def logx(flag, opts = [], range: [], index: [])
  cmd, opts = git_session('log', opts: opts)
  refs = option_sanitize(opts, collect_hash(OPT_GIT[:log]), no: collect_hash(OPT_GIT[:no][:log])).first
  case flag
  when :between, :contain
    cmd << shell_quote(range.join(flag == :between ? '..' : '...'))
  else
    cmd.merge(index)
  end
  append_nocolor
  append_pathspec refs
  source(exception: false)
end

#ls_files(flag, opts = []) ⇒ Object



1309
1310
1311
1312
1313
1314
1315
1316
# File 'lib/squared/workspace/project/git.rb', line 1309

def ls_files(flag, opts = [])
  opts = git_session('ls-files', "--#{flag}", opts: opts).last
  grep = option_sanitize(opts, OPT_GIT[:ls_files]).first
  out, banner, from = source(io: true)
  print_item banner
  ret = write_lines(out, grep: grep)
  list_result(ret, 'files', from: from, grep: grep)
end

#ls_remote(flag, opts = [], remote: nil) ⇒ Object



1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/squared/workspace/project/git.rb', line 1298

def ls_remote(flag, opts = [], remote: nil)
  cmd, opts = git_session('ls-remote', '--refs', opts: opts)
  cmd << "--#{flag}" unless flag == :remote
  grep = option_sanitize(opts, OPT_GIT[:ls_remote]).first
  cmd << shell_quote(remote) if remote
  out, banner, from = source(io: true)
  print_item banner
  ret = write_lines(out, grep: grep)
  list_result(ret, flag.to_s, from: from, grep: grep)
end

#merge(flag, opts = [], command: nil) ⇒ Object



1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
# File 'lib/squared/workspace/project/git.rb', line 1121

def merge(flag, opts = [], command: nil)
  cmd, opts = git_session('merge', opts: opts)
  case flag
  when :commit, :'no-commit'
    refs = option_sanitize(opts, OPT_GIT[:merge], no: OPT_GIT[:no][:merge]).first
    raise_error 'no branch/commit' if refs.empty?
    cmd << "--#{flag}" << '--'
    append_commit(*refs)
  else
    return unless VAL_GIT[:merge][:send].include?(command)

    cmd << "--#{command}"
  end
  source
end

#populateObject



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
410
411
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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
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
684
# File 'lib/squared/workspace/project/git.rb', line 343

def populate(*, **)
  super
  return unless ref?(Git.ref)

  namespace name do
    @@tasks[Git.ref].each do |action, flags|
      next if @pass.include?(action)

      namespace action do
        flags.each do |flag|
          case action
          when 'pull', 'fetch'
            if flag == :remote
              format_desc(action, flag, 'remote,opts*')
              task flag, [:remote] do |_, args|
                remote = param_guard(action, flag, args: args, key: :remote)
                __send__(action, flag, args.extras, remote: remote)
              end
            else
              format_desc action, flag, 'opts*'
              task flag do |_, args|
                __send__ action, flag, args.to_a
              end
            end
          when 'commit'
            case flag
            when :all
              format_desc action, flag, 'message?'
              task flag, [:message] do |_, args|
                commit(flag, message: args.fetch(:message, nil))
              end
            else
              format_desc action, flag, 'pathspec+'
              task flag do |_, args|
                refs = param_guard(action, flag, args: args.to_a)
                commit(flag, refs: refs)
              end
            end
          when 'tag'
            case flag
            when :list
              format_desc action, flag, 'opts*,pattern*'
              task flag do |_, args|
                tag flag, args.to_a
              end
            when :delete
              format_desc action, flag, 'name+'
              task flag do |_, args|
                refs = param_guard(action, flag, args: args.to_a)
                tag(flag, refs: refs)
              end
            when :add
              format_desc action, flag, 'name,message?,commit?'
              task flag, [:name, :message, :commit] do |_, args|
                name = param_guard(action, flag, args: args, key: :name)
                tag(flag, refs: [name], message: args.message, commit: args.commit)
              end
            end
          when 'stash'
            if flag == :list
              format_desc action, flag
            else
              format_desc(action, flag, '*opts', after: flag == :push ? 'pathspec*' : 'commit?')
            end
            task flag do |_, args|
              stash flag, args.to_a
            end
          when 'log', 'diff'
            case flag
            when :view, :between, :contain
              if flag == :view && action == 'log'
                format_desc action, flag, '(^)commit/H0*,pathspec*,opts*'
                task flag do |_, args|
                  index = []
                  args.to_a.each do |val|
                    if val =~ /^H(\d+)$/
                      index << "HEAD~#{$1}"
                    elsif (sha = commithash(val))
                      index << sha
                    elsif val.start_with?('^') || (!%r{^[.\\/]}.match?(val) && !%r{[\\/]$}.match?(val))
                      index << shell_quote(val)
                    end
                  end
                  logx(flag, args.to_a.drop(index.size), index: index)
                end
              else
                format_desc action, flag, 'commit1,commit2,pathspec*,opts*'
                task flag, [:commit1, :commit2] do |_, args|
                  commit1 = param_guard(action, flag, args: args, key: :commit1)
                  commit2 = param_guard(action, flag, args: args, key: :commit2)
                  __send__(action == 'log' ? :logx : :diff, flag, args.extras, range: [commit1, commit2])
                end
              end
            when :head
              format_desc action, flag, 'commit/H0*,opts*,pathspec*'
              task flag do |_, args|
                index = []
                args.to_a.each do |val|
                  break unless val =~ /^H(\d+)$/ || (sha = commithash(val))

                  index << ($1 ? "HEAD~#{$1}" : sha)
                end
                diff(flag, args.to_a.drop(index.size), index: index)
              end
            when :branch
              format_desc action, flag, 'name,opts*,pathspec*'
              task flag, [:name] do |_, args|
                branch = param_guard(action, flag, args: args, key: :name)
                diff(flag, args.extras, branch: branch)
              end
            when :files
              format_desc action, flag, 'path1,path2'
              task flag, [:path1, :path2] do |_, args|
                path1 = param_guard(action, flag, args: args, key: :path1)
                path2 = param_guard(action, flag, args: args, key: :path2)
                diff(flag, refs: [path1, path2])
              end
            end
          when 'checkout'
            case flag
            when :branch
              format_desc action, flag, 'name,create?=[bB],commit?,detach?=d'
              task flag, [:name, :create, :commit, :detach] do |_, args|
                branch = param_guard(action, flag, args: args, key: :name)
                create = args.create
                if args.commit == 'd'
                  detach = 'd'
                  commit = nil
                elsif create == 'd'
                  create = nil
                  commit = nil
                  detach = 'd'
                elsif create && create.size > 1
                  commit = create
                  create = nil
                  detach = args.commit
                else
                  detach = args.detach
                  commit = args.commit
                end
                param_guard(action, flag, args: { create: create }, key: :create, pat: /\Ab\z/i) if create
                checkout(flag, branch: branch, create: create, commit: commit, detach: detach)
              end
            when :track
              format_desc action, flag, 'origin,(^)name?'
              task flag, [:origin, :name] do |_, args|
                origin = param_guard(action, flag, args: args, key: :origin)
                checkout(flag, branch: args.name, origin: origin)
              end
            when :commit
              format_desc action, flag, 'branch/commit,opts*'
              task flag, [:commit] do |_, args|
                commit = param_guard(action, flag, args: args, key: :commit)
                checkout(flag, commit: commit)
              end
            when :detach
              format_desc action, flag, 'branch/commit?'
              task flag, [:commit] do |_, args|
                checkout(flag, commit: args.commit)
              end
            when :path
              format_desc action, flag, 'opts*,pathspec*'
              task flag do |_, args|
                checkout flag, args.to_a
              end
            end
          when 'branch'
            case flag
            when :create
              format_desc action, flag, 'name,ref?=HEAD'
              task flag, [:name, :ref] do |_, args|
                target = param_guard(action, flag, args: args, key: :name)
                branch(flag, target: target, ref: args.ref)
              end
            when :set
              format_desc(action, flag, '(^)upstream,name?')
              task flag, [:upstream, :name] do |_, args|
                upstream = param_guard(action, flag, args: args, key: :upstream)
                branch(flag, target: args.name, ref: upstream)
              end
            when :delete
              format_desc action, flag, '(^~)name+'
              task flag do |_, args|
                refs = param_guard(action, flag, args: args.to_a)
                branch(flag, refs: refs)
              end
            when :edit
              format_desc action, flag, 'name?'
              task flag, [:name] do |_, args|
                branch(flag, target: args.name)
              end
            when :list
              format_desc action, flag, 'opts*,pattern*'
              task flag do |_, args|
                branch flag, args.to_a
              end
            when :current
              format_desc action, flag
              task flag do
                branch flag
              end
            else
              format_desc action, flag, 'branch,oldbranch?'
              task flag, [:branch, :oldbranch] do |_, args|
                branch = param_guard(action, flag, args: args, key: :branch)
                branch(flag, refs: [args.oldbranch, branch])
              end
            end
          when 'reset'
            case flag
            when :commit
              format_desc action, flag, 'branch/commit,opts*'
              task flag, [:commit] do |_, args|
                commit = param_guard(action, flag, args: args, key: :commit)
                reset(flag, args.extras, commit: commit)
              end
            when :index
              format_desc action, flag, 'opts*,pathspec*'
              task flag do |_, args|
                reset flag, args.to_a
              end
            when :mode
              format_desc action, flag, 'mode,ref?=HEAD'
              task flag, [:mode, :ref] do |_, args|
                mode = param_guard(action, flag, args: args, key: :mode)
                reset(flag, mode: mode, ref: args.ref)
              end
            when :patch
              format_desc action, flag, 'ref,pathspec*'
              task flag, [:ref] do |_, args|
                ref = param_guard(action, flag, args: args, key: :ref)
                reset(flag, refs: args.extras, ref: ref)
              end
            end
          when 'show'
            case flag
            when :oneline
              format_desc action, flag, 'opts*,object*'
              task flag do |_, args|
                show flag, args.to_a.push('abbrev-commit')
              end
            when :format
              format_desc action, flag, 'format?,opts*,object*'
              task flag, [:format] do |_, args|
                show(flag, args.extras, format: args.format)
              end
            when :textconv
              format_desc action, flag, 'files+'
              task flag do |_, args|
                files = param_guard(action, flag, args: args.to_a)
                show(flag, files: files)
              end
            end
          when 'rebase', 'merge'
            case flag
            when :branch
              format_desc action, flag, 'opts*,upstream?,branch?'
              task flag do |_, args|
                args = param_guard(action, flag, args: args.to_a)
                rebase flag, args
              end
            when :onto
              format_desc action, flag, 'branch/commit,upstream,branch?=HEAD'
              task flag, [:commit, :upstream, :branch] do |_, args|
                commit = param_guard(action, flag, args: args, key: :commit)
                upstream = param_guard(action, flag, args: args, key: :upstream)
                rebase(flag, commit: commit, upstream: upstream, branch: args.branch)
              end
            when :commit, :'no-commit'
              format_desc action, flag, 'branch/commit+,opts*'
              task flag do |_, args|
                args = param_guard(action, flag, args: args.to_a)
                merge flag, args
              end
            when :send
              format_desc(action, flag, VAL_GIT[action.to_sym][:send], arg: nil)
              task flag, [:command] do |_, args|
                command = param_guard(action, flag, args: args, key: :command,
                                                    values: VAL_GIT[action.to_sym][:send])
                __send__(action, flag, command: command)
              end
            end
          when 'rev'
            case flag
            when :commit
              format_desc action, flag, 'ref?=HEAD,size?'
              task flag, [:ref, :size] do |_, args|
                ref = args.ref
                size = args.size
                if !size && ref.to_i > 0
                  size = ref
                  ref = nil
                end
                rev_parse(flag, ref: ref, size: size)
              end
            when :branch
              format_desc action, flag, 'ref?=HEAD'
              task flag, [:ref] do |_, args|
                rev_parse(flag, ref: args.ref)
              end
            when :build
              format_desc action, flag, OPT_GIT[:status]
              task flag do |_, args|
                revbuild flag, args.to_a
              end
            else
              format_desc action, flag, 'opts*,args*'
              task flag do |_, args|
                rev_parse flag, args.to_a
              end
            end
          when 'refs', 'files'
            if flag == :remote
              format_desc action, flag, 'remote,opts*,pattern*'
              task flag, [:remote] do |_, args|
                remote = param_guard(action, flag, args: args, key: :remote)
                ls_remote(flag, args.extras, remote: remote)
              end
            else
              format_desc action, flag, 'opts*,pattern*'
              task flag do |_, args|
                __send__(action == 'refs' ? :ls_remote : :ls_files, flag, args.to_a)
              end
            end
          when 'restore', 'git'
            format_desc(action, flag, 'opts*', before: case flag
                                                       when :rm
                                                         'source+,destination'
                                                       when :revert
                                                         'commit+'
                                                       else
                                                         'pathspec*'
                                                       end)
            task flag do |_, args|
              __send__(action, flag, args.to_a)
            end
          end
        end
      end
    end
  end
end

#pull(flag = nil, opts = [], sync: invoked_sync?('pull', flag), remote: nil) ⇒ Object



701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/squared/workspace/project/git.rb', line 701

def pull(flag = nil, opts = [], sync: invoked_sync?('pull', flag), remote: nil)
  cmd, opts = git_session('pull', flag && "--#{flag}", opts: opts)
  if flag == :rebase
    cmd << '--autostash' if option('autostash')
  elsif (val = option('rebase', ignore: false))
    cmd << case val
           when '0'
             '--no-rebase'
           else
             VAL_GIT[:rebase][:value].include?(val) ? basic_option('rebase', val) : '--rebase'
           end
  end
  append_pull(opts, OPT_GIT[:pull] + OPT_GIT[:fetch][:pull],
              no: OPT_GIT[:no][:pull] + OPT_GIT[:no][:fetch][:pull], remote: remote, flag: flag)
  source(sync: sync, sub: if verbose
                            [
                              { pat: /^(.+)(\|\s+\d+\s+)([^-]*)(-+)(.*)$/, styles: color(:red), index: 4 },
                              { pat: /^(.+)(\|\s+\d+\s+)(\++)(-*)(.*)$/, styles: color(:green), index: 3 }
                            ]
                          end, **threadargs)
end

#rebase(flag = nil, opts = [], sync: invoked_sync?('rebase', flag), commit: nil, upstream: nil, branch: nil, command: nil) ⇒ Object



723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/squared/workspace/project/git.rb', line 723

def rebase(flag = nil, opts = [], sync: invoked_sync?('rebase', flag), commit: nil, upstream: nil, branch: nil,
           command: nil)
  return pull(:rebase, sync: sync) unless flag

  cmd, opts = git_session('rebase', opts: opts)
  case flag
  when :branch
    branch = option_sanitize(opts, OPT_GIT[:rebase], no: OPT_GIT[:no][:rebase]).first
    case branch.size
    when 0
      append_head
    when 1, 2
      append_value(branch, delim: true)
    else
      append_value([branch.pop, branch.pop].reverse, delim: true)
      option_clear(branch, pass: false)
    end
  when :onto
    return unless upstream

    cmd << '--interactive' if option('interactive', 'i')
    cmd << shell_option('onto', commit) if commit
    cmd << shell_escape(upstream)
    append_head branch
  else
    return unless VAL_GIT[:rebase][:send].include?(command)

    cmd << "--#{command}"
  end
  source
end

#refObject



339
340
341
# File 'lib/squared/workspace/project/git.rb', line 339

def ref
  Git.ref
end

#reset(flag, opts = [], refs: nil, ref: nil, mode: nil, commit: nil) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
# File 'lib/squared/workspace/project/git.rb', line 903

def reset(flag, opts = [], refs: nil, ref: nil, mode: nil, commit: nil)
  cmd, opts = git_session('reset', opts: opts)
  case flag
  when :commit, :index
    files = option_sanitize(opts, OPT_GIT[:reset] + VAL_GIT[:reset], no: OPT_GIT[:no][:reset]).first
    if flag == :commit
      append_value(commit, delim: true)
      option_clear(files, pass: false)
      ref = false
    else
      (refs ||= []).concat(files)
    end
  when :mode
    return unless VAL_GIT[:reset].include?(mode)

    cmd << "--#{mode}"
    if mode == 'mixed'
      cmd << '-N' if option('n')
      cmd << '--no-refresh' if option('refresh', equals: '0')
    end
  when :patch
    cmd << '--patch'
  else
    return
  end
  unless ref == false
    append_commit(ref, head: true)
    append_pathspec(refs, pass: false) if refs
  end
  source
end

#restore(flag, opts = []) ⇒ Object



1234
1235
1236
1237
1238
1239
# File 'lib/squared/workspace/project/git.rb', line 1234

def restore(flag, opts = [])
  opts = git_session('restore', "--#{flag}", opts: opts).last
  refs = option_sanitize(opts, OPT_GIT[:restore], no: OPT_GIT[:no][:restore]).first
  append_pathspec(refs, pass: false)
  source(sync: false, stderr: true)
end

#rev_parse(flag, opts = [], ref: nil, size: nil) ⇒ Object



1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'lib/squared/workspace/project/git.rb', line 1277

def rev_parse(flag, opts = [], ref: nil, size: nil)
  cmd, opts = git_session('rev-parse', opts: opts)
  cmd << if flag == :parseopt
           '--parseopt'
         elsif opts.delete('sq-quote')
           '--sq-quote'
         end
  case flag
  when :commit
    cmd << ((n = size.to_i) > 0 ? basic_option('short', [n, 5].max) : '--verify')
    append_commit(ref, head: true)
  when :branch
    cmd << '--abbrev-ref'
    append_commit(ref, head: true)
  else
    args = option_sanitize(opts, OPT_GIT[:rev_parse][flag]).first
    append_value(args, escape: session_arg?('sq-quote'))
  end
  source(banner: verbosity > 0)
end

#revbuild(flag = nil, opts = [], sync: invoked_sync?('revbuild', flag), **kwargs) ⇒ Object



849
850
851
852
853
854
855
856
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
894
895
896
897
898
899
900
901
# File 'lib/squared/workspace/project/git.rb', line 849

def revbuild(flag = nil, opts = [], sync: invoked_sync?('revbuild', flag), **kwargs)
  statusargs = lambda do
    {
      include: relativepath(as_a(kwargs[:include]), all: true),
      exclude: relativepath(as_a(kwargs[:exclude]), all: true)
    }
  end
  unless workspace.closed
    if @revbuild
      statusargs.().each { |key, val| @revbuild[key] += val }
    else
      @revbuild = statusargs.()
    end
    return
  end
  sha = git_spawn('rev-parse --verify HEAD').first.to_s.chomp
  return if sha.empty?

  args = []
  kwargs = kwargs.key?(:include) || kwargs.key?(:exclude) ? statusargs.() : @revbuild || {}
  case flag
  when :build
    opts = option_sanitize(opts, OPT_GIT[:status], target: args).first
    option_clear(opts, append: true)
  else
    args << basic_option('untracked-files', flag) if (flag = option('untracked-files', prefix: 'git'))
    args << basic_option('ignore-submodules', flag) if (flag = option('ignore-submodules', prefix: 'git'))
    args << basic_option('ignored', flag) if (flag = option('ignored', prefix: 'git'))
  end
  if (cur = workspace.rev_entry(name)) && cur['revision'] == sha && !env('REVBUILD_FORCE')
    files = status_digest(*args, **kwargs)
    if cur['files'].size == files.size && cur['files'].find { |key, val| files[key] != val }.nil?
      if verbose
        if (since = workspace.rev_timesince(name, 'build'))
          puts log_message(Logger::INFO, name, 'no changes', subject: 'revbuild', hint: "#{since} ago")
        else
          workspace.rev_timeutc(name, 'build')
        end
      end
      return
    end
  end
  start = epochtime
  build(@output, sync: sync, from: :'git:revbuild')
rescue StandardError => e
  warn log_message(Logger::WARN, e, pass: true) if warning?
else
  if verbose
    msg = sub_style('completed', styles: theme[:active])
    puts log_message(Logger::INFO, name, msg, subject: 'revbuild', hint: time_format(epochtime - start))
  end
  workspace.rev_write(name, { 'revision' => sha, 'files' => status_digest(*args, **kwargs) }, utc: 'build')
end

#revbuild?Boolean

Returns:

  • (Boolean)


1354
1355
1356
# File 'lib/squared/workspace/project/git.rb', line 1354

def revbuild?
  build? && !!workspace.revfile
end

#show(flag, opts = [], format: nil, files: []) ⇒ Object



1241
1242
1243
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
# File 'lib/squared/workspace/project/git.rb', line 1241

def show(flag, opts = [], format: nil, files: [])
  cmd, opts = git_session('show', opts: opts)
  case flag
  when :textconv
    cmd << '--textconv'
    append_value(files.map { |val| Dir[val] }
                      .flatten
                      .select { |val| projectpath?(val) }
                      .map! { |val| shell_quote("HEAD:#{val}") })
    source(banner: false)
    return
  when :oneline
    format = flag.to_s
  end
  if format
    case (val = format.downcase)
    when 'oneline', 'short', 'medium', 'full', 'fuller', 'reference', 'email', 'raw'
      cmd << basic_option('format', val)
    else
      if format.match?(/^t?format:/) || format.include?('%')
        cmd << quote_option('pretty', format)
      else
        opts << format
      end
    end
  end
  refs = option_sanitize(opts, OPT_GIT[:show] + OPT_GIT[:diff][:show] + OPT_GIT[:log][:diff],
                         no: OPT_GIT[:no][:show] + collect_hash(OPT_GIT[:no][:log], pass: [:base])).first
  unless val == 'oneline' && session_arg?('abbrev-commit')
    cmd << basic_option('abbrev', val) if (val = option('abbrev')) && val.to_i > 0
    banner = true
  end
  append_value(refs, delim: true)
  source(exception: false, banner: banner)
end

#stash(flag = nil, opts = [], sync: invoked_sync?('stash', flag)) ⇒ Object



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
# File 'lib/squared/workspace/project/git.rb', line 786

def stash(flag = nil, opts = [], sync: invoked_sync?('stash', flag))
  if flag
    cmd, opts = git_session('stash', flag, opts: opts)
    refs = option_sanitize(opts, OPT_GIT[:stash][:common] + OPT_GIT[:stash].fetch(flag, [])).first
    case flag
    when :push
      append_pathspec refs
    when :pop, :apply, :drop
      unless refs.empty?
        cmd << shell_escape(refs.pop)
        option_clear refs
      end
    when :clear
      if confirm("Remove #{sub_style('all', styles: theme[:active])} the stash entries? [y/N] ", 'N')
        source(stdout: true)
      end
      return
    when :list
      out, banner, from = source(io: true)
      print_item banner
      ret = write_lines(out)
      list_result(ret, 'objects', from: from)
      return
    end
  else
    git_session('stash', 'push', opts: opts)
    append_option(%w[all keep-index include-untracked staged].freeze, no: true, ignore: false)
    append_message option('message', 'm', ignore: false)
  end
  source(banner: !quiet?, sync: sync, **threadargs)
end

#statusObject



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
# File 'lib/squared/workspace/project/git.rb', line 818

def status(*)
  cmd = git_session 'status'
  cmd << (option('long') ? '--long' : '--short')
  if (val = option('ignore-submodules', ignore: false))
    cmd << basic_option('ignore-submodules', case val
                                             when '0', 'none'
                                               'none'
                                             when '1', 'untracked'
                                               'untracked'
                                             when '2', 'dirty'
                                               'dirty'
                                             else
                                               'all'
                                             end)
  end
  append_pathspec
  out, banner, from = source(io: true)
  ret = write_lines(out, banner: banner, sub: if verbose
                                                r = color(:red)
                                                g = color(:green)
                                                [
                                                  { pat: /^(.)([A-Z?!])(.+)$/, styles: r, index: 2 },
                                                  { pat: /^([A-Z?!])(.+)$/, styles: g },
                                                  { pat: /^(\?\?)(.+)$/, styles: r },
                                                  { pat: /^(## )(.+)(\.{3})(.+)$/,
                                                    styles: [nil, g, nil, r], index: -1 }
                                                ]
                                              end)
  list_result(ret, 'files', from: from, action: 'modified')
end

#tag(flag, opts = [], refs: [], message: nil, commit: nil) ⇒ Object



967
968
969
970
971
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
# File 'lib/squared/workspace/project/git.rb', line 967

def tag(flag, opts = [], refs: [], message: nil, commit: nil)
  cmd, opts = git_session('tag', opts: opts)
  case flag
  when :add
    if option('sign')
      cmd << '--sign'
    elsif !session_arg?('s', 'sign', 'u', 'local-user')
      cmd << '--annotate'
    end
    if !commit && message && (sha = commithash(message))
      commit = sha
    else
      append_message message
    end
    append_value refs
    append_head commit
  when :list
    cmd << '--list'
    grep = option_sanitize(opts, OPT_GIT[:tag], no: OPT_GIT[:no][:tag]).first
    out, banner, from = source(io: true)
    print_item banner
    ret = write_lines(out, grep: grep)
    list_result(ret, 'tags', from: from, grep: grep)
    return
  when :delete
    cmd << '--delete'
    append_value refs
  else
    cmd << shell_option(flag, commit)
  end
  source
end