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

Attributes inherited from Base

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from 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, #stash, #status, #switch, #tag

Methods inherited from Base

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

Methods included from Common::Format

#enable_aixterm, #enable_drawing

Constructor Details

#initialize(autodetect: false, **kwargs) ⇒ Ruby

Returns a new instance of Ruby.



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/squared/workspace/project/ruby.rb', line 94

def initialize(*, autodetect: false, **kwargs)
  super
  if @pass.include?(Ruby.ref)
    initialize_ref Ruby.ref
    initialize_logger(**kwargs)
  else
    initialize_build(Ruby.ref, **kwargs)
    initialize_env(**kwargs)
  end
  @autodetect = autodetect
  @dependindex = GEMFILE.index { |file| basepath(file).exist? }
  @dependfile = @path + GEMFILE[@dependindex || 0]
  return if !@output[0].nil? || !@copy.nil? || @version || @autodetect || (file = rakefile).nil?

  begin
    File.foreach(file) 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 StandardError => e
    log.error e
  end
end

Class Method Details

.bannerargsObject



69
70
71
# File 'lib/squared/workspace/project/ruby.rb', line 69

def bannerargs
  [:dependfile].freeze
end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
76
77
# File 'lib/squared/workspace/project/ruby.rb', line 73

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

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

.populateObject



63
# File 'lib/squared/workspace/project/ruby.rb', line 63

def populate(*); end

.tasksObject



65
66
67
# File 'lib/squared/workspace/project/ruby.rb', line 65

def tasks
  [:outdated].freeze
end

Instance Method Details

#bundle(flag, *args) ⇒ Object



725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'lib/squared/workspace/project/ruby.rb', line 725

def bundle(flag, *args)
  cmd = bundle_session flag
  args = case flag
         when 'exec', 'cache', 'check'
           list = OPT_BUNDLE[flag.to_sym] + OPT_BUNDLE[:common]
           OptionPartition.new(args, list, cmd, project: self, args: flag == :exec).extras
         else
           args.flatten
         end
  case flag
  when 'exec', 'config'
    raise_error('no command args', hint: flag) if args.empty?
    cmd.merge(args)
  else
    option_clear args
  end
  run(from: :"bundle:#{flag}")
end

#copy(from: 'lib', into: @gemdir, override: false, **kwargs) ⇒ Object



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

