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, #ls_files, #ls_remote, #pull, #rebase, #reset, #restore, #rev_parse, #show, #stash, #status, #tag

Methods inherited from Base

#add, aliasargs, #allref, 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, #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.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/squared/workspace/project/ruby.rb', line 61

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



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

def bannerargs
  [:dependfile].freeze
end

.batchargsObject



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

def batchargs(*); end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


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

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

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

.populateObject



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

def populate(*); end

.tasksObject



36
37
38
# File 'lib/squared/workspace/project/ruby.rb', line 36

def tasks
  [:outdated].freeze
end

Instance Method Details

#bundle(cmd, *args) ⇒ Object



486
487
488
489
# File 'lib/squared/workspace/project/ruby.rb', line 486

def bundle(cmd, *args)
  args = args.flatten
  run_s(bundle_session(cmd, *args), from: :bundle)
end

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



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

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)


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

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|
    log.warn "using version #{val} (given #{@version})" if @version && @version != val
    @version = val
  end
  if @version
    out = pwd_set { `#{gem_output('list', '--local', '-d', shell_escape(project, quote: true))}` }
    if (data = /#{Regexp.escape(project)} \(([^)]+)\)/.match(out))
      ver = data[1].split(/\s*,\s*/)
      ver.unshift(@version).uniq!
      ver.each do |val|
        next unless (data = /\(#{Regexp.escape(val)}(?:,[^)]+|\b)\):([^\n]+)/.match(out))

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

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



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/squared/workspace/project/ruby.rb', line 176

def depend(flag = nil, opts: [], sync: invoked_sync?('depend', flag))
  if @depend && !flag
    super
  elsif outdated?
    cmd = bundle_session 'install'
    if flag
      cmd << "--#{flag}"
      append_bundle opts, FOR_INSTALL + OPT_INSTALL
      from = :install
    else
      if (n = option('jobs')).to_i > 0
        cmd << "-j#{n}"
      end
      from = :depend
    end
    run_rb(from: from, sync: sync)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


500
501
502
# File 'lib/squared/workspace/project/ruby.rb', line 500

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

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



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

def gemx(flag, opts: [])
  cmd = gem_session
  case flag
  when :outdated
    cmd << "-C #{shell_quote(path)}" if (pass = Gem::VERSION >= '3.4.2')
    cmd << flag
  when :'user-install'
    cmd << 'install' << "--#{flag}"
  else
    cmd << flag
  end
  no = flag == :pristine || flag == :outdated ? [] : OPT_GEM[:NO_GENERAL]
  opts, pat = option_partition(opts, gemoption(flag), no: no, first: flag != :outdated)
  out = []
  opts.each do |opt|
    if opt =~ pat
      case $1
      when 'build-root', 'config-file', 'target-rbconfig',
           'n', 'bindir', 'g', 'file', 'i', 'install-dir'
        cmd << quote_option($1, basepath($2))
      when 'p', 'http-proxy', 's', 'source'
        cmd << quote_option($1, $2)
      when 'bulk-threshold'
        cmd << basic_option($1, $2) if $2.to_i > 0
      else
        cmd << shell_option($1, $2)
      end
    else
      out << opt
    end
  end
  from = :"gem:#{flag == :'user-install' ? 'install' : flag}"
  if flag == :outdated
    log.info cmd.to_s
    on :first, from
    print_item format_banner(cmd.to_s)
    pwd_set(pass: pass, 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
  else
    if out.empty? && !cmd.find { |val| val =~ /^--system(?:=|$)/ }
      raise_error('gem', flag, hint: 'no gemname given')
    else
      if flag == :pristine
        if cmd.include?('--all')
          append_repeat 'skip', out
          out.clear
        elsif (n = out.first =~ /@/)
          name = out.first
          if n == 0
            cmd << shell_escape(project)
            version = name[1..-1]
          else
            cmd << shell_escape(name[0..(n - 1)])
            version = name[(n + 1)..-1]
          end
          cmd << shell_option('version', version)
          out.clear
        end
      end
      append_value out
    end
    run_rb(from: from)
  end
end

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



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

def outdated(flag = nil, opts: [], sync: invoked_sync?('outdated', flag))
  cmd = bundle_output 'outdated'
  if flag
    cmd << "--#{flag}"
    append_bundle(opts, OPT_OUTDATED, 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 (req = /(>=?|=|~>|!=|<=?) (#{Regexp.escape(val.join)})/.match(line))

              v = semver(val).join
              case req[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 && (data = /\b(?:source\s+(["'])(.+?)\1|remote:\s+(\S+))/.match(dependfile.read))
          status = (data[2] || data[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)


551
552
553
# File 'lib/squared/workspace/project/ruby.rb', line 551

def outdated?
  dependtype > 0
end

#populateObject



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

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 'exec', 'config'
          format_desc action, nil, 'command+'
          task action do |_, args|
            args = param_guard('bundle', action, args: args.to_a)
            bundle(action, *args)
          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'
              format_desc(action, flag, FOR_INSTALL + OPT_INSTALL) if @@task_desc
              task flag do |_, args|
                depend(flag, opts: args.to_a)
              end
            when 'update', 'outdated'
              if @@task_desc
                format_desc(action, flag, action == 'update' ? FOR_INSTALL + OPT_UPDATE : OPT_OUTDATED)
              end
              task flag do |_, args|
                __send__(action, flag, opts: args.to_a)
              end
            when 'gem'
              case flag
              when :outdated
                format_desc action, flag, gemoption(flag) if @@task_desc
                task flag do |_, args|
                  gemx(flag, opts: args.to_a)
                end
              else
                if @@task_desc
                  format_desc(action, flag, gemoption(flag),
                              after: "name+#{flag == :pristine ? '|name?@version' : ''}")
                end
                task flag, [:name] do |_, args|
                  opts = param_guard(action, flag, args: args.to_a)
                  gemx(flag, opts: opts)
                end
              end
            end
          end
        end
      end
    end
  end
end

#rake(*cmd) ⇒ Object



491
492
493
494
495
496
497
498
# File 'lib/squared/workspace/project/ruby.rb', line 491

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



90
91
92
# File 'lib/squared/workspace/project/ruby.rb', line 90

def ref
  Ruby.ref
end

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



345
346
347
348
349
# File 'lib/squared/workspace/project/ruby.rb', line 345

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