Class: Squared::Workspace::Project::Ruby

Inherits:
Git
  • Object
show all
Defined in:
lib/squared/workspace/project/ruby.rb

Constant Summary

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary collapse

Attributes inherited from Base

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Git

#autostash, #branch, #checkout, #clean, #clone, #clone?, #commit, #diff, #enabled?, #fetch, #generate, #git, #log!, #ls_files, #ls_remote, #merge, #pull, #rebase, #reset, #restore, #rev_parse, #revbuild, #revbuild?, #show, #sparse_checkout, #stash, #status, #submodule, #switch, #tag

Methods inherited from Base

#<=>, #==, #add, aliasargs, #allref, #archive, #archive?, #as, #asdf, #basepath, #basepath!, batchargs, #build, #build?, #chain, #clean, #clean?, #dependname, #dependtype, #dev?, #doc, #doc?, #empty?, #enabled?, #error, #event, #exclude?, #exist?, #first, #generate, #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

#initialize(autodetect: false, steep: 'Steepfile', rubocop: '.rubocop.yml', asdf: 'ruby', **kwargs) ⇒ Ruby

Returns a new instance of Ruby.



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/squared/workspace/project/ruby.rb', line 215

def initialize(*, autodetect: false, steep: 'Steepfile', rubocop: '.rubocop.yml', asdf: 'ruby', **kwargs)
  super
  if @pass.include?(Ruby.ref)
    initialize_ref Ruby.ref
    initialize_logger kwargs[:log]
  else
    initialize_build(Ruby.ref, **kwargs)
    initialize_env(**kwargs)
  end
  dependfile_set GEMFILE
  serve_set kwargs[:serve]
  gemfile_set kwargs[:gemspec]
  self.autodetect = autodetect
  @steepfile = basepath! steep if steep
  @rubocopfile = Pathname.new(rubocop).realpath rescue basepath!(Dir.home, '.rubocop.yml') if rubocop
  @rubygems = kwargs.fetch(:rubygems, 0)
  return unless rakefile && @output[0].nil? && @copy.nil? && !version && !self.autodetect

  begin
    File.foreach(rakefile) do |line|
      next unless line.match?(%r{\brequire\s+(["'])bundler/gem_tasks\1})

      cmd = bundle_output('exec rake').to_s
      @output[0] = "#{cmd} build"
      @copy = "#{cmd} install"
      @clean = "#{cmd} clean" if @clean.nil?
      break
    end
  rescue => e
    log.error e
  end
end

Instance Attribute Details

#autodetectObject

Returns the value of attribute autodetect.



213
214
215
# File 'lib/squared/workspace/project/ruby.rb', line 213

def autodetect
  @autodetect
end

#gemdirObject

Returns the value of attribute gemdir.



212
213
214
# File 'lib/squared/workspace/project/ruby.rb', line 212

def gemdir
  @gemdir
end

Class Method Details

.bannerargsObject



188
189
190
# File 'lib/squared/workspace/project/ruby.rb', line 188

def bannerargs
  %i[version dependfile gemname gemdir].freeze
end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


192
193
194
195
196
# File 'lib/squared/workspace/project/ruby.rb', line 192

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

  DIR_RUBY.any? { |file| val.join(file).exist? }
end

.tasksObject



184
185
186
# File 'lib/squared/workspace/project/ruby.rb', line 184

def tasks
  [:outdated].freeze
end

Instance Method Details

#bundle(flag, *args, sync: true, banner: verbose?, , with: nil, pass: nil, **kwargs) ⇒ Object



1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
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
# File 'lib/squared/workspace/project/ruby.rb', line 1390

def bundle(flag, *args, sync: true, banner: verbose?, with: nil, pass: nil, **kwargs)
  flag = flag.to_sym
  if pass.nil?
    pass = case flag
           when :add, :outdated, :update
             PASS_RUBY[:bundle][:update]
           else
             PASS_RUBY[:bundle].fetch(flag, [])
           end
  end
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  invalid = ->(a) { raise_error ArgumentError, "unrecognized args: #{a.join(', ')}", hint: flag }
  cmd = bundle_session flag
  case flag
  when :cache, :check, :clean, :init, :install, :lock, :pack, :package, :platform
    pre = true
    opts.concat(args)
  when :config
    if args.empty?
      pre = true
    else
      case (pre = args.shift)
      when 'list', 'get', 'set', 'unset'
        cmd << pre
      else
        args.unshift(pre)
      end
      opts.concat(args)
    end
  when :doctor
    case (pre = (val = args.shift) || opts.shift)
    when 'diagnose', 'ssl'
      cmd << pre
    else
      if val
        args.unshift(val)
      elsif pre
        opts.unshift(pre)
      end
      pre = true
    end
    opts.concat(args)
  when :plugin
    case (plu = args.shift)
    when 'install', 'uninstall', 'help', 'list'
      cmd << plu
    else
      invalid.call(plu)
    end
  end
  op = OptionPartition.new(opts, bundleopts(if pre == 'ssl'
                                              :doctor_ssl
                                            elsif plu
                                              plu == 'install' ? :plugin : symjoin('plugin', plu, char: '_')
                                            else
                                              flag
                                            end),
                           cmd,
                           project: self, strict: strict?, no: OPT_BUNDLE[:no][flag],
                           args: flag == :exec || flag == :config)
  op.concat(args) unless pre
  output = false
  case flag
  when :config
    if pre == 'list'
      op.clear
    elsif !op.empty?
      a = op.dup
      b, c = op.slice!(0, 2)
      d = op.arg?('global', 'local')
      getname = -> { b ? op << b : op.readline('Enter name') }
      case pre
      when 'get'
        getname.call
      when 'set'
        if d
          op << b
          b = c
          c = op.shift
        end
        getname.call
        c ? op << c : op.readline('Enter value', quote: true)
        output = true
      when 'unset'
        if d
          op << b
          b = c
        end
        getname.call
        output = true
      else
        if c && !op.arg?('parseable', 'no-parseable')
          op.adjoin('set') << b
          op.add_quote(c)
          output = true
          exit 1 unless confirm_basic('Confirm?', op, 'Y')
        elsif b
          op.adjoin('get') << b
          op.unshift(c) if c
        else
          invalid.call(a)
        end
      end
      op.clear
    else
      output = op.readline('Enter arguments', 'list')
                 .start_with?('set', 'unset')
    end
  when :plugin
    case plu
    when 'install', 'uninstall', 'help'
      op.append
    else
      op.clear
    end
  when :exec
    if op.empty? || (op.remove(':') && op.append(quote: false))
      op.readline('Enter arguments')
    else
      op.append(quote: false)
    end
  when :binstubs, :outdated, :remove, :update
    op.append(filter: GEMNAME)
      .clear(errors: true)
  when :add, :open, :show
    op.add_first(expect: 'missing gem name')
      .clear
  when :console, :gem
    op.add_first
      .clear
  else
    op.clear
  end
  print_run(op, banner, **kwargs)
  ret = run(sync: sync, banner: banner, exception: kwargs.fetch(:exception, exception?),
            from: symjoin('bundle', flag))
  success?(ret, banner, output)
end

#copy(from: gemlib, into: gemdir, override: false, **kwargs) ⇒ Object



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

def copy(from: gemlib, into: gemdir, override: false, **kwargs)
  return if @copy == false

  glob = kwargs[:include]
  pass = kwargs[:exclude]
  if @copy && !override
    return super unless @copy.is_a?(Hash)

    from = @copy[:from] if @copy.key?(:from)
    into = @copy[:into] if @copy.key?(:into)
    glob = @copy[:include] if @copy.key?(:include)
    pass = @copy[:exclude] if @copy.key?(:exclude)
  end
  return unless into

  on :first, :copy
  dest = Pathname.new(into).realpath
  print_item unless @output[0] || task_invoked?(/^copy(?::#{Ruby.ref}|$)/)
  glob = Array(glob || '**/*')
  Array(from).each_with_index do |val, i|
    a = basepath val
    b = dest + val
    c = glob[i] || glob.first
    log.info "cp #{a + c} #{b}"
    copy_dir(a, b, c, pass: pass, verbose: !silent?)
  rescue => e
    on_error e
  end
  on :last, :copy
end

#copy?Boolean

Returns:

  • (Boolean)


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
1762
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
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
# File 'lib/squared/workspace/project/ruby.rb', line 1726

def copy?
  return true if @copy.is_a?(Hash) ? copy[:into] : super
  return gemdir? if gemdir
  return false unless autodetect

  set = lambda do |val, path|
    base = Pathname.new(path.strip)
    dir = base + gempath
    return false unless dir.writable? && base.join(gempath(val, 'specifications')).exist?

    log.warn "using version #{val}".subhint("given #{version}") if version && version != val
    self.version = val
    self.gemdir = dir
  end
  if version
    begin
      case autodetect
      when 'rvm'
        pwd_set { `rvm info homes` }[/^\s+gem:\s+"(.+)"$/, 1]
      when 'rbenv'
        if pwd_set { `rbenv which ruby` } =~ %r{^(.+[\\/]versions[\\/](\d\.\d)\.[^\\/]+)[\\/]bin[\\/]ruby$}
          File.join($1, 'lib/ruby/gems', "#{$2}.0")
        end
      when 'asdf', 'mise'
        pwd_set do
          val = `#{autodetect} where ruby`.chomp
          File.join(val, 'lib/ruby/gems', "#{$1}.0") if val =~ /(\d\.\d)\.[^.]+$/
        end
      when /bundler?/
        pwd_set { `bundle env` }[/^\s+Gem Path\s+(.+)$/, 1].split(File::PATH_SEPARATOR).find do |val|
          Dir.exist?(File.join(val, 'gems'))
        end
      else
        ENV['GEM_HOME'] || ENV['GEM_ROOT']
      end
      .tap do |val|
        return true if val && set.call(version, val)
      end
    rescue => e
      log.debug e
    end
    pwd_set(pass: !gempwd.nil?) do
      out = `#{gem_output(gempwd, 'list --local -d', gemname)}`
      next unless out =~ /#{Regexp.escape(gemname)}\s+\((.+)\)$/

      split_escape($1)
        .unshift(version)
        .uniq
        .each do |val|
          next unless out =~ /(?:\(#{Regexp.escape(val)}[^)]*\)|Installed at):\s+(.+)$/

          return gemdir? if set.call(val, $1)
        end
    end
    self.gemdir = Pathname.new(Gem.dir) + gempath
  else
    parse = lambda do |path|
      return false unless path

      ver = path[Regexp.new(['', 'gems', "#{gemname}-([^#{File::SEPARATOR}]+)", ''].join(File::SEPARATOR)), 1]
      if ver && (val = path[/\A(.+)#{Regexp.escape(gempath(ver))}/, 1])
        set.call(ver, val)
      end
    end
    if semgte?('2.6')
      target = RUBY_VERSION.start_with?('2.6') ? RubyVM : $LOAD_PATH
      parse.call(target.resolve_feature_path(gemname)&.last)
    end
    unless gemdir || pwd_set { parse.call(`#{bundle_output('show', gemname)}`) }
      raise Errno::ENOENT, 'gems home'
    end
  end
rescue => e
  log.error e
  @gemdir = nil
  self.version = nil
  self.autodetect = false
else
  gemdir?
end

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



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

def depend(*, sync: invoked_sync?('depend'), **)
  if @depend
    super
  elsif outdated?
    workspace.rev_clear(name, sync: sync)
    if env('UPDATE') || env('RUBY_UPDATE')
      cmd = bundle_session 'update --all'
      option('version') do |val|
        case val
        when 'patch', 'minor', 'major'
          cmd << "--#{val}"
        end
      end
      cmd << '--strict' if option('strict')
      cmd << '--conservative' if option('conservative')
    else
      cmd = bundle_session 'install'
      option('binstubs') do |val|
        next if val == '0' || val == 'false'

        run(bundle_output('binstubs --all', case val
                                            when '1', 'true'
                                              nil
                                            else
                                              if val.start_with?('~')
                                                val = File.join(Dir.home, val == '~' ? '.bundle' : val[1..-1])
                                                if prod?
                                                  config_set('binstubs', shell_quote(val), global: true)
                                                  val = nil
                                                end
                                              else
                                                val = basepath val
                                              end
                                              quote_option('path', val) if val
                                            end), exception: false, banner: false, series: true)
      end
    end
    if prod? && !config_get('without')
      if semgte?('3')
        config_set 'without', 'development'
      else
        cmd << '--without=development'
      end
    end
    option('jobs', pat: /^\d+$/) { |val| cmd << "-j#{val}" }
    run(sync: sync, from: :depend)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


1722
1723
1724
# File 'lib/squared/workspace/project/ruby.rb', line 1722

def depend?
  @depend != false && (!@depend.nil? || outdated?)
end

#gem(flag, *args, sync: true, banner: verbose?, , with: nil, pass: nil, **kwargs) ⇒ Object



1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
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
1233
1234
1235
1236
1237
1238
1239
1240
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
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
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
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
# File 'lib/squared/workspace/project/ruby.rb', line 1030

def gem(flag, *args, sync: true, banner: verbose?, with: nil, pass: nil, **kwargs)
  flag = flag.to_sym
  if pass.nil?
    pass = case flag
           when :install, :update
             PASS_RUBY[:gem][:install]
           when :dependency, :fetch, :info, :list, :outdated, :search, :specification
             PASS_RUBY[:gem][:dependency]
           else
             PASS_RUBY[:gem].fetch(flag, [])
           end
  end
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  case flag
  when :build, :cert, :generate_index, :mirror, :outdated, :push, :server, :signin, :signout, :sources, :stale
    opts.concat(args)
  end
  op = OptionPartition.new(opts, gemopts(flag), gem_session(flag),
                           project: self, strict: strict?, no: OPT_GEM[:no][flag == :update ? :install : flag])
  from = symjoin 'gem', flag
  if flag == :outdated
    op.adjoin(gempwd, start: 0) if gempwd
    op.clear
    cmd = session_done op.target
    log.info cmd
    on :first, from
    banner = format_banner cmd
    print_item banner if sync
    major = [0, 0, 0]
    buffer = []
    filter = kwargs.fetch(:filter, {})
    semver = filter[:semver]
    update = if sync && filter[:select]
               semver ||= 'major'
               items = []
               nil
             elsif sync && filter[:interactive]
               semver ||= 'major'
               ia = true
               []
             elsif filter[:update]
               semver ||= 'minor'
               []
             end
    out = ->(val) { sync ? puts(val) : buffer << val }
    pwd_set(op.target, from: from, pass: !gempwd.nil?) do
      rows = [[%w[Gem Current Latest], nil]]
      IO.popen(cmd).each do |line|
        if line =~ /^(\S+) \((\S+) < ([^)]+)\)$/
          cur = semscan $2
          lat = semscan $3
          rows << [$~.to_a.drop(1), semtype(cur, lat)]
        else
          out.call(line)
        end
      end
      if rows.size > 1
        pad = [rows.size.to_s.size.succ, 3].max
        d = 0
        e = 0
        f = 0
        j = 0
        queue = nil
        rows.each do |row|
          a, b, c = row.first
          d = a.size if a.size > d
          e = b.size if b.size > e
          f = c.size if c.size > f
        end
        rows.each_with_index do |row, i|
          next if i == 0 && stdin?

          a, b, c = row.first
          type = row.last
          if i == 0
            line = '%-*s %-*s    %*s  %*s' % [pad, ' #', d, a, e, b, f, c]
            s = ARG[:BORDER][1] * line.size
            queue = if stdin?
                      [line, s]
                    else
                      2.times do
                        sub_style!(line, **opt_style(theme[:header], /^(.+)(?<!\dm)(#{a}|#{c})(.*)$/, 2))
                      end
                      [line, sub_style(s, borderstyle)]
                    end
          else
            g = a.ljust(d)
            pat = [/^([^.]+\.)([^.]+\..+)$/, /^([^.]+\.[^.]+\.)(.+)$/]
            pre = b.start_with?('0.')
            latest = [theme[:latest]]
            case type
            when 1
              case semver
              when 'major'
                update&.push(a)
              when 'minor', 'patch'
                next
              end
              unless stdin?
                sub_style! g, theme[:major]
                styles = %i[green bold]
                pat = pre ? pat.first : nil
                latest << :bold
              end
              major[0] += 1
            when 2
              case semver
              when 'major', 'minor'
                update&.push(a)
              when 'patch'
                next
              end
              unless stdin?
                sub_style! g, theme[:active]
                styles = %i[green]
                pat = pre ? pat.last : pat.first
              end
              major[1] += 1
            else
              case semver
              when 'major', 'minor', 'patch'
                update&.push(a)
              end
              unless stdin?
                styles = %i[yellow]
                pat = pat.last
              end
              major[2] += 1
            end
            b = b.rjust(e)
            h = c.rjust(f)
            unless stdin?
              sub_style!(b, **opt_style(colormap(styles), pat, 2))
              sub_style!(h, **opt_style(latest.flatten.compact, pat, 2))
            end
            j += 1
            if queue
              out.call(queue)
              queue = nil
            end
            s = '%s    %s  %s' % [g, b, h]
            items&.push([s, a])
            s = '%*s %s' % [pad, "#{j}.", s]
            if ia
              unless confirm_semver(s, type)
                update.delete(a)
                next
              end
            elsif !items
              out.call(s)
            end
          end
        end
      end
    end
    unless sync
      print_item banner
      puts buffer
    end
    if major.sum == 0
      puts 'No updates were found'
    else
      if items
        update = choice('Select a package', items.map(&:first),
                        multiple: true, force: false, index: true, border: true).map { |n| items[n.pred].last }
      end
      unless Array(update).empty?
        opts = ['f']
        option('document', prefix: 'gem', ignore: false) do |val|
          opts << case val
                  when '0', 'false'
                    'no-document'
                  else
                    "document=#{val}"
                  end
        end
        option('user-install', prefix: 'gem', ignore: false) do |val|
          opts << case val
                  when '0', 'false'
                    'no-user-install'
                  else
                    'user-install'
                  end
        end
        if filter[:dryrun]
          print_run gem_output('update -f', *update.quote!(escape: true)), false
        else
          gem(:update, *update, opts: opts)
        end
      end
      print_status(*major, from: :outdated)
    end
    on :last, from
    return
  end
  case flag
  when :check, :cleanup, :contents, :fetch, :info, :lock, :open, :owner, :pristine, :rdoc, :rebuild, :uninstall,
       :unpack, :update, :yank
    gems = true
    op.concat(args)
  when :dependency, :environment, :list, :search, :specification, :which
    op.concat(args)
  end
  ia = op.remove(':')
  op.each do |opt|
    if gems && !opt.start_with?('-') && !opt.match?(GEMNAME)
      op.errors << opt
    else
      op.found << opt
    end
  end
  op.swap do |a, b|
    return -1 if a.start_with?('-')

    b.start_with?('-') ? 1 : 0
  end
  case flag
  when :build
    if op.empty?
      raise_error Errno::ENOENT, 'gemspec', hint: project unless gemfile
      op.add_path(gemfile)
    else
      op.add_first(path: true)
        .clear(pass: false)
    end
  when :push
    if op.empty? || (n = op.index(':'))
      file = basepath(if !n && (spec = gemspec)
                        "#{spec.name}-#{spec.version}.gem"
                      else
                        choice_index 'Select a file', Dir.glob('*.gem', base: path)
                      end)
    else
      file = basepath(op.shift.yield_self { |val| val.include?('.') ? val : "#{val}.gem" })
      raise_error Errno::ENOENT, file, hint: flag unless file.exist?
      raise_error ArgumentError, "unrecognized args: #{op.join(', ')}", hint: flag unless op.empty?
    end
    op.add_path(file)
    return run(from: from, interactive: ['Push', 'N', gemname]) unless with || !banner
  when :exec
    min = if op.arg?('g', 'gem')
            1
          elsif !op.empty?
            op.add_first
            0
          elsif args.empty?
            op << basic_option('gem', gemname)
            1
          else
            0
          end
    op.concat(args)
    command_args(op.extras, min: min, force: min == 1 && op.empty?)
    op.append(quote: false)
  when :update
    if !op.arg?('n', 'bindir') && (bin = config_get('bin')) && Dir.exist?(bin)
      op << quote_option('bindir', bin)
    end
    if op.arg?('system')
      op.add_first(quote: false) { |val| val if val.match?(SEM_VER) }
    else
      op.append(escape: true)
    end
  when :install, :uninstall, :pristine
    if flag == :install
      post = if ia
               op.concat(args)
               readline('Enter command [args]', force: true)
             elsif op.empty?
               op.concat(args)
               nil
             elsif !args.empty?
               args.join(' ')
             end
    elsif ia
      name = op.shift || args.shift || (out = readline('Enter gem name', force: true))
      list = []
      pwd_set do
        pat = /^#{name}\s+\((.+)\)$/
        IO.popen(gem_output("list -a #{shell_quote(name)}").to_s).each do |val|
          next unless val =~ pat

          split_escape($1).each { |s| list << s unless s.start_with?('default:') }
          break
        end
      end
      ver = choice_index('Select version', list, force: out.nil?) unless list.empty?
      if ver
        op << '--force'
        op.unshift("#{name}@#{ver}")
      else
        op.unshift(name)
      end
    end
    raise_error ArgumentError, 'missing gem name', hint: flag if op.empty?
    if op.arg?('all')
      if flag == :pristine
        append_repeat 'skip', op.extras
        op.reset
      else
        op.clear
      end
    elsif (n = op.index { |val| val.match?(/(\A|[\w.-])@\d/) })
      name = op.remove_at(n)
      n = name.index('@')
      pre, ver = if n == 0
                   [gemname, name[1..-1]]
                 else
                   [name[0, n], name[n.succ..-1]]
                 end
      op.adjoin(pre, quote_option('version', ver))
        .clear
    end
    if flag == :install
      op.append_any(escape: true)
    else
      op.append(escape: true)
    end
    op.delim << post if post
  when :check, :cleanup, :contents, :fetch, :list, :lock, :rdoc
    op.append
  when :dependency, :info, :search
    op.add_first(quote: true, expect: case flag
                                      when :dependency, :search then 'no pattern for gem name'
                                      else 'missing gem name'
                                      end)
      .clear
  when :environment
    unless op.empty?
      case (action = op.shift)
      when 'home', 'path', 'user_gemhome', 'version', 'remotesources', 'platform', 'credentials'
        op << action
        op.clear
      else
        raise_error ArgumentError, "unrecognized arg: #{action}", hint: flag
      end
    end
  when :open, :owner, :unpack, :yank
    op.add_first(gemname)
      .clear
  when :rebuild
    op.add_first(expect: 'missing gem name')
      .add_first(expect: 'missing gem version')
      .clear
  when :specification
    op.add_first(expect: 'missing gem name')
      .add_first
      .clear
  when :which
    op.splice(path: true) { |val| op.exist?(val) }
      .clear
  else
    op.clear
  end
  op.clear(errors: true) if gems
  print_run(op, banner, **kwargs)
  run(banner: banner && %w[q silent quiet no-verbose].none? { |s| op.include?(shell_option(s)) },
      exception: kwargs.fetch(:exception, exception?), from: from)
end

#gemnameObject



1712
1713
1714
# File 'lib/squared/workspace/project/ruby.rb', line 1712

def gemname
  @gemname ||= ((spec = gemspec) ? spec.name : project)
end

#gemspecObject



1707
1708
1709
1710
# File 'lib/squared/workspace/project/ruby.rb', line 1707

def gemspec
  @gemspec = !gemfile.nil? && Gem::Specification.load(gemfile.to_s) rescue false if @gemspec.nil?
  @gemspec || nil
end

#irb(*args, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



1540
1541
1542
1543
# File 'lib/squared/workspace/project/ruby.rb', line 1540

def irb(*args, banner: verbose?, with: nil, pass: PASS_RUBY[:irb], **kwargs)
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  run_repl(*args, opts: opts, banner: banner, from: :irb, **kwargs)
end

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



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

def outdated(flag = nil, opts = [], sync: invoked_sync?('outdated', flag))
  cmd = bundle_output 'outdated'
  if flag
    se = has_value!(opts, 's', 'select')
    ia = has_value!(opts, 'i', 'interactive') && !se
    up = has_value!(opts, 'u', 'update')
    opts << 'only-explicit' if has_value!(opts, 'e', 'explicit')
    dryrun = has_value!(opts, 'd', 'dry-run')
    if !sync || stdin?
      se = false
      ia = false
    elsif se || ia || up
      items = []
    end
    OptionPartition.new(opts, bundleopts(:outdated), cmd << "--#{flag}", project: self, strict: strict?)
                   .clear
  elsif (up = option('u', 'update', prefix: 'bundle'))
    flag = case up
           when 'major', 'minor'
             up.to_sym
           else
             :patch
           end
    items = []
  end
  cmd << '--only-explicit' if option('only-explicit', prefix: 'bundle')
  dryrun ||= dryrun?(prefix: 'bundle')
  log.info cmd.to_s
  on :first, :outdated
  banner = format_banner cmd.to_s
  print_item banner if sync
  pwd_set(cmd, dryrun: dryrun) do
    tc = theme[:current]
    start = 0
    found = 0
    major = 0
    col = 0
    buffer = []
    out = ->(val) { sync ? puts(val) : buffer << val }
    IO.popen(cmd.temp('--no-color')).readlines(chomp: true).each do |line|
      if start > 0
        n = line.size
        unless stdin?
          line = line[0, col] if col > 0
          data = line.scan(SEM_VER)
          next unless (cur = data.shift) && (lat = data.shift)

          semver cur
          semver lat
          type = semtype cur, lat
          c = cur.join
          l = lat.join
          styles = []
          ma = lambda do
            styles = %i[green bold]
            major += 1
          end
          mi = -> { styles[0] = type == 2 ? :yellow : :green }
          if data.empty?
            type == 1 ? ma.call : mi.call
          else
            data.each do |val|
              break unless line =~ /(>=?|=|~>|!=|<=?) (#{Regexp.escape(val.join)})/

              v = semver(val).join
              case $1
              when '>', '>='
                type == 1 ? ma.call : mi.call
              when '<', '<='
                if c <= v
                  if type == 1
                    ma.call
                  else
                    styles[0] = :yellow
                  end
                end
              when '!='
                if c == l
                  styles.clear
                else
                  styles[1] = :bold
                end
              when '~>'
                if c < v && cur[0] == val[0] && !semmajor?(cur, val)
                  styles[0] = :yellow
                else
                  styles[1] = semmajor?(val, lat) ? :underline : :bold
                end
              end
            end
          end
          name = line[/^\S+/, 0]
          unless styles.empty?
            case styles.first
            when :green
              sub_style!(line, **opt_style(theme[styles.last == :bold ? :major : :active], /^(\S+)(.+)$/))
              found += 1
            when :yellow
              found += 1
            end
            sub_style!(line, **opt_style(tc, /^(.+)(#{Regexp.escape(c)})(.+)$/, 2)) if tc
            sub_style!(line, **opt_style(colormap(styles), /^((?:\S+\s+){2})(#{Regexp.escape(l)})(.*)$/, 2))
          end
        end
        s = '%2d. %s' % [start, line]
        if ia
          unless confirm_semver(s.ljust(col + 4 + line.size - n), type)
            start += 1
            next
          end
        elsif !se
          out.call(s)
        end
        items&.push([line, name])
      elsif line.start_with?('Gem')
        unless stdin?
          if ia
            line.sub!(/\sGroups$/, '')
            col = line.size
          end
          sub = [opt_style(theme[:header], /^(.+)(?<!\dm)(Gem|Latest)(.+)$/, 2)] * 2
          out.call(print_footer(" #  #{line}", reverse: true, sub: sub))
        end
      else
        next
      end
      start += 1
    end
    unless sync
      print_item banner
      puts buffer
    end
    if found > 0
      unless Array(items).empty?
        gems = if se
                 choice('Select a package', items.map(&:first),
                        multiple: true, force: false, index: true, border: true).map { |n| items[n.pred].last }
               else
                 items.map(&:last)
               end
        if dryrun
          print_run bundle_output("update --#{flag}", *gems.quote!(escape: true)), false
        else
          bundle(:update, *gems, opts: [flag.to_s])
        end
      end
      begin
        status = nil
        if gems
          status = "#{gems.size} packages were updated"
        else
          File.foreach(dependfile) do |line|
            next unless line =~ /\b(?:source\s+(["'])((?~\1))\1|remote:\s+(\S+))/

            status = ($2 || $3).chomp('/')
            break
          end
        end
      rescue => e
        log.debug e
      end
      puts print_footer(status || 'Updates are available', right: status.include?('/'))
    elsif start == 0 && banner
      puts 'No updates were found'
    end
  end
  on :last, :outdated
end

#outdated?Boolean

Returns:

  • (Boolean)


1807
1808
1809
# File 'lib/squared/workspace/project/ruby.rb', line 1807

def outdated?
  dependtype > 0 && !task_pass?('outdated')
end

#populateObject



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
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
# File 'lib/squared/workspace/project/ruby.rb', line 264

def populate(*, **)
  super
  return unless (outdated? && ref?(Ruby.ref)) || @only

  namespace name do
    Ruby.subtasks do |action, flags|
      next if task_pass?(action)

      if flags.nil?
        case action
        when 'rake'
          next unless rakefile

          format_desc action, nil, "task+|#{indexchar}index+,opts*|#,pattern*"
          task action, [:command] do |_, args|
            if args.command == '#'
              format_list(raketasks, "rake[#{indexchar}N]", 'tasks', grep: args.extras, from: rakefile, &:join)
            else
              tasks = raketasks
              cmd = nil
              opts = []
              queue = lambda do
                if cmd
                  cmd += "[#{opts.join(',')}]" unless opts.empty?
                  rake(cmd, banner: true)
                  cmd = nil
                elsif !opts.empty?
                  rake(banner: true, opts: opts)
                end
                opts.clear
              end
              args.to_a.each do |item|
                if (n, pre = indexitem(item))
                  queue.call
                  if (item = tasks[n.pred])
                    cmd = [pre, item.first].compact.join(' ')
                  elsif exception
                    indexerror n, tasks
                  else
                    log.warn "rake task #{n} of #{tasks.size}".subhint('out of range')
                    opts.clear
                    next
                  end
                else
                  opts << item
                end
              end
              queue.call
            end
          end
        when 'irb', 'pry'
          next unless action == 'irb' || gemspec?(action)

          format_desc action, nil, 'opts*,args*|:'
          task action do |_, args|
            opts = args.to_a
            args = Array(opts.delete(':') && readline('Enter file [arguments]', force: false))
            name = gemname if gemlib.any? { |file| exist?(file, "#{gemname}.rb") }
            __send__(action, *args, opts: opts, name: name, verbose: false)
          end
        when 'rdbg'
          format_desc action, nil, 'file?/:,opts*,debuggee?/::'
          task action do |_, args|
            opts = args.to_a
            cmd = opts.delete('::')
            if (n = opts.index('c'))
              args = opts.slice!(n.succ..-1)
            else
              file = opts.shift
              args = []
              if (file == ':' && (d = path)) || (file && (d = basepath(file)).directory?)
                args << choice_index('Select file', d.glob('*.rb').map { |f| f.relative_path_from(path) })
              elsif exist?(file, type: 'f')
                args << file
              else
                opts.unshift(file)
              end
            end
            args << readline('Enter debuggee [arguments]', force: false) if cmd
            rdbg(*args.compact, opts: opts, banner: false, verbose: false)
          end
        when 'rbs'
          next unless @steepfile

          data = {}
          target = nil
          File.foreach(@steepfile) do |line|
            if line =~ /^\s*target(?:\s+|\(\s*)(?::(\S+)|(["'])(.+)\2)/
              target = [[], []]
              data[$1 || $3.gsub(/[: ]/, '-')] = target
              next
            end
            next unless target && line =~ /^\s*(?:(check)|signature)\s+(["'])(.+)\2/

            target[$1 ? 1 : 0] << $3
          end
          next if data.empty?

          namespace 'rbs' do
            data.each do |key, item|
              sig, lib = item
              next if sig.empty? || lib.empty?

              format_desc action, key, 'sig?,path*'
              task key do |_, args|
                args = args.to_a
                list = lib.flat_map do |val|
                  val = File.join(val, '**/*.rb') unless val.include?('*') || val.match?(/\.[a-z\d]+$/i)
                  Dir.glob(val, base: path)
                end
                if args.empty?
                  files = choice_index('Select files', list, multiple: true, series: true,
                                                             accept: [accept_y('Generate?')])
                else
                  list.map! { |val| basepath(val).to_s }
                  files = args.each_with_object([]) do |val, out|
                    if val.include?('*')
                      out.concat(Dir.glob(val, base: path))
                    elsif !(file = basepath!(val))
                      print_error(val, hint: 'not found')
                    elsif file.directory?
                      out.concat(file.glob('**/*.rb'))
                    else
                      out << val
                    end
                  end.select { |val| list.include?(basepath(val).to_s) }
                  if files.empty?
                    print_error('steep', 'no files matched', hint: "#{key}:check")
                    exit 1
                  end
                  files.uniq!
                end
                sig = if (n = sig.index(args.first))
                        args.shift
                        sig[n]
                      elsif sig.size > 1
                        choice_index('Select a sig', sig, series: true)
                      else
                        sig.first
                      end
                rbs(:prototype, sig, *files)
              end
            end
          end
        when 'rubocop'
          next unless @rubocopfile

          format_desc action, nil, 'opts*,path*/:'
          task action do |_, args|
            opts, args = args.to_a.partition do |val|
              next true if val.match?(/(^([A-Z]|[a-z-]+)=.|^[a-z]+(-[a-z]+)*$)/)

              !val.include?('*') && !val.end_with?('/')
            end
            if opts.delete(':')
              args << (Dir.exist?('lib') ? 'lib/' : '**/*.rb') if args.empty?
              args = args.map { |val| val.end_with?('/') || Dir.exist?(val) ? File.join(val, '**/*.rb') : val }
                         .flat_map { |val| Dir.glob(val, base: path) }
              args = choice_index('Select files', args, multiple: true)
            end
            rubocop(*args, opts: opts, banner: true)
          end
        end
      else
        namespace action do
          flags.each do |flag|
            case action
            when 'outdated'
              format_desc action, flag, "#{shortname('i', 's', 'u', 'd')},e/xplicit,opts*"
              task flag do |_, args|
                outdated flag, args.to_a
              end
            when 'gem'
              case flag
              when :outdated
                format_desc action, flag, "semver?=major|minor|patch,#{shortname('i', 's', 'u', 'd')},opts*"
                task flag, [:semver] do |_, args|
                  opts = case (semver = args.semver)
                         when 'major', 'minor', 'patch'
                           args.extras
                         else
                           semver = nil
                           args.to_a
                         end
                  gem(flag, opts: opts, banner: true, filter: {
                    semver: semver,
                    update: has_value!(opts, 'u', 'update'),
                    interactive: has_value!(opts, 'i', 'interactive'),
                    select: has_value!(opts, 's', 'select'),
                    dryrun: has_value!(opts, 'd', 'dry-run')
                  })
                end
              when :build, :push, :exec, :update
                format_desc(action, flag, 'opts*', after: case flag
                                                          when :exec then 'command,args*'
                                                          when :push then 'file/:'
                                                          when :update then 'name*'
                                                          end)
                task flag do |_, args|
                  gem(flag, opts: args.to_a, banner: true)
                end
              when :install, :uninstall, :pristine
                format_desc(action, flag, 'opts*', after: flag == :pristine ? 'name*|name?@version' : 'name*')
                task flag do |_, args|
                  opts = param_guard(action, flag, args: args.to_a)
                  gem(flag, opts: opts, banner: true)
                end
              when :command
                format_desc action, flag, 'command,opts*,args*'
                task flag, [:command] do |_, args|
                  command = param_guard(action, flag, key: :command, args: args)
                  gem(command.to_sym, opts: args.extras, banner: true)
                end
              end
            when 'bundle'
              case flag
              when :config
                format_desc action, flag, 'list|set|get|unset?,opts*,args*'
                task flag do |_, args|
                  bundle(flag, *args.to_a, banner: true)
                end
              when :install, :update, :cache, :exec
                format_desc(action, flag, 'opts*', after: case flag
                                                          when :update then 'gems*'
                                                          when :exec then 'command,args*|:'
                                                          end)
                task flag do |_, args|
                  bundle(flag, opts: args.to_a, banner: flag == :exec ? verbose? : true)
                end
              when :check
                format_desc action, flag, 'gemfile?,d/ry-run?'
                task flag do |_, args|
                  args = args.to_a
                  opts = []
                  opts << 'dry-run' if has_value!(args, 'd', 'dry-run')
                  opts << "gemfile=#{shell_quote(args.pop, option: false, force: false)}" if exist?(args.first)
                  opts.concat(args)
                  bundle(:check, opts: opts, banner: true)
                end
              when :reinstall
                format_desc action, flag, 'f/orce?,l/ocal?,opts*'
                task flag do |_, args|
                  opts = args.to_a
                  opts << 'local' if has_value!(opts, 'l')
                  opts << 'redownload' if has_value!(opts, 'f', 'force')
                  if (lock = basepath!('Gemfile.lock'))
                    config = basepath '.bundle', 'config'
                    if config.exist? && config.read.match?(/\bBUNDLE_FROZEN:\s+"true"/)
                      if opts.include?('redownload')
                        run(bundle_output('config unset frozen'), banner: false)
                      else
                        print_error('Gemfile.lock is frozen', subject: name, hint: flag)
                        lock = nil
                      end
                    end
                    lock&.delete
                  end
                  bundle(:install, opts: opts, banner: true)
                end
              when :command
                format_desc action, flag, 'command,opts*,args*'
                task flag, [:command] do |_, args|
                  command = param_guard(action, flag, key: :command, args: args)
                  bundle(command.to_sym, opts: args.extras, banner: true)
                end
              end
            when 'ruby'
              case flag
              when :file
                format_desc action, flag, 'path,opts*,args*'
                task flag, [:rb] do |_, args|
                  opts = args.extras
                  args = Array(if (file = args.rb) && !file.include?('*')
                                 ENV['RUBY_ARGS']
                               else
                                 a, b, c = choice_index('Select a file', Dir.glob(file || '*.rb', base: path),
                                                        values: (file ? [] : ['Options']).push('Arguments'),
                                                        series: true)
                                 if file
                                   file = a
                                   b
                                 else
                                   file = a
                                   opts.concat(OptionPartition.strip(b))
                                   c
                                 end
                               end)
                  ruby(flag, *args, opts: opts, file: file)
                end
              when :script
                format_desc action, flag, 'opts*'
                task flag do |_, args|
                  args = args.to_a
                  multiline = case args.first
                              when ';', '#'
                                args.shift
                              else
                                %w[## ;]
                              end
                  msg = if Readline.respond_to?(:readmultiline)
                          'ruby>'
                        else
                          multiline = Array(multiline)
                          'Enter script'
                        end
                  command = ENV['RUBY_E'] || readline(msg, force: true, multiline: multiline)
                  ruby(flag, opts: args.to_a, command: command)
                end
              when :version
                format_desc action, flag, 'local?,alias?'
                task flag, [:local, :name] do |_, args|
                  ver = %w[.tool-versions .ruby-version]
                  mise = %w[mise.local.toml mise.toml]
                  s = args.local
                  if s && (%w[system latest].include?(s) || SEM_VER.match?(s) || s.start_with?(/(path|ref):/))
                    rbvm = exist?(ver.last) && !exist?(ver.first)
                    case vmname
                    when 'asdf'
                      unless rbvm
                        asdf(:set, **{ name: args.name, version: s, banner: verbose? }.compact)
                        next
                      end
                    when 'mise'
                      if mise.none? { |val| exist?(val) } && rbvm.call
                        save.call
                      else
                        cmd = session 'mise', 'use'
                        cmd << '--env local' if exist?(mise.first)
                        cmd << "#{args.name || 'ruby'}@#{s}"
                        run(banner: verbose?)
                        next
                      end
                    when nil
                      print_error('no version manager detected', subject: name)
                      next
                    end
                    File.write(basepath(ver.last), "#{s}\n") if SEM_VER.match?(s)
                    next
                  end
                  pwd_set do
                    out = []
                    tool = args.name || (args.local && !SEM_VER.match?(args.local) ? args.local : 'ruby')
                    trim = ->(s) { s[/^\D+\d+\.\d+(?:\.\S+)?/, 0].sub(/^([a-z]+)-/i, '\1 ') }
                    vm, bin = vmname(bin: true)
                    out << trim.call(case vm
                                     when 'rvm'
                                       `rvm current`[/^\S+/, 0]
                                     when 'rbenv'
                                       name = `rbenv version-name`
                                       (name =~ SEM_VER) == 0 ? "ruby #{name}" : name
                                     when 'chruby'
                                       chruby = session_output 'source', bin
                                       `#{chruby.with('ruby --version')}`
                                     when 'mise'
                                       data = parse_json(`mise ls #{tool} --json`, kind: Array)
                                       cur = `mise current #{tool}`.split.find do |val|
                                         data.any? do |item|
                                           item['version'] == val && item['installed'] && item['active']
                                         end
                                       end
                                       "ruby #{cur || data.first['version']}"
                                     when 'asdf'
                                       if @@asdf.config && File.exist?(@@asdf.config)
                                         pat = /legacy_version_file\s+=\s+(yes|no)/
                                         ver.pop unless File.read(@@asdf.config)[pat, 1] == 'yes'
                                       else
                                         ver.pop
                                       end
                                       opt = [@asdf.first]
                                       opt.unshift('--no-header') unless @@asdf.version == 15
                                       exit 1 unless (cur = `asdf current #{opt.join(' ')}`)
                                       if cur.match?(/\sfalse\b/)
                                         `ruby --version`
                                       else
                                         cur[/^\S+\s+\S+/, 0].sub(/\s+/, ' ')
                                       end
                                     else
                                       ver = nil
                                       `ruby --version`
                                     end)
                    unless workspace.windows?
                      if vm
                        out << trim.call(case vm
                                         when 'chruby'
                                           `#{chruby.with('chruby --version')}`.sub(':', '')
                                         when 'asdf'
                                           "asdf #{`asdf version`.delete_prefix('v')}"
                                         when 'mise'
                                           "mise #{parse_json(`mise version --json`, key: 'latest')}"
                                         else
                                           `#{vm} --version`
                                         end)
                      end
                      begin
                        out << ('which %s' % case vm
                                             when 'rbenv'
                                               `rbenv which #{tool}`
                                             when 'chruby'
                                               `#{chruby.with('which ruby')}`
                                             when 'asdf'
                                               `asdf which #{@asdf.first}`
                                             when 'mise'
                                               `mise which #{tool}`
                                             else
                                               `which ruby`
                                             end)
                      rescue => e
                        log.debug e
                      end
                      if ver
                        if vm == 'mise'
                          ver = mise + ver
                          pat = /^\s*#{tool}\s*=\s*\[?(.+?)\]?\s*$/
                        elsif vm != 'asdf'
                          ver.shift
                        end
                        append = ->(file, hint) { out << message("found #{file}", hint: hint) }
                        catch :found do
                          path.ascend do |dir|
                            ver.select { |val| dir.join(val).exist? }.each do |val|
                              file = dir + val
                              hint = if val.include?('mise')
                                       file.read[pat, 1]&.gsub(/["']/, '')
                                     else
                                       file.read
                                           .lines
                                           .map { |line| line.sub(/#.*$/, '').strip }
                                           .reject(&:empty?)
                                           .join(', ')
                                     end
                              append.call(file, hint)
                              throw :found if hint&.include?(out.first[/^(?:j|truffle)?ruby ([\d.]+)/, 1])
                            rescue
                              nil
                            end
                            file = case vm
                                   when 'rbenv'
                                     '.rbenv/version'
                                   when 'rvm'
                                     '.rvm/config/default'
                                   when 'mise'
                                     '.config/mise/config.toml'
                                   else
                                     next
                                   end
                            if File.exist?(file = dir.join(file))
                              hint = out.first.split(' ', 2).last
                              pat ||= SEM_VER
                              append.call(file, file.read[/^(.*(?:#{Regexp.escape(hint)}|#{pat}).*)$/, 1])
                              throw :found
                            end
                          end
                        end
                      end
                    end
                    out.map!(&:split)
                    pad = as_a(out, :first, :size).max
                    print_item
                    puts(out.map { |line| '%*s %s' % [pad, line.first, line[1..-1].join(' ')] })
                  end
                end
              when :reshim
                format_desc action, flag, 'name?'
                task flag, [:name] do |_, args|
                  case vmname
                  when 'rbenv'
                    cmd = session 'rbenv', 'rehash'
                  when 'asdf'
                    asdf(:reshim, **{ name: args.name, banner: verbose? }.compact)
                  when 'mise'
                    cmd = session('mise', 'reshim', args.name || 'ruby')
                  else
                    print_error('reshim not supported by version manager', subject: args.name)
                  end
                  success?(run(banner: verbose?), verbose?) if cmd
                end
              end
            end
          end
        end
      end
    end
  end
end

#projectObject



1716
1717
1718
1719
1720
# File 'lib/squared/workspace/project/ruby.rb', line 1716

def project
  return @project unless @project.frozen?

  @project = ((spec = gemspec) ? spec.name : @project).dup
end

#project=(val) ⇒ Object



248
249
250
# File 'lib/squared/workspace/project/ruby.rb', line 248

def project=(val)
  @project = val.dup
end

#pry(*args, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



1545
1546
1547
1548
# File 'lib/squared/workspace/project/ruby.rb', line 1545

def pry(*args, banner: verbose?, with: nil, pass: PASS_RUBY[:pry], **kwargs)
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  run_repl(*args, opts: opts, banner: banner, from: :pry, delim: false, **kwargs)
end

#rake(*args, sync: true, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
# File 'lib/squared/workspace/project/ruby.rb', line 1529

def rake(*args, sync: true, banner: verbose?, with: nil, pass: PASS_RUBY[:rake], **kwargs)
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  op = OptionPartition.new(opts, OPT_RUBY[:rake], rake_session, project: self, strict: strict?)
  op.adjoin(quote_option('f', rakefile)) if rakefile && !op.arg?('f', 'rakefile')
  op.concat(args)
  op.append(escape: true)
  print_run(op, banner, **kwargs)
  var = { 'BANNER' => '0' } unless banner
  run(op, var, sync: sync, banner: false, exception: kwargs.fetch(:exception, exception?), from: :rake)
end

#rbs(flag, *args, banner: verbose?, , with: nil, pass: nil, **kwargs) ⇒ Object



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

def rbs(flag, *args, banner: verbose?, with: nil, pass: nil, **kwargs)
  case pass
  when nil
    pass = PASS_RUBY[:rbs]
  when Array
    pass += PASS_RUBY[:rbs]
  end
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  cmd, opts = rbs_session(opts: opts)
  op = OptionPartition.new(opts, [], cmd << flag, project: self, strict: strict?)
  case flag
  when :prototype
    sig = args.shift
    y = option('y', ignore: false)
    i = 1
    args.map { |val| basepath(val).relative_path_from(path) }.each do |file|
      dir = basepath sig, file.dirname
      dir.mkpath unless dir.exist?
      base = file.basename.to_s
      rbs = dir + "#{base.stripext}.rbs"
      status = if rbs.exist?
                 case y
                 when '0', 'false'
                   'ignored'
                 else
                   next unless y || confirm_basic('Overwrite?', rbs, 'N')

                   'overwrite'
                 end
               end
      unless status == 'ignored'
        ret = run(op.target.temp(File.extname(base) == '.rbi' ? 'rbi' : 'rb', file, '>', rbs),
                  banner: false, series: true)
        if !ret
          status = 'FAIL'
        elsif File.empty?(rbs)
          status = 'empty'
        end
      end
      puts "#{i.to_s.rjust(2)}. #{rbs.relative_path_from(path)}".subhint(status)
      i += 1
    end
  else
    op.clear
      .append(*args)
    print_run(op, banner, **kwargs)
    run(banner: false, exception: kwargs.fetch(:exception, exception?), from: symjoin('rbs', flag))
  end
end

#rdbg(*args, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
# File 'lib/squared/workspace/project/ruby.rb', line 1550

def rdbg(*args, banner: verbose?, with: nil, pass: PASS_RUBY[:rdbg], **kwargs)
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  cmd = session 'rdbg'
  args.each_with_index do |val, index|
    break if val == '--'
    next unless exist?(val, type: 'f')

    args[index] = shell_quote basepath(val)
    cmd.merge(args.slice!(0, index + 1))
    break
  end
  op = OptionPartition.new(opts, OPT_RUBY[:rdbg], cmd, project: self, strict: strict?, first: [/\.rb$/])
  op.concat(args)
  op.append(quote: false, delim: true)
  print_run(op, banner, **kwargs)
  run(banner: false, exception: kwargs.fetch(:exception, exception?), from: :rdbg)
end

#refObject



260
261
262
# File 'lib/squared/workspace/project/ruby.rb', line 260

def ref
  Ruby.ref
end

#rubocop(*args, sync: true, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
# File 'lib/squared/workspace/project/ruby.rb', line 1618

def rubocop(*args, sync: true, banner: verbose?, with: nil, pass: PASS_RUBY[:rubocop], **kwargs)
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  op = OptionPartition.new(opts, OPT_RUBY[:rubocop], session('rubocop'), project: self, strict: strict?,
                                                                         no: OPT_RUBY[:no][:rubocop])
  if @rubocopfile && !op.arg?('c', 'config') && !rootpath('.rubocop.yml', ascend: true).exist?
    op.add_path(@rubocopfile, option: 'c')
  end
  op.concat(args)
  op.each do |val|
    if basepath(val).file?
      op.found << val
    else
      op.errors << val
    end
  end
  op.swap.map! { |val| basepath(val).relative_path_from(path) }
  op.append(delim: true)
    .clear(errors: true)
  print_run(op, banner, **kwargs)
  run(sync: sync, banner: banner, exception: kwargs.fetch(:exception, exception?), from: :rubocop)
end

#ruby(*args, sync: true, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/squared/workspace/project/ruby.rb', line 998

def ruby(*args, sync: true, banner: verbose?, with: nil, pass: PASS_RUBY[:ruby], **kwargs)
  if args.first.is_a?(Symbol)
    flag = args.shift
    from = symjoin 'ruby', flag
  end
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  op = OptionPartition.new(opts, OPT_RUBY[:ruby], ruby_session, project: self, strict: strict?,
                                                                multiple: [/^-e/], args: true, stdin: true)
  if kwargs[:command]
    op << quote_option('e', kwargs[:command])
  elsif kwargs[:file]
    if op.include?('-')
      op.add_path(kwargs[:file])
    else
      op.unshift(basepath(kwargs[:file]))
    end
  end
  op.concat(args)
  if op.include?('-')
    op.exist?(add: true)
  else
    op.append_any { |val| OptionPartition.parse_arg!('e', val) }
    if op.arg?('e')
      op.clear
    else
      op.append(delim: true, escape: kwargs.fetch(:escape, false), quote: kwargs.fetch(:quote, false))
    end
  end
  print_run(op, banner, **kwargs) unless flag
  run(sync: sync, banner: banner, exception: kwargs.fetch(:exception, exception?), from: from || :ruby)
end

#serve(root, bind: nil, port: 3000, **kwargs) ⇒ Object



1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
# File 'lib/squared/workspace/project/ruby.rb', line 1640

def serve(root, *, bind: nil, port: 3000, **kwargs)
  require 'webrick'
  config = kwargs.merge({ DocumentRoot: root })
  config[:BindAddress] = bind if bind
  config[:Port] = port if port
  server = WEBrick::HTTPServer.new(config)
  trap 'INT' do
    server.shutdown
  end
  server.start
end

#vmname(bin: false) ⇒ Object



1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
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
# File 'lib/squared/workspace/project/ruby.rb', line 1652

def vmname(bin: false)
  order = { 'rbenv' => -1, 'rvm' => -1, 'chruby' => -1, 'mise' => -1 }
  ENV.fetch('PATH', '').split(':').each_with_index do |val, index|
    order.each_key do |key|
      next unless val.match?(%r{[/.]#{key}/})

      order[key] = index
      break
    end
  end
  if @asdf
    [File.join(ENV.fetch('ASDF_DATA_DIR', '$HOME/.asdf'), "installs/#{@asdf.first}")]
  else
    [
      "#{ENV.fetch('RBENV_ROOT', '$HOME/.rbenv')}/bin/rbenv",
      '$HOME/.rvm/bin/rvm',
      '$HOME/.local/bin/mise',
      '/usr/bin/rbenv',
      '/usr/bin/mise',
      '/usr/local/rvm/bin/rvm',
      '/usr/share/rvm/bin/rvm',
      '/usr/local/share/chruby/chruby.sh'
    ]
    .sort do |a, b|
      c = -1
      d = -1
      order.each do |key, val|
        pat = %r{/\.?#{key}}
        c = val if a.match?(pat)
        d = val if b.match?(pat)
      end
      if c == d
        0
      elsif c == -1
        1
      elsif d == -1
        -1
      else
        c < d ? -1 : 1
      end
    end
  end
  .each do |val|
    next unless File.exist?(val = val.sub('$HOME', Dir.home))

    case (ret = File.basename(val, '.*'))
    when 'rvm', 'rbenv', 'mise', 'chruby'
      return bin ? [ret, val] : ret
    else
      return bin ? ['asdf', val] : 'asdf' if @asdf
    end
  end
  nil
end