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

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

#checkout, #commit, #diff, #fetch, #files, #pull, #rebase, #refs, #reset, #restore, #rev, #show, #stash, #status, #tag

Methods inherited from Base

#add, aliasargs, #allref, as_path, #basepath, #build, #build?, #clean, #clean?, #dependtype, #dev?, #doc, #doc?, #enabled?, #graph, #graph?, #has?, #initialize_build, #initialize_env, #initialize_logger, #initialize_ref, #inspect, #log, #prod?, ref, #ref?, #script?, #test, #test?, to_s, #to_s, #to_sym, #variable_set, #version, #with

Methods included from Common::Format

#enable_aixterm

Constructor Details

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

Returns a new instance of Ruby.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/squared/workspace/project/ruby.rb', line 44

def initialize(*, version: nil, 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
  @version = env('BUILD', version, suffix: 'VERSION')
  @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}

      @output[0] = 'bundle exec rake build'
      @copy = 'bundle exec rake install'
      @clean = 'bundle exec rake clean' if @clean.nil?
      break
    end
  rescue StandardError => e
    log.error e
  end
end

Class Method Details

.bannerargsObject



23
24
25
# File 'lib/squared/workspace/project/ruby.rb', line 23

def bannerargs
  %i[dependfile].freeze
end

.batchargsObject



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

def batchargs(*); end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
# File 'lib/squared/workspace/project/ruby.rb', line 27

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

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

.populateObject



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

def populate(*); end

.tasksObject



19
20
21
# File 'lib/squared/workspace/project/ruby.rb', line 19

def tasks
  %i[outdated].freeze
end

Instance Method Details

#bundle(flag, cmd) ⇒ Object



363
364
365
366
# File 'lib/squared/workspace/project/ruby.rb', line 363

def bundle(flag, cmd)
  guard_params('bundle', flag, args: cmd)
  run_s "bundle #{flag} #{cmd.join(' ')}"
