Class: Squared::Workspace::Project::Base

Inherits:
Object
  • Object
show all
Includes:
Comparable, Prompt, Rake::DSL, Shell, Common::Format, Support, Support::Utils, Support::Variables, System, Utils
Defined in:
lib/squared/workspace/project/base.rb

Direct Known Subclasses

Docker, Git

Constant Summary collapse

@@tasks =
{}
@@graph =
{ _: [] }
@@asdf =
Pathname.new(ENV['ASDF_DIR'] || "#{Dir.home}/.asdf").yield_self do |path|
  version = if path.join('asdf.sh').exist?
              15
            elsif ENV['ASDF_DATA_DIR'] && (path = Pathname.new(ENV['ASDF_DATA_DIR'])).exist?
              16
            end
  if version
    config = ENV['ASDF_CONFIG_FILE'] || File.join(Dir.home, '.asdfrc')
    Struct.new(:path, :version, :config).new(path, version, config)
  end
end
0

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Common::Format

emphasize, #enable_aixterm, #enable_drawing, message, raise_error

Constructor Details

#initialize(workspace, path, name, first: {}, last: {}, error: {}, common: , **kwargs) ⇒ Base

Returns a new instance of Base.



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

def initialize(workspace, path, name, *, first: {}, last: {}, error: {}, common: ARG[:COMMON], **kwargs)
  @path = path
  @workspace = workspace
  @name = name.to_s.freeze
  @project = @path.basename.to_s.freeze
  @group = kwargs[:group]&.to_s.freeze
  @envname = env_key(@name).freeze
  @depend = kwargs[:depend]
  @doc = kwargs[:doc]
  @lint = kwargs[:lint]
  @test = kwargs[:test]
  @copy = kwargs[:copy]
  @clean = kwargs[:clean]
  @release = kwargs[:release]
  self.version = kwargs[:version]
  self.exception = env_bool(kwargs[:exception], workspace.exception, strict: true)
  self.pipe = env_pipe(kwargs[:pipe], workspace.pipe, strict: true)
  self.verbose = case (val = env('VERBOSE', kwargs[:verbose]))
                 when String
                   env_bool(val, workspace.verbose, strict: true, index: true)
                 else
                   val.nil? ? workspace.verbose : val
                 end
  @global = 0
  @output = []
  @ref = []
  @children = []
  @as = hashobj
  @desc = (@name.include?(':') ? @name.split(':').join(ARG[:SPACE]) : @name).freeze
  @on = {
    event: hashobj.update({ first: first, last: last, error: error }),
    from: []
  }
  @timeout = { _: [{}.compare_by_identity, nil, 0] }
  @log = nil
  @dev = nil
  @prod = nil
  @withargs = nil
  @session = nil
  @index = -1
  @initargs = kwargs.freeze
  parent_set kwargs[:parent]
  run_set(kwargs[:run], kwargs[:env], opts: kwargs.fetch(:opts, true))
  graph_set kwargs[:graph]
  timeout_set kwargs[:timeout]
  pass_set kwargs[:pass]
  only_set kwargs[:only]
  exclude_set kwargs[:exclude]
  archive_set kwargs[:archive]
  asdf_set kwargs[:asdf]
  theme_set common
  initialize_ref Base.ref
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def children
  @children
end

#dependfileObject (readonly)

Returns the value of attribute dependfile.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def dependfile
  @dependfile
end

#exceptionObject

Returns the value of attribute exception.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def exception
  @exception
end

#groupObject (readonly)

Returns the value of attribute group.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def group
  @group
end

#nameObject (readonly)

Returns the value of attribute name.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def name
  @name
end

#parentObject (readonly)

Returns the value of attribute parent.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def parent
  @parent
end

#pathObject (readonly)

Returns the value of attribute path.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def path
  @path
end

#pipeObject

Returns the value of attribute pipe.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def pipe
  @pipe
end

#projectObject

Returns the value of attribute project.



126
127
128
# File 'lib/squared/workspace/project/base.rb', line 126

def project
  @project
end

#themeObject (readonly)

Returns the value of attribute theme.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def theme
  @theme
end

#verboseObject

Returns the value of attribute verbose.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def verbose
  @verbose
end

#workspaceObject (readonly)

Returns the value of attribute workspace.



124
125
126
# File 'lib/squared/workspace/project/base.rb', line 124

def workspace
  @workspace
end

Class Method Details

.aliasargsObject



36
# File 'lib/squared/workspace/project/base.rb', line 36

def aliasargs(*); end

.bannerargsObject



37
# File 'lib/squared/workspace/project/base.rb', line 37

def bannerargs(*); end

.batchargsObject



35
# File 'lib/squared/workspace/project/base.rb', line 35

def batchargs(*); end

.config?Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/squared/workspace/project/base.rb', line 82

def config?(*)
  false
end

.options(*args, **kwargs) ⇒ Object



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

def options(*args, **kwargs)
  name = nil
  with = []
  proj = []
  opts = []
  args.each do |val|
    case val
    when String
      if name
        opts << val
      else
        name = val
      end
    when Symbol
      if name
        proj << val
      else
        with << val
      end
    end
  end
  return if !name || (opts.empty? && kwargs.empty? && with.empty?)

  base = OPTIONS[ref]
  data = [opts.freeze, kwargs.freeze, with.freeze].freeze
  proj << :_ if proj.empty?
  proj.each { |val| (base[val] ||= {})[name.to_s] = data }
