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

#children, #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, #asdf, bannerargs, #basepath, #basepath!, batchargs, #build, #build?, #chain, #clean?, #copy, #copy?, #depend?, #dependname, #dependtype, #dev?, #doc, #doc?, #empty?, #error, #event, #exclude?, #exist?, #first, #global, #global=, #global_set, #graph, #graph?, #has?, #inject, #inspect, #last, #lint, #lint?, #localname, #log, options, populate, #prereqs, #prereqs?, #prod?, ref, #ref?, #rootpath, #run, #scope, #script?, #scriptdata, #scriptname, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #variable_set, #version, #version=, #with

Methods included from Common::Format

emphasize, #enable_aixterm, #enable_drawing, message, raise_error

Constructor Details

#initializeGit

Returns a new instance of Git.



359
360
361
362
363
# File 'lib/squared/workspace/project/git.rb', line 359

def initialize(*, **)
  super
  @submodule = exist?('.gitmodules')
  initialize_ref Git.ref if gitpath.exist?
end

Class Method Details

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


327
328
329
330
331
# File 'lib/squared/workspace/project/git.rb', line 327

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

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

.tasksObject



323
324
325
# File 'lib/squared/workspace/project/git.rb', line 323

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

Instance Method Details

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



1119
1120
1121
# File 'lib/squared/workspace/project/git.rb', line 1119

def autostash(*, sync: invoked_sync?('autostash'), **)
  pull(:autostash, sync: sync)
end

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



1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
# File 'lib/squared/workspace/project/git.rb', line 1664

