Class: Squared::Workspace::Project::Node

Inherits:
Git
  • Object
show all
Defined in:
lib/squared/workspace/project/node.rb

Constant Summary

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary

Attributes inherited from Base

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Git

#autostash, #branch, #checkout, #clean, #clone, #clone?, #commit, #diff, #enabled?, #fetch, #generate, #git, #log!, #ls_files, #ls_remote, #merge, #pull, #rebase, #reset, #restore, #rev_parse, #revbuild, #revbuild?, #show, #stash, #status, #switch, #tag

Methods inherited from Base

#<=>, #add, #allref, #archive, #archive?, #as, as_path, #basepath, #build, #build?, #chain, #clean, #clean?, #copy?, #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, #prereqs, #prereqs?, ref, #ref?, #rootpath, #script?, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #variable_set, #with

Methods included from Common::Format

#enable_aixterm, #enable_drawing

Constructor Details

#initialize(**kwargs) ⇒ Node

Returns a new instance of Node.



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/squared/workspace/project/node.rb', line 101

def initialize(*, **kwargs)
  super
  if @pass.include?(Node.ref)
    initialize_ref Node.ref
    initialize_logger(**kwargs)
  else
    initialize_build(Node.ref, prod: prod?, **kwargs)
    initialize_env(**kwargs)
  end
  @dependfile = @path + 'package.json'
  @pm = {}
end

Class Method Details

.aliasargsObject



70
71
72
# File 'lib/squared/workspace/project/node.rb', line 70

def aliasargs
  [ref, { refresh: :build }].freeze
end

.bannerargsObject



74
75
76
# File 'lib/squared/workspace/project/node.rb', line 74

def bannerargs
  %i[version dependfile].freeze
end

.batchargsObject



66
67
68
# File 'lib/squared/workspace/project/node.rb', line 66

def batchargs
  [ref, { refresh: %i[build copy] }].freeze
end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


82
83
84
85
86
# File 'lib/squared/workspace/project/node.rb', line 82

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

  val.join('package.json').exist?
end

.populateObject



60
# File 'lib/squared/workspace/project/node.rb', line 60

def populate(*); end

.prod?Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/squared/workspace/project/node.rb', line 78

def prod?
  ENV['NODE_ENV'] == 'production'
end

.tasksObject



62
63
64
# File 'lib/squared/workspace/project/node.rb', line 62

def tasks
  %i[outdated update publish].freeze
end

Instance Method Details

#bump(flag, val = nil) ⇒ Object



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

def bump(flag, val = nil)
  return unless (cur = version)

  if flag == :version
    return unless val
  else
    seg = semscan(cur, fill: false)
    case flag
    when :major
      if seg[0] != '0' || seg[2].nil?
        seg[0] = seg[0].succ
      else
        seg[2] = seg[2].succ
      end
    when :minor
      if seg[0] == '0'
        seg[4] &&= seg[4].succ
      else
        seg[2] = seg[2].succ
      end
    when :patch
      seg[4] &&= seg[4].succ
    end
    return if (val = seg.join) == cur
  end

  begin
    doc = dependfile.read
    if doc.sub!(/"version"\s*:\s*"#{cur}"/, "\"version\": \"#{val}\"")
      unless dryrun?
        dependfile.write(doc)
        log.info "bump version #{cur} to #{val} (#{flag})"
        on :first, :bump
      end
      if verbose
        major = flag == :major
        emphasize("version: #{val}", title: name, border: borderstyle, sub: [
          headerstyle,
          { pat: /\A(version:)( )(\S+)(.*)\z/, styles: color(major ? :green : :yellow), index: 3 },
          { pat: /\A(version:)(.*)\z/, styles: theme[major ? :major : :active] }
        ])
      elsif stdin?
        puts val
      end
      on :last, :bump unless dryrun?
    else
      raise_error('version not found', hint: dependfile)
    end
  rescue StandardError => e
    log.debug e
    ret = on :error, :bump, e
    raise if exception && ret != true
  end
end

#compose(target, opts = nil, script: false, args: nil, from: nil) ⇒ Object



782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'lib/squared/workspace/project/node.rb', line 782