end

.populateObject



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

def populate(*); end

.refObject



72
73
74
# File 'lib/squared/workspace/project/base.rb', line 72

def ref
  @ref ||= to_s.downcase.to_sym
end

.subtasks(val = nil, &blk) ⇒ Object



76
77
78
79
80
# File 'lib/squared/workspace/project/base.rb', line 76

def subtasks(val = nil, &blk)
  return @@tasks[val || ref].each(&blk) if block_given?

  @@tasks[ref] = val.freeze
end

.tasksObject



39
40
41
# File 'lib/squared/workspace/project/base.rb', line 39

def tasks
  (%i[build archive graph prereqs] + BLK_SET).freeze
end

.to_sObject



86
87
88
# File 'lib/squared/workspace/project/base.rb', line 86

def to_s
  super[/[^:]+\z/, 0]
end

Instance Method Details

#<=>(other) ⇒ Object



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

def <=>(other)
  return unless workspace == other.workspace
  return 0 if equal?(other)

  a, b = graph_deps
  return 1 if a.include?(other)

  c, d = graph_deps other
  e = b - d
  f = d - b
  if parent == other.parent
    g = []
    h = []
  else
    g = a - c
    h = c - a
  end
  g << self
  h << other
  e.concat(g)
  f.concat(h)
  if g.any? { |val| f.include?(val) }
    -1
  elsif h.any? { |val| e.include?(val) }
    1
  elsif e.any? { |val| f.include?(val) } # rubocop:disable Lint/DuplicateBranch
    -1
  elsif f.any? { |val| e.include?(val) } # rubocop:disable Lint/DuplicateBranch
    1
  elsif @index >= 0 && (i = other.index_get) >= 0
    @index <=> i
  end
rescue => e
  log&.debug e
  nil
end

#==(other) ⇒ Object



182
183
184
# File 'lib/squared/workspace/project/base.rb', line 182

def ==(other)
  equal?(other)
end

#add(path, name = nil, **kwargs, &blk) ⇒ Object



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

def add(path, name = nil, **kwargs, &blk)
  if path.is_a?(String) && path =~ %r{\A(.+)[\\/]\*+\z}
    return self unless checkdir?(path = basepath($1))

    path = path.children.select { |val| checkdir?(val) }
  end
  if path.is_a?(Array)
    name = self.name if name == true
    path.each { |val| add(val, name && task_join(name, File.basename(val)), **kwargs, &blk) }
  elsif projectpath?(path = basepath(path)) && checkdir?(path)
    kwargs = hashdup(@withargs).update(kwargs) if @withargs
    kwargs[:group] = group if group && !kwargs.key?(:group)
    kwargs[:ref] = ref unless kwargs.key?(:ref)
    name = case name
           when String, Symbol
             name.to_s
           else
             path.basename
           end
    target = children
    workspace.add(path, name, parent: self, **kwargs) do
      target << self
      instance_eval(&blk) if block_given?
    end
  end
  self
end

#allref(&blk) ⇒ Object



1130
1131
1132
# File 'lib/squared/workspace/project/base.rb', line 1130

def allref(&blk)
  @ref.reverse_each(&blk)
end

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



556
557
558
559
560
# File 'lib/squared/workspace/project/base.rb', line 556

def archive(*, sync: invoked_sync?('archive'), **)
  return unless @archive.is_a?(Hash)

  unpack(path, **@archive, sync: sync, from: :archive)
end

#archive?Boolean

Returns:

  • (Boolean)


1056
1057
1058
# File 'lib/squared/workspace/project/base.rb', line 1056

def archive?
  @archive.is_a?(Hash) && (!path.exist? || path.empty?)
end

#as(cmd, script, to = nil) ⇒ Object



841
842
843
844
845
846
847
848
849
# File 'lib/squared/workspace/project/base.rb', line 841

def as(cmd, script, to = nil)
  data = @as[cmd.to_sym]
  if script.is_a?(Enumerable)
    script.each { |key, val| data[key.to_s] = val }
  elsif to
    data[script.to_s] = to
  end
  self
end

#asdf(flag, opts = [], name: nil, version: nil, banner: true) ⇒ Object



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