def branch(flag = nil, opts = [], refs: [], ref: nil, target: nil, remote: nil)
  cmd, opts = git_session('branch', opts: opts)
  stdout = false
  case flag
  when :create
    option('track', ignore: false) do |val|
      cmd << case val
             when '0', 'false'
               '--no-track'
             when 'direct', 'inherit'
               basic_option 'track', val
             else
               '--track'
             end
    end
    cmd << '--force' if option('f', 'force')
    cmd << shell_quote(target)
    cmd << shell_quote(ref) if ref
  when :track
    raise_error 'invalid upstream', hint: ref unless ref.include?('/')
    if ref.delete_prefix!('^')
      cmd << '--unset-upstream' << shell_quote(ref)
      remote = false
      stdout = true
    else
      cmd << quote_option('set-upstream-to', ref)
      cmd << shell_quote(target) if target
    end
  when :delete
    remote&.each { |val| source git_output('push --delete', *val.split('/', 2).quote!) }
    force, list = refs.partition { |val| val.start_with?('~', '^') }
    force.each do |val|
      r = '-r' if val.delete!('~')
      source git_output('branch', val.delete!('^') ? '-D' : '-d', r, shell_quote(val))
    end
    return if list.empty?

    cmd << '-d'
    append_value list
    remote = nil
  when :move, :copy
    s = +"-#{flag.to_s[0]}"
    s.upcase! if option('f', 'force')
    cmd << s
    cmd.merge(refs.compact.quote!)
    stdout = true
  when :current
    cmd << '--show-current'
    source(banner: verbose?, stdout: true)
    return
  when :list
    op = OptionPartition.new(opts, OPT_GIT[:branch], cmd << '--list',
                             project: self, strict: strict?, no: OPT_GIT[:no][:branch], single: /\Av+\z/)
    op.each { |val| op.add_quote(val) }
    out, banner, from = source(io: true)
    print_item banner
    ret = write_lines(out, sub: [
      opt_style(color(:green), /^(\*\s+)(\S+)(.*)$/, 2),
      opt_style(color(:red), %r{^(\s*)(remotes/\S+)(.*)$}, 2)
    ])
    list_result(ret, 'branches', from: from)
    return
  else
    if (head = git_spawn('rev-parse --abbrev-ref HEAD').chomp).empty?
      ret = 0
    else
      git_spawn 'fetch --all --prune --quiet' if option('sync')
      cmd << '-vv --no-abbrev --list'
      out, banner, from = source(io: true)
      first = workspace.size > 1
      grep = first ? [/^\*\s+#{Regexp.escape(head)}\s/] : []
      ret = write_lines(out, grep: grep, banner: banner, first: first) do |line, index|
        next line if stdin?

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

  source git_output('push -u', shell_quote(ref.split('/', 2).first), shell_quote(target))
end

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



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

def checkout(flag, opts = [], branch: nil, origin: nil, create: nil, commit: nil, detach: nil, merge: false)
  cmd, opts = git_session('checkout', opts: opts)
  append_option 'f', 'force', 'merge'
  case flag
  when :branch
    cmd << '--detach' if detach == 'd' || option('detach')
    append_option('track', equals: true)
    cmd << (create ? quote_option(create, branch) : branch) << commit
  when :track
    cmd << quote_option(branch.delete_prefix!('^') ? 'B' : 'b', branch) if branch
    cmd << '--track' << shell_quote(origin)
  when :detach
    cmd << '-m' if merge
    cmd << '--detach' << commit
  else
    op = OptionPartition.new(opts, OPT_GIT[:checkout] + OPT_GIT[:log][:diff_context], cmd,
                             project: self, strict: strict?, no: OPT_GIT[:no][:checkout],
                             first: (matchpathspec if flag == :path))
    if flag == :path
      append_head
      append_pathspec(op.extras, pass: false)
      return success?(source)
    end
    op.append(commit)
      .clear(pass: false)
  end
  source
end

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



1019
1020
1021
1022
# File 'lib/squared/workspace/project/git.rb', line 1019

def clean(*, sync: invoked_sync?('clean'), **)
  workspace.rev_clear(name, sync: sync)
  super
end

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



1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
# File 'lib/squared/workspace/project/git.rb', line 1136

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

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

#clone?Boolean

Returns:

  • (Boolean)


1988
1989
1990
# File 'lib/squared/workspace/project/git.rb', line 1988

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

#commit(flag, opts = [], refs: [], ref: nil, squash: nil, pick: nil, message: nil, pass: false) ⇒ Object



1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
# File 'lib/squared/workspace/project/git.rb', line 1542

def commit(flag, opts = [], refs: [], ref: nil, squash: nil, pick: nil, message: nil, pass: false)
  fixup = flag == :fixup
  amend = flag.match?(/^amend/) && !fixup
  unless flag == :add || pick == 'reword'
    pathspec = if flag == :all || ((fixup || amend) && refs.size == 1 && refs.first == '*')
                 '--all'
               elsif (refs = projectmap(refs)).empty?
                 raise 'no qualified pathspec'
               else
                 "-- #{refs.join(' ')}"
               end
  end
  if fixup
    ret = source(git_session('commit', basic_option('fixup', pick ? "#{pick}:#{ref}" : ref), pathspec))
    source git_output('rebase --autosquash', squash) if ret && squash.is_a?(String)
    return ret
  end
  message ||= messageopt
  unless message || amend
    return if pass

    message = readline('Enter message', force: true)
  end
  branch = nil
  origin = nil
  upstream = nil
  cmd, opts = git_session('add', opts: opts)
  op = OptionPartition.new(opts, OPT_GIT[:add] + OPT_GIT[:log][:diff_context], cmd,
                           project: self, strict: strict?, no: OPT_GIT[:no][:add], first: matchpathspec)
  op << '--verbose' unless silent?
  format = '%(if)%(HEAD)%(then)%(refname:short)...%(upstream:short)...%(upstream:track)%(end)'
  git_spawn 'fetch --no-tags --quiet'
  foreachref('heads', format: format).each do |line|
    next if line.empty?

    branch, origin, hint = line.split('...')
    if hint && !hint.match?(/^\[(\D+0,\D+0)\]$/)
      raise_error 'work tree is not usable', hint: hint[1..-2]
    elsif (!origin || origin.empty?) && !dryrun?
      return nil if pass

      unless (origin = option('upstream', prefix: 'git', ignore: false))
        if (origin = choice_refs('Choose an upstream', 'remotes', attempts: 1, force: false))
          git_spawn 'branch', quote_option('set-upstream-to', origin)
          break
        end
        origin = readline('Enter an upstream', force: true)
      end
      upstream = true
    end
    break
  end
  if pathspec
    op << pathspec
  else
    append_pathspec op.extras
  end
  co = git_session('commit', options: false)
  pu = git_output 'push'
  co << '--amend' if amend
  pu << '--set-upstream' if upstream
  if dryrun?
    op.adjoin('--dry-run')
    co << '--dry-run'
    pu << '--dry-run'
  end
  if message
    append_message message
  elsif flag == :'amend-orig' || option('edit', equals: '0')
    co << '--no-edit'
  end
  pu << '--force-with-lease' if amend
  pu.merge(repotrack(origin, branch))
  adding = git_spawn 'diff --name-only --no-color'
  source op
  cached = git_spawn 'diff --cached --name-only --no-color'
  if amend || !cached.empty? || dryrun?
    if adding.empty? && !cached.empty? && banner?
      puts(cached.lines(chomp: true).map { |val| "cached #{shell_quote(val)}" })
    end
    source co
    source pu
  else
    if banner?
      puts 'Nothing to commit'
    elsif stdout?
      puts log_message('nothing to commit', subject: name, hint: flag)
    end
    exit 1
  end
end

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



1014
1015
1016
1017
# File 'lib/squared/workspace/project/git.rb', line 1014

def depend(*, sync: invoked_sync?('depend'), **)
  workspace.rev_clear(name, sync: sync)
  super
end

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



1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
# File 'lib/squared/workspace/project/git.rb', line 1484

def diff(flag, opts = [], refs: [], branch: nil, range: [], index: [], from: :diff)
  cmd, opts = git_session(from, opts: opts)
  list = if from == :'range-diff'
           OPT_GIT[:range_diff]
         else
           no = OPT_GIT[:no][:log][:diff]
           collect_hash(OPT_GIT[:diff]) + OPT_GIT[:log][:diff] + OPT_GIT[:log][:diff_context]
         end
  op = OptionPartition.new(opts, list, cmd, project: self, strict: strict?, no: no,
                                            first: (matchpathspec unless flag == :files))
  case flag
  when :files, :view, :between, :contain
    op.delete('--cached')
  end
  append_nocolor
  if flag == :files
    op << '--no-index'
    patch = refs.pop
    append_pathspec(refs, parent: true)
  else
    op << '--merge-base' if option('merge-base')
    case flag
    when :view
      op.merge(range)
    when :between, :contain
      op.delete('--merge-base')
      op.add_quote(range.join(flag == :between ? '..' : '...'))
    else
      op.add_quote(branch) if branch
      if !index.empty?
        if op.arg?('cached')
          raise_error "single commit: #{index.join(', ')}", hint: 'cached' unless index.size == 1
          op << index.first
        else
          op.merge(index)
        end
      elsif (n = option('index', ignore: false))
        op << "HEAD~#{n}"
      end
    end
    if (n = op.index('>'))
      patch = op.slice!(n, 2)[1]
    elsif !op.exist?(op.last)
      patch ||= op.pop
    end
    append_pathspec op.extras
  end
  if patch
    patch = basepath patch.delete_prefix('>')
    exit 1 if patch.exist? && !confirm_basic('Overwrite?', patch)
    op << '>' << shell_quote(patch)
    source(banner: false, from: from)
    puts patch.read if patch.exist? && (stdin? || verbose?)
  else
    source(exception: op.arg?('exit-code'), from: from)
  end
end

#enabled?(**kwargs) ⇒ Boolean

Returns:

  • (Boolean)


1996
1997
1998
# File 'lib/squared/workspace/project/git.rb', line 1996

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

#fetch(flag = nil, opts = [], sync: invoked_sync?('fetch', flag), remote: nil, banner: !sync || verbose? || task_invoked?('fetch')) ⇒ Object



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

def fetch(flag = nil, opts = [], sync: invoked_sync?('fetch', flag), remote: nil,
          banner: !sync || verbose? || task_invoked?('fetch'))
  opts = git_session('fetch', opts: opts).last
  opts << 'all' if flag == :all || option('all')
  append_pull(opts, collect_hash(OPT_GIT[:fetch]), flag: flag, from: :fetch, remote: remote,
                                                   no: collect_hash(OPT_GIT[:no][:fetch]))
  if sync
    source(banner: banner)
  else
    source(sync: false, banner: banner, **threadargs)
  end
end

#generate(keys = []) ⇒ Object



1009
1010
1011
1012
# File 'lib/squared/workspace/project/git.rb', line 1009

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

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



1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
# File 'lib/squared/workspace/project/git.rb', line 1905

def git(flag, opts = [])
  cmd, opts = git_session(flag, opts: opts)
  list = OPT_GIT[:git].fetch(flag, []) + OPT_GIT.fetch(flag, [])
  case flag
  when :add
    list.concat(OPT_GIT[:log][:diff_context])
  when :revert
    list.concat(VAL_GIT[:rebase][:send])
  when :'sparse-checkout'
    cmd << 'set'
  end
  op = OptionPartition.new(opts, list, cmd, project: self, strict: strict?,
                                            no: OPT_GIT[:no][flag], single: /\A\d+\z/,
                                            first: case flag
                                                   when :blame, :revert, :'sparse-checkout' then nil
                                                   else matchpathspec
                                                   end)
  case flag
  when :blame
    raise Errno::ENOENT, 'no file target' unless (n = op.index { |s| basepath(s).file? })

    op.append(basepath(op.remove_at(n)), delim: true)
      .clear
  when :revert
    if op.arg?(*VAL_GIT[:rebase][:send])
      op.clear
    elsif op.empty?
      raise 'no commit target'
    else
      append_commit(*op.extras)
    end
  when :add
    unless op.arg?('pathspec-from-file')
      grep, pathspec = op.partition { |val| OptionPartition.pattern?(val) }
      unless grep.empty? && !pathspec.empty?
        grep.map! { |val| Regexp.new(val[1..-2]) }
        files = status_data
          .map do |a, b|
            next if b.strip.empty? || (!grep.empty? && grep.none? { |pat| pat.match?(a) })

            "#{sub_style(b, color(:red))} #{a}"
          end
          .compact
        unless files.empty?
          files = choice_index('Select files', files, multiple: true, trim: /^\S+\s/,
                                                      accept: [accept_y('Add?')])
        end
        op.swap(pathspec + files)
      end
    end
    return source(git_session('status -s'), banner: false) unless append_pathspec(op.extras)
  when :mv
    refs = projectmap op.extras
    raise 'no source/destination' unless refs.size > 1

    op.merge(refs)
  when :rm, :clean, :'sparse-checkout'
    append_pathspec(op.extras, expect: flag != :clean, resolve: flag != :'sparse-checkout')
  when :grep
    delim = false
    op.each do |val|
      if val == '--'
        delim = true
        op.delim
      elsif delim
        op.add_path(val)
      elsif op.exist?(val, glob: true)
        delim = true
        op.delim
          .add_path(val)
      else
        op.add_quote(val)
      end
    end
  end
  case flag
  when :revert, :mv, :rm
    source(sync: false, stderr: true)
  else
    success?(source, flag == :'sparse-checkout' || (flag == :add && !op.arg?('verbose')))
  end
end

#log!(flag, opts = [], range: [], index: [], grep: []) ⇒ Object



1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
# File 'lib/squared/workspace/project/git.rb', line 1466

def log!(flag, opts = [], range: [], index: [], grep: [])
  cmd, opts = git_session('log', opts: opts)
  op = OptionPartition.new(opts, collect_hash(OPT_GIT[:log]), cmd, project: self, strict: strict?,
                                                                   no: collect_hash(OPT_GIT[:no][:log]),
                                                                   first: matchpathspec)
  case flag
  when :between, :contain
    op.add_quote(range.join(flag == :between ? '..' : '...'))
  when :grep
    op.merge(grep.map { |val| quote_option('grep', val) })
  else
    op.merge(index)
  end
  append_nocolor
  append_pathspec op.extras
  source(exception: false)
end

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



1895
1896
1897
1898
1899
1900
1901
1902
1903
# File 'lib/squared/workspace/project/git.rb', line 1895

def ls_files(flag, opts = [])
  cmd, opts = git_session("ls-files --#{flag}", opts: opts)
  op = OptionPartition.new(opts, OPT_GIT[:ls_files], cmd, project: self, strict: strict?)
  op.splice(path: true, pattern: true)
  out, banner, from = source(io: true)
  print_item banner
  ret = write_lines(out, grep: op.extras)
  list_result(ret, 'files', grep: op.extras, from: from)
end

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



1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
# File 'lib/squared/workspace/project/git.rb', line 1884

def ls_remote(flag, opts = [], remote: nil)
  cmd, opts = git_session('ls-remote --refs', opts: opts)
  cmd << "--#{flag}" unless flag == :remote
  op = OptionPartition.new(opts, OPT_GIT[:ls_remote], cmd, project: self, strict: strict?)
  op.add_quote(remote) if remote
  out, banner, from = source(io: true)
  print_item banner
  ret = write_lines(out, grep: op.extras, prefix: "refs/#{flag}/")
  list_result(ret, flag.to_s, grep: op.extras, from: from)
end

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



1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
# File 'lib/squared/workspace/project/git.rb', line 1634

def merge(flag, opts = [], command: nil, branch: nil)
  cmd, opts = git_session('merge', opts: opts)
  display = false
  case flag
  when :commit, :'no-commit'
    op = OptionPartition.new(opts, OPT_GIT[:merge], cmd, project: self, strict: strict?,
                                                         no: OPT_GIT[:no][:merge])
    op << "--#{flag}"
    op.delim
    if branch
      op << branch
      op.clear(pass: false)
    else
      raise ArgumentError, 'no branch/commit' if op.empty?

      append_commit(*op.extras)
    end
  else
    unless gitpath('MERGE_HEAD').exist?
      puts log_message('no merge in progress', subject: name, hint: command) if stdout?
      exit 1
    end
    return unless VAL_GIT[:merge][:send].include?(command)

    cmd << "--#{command}"
    display = command == 'abort'
  end
  success?(source, display)
end

#populateObject



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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
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
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
902
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
934
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
966
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
999
1000
1001
1002
1003
1004
1005
1006
1007
# File 'lib/squared/workspace/project/git.rb', line 369

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

  namespace name do
    Git.subtasks do |action, flags|
      next if task_pass?(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|
                args = if (remote = args.remote)
                         args.extras
                       else
                         remote = choice_remote
                         args.to_a
                       end
                __send__(action, flag, args, remote: remote)
              end
            else
              format_desc(action, flag, 'opts*', after: ('pattern*' if flag == :all && action == 'pull'))
              task flag do |_, args|
                __send__ action, flag, args.to_a
              end
            end
          when 'submodule'
            break unless @submodule

            case flag
            when :branch
              format_desc action, flag, 'path,name?'
              task flag, [:path, :name] do |_, args|
                path = param_guard(action, flag, args: args, key: :path)
                branch = args.name
                submodule(flag, [branch ? 'b' : 'd'], branch: branch, path: path)
              end
            when :url
              format_desc action, flag, 'path,url,opts*'
              task flag, [:path, :url] do |_, args|
                path = param_guard(action, flag, args: args, key: :path)
                url = param_guard(action, flag, args: args, key: :url)
                submodule(flag, args.extras, path: path, url: url)
              end
            else
              format_desc action, flag, 'opts*,path*'
              task flag do |_, args|
                submodule 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.message)
              end
            else
              format_desc(action, flag, 'pathspec+', before: ('opts*' if flag == :add))
              task flag do |_, args|
                if flag == :fixup
                  ref, squash, pick = choice_commit(reflog: false, accept: [accept_b('Auto squash?')],
                                                    values: 'Pick [amend|reword]')
                  pick &&= case pick.downcase
                           when 'a', 'amend'
                             'amend'
                           when 'r', 'reword'
                             'reword'
                           end
                  if squash
                    found = false
                    git_spawn('log --format=%h', stdout: false).each do |val|
                      if found
                        squash = val.chomp
                        break
                      end
                      found = val.chomp == ref
                    end
                  end
                end
                opts = []
                refs = []
                unless pick == 'reword'
                  if flag == :add
                    opts = param_guard(action, flag, args: args.to_a)
                  elsif (refs = args.to_a).empty?
                    refs = readline('Enter file patterns', force: true).shellsplit
                  end
                end
                commit(flag, opts, refs: refs, ref: ref, squash: squash, pick: pick)
              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 = args.to_a
                if refs.empty?
                  refs = choice_refs('Choose a tag', 'tags', multiple: true, series: true, accept: 'Delete?')
                  remote = choice_remote
                end
                tag(flag, refs: refs, remote: remote)
              end
            when :add, :sign
              format_desc action, flag, 'name,message?,commit?,remote?'
              task flag, [:name, :message, :commit, :remote] do |_, args|
                remote = if (name = args.name)
                           message = args.message
                           commit = commithead args.commit
                           args.remote
                         else
                           commit, name, message = choice_commit(reflog: false, series: true,
                                                                 values: [
                                                                   ['Enter tag name', true],
                                                                   'Enter message'
                                                                 ])
                           choice_remote
                         end
                ret = tag(flag, refs: [name], message: message, commit: commit, remote: remote)
                success?(ret, !remote)
              end
            end
          when 'stash'
            format_desc(action, flag, 'opts*', after: case flag
                                                      when :push then 'pathspec*,:'
                                                      when :branch then 'name,stash/:'
                                                      when :clear, :list, :all then nil
                                                      else 'stash?|:'
                                                      end)
            task flag do |_, args|
              stash flag, args.to_a
            end
          when 'log', 'diff', 'range-diff'
            case flag
            when :view, :between, :contain
              if action == 'log' && flag == :view
                format_desc action, flag, '(^)commit*|:,opts*,pathspec*'
                task flag do |_, args|
                  args = args.to_a
                  if args.first == ':'
                    args.shift
                    index = choice_commit(multiple: true)
                  else
                    index = args.each_with_object([]) do |val, out|
                      if matchhead(val)
                        out << commithead(val)
                      elsif (sha = commithash(val))
                        out << sha
                      elsif val.start_with?('^')
                        out << shell_quote(val)
                      else
                        break out
                      end
                    end
                    args = args.drop(index.size)
                  end
                  log!(flag, args, index: index)
                end
                next
              end
              format_desc action, flag, 'commit1,commit2,opts*,pathspec*'
              task flag, [:commit1, :commit2] do |_, args|
                commit1 = commithead args.commit1
                if commit1
                  range = [commit1, commithead(param_guard(action, flag, args: args, key: :commit2))]
                  opts = args.extras
                else
                  range, opts, refs = choice_commit(multiple: flag == :view ? true : 2,
                                                    values: %w[Options Pathspec])
                  range.reverse!
                  opts = OptionPartition.strip(opts)
                  opts.concat(refs.shellsplit) if refs
                end
                if action == 'log'
                  log!(flag, opts, range: range)
                else
                  diff(flag, opts, range: range, from: action.to_sym)
                end
              end
            when :head
              format_desc action, flag, 'commit*|:,opts*,pathspec*'
              task flag do |_, args|
                args = args.to_a
                if args.first == ':'
                  args.shift
                  index = choice_commit(multiple: true)
                else
                  index = args.each_with_object([]) do |val, out|
                    break out unless (sha = commithead(val) || commithash(val))

                    out << sha
                  end
                  args = args.drop(index.size)
                end
                diff(flag, args, 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,patch?'
              task flag, [:path1, :path2, :patch] 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, args.patch])
              end
            when :grep
              format_desc action, flag, 'pattern+,a/ll-match?,in/vert-grep?,i/E/F/P?,max-count?=i,f/ormat?=s'
              task flag do |_, args|
                grep = args.to_a
                opts = ['oneline']
                while (last = grep.pop)
                  case last
                  when '--'
                    grep << '--' if grep.empty?
                    break
                  when /^a(ll-match)?$/
                    opts << 'all-match'
                  when /^in(vert-grep)?$/
                    opts << 'invert-grep'
                  when 'i', 'E', 'F', 'P'
                    opts << last
                  else
                    if last =~ /^(f(-ormat)?)=(.+)$/
                      opts.shift
                      opts << "format=#{$1}"
                    elsif last =~ /^(max(-count)?)=(\d+)$/
                      opts << "max-count=#{$1}"
                    else
                      grep << last
                      break
                    end
                  end
                end
                param_guard(action, flag, args: grep)
                log!(flag, opts, grep: grep)
              end
            end
          when 'checkout'
            case flag
            when :branch
              format_desc action, flag, 'name,create?=[bB],commit?,d/etach?'
              task flag, [:name, :create, :commit, :detach] do |_, args|
                if (branch = args.name)
                  create = args.create
                  detach = if args.commit == 'd'
                             commit = nil
                             'd'
                           elsif create == 'd'
                             create = nil
                             commit = nil
                             'd'
                           elsif create && create.size > 1
                             commit = commithead create
                             create = nil
                             args.commit
                           else
                             commit = commithead args.commit
                             args.detach
                           end
                  param_guard(action, flag, args: { create: create }, key: :create, pat: /^[Bb]$/) if create
                else
                  branch = choice_refs 'Choose a branch to switch'
                end
                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|
                if (origin = args.origin)
                  branch = args.name
                else
                  origin, branch = choice_refs('Choose a remote', 'remotes', values: 'Enter branch name')
                end
                checkout(flag, branch: branch, origin: origin)
              end
            when :commit
              format_desc action, flag, 'ref,opts*'
              task flag, [:commit] do |_, args|
                commit = commithead args.commit
                args = if commit
                         args.extras
                       else
                         commit, opts = choice_commit(values: 'Options')
                         OptionPartition.strip(opts)
                       end
                checkout(flag, args, commit: commit)
              end
            when :detach
              format_desc action, flag, 'ref?'
              task flag, [:commit] do |_, args|
                commit = commithead args.commit
                unless commit
                  commit, merge = choice_commit(values: 'Merge? [y/N]')
                  merge = merge&.upcase == 'Y'
                end
                checkout(flag, commit: commit, merge: merge)
              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/:'
              task flag, [:name, :ref] do |_, args|
                target = param_guard(action, flag, args: args, key: :name)
                ref = commithead args.ref
                if ref == ':'
                  ref, remote = choice_refs('Choose a remote', 'remotes', accept: [accept_b('Push?')])
                end
                branch(flag, target: target, ref: ref, remote: remote)
              end
            when :track
              format_desc action, flag, '(^~)upstream?,name?'
              task flag, [:upstream, :name] do |_, args|
                if (ref = args.upstream)
                  target = args.name
                  remote = true if ref.delete_prefix!('~')
                else
                  ref, remote, target = choice_refs('Choose a remote', 'remotes', accept: [accept_b('Push?')],
                                                                                  values: 'Enter branch name')
                end
                branch(flag, target: target, ref: ref, remote: remote)
              end
            when :delete
              format_desc action, flag, '[^~]name*,:?'
              task flag do |_, args|
                refs = args.to_a
                if refs.empty? || (i = refs.last == ':')
                  accept = ['Delete?']
                  accept << accept_b('Force?') unless i
                  remote = choice_refs('Choose a branch', i ? 'remotes' : 'heads', multiple: true,
                                                                                   accept: accept)
                  if i
                    refs.pop
                  else
                    refs = remote.first
                    refs.map! { |val| "^#{val}" } if remote[1]
                    remote = nil
                  end
                end
                branch(flag, refs: refs, remote: remote)
              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|
                if (branch = args.branch)
                  oldbranch = args.oldbranch
                else
                  oldbranch, branch = choice_refs("Choose a branch to #{flag}",
                                                  values: [['Enter new branch name', true]])
                end
                branch(flag, refs: [oldbranch, branch])
              end
            end
          when 'switch'
            case flag
            when :create
              format_desc action, flag, '(^)name,ref/:'
              task flag, [:name, :commit] do |_, args|
                branch = param_guard(action, flag, args: args, key: :name)
                commit = commithead args.commit
                commit, track = choice_commit(force: false, values: 'Track? [Y/n]') if commit == ':'
                switch(flag, branch: branch, commit: commit, track: track)
              end
            when :detach
              format_desc action, flag, 'ref?'
              task flag, [:commit] do |_, args|
                commit = commithead(args.commit) || choice_commit(force: false)
                switch(flag, commit: commit)
              end
            when :branch
              format_desc action, flag, 'name/:,opts*'
              task flag, [:name] do |_, args|
                args = if (branch = args.name)
                         branch = nil if branch == ':'
                         args.extras
                       else
                         []
                       end
                switch(flag, args, branch: branch || choice_refs('Choose a branch'))
              end
            end
          when 'reset'
            case flag
            when :commit
              format_desc action, flag, 'ref/:,opts*'
              task flag, [:commit] do |_, args|
                commit = commithead args.commit
                args = if commit && commit != ':'
                         args.extras
                       else
                         commit, mode = choice_commit(values: ['Mode [mixed|soft|hard|N]'])
                         args.extras.concat(case mode&.downcase
                                            when 'h', 'hard' then ['hard']
                                            when 's', 'soft' then ['soft']
                                            when 'n', 'N' then %w[mixed N]
                                            else ['mixed']
                                            end)
                       end
                success?(reset(flag, args, commit: commit))
              end
            when :index, :undo
              format_desc(action, flag, ('opts*,pathspec*' if flag == :index))
              task flag do |_, args|
                reset(flag, flag == :index ? args.to_a : [])
              end
            when :mode
              format_desc action, flag, 'mode,ref/:'
              task flag, [:mode, :ref] do |_, args|
                mode = param_guard(action, flag, args: args, key: :mode)
                ref = commithead args.ref
                reset(flag, mode: mode, ref: ref == ':' ? choice_commit(reflog: false) : ref)
              end
            when :patch
              format_desc action, flag, 'ref/:,pathspec*'
              task flag, [:ref] do |_, args|
                ref = commithead args.ref
                reset(flag, refs: args.extras, ref: !ref || ref == ':' ? choice_commit(reflog: false) : ref)
              end
            end
          when 'show'
            case flag
            when :oneline
              format_desc action, flag, 'opts*,object*'
              task flag do |_, args|
                show flag, args.to_a
              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, 'upstream,branch?,opts*'
              task flag, [:upstream] do |_, args|
                args = if (upstream = args.upstream)
                         args.extras
                       else
                         upstream, opts = choice_refs('Choose upstream branch', values: 'Options')
                         OptionPartition.strip(opts)
                       end
                rebase(flag, args, upstream: upstream)
              end
            when :onto
              format_desc action, flag, 'ref,upstream,branch?'
              task flag, [:commit, :upstream, :branch] do |_, args|
                commit = commithead args.commit
                args = if commit
                         upstream = param_guard(action, flag, args: args, key: :upstream)
                         branch = args.branch
                         []
                       else
                         commit = choice_refs 'Choose "onto" branch'
                         target, opts = choice_commit(reflog: false, multiple: 2, values: 'Options')
                         branch, upstream = target
                         OptionPartition.strip(opts)
                       end
                rebase(flag, args, commit: commit, upstream: upstream, branch: branch)
              end
            when :commit, :'no-commit'
              format_desc action, flag, 'branch|:,ours|theirs?,opts*'
              task flag, [:branch] do |_, args|
                current = `#{git_output('branch --show-current')}`.chomp
                if (branch = args.branch)
                  branch = choice_refs('Choose a branch', accept: "#{action.capitalize}?") if branch == ':'
                  opts = args.extras
                  if has_value!(opts, 'ours')
                    opts << 's=ort' << 'X=ours'
                  elsif has_value!(opts, 'theirs')
                    opts << 's=ort' << 'X=theirs'
                  end
                else
                  branch, opts = choice_refs('Choose a branch', values: 'Options',
                                                                accept: "Merge with #{current}?")
                  opts = OptionPartition.strip(opts)
                end
                raise ArgumentError, 'nothing to merge' if current == branch

                merge(flag, opts, branch: branch)
              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?,size?'
              task flag, [:ref, :size] do |_, args|
                ref = commithead args.ref
                size = args.size
                if !size && ref.to_i.between?(1, 40)
                  size = ref
                  ref = nil
                end
                rev_parse(flag, ref: ref, size: size)
              end
            when :branch
              format_desc action, flag, 'ref?=HEAD|upstream|push'
              task flag, [:ref] do |_, args|
                ret = rev_parse(flag, ref: args.ref || 'upstream')
                puts ret unless ret.empty?
              end
            when :build
              next unless build?

              format_desc action, flag, 'opts*'
              task flag do |_, args|
                revbuild flag, args.to_a
              end
            when :output
              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|
                ls_remote(flag, args.extras, remote: args.remote)
              end
            else
              format_desc(action, flag, 'opts*,pattern*', after: ('pathspec*' if action == 'files'))
              task flag do |_, args|
                __send__(action == 'refs' ? :ls_remote : :ls_files, flag, args.to_a)
              end
            end
          when 'restore'
            case flag
            when :source
              format_desc action, flag, 'ref,opts*,pathspec*'
              task flag, [:commit] do |_, args|
                commit = commithead args.commit
                args = if commit
                         args.extras
                       else
                         commit, opts, files = choice_commit(values: ['Options', ['Pathspec', true]])
                         files &&= files.shellsplit
                         OptionPartition.strip(opts)
                       end
                restore(flag, args, commit: commit, files: files)
              end
            when :staged, :worktree
              format_desc action, flag, 'opts*,pathspec*|:'
              task flag do |_, args|
                args = args.to_a
                if args.empty? || args.last == ':'
                  files = status_data.each_with_object([]) do |row, out|
                    out << row[0] if row[flag == :staged ? 2 : 1].match?(/[AMDRTC]/)
                  end
                  unless files.empty?
                    files = choice_index('Select a file', files, multiple: true, force: false,
                                                                 accept: 'Restore?')
                  end
                  args.pop
                  args, glob = args.partition { |val| val.match?(/^([a-z-]+=|[^*]+$)/) }
                  files.concat(glob)
                  next if args.empty? && files.empty?
                end
                restore(flag, args, files: files)
              end
            end
          when 'sparse-checkout'
            break unless matchfile(gitpath('config.worktree'), /\bsparseCheckout\s+=\s+true/)

            format_desc(action, flag, 'opts*', after: ('dir+' if flag == :add))
            task flag do |_, args|
              sparse_checkout flag, args.to_a
            end
          when 'git'
            before = case flag
                     when :blame
                       'file'
                     when :mv
                       'source+,destination'
                     when :revert
                       'commit+'
                     end
            after = case flag
                    when :add
                      'pathspec*,pattern*'
                    when :grep
                      'tree*,pathspec*'
                    when :'sparse-checkout'
                      'dir+'
                    when :clean, :rm, :status
                      'pathspec*'
                    end
            format_desc(action, flag, 'opts*', before: before, after: after)
            task flag do |_, args|
              __send__(flag == :status ? :status : :git, flag, args.to_a)
            end
          end
        end
      end
    end
  end
