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

#branch, #checkout, #clone, #clone?, #commit, #diff, #enabled?, #fetch, #generate, #logx, #ls_files, #ls_remote, #pull, #rebase, #reset, #restore, #rev_parse, #show, #stash, #status, #tag

Methods inherited from Base

#add, aliasargs, #allref, #as, as_path, #basepath, #build, #build?, #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?, #script?, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #variable_set, #version, #with

Methods included from Common::Format

#enable_aixterm

Constructor Details

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

Returns a new instance of Ruby.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/squared/workspace/project/ruby.rb', line 70

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 = basepath(GEMFILE[@dependindex || 0])
  return if !@output[0].nil? || !@copy.nil? || @version || @autodetect || (file = rakefile).nil?

  begin
    File.foreach(file) do |line|
      next unless line =~ %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



48
49
50
# File 'lib/squared/workspace/project/ruby.rb', line 48

def bannerargs
  [:dependfile].freeze
end

.batchargsObject



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

def batchargs(*); end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
# File 'lib/squared/workspace/project/ruby.rb', line 52

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

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

.populateObject



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

def populate(*); end

.tasksObject



44
45
46
# File 'lib/squared/workspace/project/ruby.rb', line 44

def tasks
  [:outdated].freeze
end

Instance Method Details

#bundle(flag, *args) ⇒ Object



511
512
513
514
515
516
517
518
519
520
521
# File 'lib/squared/workspace/project/ruby.rb', line 511

def bundle(flag, *args)
  args = args.flatten
  cmd = bundle_session flag
  case flag
  when 'exec', 'check'
    args = option_sanitize(args, OPT_BUNDLE[flag.to_sym] + OPT_BUNDLE[:common], args: flag == :exec).first
  end
  raise_error('bundle', flag, hint: 'no command given') unless !args.empty? || flag == 'check'
  cmd.merge(args)
  run(from: :"bundle:#{flag}")