def compose(target, opts = nil, script: false, args: nil, from: nil, **)
  return unless target

  if script
    ret = session dependbin, 'run'
    raise_error("#{dependbin} run: given #{target}", hint: from) unless append_any(target, build: true)
    append_any opts
    append_loglevel
    append_any(args, delim: true)
    ret
  else
    case target
    when String
      target
    when Hash
      append_hash(target).join(' ')
    when Enumerable
      target.to_a.join(' ')
    else
      raise_error("compose: given #{target}", hint: from)
    end
  end
end

#copy(from: 'build', into: 'node_modules', scope: nil, also: nil, create: nil, workspace: false, link: false, force: false, override: false, sync: invoked_sync?('copy'), **kwargs) ⇒ Object



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

def copy(from: 'build', into: 'node_modules', scope: nil, also: nil, create: nil, workspace: false,
         link: false, force: false, override: false, sync: invoked_sync?('copy'), **kwargs)
  glob = kwargs[:include]
  pass = kwargs[:exclude]
  if @copy && !override
    return super unless @copy.is_a?(Hash)

    from = @copy[:from] if @copy.key?(:from)
    into = @copy[:into] if @copy.key?(:into)
    workspace = @copy[:workspace] if @copy.key?(:workspace)
    link = @copy[:link] if @copy.key?(:link)
    force = @copy[:force] if @copy.key?(:force)
    scope = @copy[:scope] if @copy.key?(:scope)
    also = @copy[:also] if @copy.key?(:also)
    create = @copy[:create] if @copy.key?(:create)
    glob = @copy[:include] if @copy.key?(:include)
    pass = @copy[:exclude] if @copy.key?(:exclude)
  elsif @copy == false
    return
  end
  items = []
  if build? && path != @workspace.home && @workspace.home?
    items << @workspace.home
    @workspace.rev_clear(@workspace.find(@workspace.home).name, sync: sync)
  end
  items.concat(as_a(also)) if also
  return if items.empty?

  on :first, :copy
  print_item unless @output[0] || !verbose || task_invoked?(/^copy(?::#{Node.ref}|$)/)
  items.each do |dir|
    case dir
    when Pathname
      dest = dir
      @workspace.rev_clear(dest, sync: sync)
    when String
      dest = @workspace.root + dir
      @workspace.rev_clear(dest, sync: sync)
    when Symbol
      if (proj = @workspace.find(name: dir))
        @workspace.rev_clear(proj.name, sync: sync)
        dest = proj.path
      else
        log.warn message("copy project :#{dir}", hint: 'not found')
        dest = nil
      end
    when Hash
      from = dir[:from] if dir.key?(:from)
      into = dir[:into] if dir.key?(:into)
      scope = dir[:scope] if dir.key?(:scope)
      link = dir[:link] if dir.key?(:link)
      force = dir[:force] if dir.key?(:force)
      dest = dir[:target]
      create = dir[:create]
      workspace = dir[:workspace]
      glob = dir[:include]
      pass = dir[:exclude]
      dest = items.first unless dest && dest != true
      @workspace.rev_clear(dest, sync: sync) unless dest == true
    when Project::Base
      dest = dir.path
      @workspace.rev_clear(dir.name, sync: sync)
    else
      raise_error "copy: given #{dir}"
    end
    next unless from && dest&.directory?

    from = path + from
    glob = Array(glob || '**/*')
    target = []
    if workspace
      from.glob('*').each do |entry|
        next unless entry.directory?

        sub = if (proj = @workspace.find(entry))
                proj.packagename
              elsif (file = entry + 'package.json').exist?
                begin
                  doc = JSON.parse(file.read)
                rescue StandardError => e
                  log.error e
                  raise if exception
                else
                  doc['name']
                end
              end
        if sub
          target << [entry, dest.join(into, sub)]
        else
          log.debug message("package.json in \"#{entry}\"", hint: 'not found')
        end
      end
    else
      target << [from, dest.join(into, scope || project)]
    end
    target.each do |src, to|
      glob.each { |val| log.info "cp #{from + val} #{to}" }
      begin
        copy_dir(src, to, glob, create: create, link: link, force: force, pass: pass, verbose: verbose)
      rescue StandardError => e
        log.error e
        ret = on :error, :copy, e
        raise if exception && ret != true
      end
    end
  end
  on :last, :copy
end

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



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

def depend(flag = nil, *, sync: invoked_sync?('depend', flag), packages: [], save: nil, exact: nil, **)
  if @depend && !flag
    super
  elsif outdated?
    workspace.rev_clear(name, sync: sync)
    return update if !flag && env('NODE_UPDATE')

    if (yarn = dependtype(:yarn)) > 0
      cmd = session 'yarn'
      if flag == :add
        cmd << 'add'
        cmd << "--#{save}" unless save == 'prod'
        cmd << '--exact' if exact
      else
        cmd << 'install'
        cmd << '--ignore-engines' if yarn == 1 && !option('ignore-engines', equals: '0')
      end
    elsif pnpm?
      cmd = session 'pnpm'
      if flag == :add
        cmd << 'add' << "--save-#{save}"
        cmd << '--save-exact' if exact
      else
        cmd << 'install'
      end
      option('public-hoist-pattern', ignore: false) do |val|
        split_escape(val).each { |opt| cmd << shell_option('public-hoist-pattern', opt) }
      end
      cmd << '--ignore-workspace' if env('NODE_WORKSPACES', equals: '0')
      append_nocolor
    else
      cmd = session 'npm', 'install'
      if flag == :add
        cmd << "--save-#{save}"
        cmd << '--save-exact' if exact
        cmd.merge(packages.map { |pkg| shell_escape(pkg) })
      end
      cmd << '--workspaces=false' if env('NODE_WORKSPACES', equals: '0')
      cmd << '--package-lock=false' if option('package-lock', equals: '0')
      append_nocolor
    end
    append_loglevel
    run(from: :depend, sync: sync)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


806
807
808
# File 'lib/squared/workspace/project/node.rb', line 806

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

#dependtype(prog) ⇒ Object



882
883
884
885
886
887
# File 'lib/squared/workspace/project/node.rb', line 882

def dependtype(prog)
  return @pm[prog] if @pm.key?(prog)

  meth = :"#{prog}?"
  respond_to?(meth) && __send__(meth) ? @pm[prog] : 0
end

#dev?Boolean

Returns:

  • (Boolean)


874
875
876
# File 'lib/squared/workspace/project/node.rb', line 874

def dev?
  super && (!Node.prod? || (@dev == true && !prod?))
end

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



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
# File 'lib/squared/workspace/project/node.rb', line 438

def outdated(flag = nil, opts = [], sync: invoked_sync?('outdated', flag))
  dryrun = opts.include?('dry-run') || opts.include?('d')
  if pnpm? && read_packagemanager(version: '7.15', update: true)
    cmd = session 'pnpm', 'outdated'
    dryrun ||= dryrun?('pnpm')
  else
    cmd = session 'npm', 'outdated'
    dryrun ||= dryrun?('npm')
  end
  unless dryrun
    log.info cmd.to_s
    on :first, :outdated
  end
  banner = format_banner(cmd.temp(dryrun ? ' --dry-run' : nil))
  print_item banner if sync
  begin
    data = pwd_set { `#{cmd.temp('--json', '--loglevel=error')}` }
    doc = dependfile.read
    json = JSON.parse(doc)
  rescue StandardError => e
    log.error e
    unless dryrun
      ret = on :error, :outdated, e
      raise if exception && ret != true
    end
    warn log_message(Logger::WARN, e) if warning?
    return
  else
    dep1 = json['dependencies'] || {}
    dep2 = json['devDependencies'] || {}
    target = json['name']
  end
  found = []
  avail = []
  rev = flag || (prod? ? :patch : :minor)
  inter = opts.include?('interactive') || opts.include?('i')
  unless data.empty?
    JSON.parse(data).each_pair do |key, val|
      val = val.find { |obj| obj['dependent'] == target } if val.is_a?(Array)
      next unless val && (file = dep1[key] || dep2[key]) && file != '*'

      latest = val['latest']
      ch = file[0]
      if ch.match?(/[~^]/)
        file = file[1..-1]
      elsif inter && rev == :major
        major = true
      else
        avail << [key, file, latest, true]
        next
      end
      current = val['current'] || file
      want = rev == :major && !latest[SEM_VER, 6] ? latest : val['wanted']
      next unless (current != want || file != want) && (want.match?(SEM_VER) || !file.match?(SEM_VER))

      f = semscan file
      w = semscan want
      a = f[0]
      b = f[2]
      c = w[0]
      d = w[2]
      case rev
      when :major
        upgrade = a == '0' ? c == '0' || c == '1' : true
      when :minor
        upgrade = ch == '^' && (a == '0' ? c == '0' && b == d : a == c)
      when :patch
        upgrade = a == c && b == d && f[4] != w[4]
      end
      if upgrade && !w[5]
        next if file == want

        found << [key, file, want, if a != c
                                     1
                                   elsif b != d
                                     a == '0' ? 1 : 3
                                   else
                                     5
                                   end, major, f, w]
      elsif !major
        avail << [key, file, latest, latest != current]
      end
    end
  end
  pending = 0
  modified = 0
  size_col = ->(items, i) { items.map { |a| a[i] }.max_by(&:size).size }
  pad_ord = lambda do |val, ord|
    ret = val.succ.to_s
    ord.size > 9 ? ret.rjust(ord.size.to_s.size) : ret
  end
  footer = lambda do |val, size|
    next unless verbose

    msg, hint = if modified == -1
                  ['Packages were updated', 'more possible']
                else
                  ['No packages were updated', 'possible']
                end
    possible = pending + val
    puts print_footer(empty_status(msg, hint, possible == size ? 0 : possible))
  end
  print_item banner unless sync
  if !found.empty?
    col1 = size_col.call(found, 0) + 4
    col2 = size_col.call(found, 1) + 4
    found.each_with_index do |item, i|
      a, b, c, d, e = item
      f = inter && (rev != :major || e || semmajor?(item[5], item[6]))
      if f && !confirm_outdated(a, c, (d / 2.0).ceil, b, lock: e, col1: col1)
        cur = -1
      else
        cur = modified
        doc.sub!(/("#{Regexp.escape(a)}"\s*:\s*)"([~^])#{e ? '?' : ''}#{Regexp.escape(b)}"/) do |capture|
          if $2 == '~' && rev != :patch
            cur = -1
            pending += 1
            capture
          else
            modified += 1
            "#{$1}\"#{$2 || (d == 1 && e ? '^' : '')}#{c}\""
          end
        end
      end
      a = a.ljust(col1)
      b = b.ljust(col2)
      b = sub_style(b, styles: theme[:current]) if theme[:current]
      c = if cur == -1
            'SKIP'
          elsif modified == cur
            'FAIL'
          elsif d == 1
            a = sub_style(a, styles: theme[:major])
            sub_style(c, :bold, styles: color(:green))
          else
            sub_style(c, pat: SEM_VER, styles: color(d == 3 ? :green : :yellow), index: d)
          end
      puts "#{pad_ord.call(i, found)}. #{a + b + c}"
    end
    pending = avail.reduce(pending) { |a, b| a + (b[3] ? 0 : 1) }
    if dryrun || (modified == 0 && pending > 0)
      footer.call(modified, found.size)
    elsif modified > 0
      modified = -1
      footer.call(0, found.size)
      File.write(dependfile, doc)
      commit(:add, refs: ['package.json'], pass: true)
      install if opts.include?('prune') || opts.include?('p')
    end
  elsif !avail.empty?
    col1 = size_col.call(avail, 0) + 4
    col2 = size_col.call(avail, 1)
    col3 = size_col.call(avail, 2) + 4
    avail.each_with_index do |item, i|
      a, b, c, d = item
      a = a.ljust(col1)
      b = sub_style(b.ljust(col2), styles: color(d ? :red : :yellow))
      c = c.ljust(col3)
      unless d
        a = sub_style(a, styles: theme[:active])
        c = sub_style(c, styles: color(:green))
        pending += 1
      end
      puts "#{pad_ord.call(i, avail)}. #{a + c + b} (#{d ? 'locked' : 'latest'})"
    end
    footer.call(0, avail.size)
  else
    puts 'No updates were found'
  end
  on :last, :outdated unless dryrun
end

#outdated?Boolean

Returns:

  • (Boolean)


810
811
812
# File 'lib/squared/workspace/project/node.rb', line 810

def outdated?
  dependfile.exist?
end

#pack(opts = []) ⇒ Object



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

def pack(opts = [])
  return unless version

  cmd = session dependbin, 'pack'
  if dependtype(:yarn) > 1
    op = OptionPartition.new(opts, OPT_BERRY[:pack], cmd, project: self)
    op << quote_option('out', Pathname.pwd + "#{project}-#{version}.tgz") unless op.arg?('out')
  else
    op = OptionPartition.new(opts, pnpm? ? OPT_PNPM[:pack] : OPT_NPM[:pack] + OPT_NPM[:common], cmd,
                             project: self)
    unless pnpm?
      op.each do |opt|
        next unless opt =~ op.values

        case $1
        when 'w', 'workspace'
          op << ($2.match?(%r{[\\/]}) ? quote_option($1, path + $2) : shell_option($1, $2))
          op.found << opt
        end
      end
    end
    op << quote_option('pack-destination', Dir.pwd) unless op.arg?('pack-destination')
  end
  op.clear
  run(from: :pack)
end

#package(flag, opts = [], from: nil) ⇒ Object



646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/squared/workspace/project/node.rb', line 646

def package(flag, opts = [], from: nil)
  workspace.rev_clear(name)
  if (yarn = dependtype(:yarn)) > 0
    cmd = session 'yarn', if flag == :update
                            flag = yarn == 1 ? 'upgrade' : 'up'
                          else
                            flag
                          end
    op = OptionPartition.new(opts, if yarn == 1
                                     OPT_YARN.fetch(flag, []) + OPT_YARN[:common]
                                   else
                                     OPT_BERRY[flag]
                                   end, cmd, project: self)
    op.clear
    append_loglevel
  else
    if pnpm?
      cmd = session 'pnpm', flag
      list = OPT_PNPM[:install_base] + OPT_PNPM.fetch(flag, []) + OPT_PNPM[:common]
      list.concat(OPT_PNPM[:install_as] + OPT_PNPM[:filter]) unless flag == :dedupe
      no = OPT_PNPM[:"#{flag}_no"]
    else
      cmd = session 'npm', flag
      list = OPT_NPM[:install_base] + OPT_NPM.fetch(flag, []) + OPT_NPM[:common]
      list.concat(OPT_NPM[:install_as]) unless flag == :dedupe
      no = OPT_NPM[:install_no]
      cmd << '--save=true' if option('save')
    end
    op = OptionPartition.new(opts, list, cmd, no: no, project: self)
    op.each do |opt|
      if opt =~ op.values
        case $1
        when 'w', 'workspace'
          op << ($2.match?(%r{[\\/]}) ? quote_option($1, path + $2) : shell_option($1, $2))
        end
      elsif opt.include?('=')
        op.errors << opt
      else
        op.found << opt
      end
    end
    op.swap
    append_nocolor
    append_loglevel
    if flag == :dedupe
      op.clear
    else
      op.append(escape: true)
    end
    op.clear(errors: true)
  end
  run(from: from || :"package:#{flag}")
end

#packagenameObject



893
894
895
# File 'lib/squared/workspace/project/node.rb', line 893

def packagename
  read_packagemanager :name
end

#pnpm?Boolean

Returns:

  • (Boolean)


843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
# File 'lib/squared/workspace/project/node.rb', line 843

def pnpm?
  (@pm[:pnpm] ||= if rootpath('pnpm-lock.yaml', ascend: dependext).exist?
                    begin
                      require 'yaml'
                      doc = YAML.load_file(basepath('node_modules/.modules.yaml', ascend: dependext))
                      @pm[:_] = doc['packageManager']
                      case doc['nodeLinker']
                      when 'hoisted'
                        1
                      when 'pnp'
                        3
                      else
                        4
                      end
                    rescue StandardError => e
                      log.debug e
                      4
                    end
                  else
                    (read_packagemanager || read_install)&.start_with?('pnpm') ? 4 : 0
                  end) > 0
end

#populateObject



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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
# File 'lib/squared/workspace/project/node.rb', line 118

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

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

      if flags.nil?
        case action
        when 'add'
          format_desc action, nil, 'save?=prod|dev|optional|peer,name+'
          task action, [:save] do |_, args|
            save = param_guard(action, 'save', args: args, key: :save)
            if save.start_with?('=')
              exact = true
              save = save[1..-1]
            end
            case save
            when 'prod', 'dev', 'optional', 'peer'
              packages = args.extras
            else
              save = 'prod'
              packages = args.to_a
            end
            param_guard(action, 'name', args: packages)
            depend(:add, packages: packages, save: save, exact: exact)
          end
        when 'run'
          next if (list = read_scripts).empty?

          format_desc action, nil, "script,opts*|#{indexchar}index+|#,pattern*"
          task action, [:script] do |_, args|
            if args.script == '#'
              format_list(list, "run[#{indexchar}N]", 'scripts', grep: args.extras, from: dependfile)
            else
              args = param_guard(action, 'script', args: args.to_a)
              opts = []
              args.each do |val|
                if (n, extra = indexitem(val))
                  if (item = list[n - 1])
                    val = extra ? "#{item.first} #{extra}" : item.first
                  elsif exception
                    indexerror n, list
                  else
                    next log.warn "run script #{n} of #{list.size} (out of range)"
                  end
                  run compose(val, script: true)
                else
                  opts << val
                end
              end
              next if opts.empty?

              list = if (yarn = dependtype(:yarn)) > 0
                       yarn == 1 ? OPT_YARN[:run] + OPT_YARN[:common] : OPT_BERRY[:run]
                     elsif pnpm?
                       OPT_PNPM[:run] + OPT_PNPM[:filter] + OPT_PNPM[:common]
                     else
                       OPT_NPM[:run] + OPT_NPM[:common]
                     end
              op = OptionPartition.new(opts, list, session(dependbin, 'run'), project: self)
              op << op.extras.shift
              op.append(delim: true, quote: false)
              run(from: :run)
            end
          end
        when 'exec'
          format_desc action, nil, 'pkg/cmd,opts*,args*'
          task action, [:package] do |_, args|
            if (package = args.package)
              args = args.extras
              if pnpm?
                pre = ->(ch) { "-#{ch}" if (ch = args.delete(ch)) }
                cmd = session 'pnpm', pre.call('r'), pre.call('c'), 'exec'
                list = OPT_PNPM[:exec] + OPT_PNPM[:filter] + OPT_PNPM[:common]
              else
                cmd = session 'npm', 'exec'
                list = OPT_NPM[:exec] + OPT_NPM[:common]
              end
              op = OptionPartition.new(args, list, cmd, project: self)
              if op.empty?
                op << package
                if (args = readline('Enter arguments', force: false))
                  op << '--' unless pnpm?
                  op << args
                end
              else
                op << '--' unless pnpm?
                op << package << op.join(' ')
              end
            else
              session 'npm', 'exec', quote_option('c', readline('Enter command', force: true), double: true)
            end
            run(from: :exec)
          end
        when 'nvm'
          next unless ENV['NVM_DIR']

          format_desc action, nil, 'version,args*'
          task action, [:version] do |_, args|
            version = param_guard(action, 'version', args: args, key: :version)
            args = args.extras
            args << readline('Enter command', force: true) if args.empty?
            args.prepend(File.join(ENV['NVM_DIR'], 'nvm-exec'))
            run(args.join(' '), { 'NODE_VERSION' => version }, banner: false, from: :nvm)
          end
        when 'pack'
          format_desc action, nil, 'opts*'
          task action do |_, args|
            pack args.to_a
          end
        end
      else
        namespace action do
          flags.each do |flag|
            case action
            when 'outdated'
              format_desc(action, flag, %w[prune interactive dry-run].freeze, arg: 'opts?')
              task flag do |_, args|
                outdated flag, args.to_a
              end
            when 'package'
              format_desc(action, flag, 'opts*', after: flag == :dedupe ? nil : 'name*')
              task flag do |_, args|
                package flag, args.to_a
              end
            when 'bump'
              if flag == :version
                format_desc action, flag, 'version'
                task flag, [:version] do |_, args|
                  version = param_guard(action, flag, args: args, key: :version)
                  bump flag, version
                end
              else
                format_desc action, flag
                task flag do
                  bump flag
                end
              end
            when 'publish'
              format_desc(action, flag, 'otp?,dry-run?,public|restricted?', before: flag == :tag ? 'tag' : nil)
              task flag do |_, args|
                args = args.to_a
                dryrun = true if args.delete('dry-run') || args.delete('d')
                if args.delete('public') || args.delete('p')
                  access = 'public'
                elsif args.delete('restricted') || args.delete('r')
                  access = 'restricted'
                end
                if flag == :latest
                  otp = args.first
                else
                  tag, otp = param_guard(action, flag, args: args)
                end
                publish(flag, otp: otp, tag: tag, dryrun: dryrun, access: access)
              end
            end
          end
        end
      end
    end
  end
end

#prod?Boolean

Returns:

  • (Boolean)


878
879
880
# File 'lib/squared/workspace/project/node.rb', line 878

def prod?
  @prod != false && (Node.prod? || super)
end

#publish(flag = nil, sync: invoked_sync?('publish', flag), otp: nil, tag: nil, dryrun: nil, access: nil) ⇒ Object



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/squared/workspace/project/node.rb', line 614

def publish(flag = nil, *, sync: invoked_sync?('publish', flag), otp: nil, tag: nil, dryrun: nil, access: nil)
  if !version || read_packagemanager(:private)
    warn log_message(Logger::WARN, 'invalid task "publish"', subject: name, hint: version ? 'private' : nil)
    return
  end
  cmd = session 'npm', 'publish'
  cmd << basic_option('otp', otp) if otp ||= option('otp')
  cmd << basic_option('tag', tag) if tag ||= option('tag')
  cmd << basic_option('access', access) if access ||= option('access')
  dryrun = dryrun?('npm') if dryrun.nil?
  if dryrun
    cmd << '--dry-run'
  else
    from = :publish
    log.info cmd.to_s
  end
  if sync
    run(from: from, sync: sync, interactive: !dryrun && "Publish #{sub_style(project, styles: theme[:active])}")
  else
    on :first, from
    pwd_set(from: from) do
      require 'open3'
      banner = format_banner cmd.to_s
      Open3.popen2e(cmd.done) do |_, out|
        write_lines(out, sub: npmnotice + [pat: /^(.+)(Tarball .+)$/, styles: color(:blue), index: 2],
                         banner: banner)
      end
    end
    on :last, from
  end
end

#refObject



114
115
116
# File 'lib/squared/workspace/project/node.rb', line 114

def ref
  Node.ref
end

#refresh?Boolean

Returns:

  • (Boolean)


818
819
820
# File 'lib/squared/workspace/project/node.rb', line 818

def refresh?
  !Node.prod?
end

#updateObject



610
611
612
# File 'lib/squared/workspace/project/node.rb', line 610

def update(*)
  package('update', from: :update)
end

#update?Boolean

Returns:

  • (Boolean)


814
815
816
# File 'lib/squared/workspace/project/node.rb', line 814

def update?
  outdated?
end

#versionObject



889
890
891
# File 'lib/squared/workspace/project/node.rb', line 889

def version
  super || (@version = read_packagemanager(:version))
end

#workspaces?Boolean

Returns:

  • (Boolean)


866
867
868
869
870
871
872
# File 'lib/squared/workspace/project/node.rb', line 866

def workspaces?
  if pnpm?
    basepath('pnpm-workspace.yaml').exist?
  else
    read_packagemanager(:workspaces).is_a?(Array)
  end
end

#yarn?Boolean

Returns:

  • (Boolean)


822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/squared/workspace/project/node.rb', line 822

def yarn?
  (@pm[:yarn] ||= if rootpath('yarn.lock', ascend: dependext).exist?
                    if (rc = rootpath('.yarnrc.yml', ascend: dependext)).exist?
                      begin
                        require 'yaml'
                        doc = YAML.load_file(rc)
                        doc.nodeLinker == 'node-modules' ? 2 : 3
                      rescue StandardError => e
                        log.debug e
                        3
                      end
                    else
                      1
                    end
                  elsif (ver = read_packagemanager || read_install)&.start_with?('yarn')
                    ver == 'yarn' || ver.include?('@1') ? 1 : 3
                  else
                    0
                  end) > 0
end