end

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



1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
# File 'lib/squared/workspace/project/git.rb', line 1024

def pull(flag = nil, opts = [], sync: invoked_sync?('pull', flag), remote: nil, hint: nil)
  cmd, opts = git_session('pull', opts: opts)
  cmd << '--autostash' if option('autostash')
  if flag == :rebase
    cmd << '--rebase'
  else
    option('rebase', ignore: false) do |val|
      cmd << case val
             when '0', 'false'
               '--no-rebase'
             else
               VAL_GIT[:rebase][:value].include?(val) ? basic_option('rebase', val) : '--rebase'
             end
    end
    case flag
    when :all
      unless git_spawn('status -s -z --untracked-files=all').empty?
        if confirm('Stash local changes?', 'Y')
          git_spawn 'stash push --keep-index --quiet'
        elsif !(force = confirm('Force checkout?', 'N'))
          return
        end
        printsucc
      end
      op = OptionPartition.new(opts, OPT_GIT[:pull], cmd, project: self, strict: strict?,
                                                          no: OPT_GIT[:no][:pull])
      opts -= op.extras
      reg = matchmap op
      session_done op.target
      heads = []
      cur = nil
      foreachref('heads', format: '%(if)%(HEAD)%(then)* %(end)%(refname:short)').each do |line|
        cur ||= line.delete_prefix!('* ')
        heads << line if matchany?(reg, line)
      end
      raise_error 'head not found', hint: 'for-each-ref' unless cur
      opts << 'ff-only' if opts.empty? && option('ff-only', notequals: '0')
      (heads.dup << cur).each_with_index do |branch, i|
        next unless (i < heads.size && cur != branch) || i == heads.size

        git_spawn 'switch --quiet', force && '--force', shell_quote(branch)
        pull(nil, opts, sync: false, hint: branch) if heads.include?(branch)
      end
      return
    when :autostash
      cmd << '--autostash'
    end
  end
  append_pull(opts, OPT_GIT[:pull] + OPT_GIT[:fetch][:pull],
              flag: flag, from: :pull, remote: remote, no: OPT_GIT[:no][:pull] + OPT_GIT[:no][:fetch][:pull])
  if sync
    source(hint: hint)
  else
    source(sync: false, sub: if stdout?
                               [
                                 opt_style(color(:red), /^(.+)(\|\s+\d+\s+)([^-]*)(-+)(.*)$/, 4),
                                 opt_style(color(:green), /^(.+)(\|\s+\d+\s+)(\++)(.*)$/, 3)
                               ]
                             end, hint: hint, **threadargs)
  end