def copy(from: 'lib', into: @gemdir, override: false, **kwargs)
  glob = kwargs[:include]
  pass = kwargs[:exclude]
  if @copy && !override
    return super unless @copy.is_a?(Hash)

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

  on :first, :copy
  dest = Pathname.new(into).realpath
  print_item unless @output[0] || task_invoked?(/^copy(?::#{Ruby.ref}|$)/)
  glob = as_a(glob || '**/*')
  as_a(from).each_with_index do |val, i|
    a = path + val
    b = dest + val
    c = glob[i] || glob.first
    log.info "cp #{a + c} #{b}"
    begin
      copy_dir(a, b, c, pass: pass, verbose: verbose)
    rescue StandardError => e
      log.error e
      ret = on(:error, :copy, e)
      raise if exception && ret != true
    end
  end
  on :last, :copy
end

#copy?Boolean

Returns:

  • (Boolean)


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

def copy?
  return true if super || (@copy.is_a?(Hash) && copy.fetch(:into, nil))
  return gemdir? if @gemdir

  if @version
    begin
      case @autodetect
      when 'rvm'
        @gemdir = pwd_set { `rvm info homes` }[/^\s+gem:\s+"(.+)"$/, 1]
      when 'rbenv'
        if pwd_set { `rbenv which ruby` } =~ %r{^(.+[\\/]versions[\\/](\d\.\d)\.[^\\/]+)[\\/]bin[\\/]ruby$}
          @gemdir = File.join($1, 'lib/ruby/gems', "#{$2}.0")
        end
      when 'asdf'
        @gemdir = pwd_set { `asdf where ruby` }
        @gemdir = @gemdir =~ /(\d\.\d)\.[^.]+$/ && File.join(@gemdir, 'lib/ruby/gems', "#{$1}.0")
      when /bundler?/
        @gemdir = pwd_set { `bundle env` }[/^\s+Gem Home\s+(.+)$/, 1]
      end
    rescue StandardError => e
      log.debug e
    else
      @gemdir = Pathname.new(@gemdir) if @gemdir
    end
    return true if gemdir?
  end
  return false unless @autodetect

  set = lambda do |val, path|
    log.warn "using version #{val} (given #{@version})" if @version && @version != val
    @version = val
    @gemdir = Pathname.new(path.strip) + gempath
  end
  if @version
    pwd = gempwd
    pwd_set(pass: !pwd.nil?) do
      out = `#{gem_output(pwd, 'list --local -d', project)}`
      if out =~ /#{Regexp.escape(project)} \(([^)]+)\)/
        ver = $1.split(/\s*,\s*/)
        ver.unshift(@version).uniq!
        ver.each do |val|
          next unless out =~ /\(#{Regexp.escape(val)}(?:,[^)]+|\b)\):([^\n]+)/

          set.call(val, $1)
          break
        end
      end
    end
  end
  unless @gemdir
    parse = lambda do |path|
      next unless path

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

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



252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/squared/workspace/project/ruby.rb', line 252

def depend(*, sync: invoked_sync?('depend'), **)
  if @depend
    super
  elsif outdated?
    workspace.rev_clear(name, sync: sync)
    cmd = bundle_session 'install'
    cmd << '--without=development' if prod?
    if (n = option('jobs')).to_i > 0
      cmd << "-j#{n}"
    end
    run_rb(from: :depend, sync: sync)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


772
773
774
# File 'lib/squared/workspace/project/ruby.rb', line 772

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

#gem!(flag, opts = [], filter: nil) ⇒ Object



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

def gem!(flag, opts = [], filter: nil)
  cmd = gem_session
  case flag
  when :outdated
    cmd << gempwd << 'outdated'
  when :push
    cmd << 'push' << project
  else
    cmd << flag
  end
  list = OPT_GEM[flag] + OPT_GEM[:common]
  from = :"gem:#{flag}"
  case flag
  when :install, :update
    list.concat(OPT_GEM[:install_base])
    first = ['=']
  when :uninstall, :pristine
    first = ['=']
  end
  cmd.merge(preopts)
  op = OptionPartition.new(opts, list, cmd, project: self, no: OPT_GEM[:no][flag], first: first)
  op.each do |opt|
    if opt =~ op.values
      case $1
      when 'g', 'gem'
        op << (flag == :exec ? shell_option($1, $2) : quote_option($1, path + $2))
      end
    elsif opt.include?('=') && !%i[outdated build push exec].include?(flag)
      op.errors << opt
    else
      op.found << opt
    end
  end
  op.swap
  case flag
  when :outdated
    log.info cmd.to_s
    op.clear
    on :first, from
    print_item format_banner(cmd.to_s)
    major = 0
    minor = 0
    patch = 0
    update = []
    pwd_set(pass: !pwd.nil?, from: from) do
      items = [[%w[Gem Current Latest], nil]]
      IO.popen(cmd.done).each do |line|
        if line =~ /^(\S+) \((\S+) < ([^)]+)\)$/
          cur = semscan $2
          lat = semscan $3
          items << [$~.to_a.drop(1), if semmajor?(cur, lat)
                                       1
                                     else
                                       cur[2] == lat[2] ? 3 : 2
                                     end]
        else
          puts line
        end
      end
      if items.size > 1
        pad = [items.size.to_s.size + 1, 3].max
        d = 0
        e = 0
        f = 0
        j = 0
        queue = nil
        items.each do |item|
          a, b, c = item.first
          d = a.size if a.size > d
          e = b.size if b.size > e
          f = c.size if c.size > f
        end
        items.each_with_index do |item, i|
          next if i == 0 && stdin?

          a, b, c = item.first
          if i == 0
            line = "#{' #'.ljust(pad)} #{a.ljust(d)}    #{b.rjust(e)}  #{c.rjust(f)}"
            n = line.size
            2.times do
              line = sub_style(line, pat: /^(.+)(?<!\dm)(#{a}|#{c})(.*)$/, styles: theme[:header], index: 2)
            end
            queue = [line, sub_style(ARG[:BORDER][1] * n, styles: borderstyle)]
          else
            g = a.ljust(d)
            pat = [/^([^.]+\.)([^.]+\..+)$/, /^([^.]+\.[^.]+\.)(.+)$/]
            pre = b.start_with?('0.')
            latest = [theme[:current]]
            case item.last
            when 1
              case filter
              when 'major'
                update << a
              when 'minor', 'patch'
                next
              end
              g = sub_style(g, styles: theme[:major])
              major += 1
              styles = %i[green bold]
              pat = pre ? pat.first : nil
              latest << :bold
            when 2
              case filter
              when 'major', 'minor'
                update << a
              when 'patch'
                next
              end
              g = sub_style(g, styles: theme[:active])
              minor += 1
              styles = %i[green]
              pat = pre ? pat.last : pat.first
            else
              case filter
              when 'major', 'minor', 'patch'
                update << a
              end
              patch += 1
              styles = %i[yellow]
              pat = pat.last
            end
            b = b.rjust(e)
            b = sub_style(b, *colormap(styles), pat: pat, index: 2)
            h = sub_style(c.rjust(f), styles: latest.flatten.compact, pat: pat, index: 2)
            j += 1
            if queue
              puts queue
              queue = nil
            end
            puts "#{"#{j}.".rjust(pad)} #{g}    #{b}  #{h}"
            update << a if filter == 'interactive' && confirm_outdated(a, c, item.last)
          end
        end
      end
    end
    if major + minor + patch == 0
      puts 'No updates were found'
    else
      unless update.empty?
        cmd = gem_output 'update', '-f'
        if (val = option('document', prefix: 'gem', ignore: false))
          cmd << case val
                 when '0', 'false'
                   '--no-document'
                 else
                   basic_option('document', val)
                 end
        end
        if (val = option('user-install', prefix: 'gem', ignore: false))
          cmd << case val
                 when '0', 'false'
                   '--no-user-install'
                 else
                   '--user-install'
                 end
        end
        cmd.merge(update)
        run(cmd, banner: false, from: :'gem:update')
      end
      unless stdin?
        status = print_footer("major #{major} / minor #{minor} / patch #{patch}", right: true).split("\n")
        status[1] = sub_style(status[1], pat: /^( +major )(\d+)(.+)$/, styles: theme[:major], index: 2)
        status[1] = sub_style(status[1], pat: /^(.+)(minor )(\d+)(.+)$/, styles: theme[:active], index: 3)
        puts status
      end
    end
    on :last, from
    return
  when :build, :push
    if !op.empty?
      if flag == :build && op.size == 1
        op << shell_quote(path + op.first)
      else
        raise_error("unknown args: #{op.join(', ')}", hint: flag)
      end
    elsif flag == :build
      spec = [path + "#{project}.gemspec", path + "#{name}.gemspec", *Dir.glob(path + '*.gemspec')]
      op << File.basename(spec) if (spec = spec.find { |file| File.exist?(file) })
    end
  when :exec
    raise_error('missing command', hint: flag) if op.empty?
    op << project << op.join(' ')
  else
    raise_error('missing gemname', hint: flag) if op.empty? && !op.arg?('system')
    if flag == :pristine
      if op.arg?('all')
        append_repeat 'skip', op.extras
        op.extras.clear
      elsif (n = op.first.index('@'))
        name = op.shift
        if n == 0
          op << project
          ver = name[1..-1]
        else
          op << shell_escape(name[0, n])
          ver = name[n + 1..-1]
        end
        op << shell_option('version', ver)
        op.clear
      end
    end
    op.append.clear(errors: true)
  end
  run_rb(from: from)
end

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



417
418
419
420
421
# File 'lib/squared/workspace/project/ruby.rb', line 417

def install(flag, opts = [])
  bundle_session 'install', "--#{flag}"
  append_bundle opts, OPT_BUNDLE[:install_base] + OPT_BUNDLE[:install] + OPT_BUNDLE[:common]
  run_rb(from: :install)
end

#irb(name, opts = [], path: @path + 'lib', load: nil) ⇒ Object



757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/squared/workspace/project/ruby.rb', line 757

def irb(name, opts = [], path: @path + 'lib', load: nil)
  op = OptionPartition.new(opts, OPT_RUBY[:irb], session('irb'), project: self, first: [/\.rb$/])
  r = as_a name
  r.unshift('bundler/setup') unless load
  r.each { |val| op << shell_option('r', val, merge: true) }
  as_a(path).each { |val| op << quote_option('I', val, merge: true) }
  if load
    op << '--' << load
    op.clear
  else
    op.append(delim: true)
  end
  run(banner: false)
end

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



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

def outdated(flag = nil, opts = [], sync: invoked_sync?('outdated', flag))
  cmd = bundle_output 'outdated'
  if flag
    cmd << "--#{flag}"
    append_bundle(opts, OPT_BUNDLE[:outdated] + OPT_BUNDLE[:common], target: cmd)
  end
  log.info cmd.to_s
  on :first, :outdated
  banner = format_banner(cmd.to_s)
  print_item banner if sync
  pwd_set(from: :outdated) do
    start = 0
    found = 0
    major = 0
    buffer = []
    out = ->(val) { sync ? puts(val) : buffer << val }
    IO.popen(cmd.temp('--no-color')).each do |line|
      if start > 0
        unless stdin?
          data = line.scan(SEM_VER)
          next unless (cur = data.shift) && (lat = data.shift)

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

              v = semver(val).join
              case $1
              when '>', '>='
                semmajor?(cur, lat) ? major_set.call : minor_set.call
              when '<', '<='
                if c <= v
                  if semmajor?(cur, lat)
                    major_set.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
                elsif semmajor?(val, lat)
                  styles[1] = :underline
                else
                  styles[1] = :bold
                end
              end
            end
          end
          unless styles.empty?
            case styles.first
            when :green
              line = sub_style(line, pat: /^(\S+)(.+)$/, styles: theme[styles.last == :bold ? :major : :active])
              found += 1
            when :yellow
              found += 1
            end
            if theme[:current]
              line = sub_style(line, styles: theme[:current], pat: /^(.+)(#{Regexp.escape(c)})(.+)$/, index: 2)
            end
            line = sub_style(line, *colormap(styles), pat: /^((?:\S+\s+){2})(#{Regexp.escape(l)})(.*)$/,
                                                      index: 2)
          end
        end
        out.call("#{start.to_s.rjust(2)}. #{line}")
      elsif line.start_with?('Gem')
        unless stdin?
          sub = { pat: /^(.+)(?<!\dm)(Gem|Latest)(.+)$/, styles: theme[:header], index: 2 }
          out.call(print_footer(" #  #{line.chomp}", reverse: true, sub: [sub, sub]))
        end
      else
        next
      end
      start += 1
    end
    unless sync
      print_item banner
      puts buffer
    end
    if found > 0
      begin
        if major == 0 && dependfile.read =~ /\b(?:source\s+(["'])(.+?)\1|remote:\s+(\S+))/
          status = ($2 || $3).chomp('/')
          right = true
        end
      rescue StandardError => e
        log.debug e
      ensure
        status ||= 'Updates are available'
      end
      puts print_footer(empty_status(status, 'major', major, always: !right), right: right)
    elsif start == 0
      puts 'No updates were found'
    end
  end
  on :last, :outdated
end

#outdated?Boolean

Returns:

  • (Boolean)


850
851
852
# File 'lib/squared/workspace/project/ruby.rb', line 850

def outdated?
  dependtype > 0
end

#populateObject



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
247
248
249
250
# File 'lib/squared/workspace/project/ruby.rb', line 127

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

  namespace name do
    Ruby.subtasks do |action, flags|
      next if @pass.include?(action)

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

          format_desc action, nil, 'tasks*,opts*|^index|#,pattern*'
          task action, [:command] do |_, args|
            if args.command == '#'
              format_list(read_rakefile, 'rake[^N]', 'tasks', grep: args.extras, from: rakefile.to_s,
                                                              each: ->(val) { val[0] + val[1].to_s })
            elsif (n, opts = indexitem(args.command))
              list = read_rakefile
              if (item = list[n - 1])
                cmd = opts ? "#{opts} #{item.first}" : item.first
              elsif exception
                indexerror n, list
              else
                log.warn "rake task #{n} of #{list.size} (out of range)"
                next
              end
              rake(args.extras.empty? ? cmd : cmd + shell_escape("[#{args.extras.join(',')}]"))
            else
              rake(opts: args.to_a)
            end
          end
        when 'irb'
          next unless (spec = basepath("#{project}.gemspec") || basepath("#{name}.gemspec"))
          next unless basepath('lib').join("#{gemname = stripext(spec)}.rb").exist?

          format_desc action, nil, 'opts*,args*|:'
          task action do |_, args|
            args = args.to_a
            if args.last == ':'
              args.pop
              load = readline('Enter file and arguments', force: false)
            end
            irb(gemname, args, load: load)
          end
        else
          format_desc(action, nil, OPT_BUNDLE[action.to_sym], after: case action
                                                                     when 'cache', 'check' then nil
                                                                     else 'command+' end)
          task action do |_, args|
            bundle(action, *args.to_a)
          end
        end
      else
        namespace action do
          flags.each do |flag|
            case action
            when 'install', 'update', 'outdated'
              format_desc action, flag, 'opts*'
              task flag do |_, args|
                __send__ action, flag, args.to_a
              end
            when 'gem'
              case flag
              when :outdated
                format_desc action, flag, 'major|minor|patch|interactive?,opts*'
                task flag, [:semver] do |_, args|
                  case (filter = args.semver)
                  when 'major', 'minor', 'patch', 'interactive', 'i'
                    filter = 'interactive' if filter == 'i'
                    args = args.to_a.drop(1)
                  else
                    filter = nil
                    args = args.to_a
                  end
                  gem!(flag, args, filter: filter)
                end
              when :build, :push, :exec
                format_desc(action, flag, 'opts*', before: flag == :exec ? 'command+' : nil)
                task flag do |_, args|
                  gem! flag, args.to_a
                end
              else
                format_desc action, flag, "opts*,name+#{flag == :pristine ? '|name?@version' : ''}"
                task flag do |_, args|
                  args = param_guard(action, flag, args: args.to_a)
                  gem! flag, args
                end
              end
            when 'ruby'
              case flag
              when :file
                format_desc action, flag, 'path,opts*,args*'
                task flag, [:rb] do |_, args|
                  if (file = args.rb)
                    args = args.to_a.drop(1)
                  else
                    file, opts, extra = choice_index('Select a file', Dir.glob('*.rb', base: path),
                                                     values: %w[Options Arguments], force: true, series: true)
                    args = OptionPartition.strip(opts)
                    ENV['RUBY_ARGS'] = extra if extra
                  end
                  ruby(flag, args, file: file)
                end
              when :script
                format_desc action, flag, 'opts*,args*'
                task flag do |_, args|
                  command = ENV['RUBY_E'] || readline('Enter script', force: true, multiline: ['##', ';'])
                  ruby(flag, args.to_a, command: command)
                end
              when :version
                format_desc action, flag
                task flag do
                  ruby flag
                end
              end
            end
          end
        end
      end
    end
  end
end

#rake(*args, opts: []) ⇒ Object



744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/squared/workspace/project/ruby.rb', line 744

def rake(*args, opts: [])
  op = OptionPartition.new(opts, OPT_RUBY[:rake], [quote_option('f', rakefile)], project: self)
  args.concat(op.extras)
  if args.empty?
    args << nil
  else
    args.flatten!
  end
  cmd = rake_output(*op.to_a)
  args.map! { |val| cmd.temp(val) }
  run_s(args, banner: false, from: :rake)
end

#refObject



123
124
125
# File 'lib/squared/workspace/project/ruby.rb', line 123

def ref
  Ruby.ref
end

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



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

def ruby(flag, opts = [], file: nil, command: nil)
  case flag
  when :file, :script
    op = OptionPartition.new(opts, OPT_RUBY[:ruby], ruby_session, project: self, args: true)
    if file
      op.extras.unshift(shell_quote(path + file))
    elsif command
      op << quote_option('e', command, option: false)
    end
    if (args = ENV['RUBY_ARGS'])
      op.extras << args
    end
    op.append(delim: true, escape: false, quote: false) unless op.empty?
  when :version
    pwd_set do
      out = []
      [
        '$HOME/.rvm/bin/rvm',
        '/usr/local/rvm/bin/rvm',
        '/usr/share/rvm/bin/rvm',
        "#{ENV.fetch('RBENV_ROOT', '$HOME/.rbenv')}/bin/rbenv",
        '/usr/bin/rbenv',
        '/usr/local/share/chruby/chruby.sh',
        "#{ENV.fetch('ASDF_DATA_DIR', '$HOME/.asdf')}/plugins/ruby/bin/install",
        ''
      ].each do |val|
        next unless val.empty? || File.exist?(val.sub('$HOME', Dir.home))

        trim = ->(s) { s[/\A\D+\d+\.\d+(?:\.\S+)?/, 0].sub(/\A([a-z]+)-/i, '\1 ') }
        ver = '.ruby-version'
        out << trim.call(case (cmd = File.basename(val))
                         when 'rvm'
                           `rvm current`[/^\S+/, 0]
                         when 'rbenv'
                           name = `rbenv version-name`
                           name =~ SEM_VER ? "ruby #{name}" : name
                         when 'chruby.sh'
                           chruby = session_output 'source', val
                           `#{chruby.with('ruby --version')}`
                         when 'install'
                           ver = '.tool-versions'
                           `asdf current ruby`[/ruby\s+\S+/, 0].sub(/\s+/, ' ')
                         else
                           ver = nil
                           `ruby --version`
                         end)
        unless val.empty?
          out << trim.call(case cmd
                           when 'chruby.sh'
                             `#{chruby.with('chruby --version')}`.sub(':', '')
                           when 'install'
                             "asdf #{`asdf version`.sub(/^v/, '')}"
                           else
                             `#{cmd} --version`
                           end)
        end
        begin
          out << ('which %s' % case cmd
                               when 'rbenv'
                                 `rbenv which ruby`
                               when 'chruby.sh'
                                 `#{chruby.with('which ruby')}`
                               when 'install'
                                 `asdf which ruby`
                               else
                                 `which ruby`
                               end)
        rescue StandardError => e
          log.debug e
        end
        if ver
          path.ascend do |ent|
            next unless (ent += ver).exist?

            hint = File.read(ent).lines(chomp: true).reject(&:empty?).join(', ') rescue nil
            out << message("found #{ent}", hint: hint)
          end
        end
        break
      end
      out.map!(&:split)
      pad = out.map(&:first).map!(&:size).max
      puts(out.map! { |line| "#{line.first.rjust(pad)} #{line[1..-1].join(' ')}" })
    end
    return
  end
  run_rb(banner: op.arg?('v'), from: :"ruby:#{flag}")
end

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



423
424
425
426
427
428
# File 'lib/squared/workspace/project/ruby.rb', line 423

def update(flag, opts = [])
  bundle_session 'update', "--#{flag}"
  append_bundle(opts, OPT_BUNDLE[:install_base] + OPT_BUNDLE[:update] + OPT_BUNDLE[:common],
                append: flag == :all ? nil : /\A\w+=/)
  run_rb(from: :update)
end