end

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



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/squared/workspace/project/ruby.rb', line 210

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

  dest = Pathname.new(into).realpath
  print_item unless @output[0] || task_invoked?(/\Acopy(?::#{Ruby.ref}|\z)/)
  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}"
    copy_d(a, b, glob: c, pass: pass, verbose: verbose)
  end
end

#copy?Boolean

Returns:

  • (Boolean)


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

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

  if @version && (val = ENV['GEM_HOME'])
    @gemdir = Pathname.new(val).join(gempath)
    return true if gemdir?
  end
  return false unless @autodetect

  unsafe = ->(hint) { raise_error('failed to parse', hint: hint) }
  out = pwd_set { `gem list --local -d #{project}` }
  unsafe.('version') unless (data = /#{Regexp.escape(project)} \(([^)]+)\)/.match(out))
  ver = data[1].split(/\s*,\s*/)
  ver.unshift(@version).uniq! if @version
  ver.each do |v|
    next unless (data = /\(#{Regexp.escape(v)}(?:,[^)]+|\b)\):([^\n]+)/.match(out))

    log.warn "using version #{v} (given #{@version})" if @version && @version != v
    @version = v
    break
  end
  unsafe.('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



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

def depend(flag = nil, opts: [], sync: invoked_sync?('depend', flag))
  if @depend && !flag
    super
  elsif outdated?
    case flag
    when :gem
      gem_session 'install'
      append_value opts
    when :with, :without
      bundle_session 'install'
      append_repeat flag, opts
    when :redownload, :local, :'prefer-local'
      cmd = bundle_session 'install', "--#{flag}"
      if (val = option('trust-policy', ignore: false))
        cmd << shell_option('trust-policy', case val
                                            when '0'
                                              'NoSecurity'
                                            when '1'
                                              'AlmostNoSecurity'
                                            when '2'
                                              'LowSecurity'
                                            when '3'
                                              'MediumSecurity'
                                            when '4'
                                              'HighSecurity'
                                            else
                                              val
                                            end, escape: false)
      end
      append_bundle opts, OPT_INSTALL
    else
      bundle_session 'install'
      append_bundle
    end
    run_rb(sync: sync)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


377
378
379
# File 'lib/squared/workspace/project/ruby.rb', line 377

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

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



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

def outdated(rev = nil, opts: [], sync: invoked_sync?('outdated', rev))
  cmd = bundle_session 'outdated', rev && "--#{rev}"
  append_bundle opts, OPT_OUTDATED
  cmd = session_done(cmd)
  log.info cmd
  banner = format_banner(cmd)
  print_item banner if sync
  start = 0
  found = 0
  major = 0
  pwd_set do
    buffer = []
    out = ->(val) { sync ? puts(val) : buffer << val }
    IO.popen("#{cmd} --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[0]
            when :green
              line = sub_style(line, pat: /^(\S+)(.+)$/, styles: theme[styles[1] == :bold ? :major : :active])
              found += 1
            when :yellow
              found += 1
            end
            styles = styles.compact.map { |s| color(s) }.flatten
            line = sub_style(line, pat: /^((?:\S+\s+){2})(#{Regexp.escape(l)})(.*)$/, index: 2, styles: styles)
          end
        end
        out.("#{start.to_s.rjust(2)}. #{line}")
        start += 1
      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
        start += 1
      end
    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
end

#outdated?Boolean

Returns:

  • (Boolean)


414
415
416
# File 'lib/squared/workspace/project/ruby.rb', line 414

def outdated?
  dependtype > 0
end

#populateObject



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
# File 'lib/squared/workspace/project/ruby.rb', line 77

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

  namespace name do
    @@tasks[Ruby.ref].each do |action, flags|
      if flags.nil?
        case action
        when :exec, :config
          desc format_desc(action, nil, 'command+')
          task action, [:command] do |_, args|
            bundle(action, args.to_a)
          end
        when :rake
          next unless rakefile

          desc 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
              case flag
              when :gem
                desc format_desc(action, flag, 'name+')
                task flag, [:name] do |_, args|
                  opts = guard_params(action, flag, args: args.to_a)
                  depend(flag, opts: opts)
                end
              when :with, :without
                desc format_desc(action, flag, 'group+')
                task flag, [:group] do |_, args|
                  opts = guard_params(action, flag, args: args.to_a)
                  depend(flag, opts: opts)
                end
              else
                desc format_desc(action, flag, OPT_INSTALL)
                task flag, [:opts] do |_, args|
                  depend(flag, opts: args.to_a)
                end
              end
            when :update, :outdated
              desc format_desc(action, flag, action == :update ? OPT_UPDATE : OPT_OUTDATED)
              task flag, [:opts] do |_, args|
                __send__(action, flag, opts: args.to_a)
              end
            when :pristine
              case flag
              when :gem
                desc format_desc(action, flag, 'name+')
                task flag, [:name] do |_, args|
                  opts = guard_params(action, flag, args: args.to_a)
                  pristine(flag, opts: opts)
                end
              when :all
                desc format_desc(action, flag, 'skip*')
                task flag, [:skip] do |_, args|
                  pristine(flag, opts: args.to_a)
                end
              when :version
                desc format_desc(action, flag, 'version?')
                task flag, [:version] do |_, args|
                  version = guard_params(action, flag, args: args, key: :version)
                  pristine(flag, version: version)
                end
              end
            end
          end
        end
      end
    end
  end
end

#pristine(flag, version: nil, opts: []) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/squared/workspace/project/ruby.rb', line 349

def pristine(flag, version: nil, opts: [])
  cmd = gem_session 'pristine'
  case flag
  when :gem
    append_value opts
  when :all
    cmd << '--all'
    append_repeat 'skip', opts
  when :version
    cmd << project << shell_option('version', version)
  end
  run_rb
end

#rake(*cmd) ⇒ Object



368
369
370
371
372
373
374
375
# File 'lib/squared/workspace/project/ruby.rb', line 368

def rake(*cmd)
  file = shell_option('rakefile', rakefile, quote: true, escape: false)
  if cmd.empty?
    run_s("rake #{file}", chdir: workspace.pwd)
  else
    run_s(*cmd.map { |val| "rake #{file} #{val}" }, chdir: workspace.pwd, banner: false)
  end
end

#refObject



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

def ref
  Ruby.ref
end

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



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

def update(flag, opts: [])
  bundle_session 'update', "--#{flag}"
  append_bundle opts, OPT_UPDATE
  run_rb
end