end

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



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

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
    return unless upstream

    op = OptionPartition.new(opts, OPT_GIT[:rebase], cmd, project: self, strict: strict?,
                                                          no: OPT_GIT[:no][:rebase])
    op << upstream
    append_head op.shift&.delete_prefix(':')
    op.clear(pass: false)
  when :onto
    return unless upstream

    cmd << '--interactive' if option('interactive', 'i')
    cmd << shell_option('onto', commit) if commit
    cmd << upstream
    append_head branch
  else
    unless gitpath('REBASE_HEAD').exist?
      puts log_message('no rebase in progress', subject: name, hint: command) if stdout?
      exit 1
    end
    return unless VAL_GIT[:rebase][:send].include?(command)

    cmd << "--#{command}"
  end
  source(sync: sync)
end

#refObject



365
366
367
# File 'lib/squared/workspace/project/git.rb', line 365

def ref
  Git.ref
end

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



1366
1367
1368
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
1395
1396
1397
1398
1399
# File 'lib/squared/workspace/project/git.rb', line 1366

def reset(flag, opts = [], refs: nil, ref: nil, mode: nil, commit: nil)
  cmd, opts = git_session('reset', opts: opts)
  case flag
  when :commit, :index
    op = OptionPartition.new(opts, OPT_GIT[:reset] + VAL_GIT[:reset] + OPT_GIT[:log][:diff_context], cmd,
                             project: self, strict: strict?, no: OPT_GIT[:no][:reset],
                             first: (matchpathspec if flag == :index))
    if flag == :commit
      op.append(commit)
        .clear(pass: false)
      ref = false
    else
      refs = op.extras
    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'
  when :undo
    cmd << '--hard HEAD@{1}'
    ref = false
  end
  unless ref == false
    append_commit(ref, head: true)
    append_pathspec(refs, pass: false) if refs
  end
  source