end

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



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

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

    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)
  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 = basepath(val)
    b = dest.join(val)
    c = glob[i] || glob.first
    log.info "cp #{a.join(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)


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

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

  if @version && (home = ENV['GEM_HOME'])
    @gemdir = Pathname.new(home).join(gempath)
    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).join(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.(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.(ver, val)
      end
    end
    if RUBY_VERSION >= '2.6'
      target = RUBY_VERSION.start_with?('2.6') ? RubyVM : $LOAD_PATH
      parse.(target.resolve_feature_path(project)&.last)
    end
    pwd_set { parse.(`#{bundle_output('show', project)}`) } unless @gemdir
  end
  raise_error('failed to parse', 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



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/squared/workspace/project/ruby.rb', line 180

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

#depend?Boolean

Returns:

  • (Boolean)


532
533
534
# File 'lib/squared/workspace/project/ruby.rb', line 532

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

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



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

def gemx(flag, opts = [])
  cmd = gem_session
  case flag
  when :outdated
    if (pwd = gempwd)
      cmd << pwd
    end
    cmd << flag
  when :push
    raise_error('gem not found', hint: flag) if opts.empty? || !(file = path + opts.shift).exist?
    cmd << flag << shell_quote(file)
  when :'user-install'
    cmd << 'install' << '--user-install'
  else
    cmd << flag
  end
  list = OPT_GEM[flag == :'user-install' ? :install : flag] + OPT_GEM[:common]
  case flag
  when :install, :'user-install', :update
    list += OPT_GEM[:shared]
    no = OPT_GEM[:shared_no]
    first = true
  when :pristine
    first = true
  end
  opts, pat = option_sanitize(opts, list, no: no, first: first)
  out = []
  opts.each do |opt|
    if opt =~ pat
      case $1
      when 'g', 'gem'
        cmd << (flag == :exec ? basic_option($1, $2) : quote_option($1, basepath($2)))
      end
    else
      out << opt
    end
  end
  from = :"gem:#{flag == :'user-install' ? 'install' : flag}"
  case flag
  when :outdated
    log.info cmd.to_s
    on :first, from
    print_item format_banner(cmd.to_s)
    pwd_set(pass: !pwd.nil?, from: from) do
      items = [[%w[Gem Current Latest], nil]]
      IO.popen(cmd.done).each do |line|
        if (data = line.match(/^(\S+) \((\S+) < ([^)]+)\)$/))
          cur = semscan(data[2])
          lat = semscan(data[3])
          items << [data.to_a.drop(1), if semmajor?(cur, lat)
                                         %i[green bold]
                                       else
                                         cur[2] == lat[2] ? [:yellow] : [:green]
                                       end]
        else
          puts line
        end
      end
      if items.size == 1
        puts 'No updates were found'
      else
        pad = [items.size.to_s.size + 1, 3].max
        d = 0
        e = 0
        f = 0
        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
        major = 0
        minor = 0
        patch = 0
        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
            puts line
            puts '-' * n
          else
            styles = item.last
            a = a.ljust(d)
            if styles.first == :green
              a = sub_style(a, styles: if styles.size == 2
                                         major += 1
                                         theme[:major]
                                       else
                                         minor += 1
                                         theme[:active]
                                       end)
            else
              patch += 1
            end
            b = b.rjust(e)
            b = sub_style(b, styles: theme[:current]) if theme[:current]
            c = sub_style(c.rjust(f), *colormap(styles))
            puts "#{"#{i}.".rjust(pad)} #{a}    #{b}  #{c}"
          end
        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
    end
    on :last, from
    return
  when :build, :push
    if !out.empty?
      if flag == :build && out.size == 1
        cmd << basepath(out.first)
      else
        raise_error('gem', flag, out.join(', '), hint: 'unrecognized option')
      end
    elsif flag == :build
      cmd << "#{project}.gemspec"
    end
  when :exec
    raise_error('gem', flag, hint: 'no command given') if out.empty?
    cmd << basic_option('gem', project) unless session_arg?('g', 'gem')
    cmd << '--' << out.join(' ')
  else
    if out.empty? && cmd.none? { |val| val =~ /^--system(?:=|$)/ }
      raise_error('gem', flag, hint: 'no gemname given')
    end
    if flag == :pristine
      if session_arg?('all')
        append_repeat 'skip', out
        out.clear
      elsif (n = out.first =~ /@/)
        name = out.first
        if n == 0
          cmd << project
          version = name[1..-1]
        else
          cmd << shell_escape(name[0, n])
          version = name[(n + 1)..-1]
        end
        cmd << shell_option('version', version)
        out.clear
      end
    end
    append_value(out, escape: true)
  end
  run_rb(from: from)
end

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



342
343
344
345
346
# File 'lib/squared/workspace/project/ruby.rb', line 342

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

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



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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/squared/workspace/project/ruby.rb', line 225

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.() : minor_set.()
          else
            data.each do |val|
              break unless line =~ /(>=?|=|~>|!=|<=?) (#{Regexp.escape(val.join)})/

              v = semver(val).join
              case $1
              when '>', '>='
                semmajor?(cur, lat) ? major_set.() : minor_set.()
              when '<', '<='
                if c <= v
                  if semmajor?(cur, lat)
                    major_set.()
                  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.("#{start.to_s.rjust(2)}. #{line}")
      elsif line =~ /^Gem /
        unless stdin?
          sub = { pat: /^(.+)(?<!\dm)(Gem|Latest)(.+)$/, styles: theme[:header], index: 2 }
          out.(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)


592
593
594
# File 'lib/squared/workspace/project/ruby.rb', line 592

def outdated?
  dependtype > 0
end

#populateObject



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
# File 'lib/squared/workspace/project/ruby.rb', line 103

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

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

      if flags.nil?
        case action
        when 'config', 'exec', 'check'
          format_desc(action, nil, case action
                                   when 'exec', 'check'
                                     OPT_BUNDLE[action.to_sym]
                                   end, after: action == 'check' ? nil : 'command+')
          task action do |_, args|
            bundle action, args.to_a
          end
        when 'rake'
          next unless rakefile

          format_desc action, nil, "command*|#{indexchar}index,args*|#,pattern*"
          task action, [:command] do |_, args|
            if args.command == '#'
              format_list(read_rakefile, "rake[#{indexchar}N]", 'tasks', grep: args.extras, from: rakefile.to_s,
                                                                         each: ->(val) { val[0] + val[1].to_s })
            elsif (data = indexitem(args.command))
              n, opts = data
              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(*args.to_a)
            end
          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, :build, :push, :exec
                format_desc(action, flag, 'opts*', before: case flag
                                                           when :exec then 'command+'
                                                           when :push then 'file'
                                                           end)
                task flag do |_, args|
                  gemx flag, args.to_a
                end
              else
                format_desc action, flag, "opts*,name+#{flag == :pristine ? '|name?@version' : ''}"
                task flag do |_, args|
                  opts = param_guard(action, flag, args: args.to_a)
                  gemx flag, opts
                end
              end
            end
          end
        end
      end
    end
  end
end

#rake(*cmd) ⇒ Object



523
524
525
526
527
528
529
530
# File 'lib/squared/workspace/project/ruby.rb', line 523

def rake(*cmd)
  if cmd.empty?
    run_s(rake_output(rakeapp), from: :rake, chdir: workspace.pwd, banner: false)
  else
    cmd = cmd.flatten.map { |val| rake_output(rakeapp, val) }
    run_s(cmd, from: :rake, chdir: workspace.pwd, banner: false)
  end
end

#refObject



99
100
101
# File 'lib/squared/workspace/project/ruby.rb', line 99

def ref
  Ruby.ref
end

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



348
349
350
351
352
353
# File 'lib/squared/workspace/project/ruby.rb', line 348

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