Class: Squared::Repo::Project::Node

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

Instance Attribute Summary

Attributes inherited from Base

#group, #name, #path, #project, #workspace

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Git

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

Methods included from Common::Format

#check_style, #emphasize, #log_message, #log_title, #sub_style

Methods inherited from Base

#base_path, #build, #build?, #clean, #clean?, #doc, #doc?, #enabled?, #has?, #refresh, #refresh?, #styles, to_s, #to_s, #to_sym, #verbose?

Methods included from Common

#as_a, #get, #message, #set

Constructor Details

#initialize(name, project, workspace, **kwargs) ⇒ Node

Returns a new instance of Node.



34
35
36
37
38
39
40
# File 'lib/squared/repo/project/node.rb', line 34

def initialize(name, project, workspace, **kwargs)
  super
  @clean ||= ['build/']
  @dev = workspace.bool_match(env('BUILD', suffix: 'DEV'), kwargs.delete(:dev))
  @prod = workspace.bool_match(env('BUILD', suffix: 'PROD'), kwargs.delete(:prod))
  @package = {}
end

Class Method Details

.is_a?(path) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
25
26
# File 'lib/squared/repo/project/node.rb', line 20

def is_a?(path)
  if path.is_a?(::String) || path.is_a?(::Pathname)
    Pathname.new(path).join('package.json').exist?
  else
    super
  end
end

.prod?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/squared/repo/project/node.rb', line 16

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

.tasksObject



8
9
10
# File 'lib/squared/repo/project/node.rb', line 8

def tasks
  nil
end

.to_symObject



12
13
14
# File 'lib/squared/repo/project/node.rb', line 12

def to_sym
  :node
end

Instance Method Details

#compose(opts) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/squared/repo/project/node.rb', line 275

def compose(opts)
  cmd = [if yarn?
           'yarn'
         else
           pnpm? ? 'pnpm' : 'npm'
         end]
  cmd << 'run'
  append_loglevel cmd
  if opts.is_a?(::Array)
    cmd += opts
  else
    cmd << (opts || @workspace.script)
  end
  cmd.join(' ')
end

#copy(from: 'build', glob: '**/*', basedir: 'node_modules', into: nil, also: [], override: false) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/squared/repo/project/node.rb', line 69

def copy(from: 'build', glob: '**/*', basedir: 'node_modules', into: nil, also: [], override: false)
  if @copy && !override
    return super if @copy.is_a?(::String)

    from = @copy[:from] if @copy.key?(:from)
    glob = @copy[:glob] if @copy.key?(:glob)
    basedir = @copy[:basedir] if @copy.key?(:basedir)
    into = @copy[:into] if @copy.key?(:into)
    also = @copy[:also] if @copy.key?(:also)
  end
  return unless basedir

  items = [@project == @workspace.main ? nil : @workspace.home].concat(as_a(also))
  items.each_with_index do |dir, i|
    if i == 0
      next unless dev? & !doc?

      dest = dir
    elsif dir.is_a?(::String)
      dest = @workspace.root_path(dir)
    elsif dir.is_a?(::Symbol)
      dest = Repo.resolve(dir)&.path
    elsif dir.is_a?(Project)
      dest = dir.path
    elsif dir.is_a?(::Hash)
      into = nil
      glob = nil
      dir.each do |key, val|
        case key.to_sym
        when :from
          from = val
        when :glob
          glob = val
        when :basedir
          basedir = val
        when :into
          into = val
        end
      end
      next unless into
    end
    next unless dest&.directory?

    from = base_path(from)
    dest = dest.join(basedir, into || @project)
    warn "cp #{from.join(glob)} #{dest}"
    copy_d(from, dest, glob: glob, verbose: verbose?)
  end
end

#copy?Boolean

Returns:

  • (Boolean)


301
302
303
# File 'lib/squared/repo/project/node.rb', line 301

def copy?
  !@copy.nil?
end

#depend(flag = nil) ⇒ Object



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

def depend(flag = nil)
  if @depend
    super
  else
    force = flag == :force
    dedupe = flag == :dedupe
    if (yarn = install_type(:yarn)) > 0
      cmd = session 'yarn', 'install'
      if yarn > 1
        cmd << '--check-cache' if force
      else
        cmd << '--production' if prod?
        cmd << '--force' if force
        cmd << '--ignore-engines' unless env('YARN_IGNORE_ENGINES', equals: '0')
      end
    elsif pnpm?
      cmd = session 'pnpm'
      if dedupe
        cmd << 'dedupe'
      else
        cmd << 'install'
        cmd << '--force' if force
      end
      cmd << '--prod' if prod?
      append_nocolor
    else
      cmd = session 'npm'
      cmd << (dedupe ? 'dedupe' : 'install')
      cmd << '--omit=dev' if prod?
      cmd << '--force' if force
      append_nocolor
    end
    append_loglevel
    run(exception: @workspace.exception)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


297
298
299
# File 'lib/squared/repo/project/node.rb', line 297

def depend?
  !@depend.nil? || outdated?
end

#dev?Boolean

Returns:

  • (Boolean)


353
354
355
356
357
# File 'lib/squared/repo/project/node.rb', line 353

def dev?
  return false if Node.prod?

  @workspace.dev?(@dev, script: @output.last)
end

#install_type(prog) ⇒ Object



291
292
293
294
295
# File 'lib/squared/repo/project/node.rb', line 291

def install_type(prog)
  key = :"#{prog}?"
  send(key) if respond_to?(key)
  @package[prog.to_sym] || 0
end

#outdated(rev = nil, opts: []) ⇒ Object



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