end

#restore(flag, opts = [], commit: nil, files: nil) ⇒ Object



1804
1805
1806
1807
1808
1809
1810
1811
1812
# File 'lib/squared/workspace/project/git.rb', line 1804

def restore(flag, opts = [], commit: nil, files: nil)
  cmd, opts = git_session('restore', shell_option(flag, commit, escape: false, force: false), opts: opts)
  op = OptionPartition.new(opts,
                           OPT_GIT[:restore] + OPT_GIT[:log][:diff_context],
                           cmd,
                           project: self, strict: strict?, no: OPT_GIT[:no][:restore], first: matchpathspec)
  append_pathspec(op.extras + (files || []), pass: false)
  source(sync: false, stderr: true)
end

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



1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
# File 'lib/squared/workspace/project/git.rb', line 1844

def rev_parse(flag, opts = [], ref: nil, size: nil)
  cmd, opts = git_session('rev-parse', opts: opts)
  case flag
  when :commit
    cmd << (size.to_i.zero? ? '--verify' : basic_option('short', [size.to_i, 5].max))
    append_commit(ref, head: true)
  when :branch
    cmd << '--abbrev-ref' << '--symbolic-full-name' << shell_quote(case ref
                                                                   when 'upstream', 'push'
                                                                     "@{#{ref}}"
                                                                   else
                                                                     ref
                                                                   end)
    return git_spawn(cmd, exception: false).chomp
  when :output
    if opts.delete('sq-quote')
      cmd << '--sq-quote'
      args = true
    end
    OptionPartition.new(opts, OPT_GIT[:rev_parse], cmd,
                        project: self, strict: strict?, no: OPT_GIT[:no][:rev_parse], args: args)
                   .append(escape: args)
  end
  source(banner: verbose?)