def asdf(flag, opts = [], name: nil, version: nil, banner: true)
  return unless @asdf

  cmd = flag == :update ? session('asdf', 'plugin update') : session('asdf', flag)
  name ||= @asdf.first
  legacy = @@asdf.version == 15
  case flag
  when :set
    u = has_value?(opts, 'u', 'home')
    cmd << if legacy
             cmd.delete(flag)
             u ? 'global' : 'local'
           elsif has_value?(opts, 'p', 'parent')
             '--parent'
           elsif u
             '--home'
           end
    cmd << name << version
  when :env, :exec
    cmd << name if flag == :env || !opts.first.start_with?(/#{name}\b/)
    cmd.merge(opts)
  when :current
    cmd << '--no-header' unless legacy
    cmd << name
  else
    cmd << name
    banner = false if flag == :latest || flag == :where
  end
  success?(run(banner: banner, from: symjoin('asdf', flag)), banner, flag == :set || flag == :reshim)
end

#basepath(*args) ⇒ Object



1134
1135
1136
# File 'lib/squared/workspace/project/base.rb', line 1134

def basepath(*args)
  path.join(*args)
end

#basepath!(*args, type: nil) ⇒ Object



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

def basepath!(*args, type: nil)
  ret = basepath(*args)
  return unless ret.exist?

  if type
    (type.is_a?(String) ? type.chars : type).each do |ch|
      case ch
      when 'f'
        return nil unless ret.file?
      when 'd'
        return nil unless ret.directory?
      when 'l'
        return nil unless ret.symlink?
      when 'r'
        return nil unless ret.readable?
      when 'w'
        return nil unless ret.writable?
      when 'e'
        return nil unless ret.executable?
      else
        return nil
      end
    end
  end
  ret
end

#build(*args, sync: invoked_sync?('build'), from: :run) ⇒ Object



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

def build(*args, sync: invoked_sync?('build'), from: :run, **)
  banner = !silent?
  if args.empty?
    return unless from == :run

    banner = verbose? if from_base?('build')
    run_b(@run, sync: sync, banner: banner, from: from) if series?(@run)
    args = @output
  end
  if args.first.is_a?(Struct)
    f, blk = args.first.to_a
    args[0] = instance_eval(&blk) || f
    return unless args.first
  end
  if args.all?(Array)
    var = {}
    cmd = args.each_with_object([]) do |val, out|
      case val.first
      when Proc
        instance_exec(*val[1..-1], &val.first)
        next
      when Method
        val.first.call(*val[1..-1])
        next
      end
      a, b, c, d, e = val
      case b
      when Hash
        b = append_hash(b, target: [], build: true).join(' ')
      when Enumerable
        b = b.to_a.join(' ')
      end
      d = append_hash(d, target: []).join(' ') if d.is_a?(Hash)
      if a
        out << [replace_bin(as_get(a, from, 1)), d, b].compact.join(' ')
      else
        next unless respond_to?(:compose)

        out << a if (a = compose(as_get(b, from, 2), d, script: true, args: e, from: from))
      end
      var.update(c) if c.is_a?(Hash)
    end.join(' && ')
  else
    cmd, opts, var, flags, extra = args
    if cmd
      return run_b(cmd, sync: sync, from: from) if cmd.is_a?(Proc) || cmd.is_a?(Method)

      cmd = replace_bin as_get(cmd, from, 1)
      opts = compose(opts, script: false) if opts && respond_to?(:compose)
      flags = append_hash(flags, target: []).join(' ') if flags.is_a?(Hash)
      cmd = case opts
            when Hash
              [cmd, flags].concat(append_hash(opts, target: [], build: true))
                          .compact
                          .join(' ')
            when Enumerable
              cmd = Array(cmd).concat(opts.to_a)
              cmd.map! { |val| "#{val} #{flags}" } if flags
              cmd.join(' && ')
            else
              [cmd, flags, opts].compact.join(' ')
            end
    else
      return unless (opts || extra) && respond_to?(:compose)

      cmd = compose(as_get(opts, from, 2), flags, script: true, args: extra, from: from)
      from = :script if from == :run && script?
    end
  end
  run(cmd, var, sync: sync, banner: banner, from: from)
end

#build?Boolean

Returns:

  • (Boolean)


1044
1045
1046
# File 'lib/squared/workspace/project/base.rb', line 1044

def build?
  !!@output[0] || script? || series?(@run)
end

#chain(*args, **kwargs) ⇒ Object



438
439
440
441
# File 'lib/squared/workspace/project/base.rb', line 438

def chain(*args, **kwargs)
  workspace.chain(*args, project: self, **kwargs)
  self
end

#clean(*args, sync: invoked_sync?('clean'), pass: false, **kwargs) ⇒ Object



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

def clean(*args, sync: invoked_sync?('clean'), pass: false, **kwargs)
  return unless @clean

  on :first, :clean unless pass
  case @clean
  when Struct
    if (val = instance_eval(&@clean.block) || @clean.run)
      @clean = @clean.tap do
        @clean = val
        clean(*args, sync: sync, pass: true, **kwargs)
      end
    end
  when String
    run_s(@clean, sync: sync)
  when Hash
    begin
      @clean.each { |cmd, opts| build(cmd.to_s, opts, sync: sync) }
    rescue => e
      on_error(e, fatal: prod?)
    end
  else
    if @clean.is_a?(Enumerable) && !series?(@clean)
      @clean.each do |val|
        src = basepath(val = val.to_s)
        if src.directory? && val.match?(%r{[\\/]\z})
          log&.warn "rm -rf #{src}"
          rm_rf(src, verbose: !silent?)
        else
          log&.warn "rm #{src}"
          (val.include?('*') ? Dir[src] : [src]).each do |file|
            next unless File.file?(file)

            File.delete(file)
          rescue => e
            print_error(Logger::ERROR, e, subject: name)
          end
        end
      end
    else
      run_b(@clean, sync: sync)
    end
  end
  on :last, :clean unless pass
end

#clean?Boolean

Returns:

  • (Boolean)


1088
1089
1090
# File 'lib/squared/workspace/project/base.rb', line 1088

def clean?
  runnable?(@clean) || workspace.task_defined?(name, 'clean')
end

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



574
575
576
# File 'lib/squared/workspace/project/base.rb', line 574

def copy(*, sync: invoked_sync?('copy'), **)
  run_b(@copy, sync: sync, from: :copy)
end

#copy?Boolean

Returns:

  • (Boolean)


1072
1073
1074
# File 'lib/squared/workspace/project/base.rb', line 1072

def copy?
  runnable?(@copy) || workspace.task_defined?(name, 'copy')
end

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



527
528
529
# File 'lib/squared/workspace/project/base.rb', line 527

def depend(*, sync: invoked_sync?('depend'), **)
  run_b(@depend, sync: sync, from: :depend)
end

#depend?Boolean

Returns:

  • (Boolean)


1052
1053
1054
# File 'lib/squared/workspace/project/base.rb', line 1052

def depend?
  !!@depend
end

#dependnameObject



1120
1121
1122
# File 'lib/squared/workspace/project/base.rb', line 1120

def dependname
  @dependname ||= dependfile&.basename.to_s
end

#dependtypeObject



1116
1117
1118
# File 'lib/squared/workspace/project/base.rb', line 1116

def dependtype(*)
  dependindex&.succ || 0
end

#dev?Boolean

Returns:

  • (Boolean)


1092
1093
1094
# File 'lib/squared/workspace/project/base.rb', line 1092

def dev?
  @dev != false && workspace.dev?(pat: @dev, **scriptargs)
end

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



562
563
564
# File 'lib/squared/workspace/project/base.rb', line 562

def doc(*, sync: invoked_sync?('doc'), **)
  run_b(@doc, sync: sync, banner: from_base?('doc') ? verbose? : !silent?, from: :doc)
end

#doc?Boolean

Returns:

  • (Boolean)


1076
1077
1078
# File 'lib/squared/workspace/project/base.rb', line 1076

def doc?
  !!@doc
end

#empty?Boolean

Returns:

  • (Boolean)


1100
1101
1102
# File 'lib/squared/workspace/project/base.rb', line 1100

def empty?
  children.empty?
end

#enabled?(ref = nil) ⇒ Boolean

Returns:

  • (Boolean)


1021
1022
1023
1024
1025
# File 'lib/squared/workspace/project/base.rb', line 1021

def enabled?(ref = nil, **)
  return false if ref && Array(ref).none? { |val| ref?(val) }

  (path.directory? && !path.empty?) || archive?
end

#error(key, *args, **kwargs, &blk) ⇒ Object



830
831
832
# File 'lib/squared/workspace/project/base.rb', line 830

def error(key, *args, **kwargs, &blk)
  event(:error, key, *args, **kwargs, &blk)
end

#event(name, key, *args, override: false, **kwargs, &blk) ⇒ Object



834
835
836
837
838
839
# File 'lib/squared/workspace/project/base.rb', line 834

def event(name, key, *args, override: false, **kwargs, &blk)
  args.unshift(blk) if block_given?
  ev = @on[:event][name.to_sym]
  (override ? ev[key.to_sym] = [] : ev[key.to_sym] ||= []) << [args, kwargs]
  self
end

#exclude?(*refs) ⇒ Boolean

Returns:

  • (Boolean)


1104
1105
1106
# File 'lib/squared/workspace/project/base.rb', line 1104

def exclude?(*refs)
  !@exclude.empty? && has_value?(@exclude, *refs)
end

#exist?(*args, type: nil) ⇒ Boolean

Returns:

  • (Boolean)


1038
1039
1040
1041
1042
# File 'lib/squared/workspace/project/base.rb', line 1038

def exist?(*args, type: nil)
  return false if args.first.nil?

  type ? !basepath!(*args, type: type).nil? : basepath(*args).exist?
end

#first(key, *args, **kwargs, &blk) ⇒ Object



822
823
824
# File 'lib/squared/workspace/project/base.rb', line 822

def first(key, *args, **kwargs, &blk)
  event(:first, key, *args, **kwargs, &blk)
end

#generate(keys) ⇒ Object



397
398
399
# File 'lib/squared/workspace/project/base.rb', line 397

def generate(keys, **)
  task_build keys
end

#global(*args) ⇒ Object



925
926
927
928
929
930
931
932
933
934
# File 'lib/squared/workspace/project/base.rb', line 925

def global(*args)
  @global > 0 && @global.anybits?(case args.size
                                  when 1
                                    args.first
                                  when 0
                                    1 | 2
                                  else
                                    args.reduce(0) { |a, b| a | b }
                                  end)
end

#global=(val) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/squared/workspace/project/base.rb', line 254

def global=(val)
  return if @global == -1

  @global = if val == 0
              0
            elsif val.nil?
              -1
            elsif val < 0
              @global ^ val.abs
            else
              @global | val
            end
end

#global_set(name = nil, **kwargs) ⇒ Object



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

def global_set(name = nil, **kwargs)
  return if (n = @global) == -1

  @global = 0
  data = scriptdata(name: name)
  if n.anybits?(1 << 31)
    @global = (n & (1 | 2)) | (1 << 31)
  elsif @output[0] != false
    kwargs.update(@initargs) if name
    if @output[0].nil?
      if data[:script]
        unless kwargs[:script] == false
          script_set(data[:script], args: data.fetch(:args, kwargs[:args]), prod: kwargs[:prod], global: true)
        end
      elsif data[:run]
        run_set(data[:run], global: true)
      end
      if kwargs[:script]
        script_set(kwargs[:script], args: kwargs[:args]) unless data[:env][:script]
      elsif @script
        if @script[:script]
          script_set(@script[:script], args: @script.fetch(:args, kwargs[:args])) unless data[:global][:script]
        elsif @script[:run] && !data[:global][:run]
          run_set @script[:run]
        end
      end
    elsif data[:run] && data[:env][:run]
      run_set(data[:run], global: true)
    end
  end
  self.global = 4 if data[:global][:doc] && doc?
  self.global = 8 if data[:global][:test] && test?
end

#graph(start = [], tasks = nil, sync: invoked_sync?('graph'), pass: [], out: nil, order: nil) ⇒ Object



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

def graph(start = [], tasks = nil, *, sync: invoked_sync?('graph'), pass: [], out: nil, order: nil, **)
  env('GRAPH', strict: true) do |val|
    tasks ||= []
    split_escape(val) do |task|
      if ref?(task.to_sym) && (script = workspace.script_get(:graph, ref: task.to_sym))
        tasks.concat(script[:graph])
      else
        tasks << task
      end
    end
  end
  env('GRAPH', suffix: 'PASS') { |val| pass.concat(split_escape(val)) }
  start, neg = start.partition { |name| !name.start_with?('-') }
  data = graph_collect(self, start, pass: neg.map { |name| name[1..-1] })
  unless out
    data[name] << self
    on :first, :graph
  end
  ret = graph_branch(self, data, tasks, out, sync: sync, pass: pass, order: order)
rescue => e
  on_error(e, exception: true, dryrun: !out.nil?)
else
  if out
    if order
      out.map do |val|
        name = ret.find { |proj| val.match?(/ #{Regexp.escape(proj.name)}(@\d|\z)/) }&.name
        (n = name && order[name]) ? val.subhint(n.succ) : val
      end
    else
      [out, ret]
    end
  else
    on :last, :graph
  end
end

#graph?Boolean

Returns:

  • (Boolean)


1060
1061
1062
# File 'lib/squared/workspace/project/base.rb', line 1060

def graph?
  @graph.is_a?(Array) && !@graph.empty?
end

#has?(meth, ref = nil, all: false, missing: false) ⇒ Boolean

Returns:

  • (Boolean)


1027
1028
1029
1030
1031
1032
# File 'lib/squared/workspace/project/base.rb', line 1027

def has?(meth, ref = nil, all: false, missing: false)
  return false if ref && !ref?(ref)

  pred = :"#{meth}?"
  respond_to?(pred, all) ? __send__(pred) : missing
end

#inject(obj, *args, **kwargs, &blk) ⇒ Object



443
444
445
446
447
448
449
450
451
452
453
# File 'lib/squared/workspace/project/base.rb', line 443

def inject(obj, *args, **kwargs, &blk)
  if enabled?
    raise 'link not compatible' unless obj.respond_to?(:link) && (out = obj.link(self, *args, **kwargs, &blk))

    out.build if out.respond_to?(:build)
  end
  self
rescue => e
  print_error(e, subject: name, hint: obj)
  self
end

#inspectObject



1192
1193
1194
# File 'lib/squared/workspace/project/base.rb', line 1192

def inspect
  "#<#{self.class}: #{name} => #{self}>"
end

#last(key, *args, **kwargs, &blk) ⇒ Object



826
827
828
# File 'lib/squared/workspace/project/base.rb', line 826

def last(key, *args, **kwargs, &blk)
  event(:last, key, *args, **kwargs, &blk)
end

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



566
567
568
# File 'lib/squared/workspace/project/base.rb', line 566

def lint(*, sync: invoked_sync?('lint'), **)
  run_b(@lint, sync: sync, from: :lint)
end

#lint?Boolean

Returns:

  • (Boolean)


1080
1081
1082
# File 'lib/squared/workspace/project/base.rb', line 1080

def lint?
  !!@lint
end

#localnameObject



1177
1178
1179
# File 'lib/squared/workspace/project/base.rb', line 1177

def localname
  workspace.task_localname(name)
end

#logObject



1124
1125
1126
1127
1128
# File 'lib/squared/workspace/project/base.rb', line 1124

def log
  return @log unless @log.is_a?(Array)

  @log = Logger.new(enabled? ? @log.first : nil, **@log.last)
end

#populate(keys) ⇒ Object



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

def populate(keys, **)
  task_build keys
  return unless ref?(Base.ref)

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

      if flags.nil?
        case action
        when 'serve'
          next unless serve?

          format_desc action, nil, 'root,port?,bind?,opts*'
          task action, [:root] do |_, args|
            if !args.root && @serve
              kwargs = @serve.dup
              root = kwargs.delete(:root)
              opts = kwargs.delete(:opts) || []
            else
              root = param_guard(action, 'path', args: args, key: :root)
              opts = args.extras
              unless opts.empty?
                port = opts.shift
                if port.match?(/^\d+$/)
                  bind = opts.shift
                else
                  bind = port
                  port = nil
                end
                if bind&.start_with?('-')
                  opts << bind
                  bind = nil
                end
              end
              kwargs = { port: port, bind: bind }.compact
            end
            serve(basepath(root).to_s, opts, **kwargs)
          end
        end
      else
        namespace action do
          flags.each do |flag|
            case action
            when 'graph'
              break unless graph?

              format_desc action, flag, '(-)project*'
              task flag do |_, args|
                args = args.to_a.reject { |val| val == name }
                if flag == :run
                  graph args
                else
                  out = graph(args, out: [], order: {})
                  emphasize(out, title: path, right: true, border: borderstyle, sub: [
                    opt_style(theme[:header], /\A(#{Regexp.escape(path.to_s)})(.*)\z/),
                    opt_style(theme[:active], /\A(#{Regexp.escape(name)})(.*)\z/),
                    opt_style(theme[:inline], /\A((?~ \() \()(\d+)(\).*)\z/, 2)
                  ])
                end
              end
            when 'unpack'
              format_desc(action, flag, 'tag/url,dir,digest?,f/orce?', before: ('ext' if flag == :ext))
              params = %i[tag dir digest force]
              params.unshift(:ext) if flag == :ext
              task flag, params do |_, args|
                ext = flag == :ext ? param_guard(action, flag, args: args, key: :ext) : flag.to_s
                tag = param_guard(action, flag, args: args, key: :tag)
                dir = param_guard(action, flag, args: args, key: :dir)
                unless tag.match?(URI_SCHEME)
                  tag = unpack_get tag, ext
                  tag ||= if @release
                            "%s.#{ext}" % [@release.include?('??') ? @release.sub('??', tag) : @release + tag]
                          else
                            raise_error ArgumentError, "no base uri: #{tag}", hint: ext
                          end
                end
                force = case (digest = args.digest)
                        when 'f', 'force'
                          digest = nil
                          true
                        else
                          args.fetch(:force, false)
                        end
                unpack(basepath(dir), uri: tag, digest: digest, ext: ext, force: force)
              end
            when 'asdf'
              break unless @asdf

              case flag
              when :set
                format_desc action, flag, 'version,dir?=u/home|p/arent'
                task flag, [:version] do |_, args|
                  args = if (version = args.version)
                           args.extras
                         else
                           version, opts = choice_index('Select a version',
                                                        @asdf[1].children
                                                                .map(&:basename)
                                                                .sort { |a, b| b <=> a }
                                                                .push('latest', 'system'),
                                                        accept: [accept_y('Confirm?')],
                                                        values: 'Options')
                           OptionPartition.strip(opts)
                         end
                  asdf(flag, args, version: version)
                end
              else
                format_desc(action, flag, case flag when :exec, :env then 'command' end)
                task flag do |_, args|
                  args = args.to_a
                  if args.empty? && (flag == :exec || flag == :env)
                    args << readline('Enter command', force: flag == :exec)
                  end
                  asdf flag, args
                end
              end
            end
          end
        end
      end
    end
  end
end

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



531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/squared/workspace/project/base.rb', line 531

def prereqs(*, sync: invoked_sync?('prereqs'), **)
  on :first, :prereqs
  graph_deps.flatten(1).sort.each do |proj|
    next if @@graph[:_].include?(proj)

    if (val = ENV["PREREQS_#{proj.envname_get}"] || ENV["PREREQS_#{proj.ref.upcase}"])
      split_escape(val) do |meth|
        if proj.has?(meth)
          begin
            proj.__send__(meth, sync: sync)
          rescue => e
            on_error(e, exception: true)
          end
        else
          print_error('prereqs', "method: #{meth}", subject: name, hint: 'undefined')
        end
      end
    elsif proj.build?
      proj.build(sync: sync)
    end
    @@graph[:_] << proj
  end
  on :last, :prereqs
end

#prereqs?Boolean

Returns:

  • (Boolean)


1064
1065
1066
1067
1068
1069
1070
# File 'lib/squared/workspace/project/base.rb', line 1064

def prereqs?
  target = self
  begin
    return true if target.graph?
  end while (target = target.parent)
  false
end

#prod?Boolean

Returns:

  • (Boolean)


1096
1097
1098
# File 'lib/squared/workspace/project/base.rb', line 1096

def prod?
  @prod != false && workspace.prod?(pat: @prod, **scriptargs)
end

#refObject



268
269
270
# File 'lib/squared/workspace/project/base.rb', line 268

def ref
  Base.ref
end

#ref?(val) ⇒ Boolean

Returns:

  • (Boolean)


1034
1035
1036
# File 'lib/squared/workspace/project/base.rb', line 1034

def ref?(val)
  @ref.include?(val)
end

#rootpath(*args, ascend: nil) ⇒ Object



1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
# File 'lib/squared/workspace/project/base.rb', line 1165

def rootpath(*args, ascend: nil)
  ret = basepath(*args)
  return ret unless ascend && !ret.exist?

  path.parent.ascend.each do |dir|
    target = dir.join(*args)
    return target if target.exist?
    break if (ascend.is_a?(String) && dir.join(ascend).exist?) || workspace.root == dir || parent&.path == dir
  end
  ret
end

#run(cmd = @session, var = nil, exception: exception?, , sync: true, banner: true, from: nil, chdir: path, interactive: nil, hint: nil, series: false, timeout: nil, send: :system) ⇒ Object



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

def run(cmd = @session, var = nil, exception: exception?, sync: true, banner: true, from: nil, chdir: path,
        interactive: nil, hint: nil, series: false, timeout: nil, send: :system, **)
  unless cmd
    print_error('no command session started', subject: project, hint: from, pass: true)
    return
  end
  cmd = cmd.target if cmd.is_a?(OptionPartition)
  if interactive && sync && (!@session || !option('y'))
    print_item(series: true)
    msg, y, h = case interactive
                when Array
                  interactive
                when String
                  [interactive, 'N']
                else
                  %w[Run Y]
                end
    msg = "#{msg} #{sub_style(h, theme[:active])}" if h
    exit 1 unless confirm_basic("#{msg}?", cmd, y)
  end
  timeout = session_timeout cmd if timeout.nil?
  cmd = session_done cmd
  log&.info cmd
  on :first, from
  begin
    if cmd.start_with?(/[^:]+:[^:]/) && workspace.task_defined?(cmd)
      log&.warn "ENV discarded: #{var}" if var
      task_invoke(cmd, exception: exception, warning: warning?)
    else
      print_item(format_banner(cmd, banner: banner, hint: hint), series: series) if sync
      if var != false && (pre = runenv)
        case pre
        when Hash
          var = var.is_a?(Hash) ? pre.merge(var) : pre
        when Enumerable
          cmd = command(*pre.to_a, cmd)
        else
          cmd = command pre, cmd
        end
      end
      args = var.is_a?(Hash) ? [var, cmd] : [cmd]
      ret = shell_t(*args, name: send, chdir: chdir, exception: exception, timeout: timeout || 0)
    end
  rescue Timeout::Error => e
    print_error(Logger::ERROR, cmd, subject: name, hint: e)
    exit 1 unless exception?(Logger::DEBUG, Logger::INFO)
  rescue => e
    on_error(e, exception: true)
    false
  else
    on :last, from
    ret
  end
end

#scope(*args, **kwargs, &blk) ⇒ Object



919
920
921
922
923
# File 'lib/squared/workspace/project/base.rb', line 919

def scope(*args, **kwargs, &blk)
  namespace name do
    task(*args, **kwargs, &blk)
  end
end

#script?Boolean

Returns:

  • (Boolean)


1048
1049
1050
# File 'lib/squared/workspace/project/base.rb', line 1048

def script?
  @output[0].nil? && !!@output[1] && respond_to?(:compose)
end

#scriptdata(*keys, name: nil) ⇒ Object



1187
1188
1189
1190
# File 'lib/squared/workspace/project/base.rb', line 1187

def scriptdata(*keys, name: nil)
  ret = @workspace.script_find(*@ref, @group, name: name)
  keys.empty? ? ret : ret.dig(*keys)
end

#scriptname(from: :run) ⇒ Object



1181
1182
1183
1184
1185
# File 'lib/squared/workspace/project/base.rb', line 1181

def scriptname(from: :run)
  return unless (name = @output[1]) && respond_to?(:compose)

  as_get name, from, 2
end

#series(key, override: false, &blk) ⇒ Object



851
852
853
854
855
856
857
858
859
860
861
862
# File 'lib/squared/workspace/project/base.rb', line 851

def series(key, override: false, &blk)
  if blocks.include?(key.to_sym) && block_given?
    if !override && series?(target = instance_variable_get(:"@#{key}"))
      target << blk
    else
      instance_variable_set :"@#{key}", [blk]
    end
  else
    log&.warn "series: @#{key}".subhint('invalid')
  end
  self
end

#task_include?(key, ref = nil) ⇒ Boolean

Returns:

  • (Boolean)


1108
1109
1110
# File 'lib/squared/workspace/project/base.rb', line 1108

def task_include?(key, ref = nil)
  workspace.task_include?(self, key, ref) && !@pass.include?(key.to_s)
end

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



570
571
572
# File 'lib/squared/workspace/project/base.rb', line 570

def test(*, sync: invoked_sync?('test'), **)
  run_b(@test, sync: sync, from: :test)
end

#test?Boolean

Returns:

  • (Boolean)


1084
1085
1086
# File 'lib/squared/workspace/project/base.rb', line 1084

def test?
  !!@test
end

#to_sObject



1196
1197
1198
# File 'lib/squared/workspace/project/base.rb', line 1196

def to_s
  path.to_s
end

#to_symObject



1200
1201
1202
# File 'lib/squared/workspace/project/base.rb', line 1200

def to_sym
  name.to_sym
end

#unpack(target, file = nil, uri: nil, sync: true, digest: nil, ext: nil, force: false, depth: 1, headers: {}, verbose: !silent?,, from: :unpack) ⇒ Object



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

def unpack(target, file = nil, uri: nil, sync: true, digest: nil, ext: nil, force: false, depth: 1, headers: {},
           verbose: !silent?, from: :unpack)
  if !target.exist?
    target.mkpath
  elsif !target.directory?
    raise_error Errno::EEXIST, target, hint: uri
  elsif !file && !target.empty?
    raise_error Errno::EEXIST, target, hint: uri unless force || env('UNPACK_FORCE')
    create = true
  end
  if digest
    require 'digest'
    digest, type = digest.split(':', 2).reverse
    algo = case type&.downcase || digest.size
           when 32, 'md5'
             Digest::MD5
           when 'rmd160'
             Digest::RMD160
           when 40, 'sha1'
             Digest::SHA1
           when 64, 'sha256'
             Digest::SHA256
           when 96, 'sha384'
             Digest::SHA384
           when 128, 'sha512'
             Digest::SHA512
           else
             raise_error "invalid checksum: #{digest}", hint: uri
           end
  end
  env('HEADERS') do |val|
    next unless (data = parse_json(val))

    headers = headers.is_a?(Hash) ? headers.merge(data) : data
  end
  if file
    ext ||= File.extname(file)[1..-1]
  else
    require 'open-uri'
    data = nil
    (uri = Array(uri)).each_with_index do |url, i|
      URI.open(url, headers) do |f|
        data = f.read
        if algo && algo.hexdigest(data) != digest
          data = nil
          raise_error "invalid checksum: #{digest}", hint: url if i == uri.size.pred
        end
        next if ext && i == 0

        case f.content_type
        when 'application/zip'
          ext = 'zip'
        when %r{application/(?:x-)?gzip}
          ext = 'tgz'
        when 'application/x-xz'
          ext = 'txz'
        when 'application/x-7z-compressed'
          ext = '7z'
        end
      end
      break uri = url if data
    end
    unless data && (ext ||= URI.decode_www_form_component(URI.parse(uri).path[/\.([\w%]+)(?:\?|\z)/, 1]))
      raise_error(data ? TypeError : RuntimeError, "no content#{' type' if data}", hint: uri)
    end
  end
  ext = ext.downcase
  if (val = env("#{%w[zip 7z gem].include?(ext) ? ext.upcase : 'TAR'}_DEPTH", ignore: false))
    depth = val.to_i
  end
  begin
    unless file
      file = if ext == 'gem'
               dir = Dir.mktmpdir
               File.new(File.join(dir, File.basename(uri)), 'w')
             else
               require 'tempfile'
               Tempfile.new("#{name}-")
             end
      file.write(data)
      file.close
      file = Pathname.new(file)
      delete = true
    end
    if create
      print_error('force remove', subject: name, hint: target)
      target.rmtree
      target.mkpath
    end
    case ext
    when 'zip', 'aar'
      session 'unzip', shell_quote(file), quote_option('d', target)
    when 'tar', /\A(?:t|tar\.)?[gx]z\z/
      flags = +(silent? ? '' : 'v')
      if ext.end_with?('gz')
        flags += 'z'
      elsif ext.end_with?('xz')
        flags += 'J'
      end
      session 'tar', "-x#{flags}", basic_option('strip-components', depth), quote_option('f', file),
              quote_option('C', target)
      depth = 0
    when '7z'
      session '7z', 'x', shell_quote(file), "-o#{shell_quote(target)}"
    when 'gem'
      session 'gem', 'unpack', shell_quote(file), quote_option('target', target)
      depth = 0 unless val
    else
      raise_error("unsupported format: #{ext}", hint: uri || file)
    end
    run(sync: sync, banner: verbose, from: from)
    while depth > 0 && target.children.size == 1
      entry = target.children.first
      break unless entry.directory?

      i = 0
      i += 1 while (dest = target + "#{File.basename(file)}-#{i}").exist?
      FileUtils.mv(entry, dest)
      dest.each_child { |child| FileUtils.mv(child, target) }
      dest.rmdir
      target = entry
      depth -= 1
    end
  ensure
    if dir
      remove_entry dir
    elsif delete && file.exist?
      file.unlink
    end
  end
end

#variable_set(key, *args, **kwargs, &blk) ⇒ Object Also known as: apply



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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
# File 'lib/squared/workspace/project/base.rb', line 970

def variable_set(key, *args, **kwargs, &blk)
  if block_given?
    if blocks.include?(key)
      series key, &blk
      return self
    end
    args = block_args args, &blk
  end
  if variables.include?(key) || blocks.include?(key)
    val = args.size > 1 ? args : args.first
    case key
    when :index
      index_set val
    when :graph
      graph_set val
    when :timeout
      timeout_set val
    when :pass
      pass_set val
    when :only
      only_set val
    when :exclude
      exclude_set val
    when :parent
      parent_set val
    when :archive
      archive_set val
    when :serve
      serve_set val
    when :asdf
      asdf_set val
    when :run
      run_set(*args, **kwargs)
    when :script
      script_set(*args, **kwargs)
    when :env
      run_set(output[0], *args, **kwargs)
    when :dependfile
      @dependindex = nil
      @dependfile = (basepath(*args) if val)
    else
      instance_variable_set(:"@#{key}", val)
    end
  else
    log&.warn "variable_set: @#{key}".subhint('private')
  end
  self
end

#versionObject



1112
1113
1114
# File 'lib/squared/workspace/project/base.rb', line 1112

def version(*)
  @version
end

#version=(val) ⇒ Object



223
224
225
# File 'lib/squared/workspace/project/base.rb', line 223

def version=(val)
  @version = val&.to_s
end

#with(**kwargs, &blk) ⇒ Object



401
402
403
404
405
406
407
408
# File 'lib/squared/workspace/project/base.rb', line 401

def with(**kwargs, &blk)
  @withargs = (kwargs unless kwargs.empty?)
  if block_given?
    instance_eval(&blk)
    @withargs = nil
  end
  self
end