def outdated(rev = nil, opts: [])
  require 'json'
  rev ||= prod? ? :patch : :minor
  cmd = pnpm? ? 'pnpm outdated' : 'npm outdated'
  print_item format_banner(message("#{cmd}#{opts.include?('dry-run') ? ' --dry-run' : ''}"), multitask: true)
  pwd = Dir.pwd
  Dir.chdir(@path)
  info cmd
  data = `#{cmd} --json --loglevel=error`
  Dir.chdir(pwd)
  target = base_path('package.json')
  doc = File.read(target)
  json = JSON.parse(doc)
  dep1 = json['dependencies'] || {}
  dep2 = json['devDependencies'] || {}
  found = []
  avail = []
  if !data.empty?
    validate = ->(ver) { /^\d+\.\d+\.\d+$/.match?(ver) }
    JSON.parse(data).each_pair do |key, val|
      file = dep1[key] || dep2[key]
      ch = file[0]
      if !/[~^]/.match?(ch)
        avail << [key, file, val['latest'], true]
        next
      end
      file = file[1..-1]
      cur = val['current']
      want = if rev == :major && validate.(val['latest'])
               [val['latest'], val['wanted']].max { |a, b| a <=> b }
             else
               val['wanted']
             end
      next unless (cur != want || file != want) && (validate.(want) || !validate.(file))

      a, b = file.split('.')
      c, d = want.split('.')
      upgrade = false
      case rev
      when :major
        upgrade = a == '0' ? c == '0' : true
      when :minor
        upgrade = ch == '^' && (a == '0' ? c == '0' && b == d : a == c)
      when :patch
        upgrade = a == c && b == d
      end
      if upgrade
        next if file == want

        found << [key, file, want]
      else
        avail << [key, file, val['latest'], false]
      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 = 0|
    next unless verbose?

    msg, hint = if modified == -1
                  ['Packages were updated', 'more possible']
                else
                  ['No packages were updated', 'possible']
                end
    puts Project.footer(empty_status(msg, hint, pending + val))
  end
  if !found.empty?
    col1 = size_col.(found, 0)
    col2 = size_col.(found, 1)
    found.each_with_index do |item, i|
      a, b, c = item
      cur = modified
      doc.sub!(/("#{Regexp.escape(a)}"\s*:\s*)"([~^])#{Regexp.escape(b)}"/) do |capture|
        if $2 == '~' && rev != :patch
          cur = -1
          pending += 1
          capture
        else
          modified += 1
          "#{$1}\"#{$2 || ''}#{c}\""
        end
      end
      hint = if cur == -1
               'SKIP'
             else
               modified > cur ? c : 'FAIL'
             end
      puts "#{pad_ord.(i, found)}. #{a.ljust(col1)}\t#{b.ljust(col2)}\t#{hint}"
    end
    pending = avail.reduce(pending) { |a, b| a + (b[3] ? 0 : 1) }
    if opts.include?('dry-run') || (modified == 0 && pending > 0)
      footer.(modified)
    elsif modified > 0
      File.write(target, doc)
      modified = -1
      footer.()
      commit(:add, 'package.json', pass: true)
      install if opts.include?('prune')
    end
  elsif !avail.empty?
    col1 = size_col.(avail, 0)
    col2 = size_col.(avail, 2)
    avail.each_with_index do |item, i|
      a, b, c, d = item
      puts "#{pad_ord.(i, avail)}. #{a.ljust(col1)}\t#{c.ljust(col2)}\t#{d ? 'locked at' : 'from'} #{b}"
      pending += 1 unless d
    end
    footer.()
  else
    puts 'No updates were found'
  end
end

#outdated?Boolean

Returns:

  • (Boolean)


305
306
307
# File 'lib/squared/repo/project/node.rb', line 305

def outdated?
  base_path('package.json').exist?
end

#pnpm?Boolean

Returns:

  • (Boolean)


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/squared/repo/project/node.rb', line 332

def pnpm?
  (@package[:pnpm] ||= if File.exist?(base_path('pnpm-lock.yaml'))
                         begin
                           require 'yaml'
                           doc = YAML.load_file(base_path('node_modules/.modules.yaml'))
                           case doc['nodeLinker']
                           when 'hoisted'
                             1
                           when 'pnp'
                             3
                           else
                             4
                           end
                         rescue StandardError
                           4
                         end
                       else
                         env('NODE_INSTALL')&.start_with?('pnpm') ? 4 : 0
                       end) > 0
end

#populateObject



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

def populate(*)
  super
  return unless outdated?

  namespace @name do
    @@tasks[:node].each do |action, flags|
      namespace action do
        flags.each do |flag|
          case action
          when :install
            desc format_desc(action, flag)
            task flag do
              install flag
            end
          when :outdated
            desc format_desc(action, flag, %w[prune dry-run], req: 'opts?')
            task flag, [:opts] do |_, args|
              opts = collect_args(args, :opts)
              outdated(flag, opts: opts)
            end
          end
        end
      end
    end
  end
end

#prod?Boolean

Returns:

  • (Boolean)


359
360
361
362
363
# File 'lib/squared/repo/project/node.rb', line 359

def prod?
  return true if Node.prod?

  @workspace.prod?(@prod, script: @output.last)
end

#yarn?Boolean

Returns:

  • (Boolean)


309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/squared/repo/project/node.rb', line 309

def yarn?
  (@package[:yarn] ||= if File.exist?(base_path('yarn.lock'))
                         if File.exist?(rc = base_path('.yarnrc.yml'))
                           begin
                             require 'yaml'
                             doc = YAML.load_file(rc)
                             doc.nodeLinker == 'node-modules' ? 2 : 3
                           rescue StandardError
                             3
                           end
                         else
                           1
                         end
                       else
                         ver = env('NODE_INSTALL')
                         if ver&.start_with?('yarn')
                           ver.include?('@1') ? 1 : 3
                         else
                           0
                         end
                       end) > 0
end