end

#revbuild(flag = nil, opts = [], **kwargs) ⇒ Object



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
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
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
# File 'lib/squared/workspace/project/git.rb', line 1292

def revbuild(flag = nil, opts = [], **kwargs)
  kw = lambda do
    {
      include: relativepath(*Array(kwargs[:include]), all: true),
      exclude: relativepath(*Array(kwargs[:exclude]), all: true),
      before: kwargs[:before],
      after: kwargs[:after],
      pass: kwargs.fetch(:pass, true)
    }
  end
  unless workspace.closed
    if @revbuild
      kw.call.each do |key, val|
        case @revbuild[key]
        when Array
          @revbuild[key].concat(val)
        when Hash
          @revbuild[key].update(val)
        else
          @revbuild[key] = val
        end
      end
    else
      @revbuild = kw.call
    end
    return
  end
  sha = git_spawn('rev-parse --verify HEAD').chomp
  return if sha.empty?

  sync = kwargs.fetch(:sync) { invoked_sync?('revbuild', flag) }
  kwargs = kwargs.key?(:include) || kwargs.key?(:exclude) ? kw.call : @revbuild || { pass: true }
  case flag
  when :build
    op = OptionPartition.new(opts, VAL_GIT[:revbuild].map { |key| "#{key}=b?" }, project: self, strict: strict?)
    op.clear(append: true)
    args = op.to_a
  else
    args = parse_env('GIT_OPTIONS')
           .grep(/\A--#{Regexp.union(*VAL_GIT[:revbuild])}/)
           .concat(VAL_GIT[:revbuild].map { |key| option(key, prefix: 'git') { |val| basic_option(key, val) } })
           .compact
    OptionPartition.uniq!(args)
  end
  run_p(*Array(kwargs[:before]), sync: sync, from: :revbuild) if kwargs[:before]
  force = if (force = env('REVBUILD_FORCE', strict: true))
            force != '0' && force != 'false'
          elsif (force = ENV['GIT_FORCE'] || ENV['REVBUILD_FORCE'])
            split_escape(force).any? { |val| val == '1' || val == 'true' || val == name }
          end
  if !force && (cur = workspace.rev_entry(name)) && cur['revision'] == sha
    files = status_digest(*args, **kwargs)
    if cur['files'].size == files.size && cur['files'].find { |key, val| files[key] != val }.nil?
      workspace.rev_timeutc(name, 'build') unless (since = workspace.rev_timesince(name, 'build'))
      puts log_message(['revbuild', 'no changes'], subject: name, hint: ("#{since} ago" if since)) if stdout?
      return
    end
  end
  start = time_epoch
  ret = build(*@output, sync: sync, from: symjoin('git', 'revbuild'))
rescue => e
  print_error(e, pass: true)
else
  if ret == false && !kwargs[:pass]
    print_status('revbuild', subject: name, start: start, loglevel: Logger::WARN, from: :failed)
    workspace.rev_timeutc name, 'build'
  else
    run_p(*Array(kwargs[:after]), sync: sync, from: :revbuild) if kwargs[:after] && ret != false
    print_status('revbuild', subject: name, start: start)
    workspace.rev_write(name, { 'revision' => sha, 'files' => status_digest(*args, **kwargs) },
                        sync: sync, utc: 'build')
  end
end

#revbuild?Boolean

Returns:

  • (Boolean)


1992
1993
1994
# File 'lib/squared/workspace/project/git.rb', line 1992

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

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



1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
# File 'lib/squared/workspace/project/git.rb', line 1814

def show(flag, opts = [], format: nil, files: [])
  cmd, opts = git_session('show', opts: opts)
  case flag
  when :textconv
    cmd << '--textconv'
    append_value(files.flat_map { |val| Dir[val] }
                      .select { |val| projectpath?(val) }
                      .map { |val| shell_quote("HEAD:#{val}") })
    source(banner: false)
    return
  when :oneline
    format = flag.to_s
  end
  case format
  when 'oneline', 'short', 'medium', 'full', 'fuller', 'reference', 'email', 'raw'
    cmd << basic_option('format', format)
  when /^t?format:|%/
    cmd << quote_option('pretty', format)
  else
    opts << format if format
  end
  list = OPT_GIT[:show] + OPT_GIT[:diff][:show] + OPT_GIT[:log][:diff] + OPT_GIT[:log][:diff_context]
  op = OptionPartition.new(opts, list, cmd,
                           project: self,
                           strict: strict?,
                           no: OPT_GIT[:no][:show] + collect_hash(OPT_GIT[:no][:log], pass: [:base]))
  op.append(delim: true)
  source(exception: false, banner: flag != :oneline)
end

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



1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
# File 'lib/squared/workspace/project/git.rb', line 1870

def sparse_checkout(flag, opts = [])
  cmd, opts = git_session('sparse-checkout', flag, opts: opts)
  op = OptionPartition.new(opts, OPT_GIT[:sparse_checkout].fetch(flag, []), cmd,
                           project: self, strict: strict?, no: OPT_GIT[:no][:sparse_checkout][flag])
  case flag
  when :add
    append_pathspec(op.detach, expect: true, resolve: false, pass: false)
  when :clean
    op << '--dry-run' unless op.arg?('n', 'f', 'force')
  end
  op.clear
  success?(source, flag != :list)
end

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



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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
# File 'lib/squared/workspace/project/git.rb', line 1177

def stash(flag = nil, opts = [], sync: invoked_sync?('stash', flag))
  if flag
    case flag
    when :all
      opts << 'include-untracked'
      flag = :push
    when :staged
      opts << 'staged'
      flag = :push
    when :worktree
      opts << 'keep-index'
      flag = :push
    end
    unless (file = gitpath('logs/refs/stash')).exist? || flag == :push
      puts log_message('no stashes were found', subject: name, hint: flag) if stdout?
      exit 1
    end
    cmd, opts = git_session('stash', flag, opts: opts)
    list = OPT_GIT[:stash][:common] + OPT_GIT[:stash].fetch(flag, [])
    if flag == :list
      list.concat(collect_hash(OPT_GIT[:log]))
      no = collect_hash OPT_GIT[:no][:log]
    end
    op = OptionPartition.new(opts, list, cmd, project: self, strict: strict?, no: no,
                                              first: (matchpathspec if flag == :push))
    case flag
    when :push
      op.readline('Enter message', option: 'message', quote: true) if op.remove(':')
      append_pathspec op.extras
    when :pop, :apply, :drop, :branch
      if op.remove(':')
        if flag == :branch
          if op.empty?
            values = [['Branch name', true]]
          else
            op.add_first(prefix: ':')
          end
        end
        out = choice_index('Choose a stash', git_spawn('stash list', stdout: false),
                           values: values, column: /^[^@]+@\{(\d+)\}/)
        if values
          op.merge(out.reverse)
        else
          op << out
        end
      elsif !op.empty?
        op.add_first(prefix: ':')
      elsif flag == :branch
        raise ArgumentError, 'no branch name'
      end
      op.clear
    when :clear
      n = sub_style file.read.lines.size, theme[:inline]
      s = sub_style name, theme[:active]
      source(stdout: true) if confirm("Remove #{n} stash entries from #{s}?", 'N')
      return
    when :list
      op.clear
      out, banner, from = source(io: true)
      print_item banner
      list_result(write_lines(out), 'objects', from: from)
      return
    end
  else
    git_session('stash', 'push', opts: opts)
    append_option(*OptionPartition.select(OPT_GIT[:stash][:push], no: false), no: true, ignore: false)
    append_message
  end
  if sync
    source(banner: !quiet?)
  else
    source(sync: false, banner: !quiet?, **threadargs)
  end
end

#status(flag = nil, opts = []) ⇒ Object



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

def status(flag = nil, opts = [])
  cmd, opts = git_session('status', opts: opts)
  if flag
    op = OptionPartition.new(opts, OPT_GIT[:status], cmd, project: self, strict: strict?,
                                                          no: OPT_GIT[:no][:status])
    append_pathspec op.extras
  else
    cmd << (option('long') ? '--long' : '--short')
    cmd << '--branch' if option('branch')
    option('ignore-submodules', ignore: false) do |val|
      cmd << basic_option('ignore-submodules', case val
                                               when 'none', '0', 'false'
                                                 'none'
                                               when 'untracked', 'dirty'
                                                 val
                                               else
                                                 'all'
                                               end)
    end
    append_pathspec
  end
  if stdout?
    r = color(:red)
    g = color(:green)
    sub = if session_arg?('short')
            [
              opt_style(r, /^(.)([A-Z?!])(.+)$/, 2),
              opt_style(g, /^([A-Z?!])(.+)$/),
              opt_style(r, /^(\?\?)(.+)$/),
              opt_style([nil, g, nil, r], /^(## )((?~\.{3}))(\.{3})(.+)$/, -1)
            ]
          else
            opt_style(r, /^(\t+)([a-z]+: +.+)$/, 2)
          end
  end
  out, banner, from = source(io: true)
  ret = write_lines(out, banner: banner, sub: sub)
  list_result(ret, 'files', action: 'modified', from: from)
end

#submodule(flag, opts = [], branch: nil, path: nil, url: nil) ⇒ Object



1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
# File 'lib/squared/workspace/project/git.rb', line 1789

def submodule(flag, opts = [], branch: nil, path: nil, url: nil)
  cmd, opts = git_session('submodule', opts: opts)
  op = OptionPartition.new(opts, OPT_GIT[:submodule].fetch(flag, []), cmd, project: self, strict: strict?)
  case flag
  when :branch, :url
    op.adjoin("set-#{flag}")
    op.add_quote(branch, '--', path, url)
  else
    op.adjoin(flag)
    op << '--recursive' if option('r', 'recursive')
    op.splice(path: true)
  end
  success?(source, flag == :branch)
end

#switch(flag, opts = [], branch: nil, commit: nil, track: nil) ⇒ Object



1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
# File 'lib/squared/workspace/project/git.rb', line 1763

def switch(flag, opts = [], branch: nil, commit: nil, track: nil)
  cmd, opts = git_session('switch', opts: opts)
  cmd << '--force' if option('f', 'force')
  if flag == :branch
    OptionPartition.new(opts, OPT_GIT[:switch], cmd, project: self, strict: strict?, no: OPT_GIT[:no][:switch])
                   .add_quote(branch)
  else
    case flag
    when :create
      cmd << quote_option(branch.delete_prefix!('^') ? 'C' : 'c', branch)
      cmd << case (track ||= option('track', ignore: false))&.downcase
             when 'n', '0', 'false'
               '--no-track'
             when 'y', '1', 'true'
               '--track'
             when 'direct', 'inherit'
               basic_option 'track', track
             end
    when :detach
      cmd << '--detach'
    end
    append_head commit
  end
  source
end

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



1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
# File 'lib/squared/workspace/project/git.rb', line 1430

def tag(flag, opts = [], refs: [], message: nil, commit: nil, remote: nil)
  cmd, opts = git_session('tag', opts: opts)
  case flag
  when :add, :sign
    if flag == :sign || option('sign')
      cmd << '--sign'
    elsif !session_arg?('s', 'sign', 'u', 'local-user')
      cmd << '--annotate'
    end
    cmd << '--force' if option('f', 'force')
    option('trailer') { |val| cmd << quote_option('trailer', val) }
    if !commit && message && (sha = commithash(message))
      commit = sha
      message = nil
    end
    append_message message
    append_value refs
    append_head commit
  when :delete
    cmd << '--delete'
    append_value refs
  else
    op = OptionPartition.new(opts, OPT_GIT[:tag], cmd << '--list', project: self, strict: strict?,
                                                                   no: OPT_GIT[:no][:tag])
    out, banner, from = source(io: true)
    print_item banner
    ret = write_lines(out, grep: op.extras)
    list_result(ret, 'tags', grep: op.extras, from: from)
    return
  end
  if (ret = source) && (remote ||= option('remote'))
    git_spawn('push', ('-d' if flag == :delete), remote, *refs.quote!)
  end
  ret
end