Class: Squared::Workspace::Project::Python

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

Constant Summary

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary collapse

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, aliasargs, #allref, #archive, #archive?, #as, as_path, #basepath, batchargs, #build, #build?, #chain, #clean, #clean?, #copy, #copy?, #dependtype, #dev?, #doc, #doc?, #enabled?, #error, #event, #exclude?, #first, #generate, #graph, #graph?, #has?, #initialize_build, #initialize_env, #initialize_events, #initialize_logger, #initialize_ref, #inject, #inspect, #last, #lint, #lint?, #localname, #log, #prereqs, #prereqs?, #prod?, ref, #ref?, #rootpath, #script?, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #version, #with

Methods included from Common::Format

#enable_aixterm, #enable_drawing

Constructor Details

#initialize(editable: '.', verbose: nil, **kwargs) ⇒ Python

Returns a new instance of Python.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/squared/workspace/project/python.rb', line 81

def initialize(*, editable: '.', verbose: nil, **kwargs)
  super
  if @pass.include?(Python.ref)
    initialize_ref Python.ref
    initialize_logger(**kwargs)
  else
    initialize_build(Python.ref, **kwargs)
    initialize_env(**kwargs)
  end
  @verbose = verbose.size if verbose.is_a?(String) && verbose.match?(/\Av+\z/)
  dependfile_set DEP_PYTHON
  editable_set editable
  venv_set kwargs[:venv]
end

Instance Attribute Details

#editableObject (readonly)

Returns the value of attribute editable.



79
80
81
# File 'lib/squared/workspace/project/python.rb', line 79

def editable
  @editable
end

#venvObject (readonly)

Returns the value of attribute venv.



79
80
81
# File 'lib/squared/workspace/project/python.rb', line 79

def venv
  @venv
end

Class Method Details

.bannerargsObject



64
65
66
# File 'lib/squared/workspace/project/python.rb', line 64

def bannerargs
  %i[dependfile venv].freeze
end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
75
76
# File 'lib/squared/workspace/project/python.rb', line 72

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

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

.populateObject



58
# File 'lib/squared/workspace/project/python.rb', line 58

def populate(*); end

.tasksObject



60
61
62
# File 'lib/squared/workspace/project/python.rb', line 60

def tasks
  [:outdated].freeze
end

.venv?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/squared/workspace/project/python.rb', line 68

def venv?
  Dir.exist?(ENV.fetch('VIRTUAL_ENV', ''))
end

Instance Method Details

#build!(flag, opts = []) ⇒ Object



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

def build!(flag, opts = [])
  case flag
  when :python
    cmd, opts = python_session('-m build', opts: opts)
    list = OPT_PYTHON[:build]
  when :poetry
    cmd = poetry_session 'build'
    list = OPT_POETRY[:build] + OPT_POETRY[:common]
  when :pdm
    cmd, opts = pdm_session('build', opts: opts)
    list = OPT_PDM[:build]
  when :hatch
    cmd, opts = hatch_session('build', opts: opts)
    list = OPT_HATCH[:build]
  end
  srcdir = nil
  op = OptionPartition.new(opts, list, cmd, project: self, single: singleopt(flag))
  op.each do |opt|
    if !srcdir && basepath(opt.chomp('*')).exist? && projectpath?(opt.chomp('*'))
      srcdir = opt
    else
      op.found << opt
    end
  end
  op.swap
  case flag
  when :poetry, :pdm
    if srcdir
      args = flag == :pdm ? ['d', 'dest'] : ['o', 'output']
      if op.arg?(*args)
        op.extras << srcdir
      else
        op << quote_option(args.last, path + srcdir)
      end
      srcdir = nil
    end
  when :hatch
    if ENV['HATCH_BUILD_LOCATION']
      srcdir = nil
    else
      srcdir ||= path
    end
    op << basic_option('p', project) unless ENV['HATCH_PROJECT'] || op.arg?('p', 'project')
  end
  op << shell_quote(path + srcdir) if srcdir
  op.clear
  run(from: :"#{flag}:build")
end

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



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

def depend(flag = nil, opts = [], sync: invoked_sync?('depend', flag), target: nil, **)
  if @depend && !flag
    super
  elsif outdated?
    venv_init
    workspace.rev_clear(name, sync: sync)
    if !flag && dependtype == 1
      cmd = poetry_session 'install', '-n'
      cmd << '--no-root' if option('no-root')
    else
      cmd = pip_session 'install'
      if flag
        case flag
        when :user
          cmd << '--user'
        when :target
          cmd << quote_option('target', path + target)
        when :force
          cmd << '--force-reinstall'
        end
        append_pip(flag, opts, from: :install)
      else
        append_global
      end
      cmd << "-r #{DEP_PYTHON[4]}" if basepath(DEP_PYTHON[4]).exist? && !session_arg?('r', 'requirement')
      append_editable
    end
    run(from: :depend, sync: sync)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


585
586
587
# File 'lib/squared/workspace/project/python.rb', line 585

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

#install(flag, opts = [], strategy: nil) ⇒ Object



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/squared/workspace/project/python.rb', line 442

def install(flag, opts = [], strategy: nil)
  cmd = pip_session 'install'
  out = append_pip(flag, opts, from: :install)
  case flag
  when :editable
    cmd << quote_option('e', out.pop || editable || '.')
    option_clear out
  when :upgrade
    raise_error('no packages listed', hint: flag) if out.empty?
    cmd << '--upgrade'
    cmd << basic_option('upgrade-strategy', strategy) if strategy
    append_value out
  end
  run(from: :install)
end

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



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/squared/workspace/project/python.rb', line 353

def outdated(flag = nil, opts = [], sync: invoked_sync?('outdated'))
  cmd = pip_session 'list', '--outdated'
  append_global
  cmd = session_done cmd
  log.info cmd
  on :first, :outdated
  banner = format_banner cmd
  print_item banner if sync
  start = 0
  found = 0
  major = []
  minor = []
  patch = []
  pwd_set(from: :outdated) do
    buffer = []
    out = ->(val) { sync ? puts(val) : buffer << val }
    IO.popen(runenv || {}, cmd).each do |line|
      next if line.match?(/^[ -]+$/)

      if start > 0
        unless stdin?
          cur, lat = line.scan(SEM_VER)
          next unless cur && lat

          latest = lat.join
          current = cur.join
          semver cur
          semver lat
          name = line.split(' ', 2).first
          type = if semmajor?(cur, lat)
                   major << name
                   2
                 elsif cur[2] == lat[2]
                   patch << name
                   0
                 else
                   minor << name
                   1
                 end
          if type == 0
            styles = color(:yellow)
          else
            styles = color(:green)
            line = sub_style(line, pat: /^(\S+)(.+)$/, styles: if type == 2
                                                                 styles << :bold
                                                                 theme[:major]
                                                               else
                                                                 theme[:active]
                                                               end)
          end
          if theme[:current]
            line = sub_style(line, pat: /^(.+)(#{Regexp.escape(current)})(.+)$/, styles: theme[:current],
                                   index: 2)
          end
          line = sub_style(line, pat: /^(.+)(#{Regexp.escape(latest)})(.+)$/, styles: styles, index: 2)
          found += 1
        end
        out.call("#{start.to_s.rjust(2)}. #{line}")
        start += 1
      elsif line.start_with?('Package')
        unless stdin?
          sub = { pat: /^(.*)(?<!\dm)(Package|Latest)(.+)$/, styles: theme[:header], index: 2 }
          out.call(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
      print_status(major.size, minor.size, patch.size, from: :outdated)
      pkg = case flag
            when :major
              major + minor + patch
            when :minor
              minor + patch
            when :patch
              patch
            end
      install(:upgrade, pkg, strategy: opts.include?('eager') ? 'eager' : nil) unless !pkg || pkg.empty?
    elsif start == 0
      puts 'No updates were found'
    end
  end
  on :last, :outdated
end

#outdated?Boolean

Returns:

  • (Boolean)


589
590
591
# File 'lib/squared/workspace/project/python.rb', line 589

def outdated?
  dependtype > 0
end

#pip(flag, opts = []) ⇒ Object



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/squared/workspace/project/python.rb', line 543

def pip(flag, opts = [])
  cmd = pip_session flag
  out = append_pip(nil, opts, from: flag)
  case flag
  when :uninstall
    raise_error('no packages listed', hint: 'uninstall') if out.empty?
    cmd.merge(out)
  when :freeze
    venv_init
    ret = basepath(out.shift || DEP_PYTHON[4])
    cmd << '>' << shell_quote(ret)
    option_clear out
  end
  run(from: :"pip:#{flag}")
  ret
end

#populateObject



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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
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
# File 'lib/squared/workspace/project/python.rb', line 111

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

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

      if flags.nil?
        case action
        when 'run'
          next unless pyprojectfile

          format_desc action, nil, "script+|#{indexchar}index+|#,pattern*"
          task action, [:command] do |_, args|
            found = 0
            ['tool.poetry.scripts', 'tool.pdm.scripts', 'project.scripts'].each_with_index do |table, index|
              next if (list = read_pyproject(table)).empty?

              if args.command == '#'
                format_list(list, "run[#{indexchar}N]", 'scripts', grep: args.extras, from: pyprojectfile)
                found |= 1
              else
                args.to_a.each do |val|
                  if (n, = indexitem(val))
                    if (script, = list[n - 1])
                      case index
                      when 0
                        script = session_output 'poetry', 'run', script
                      when 1
                        script = pdm_session 'run', script
                      else
                        venv_init
                      end
                      found |= 1
                      run(script, from: :run)
                    elsif exception
                      indexerror n, list
                    else
                      found |= 2
                      log.warn "run script #{n} of #{list.size} (out of range)"
                    end
                  else
                    case index
                    when 0
                      found |= 1
                      run(session_output('poetry', 'run', val), from: :run)
                    when 1
                      found |= 1
                      run(pdm_session('run', val), from: :run)
                    else
                      raise_error("script: #{val}", hint: 'unknown') if exception
                      found |= 2
                      log.warn "run script \"#{val}\" (not indexed)"
                    end
                  end
                end
              end
              break
            end
            unless found.anybits?(1)
              puts log_message(found == 0 ? Logger::INFO : Logger.WARN,
                               "no scripts #{found == 0 ? 'found' : 'executed'}",
                               subject: name, hint: pyprojectfile)
            end
          end
        when 'exec'
          format_desc action, nil, 'command|:,args*'
          task action do |_, args|
            i = (args = args.to_a).delete(':')
            cmd = if i && !workspace.windows?
                    readline('Enter script', force: true, multiline: ['##', ';'])
                  elsif i || args.empty?
                    readline('Enter command', force: true)
                  else
                    if (val = command_args(args, prefix: 'python'))
                      args << val
                    end
                    args.join(' ')
                  end
            shell(cmd, name: :exec, chdir: path)
          end
        end
      else
        namespace action do
          flags.each do |flag|
            case action
            when 'venv'
              if flag == :create
                format_desc action, flag, 'dir,opts*'
                task flag, [:dir] do |_, args|
                  dir = path + param_guard(action, flag, args: args, key: :dir)
                  venv_create dir, args.extras
                end
              elsif venv
                case flag
                when :remove
                  next unless projectpath?(venv)

                  format_desc action, flag, 'c|create?,d|depend?'
                  task flag do |_, args|
                    rm_rf(venv, verbose: true)
                    venv_init if has_value?(%w[c create], args.to_a)
                    depend if has_value?(%w[d depend], args.to_a)
                  end
                when :exec
                  format_desc action, flag, 'command,args*'
                  task flag do |_, args|
                    args = args.to_a
                    if args.empty?
                      args = readline('Enter command', force: true).split(' ', 2)
                    elsif args.size == 1 && !option('interactive', prefix: 'venv', equals: '0')
                      args << readline('Enter arguments', force: false)
                    end
                    venv_init
                    run args.join(' ')
                  end
                when :show
                  format_desc action, flag
                  task flag do
                    puts venv
                  end
                end
              end
            when 'pip'
              case flag
              when :freeze
                format_desc action, flag, "file?=#{DEP_PYTHON[4]},opts*"
                task flag do |_, args|
                  if (file = pip(flag, args.to_a)) && verbose
                    puts File.read(file)
                  end
                end
              when :uninstall
                format_desc action, flag, 'package+,opts*'
                task flag do |_, args|
                  pip flag, args.to_a
                end
              end
            when 'install'
              format_desc(action, flag, 'opts*', before: case flag
                                                         when :target then 'dir'
                                                         when :editable then 'path/url?'
                                                         when :upgrade then 'strategy?,package+'
                                                         end)
              case flag
              when :editable
                task flag do |_, args|
                  install flag, args.to_a
                end
              when :upgrade
                task flag, [:strategy] do |_, args|
                  case (strategy = args.strategy)
                  when 'eager', 'only-if-needed'
                    args = args.extras
                  else
                    args = args.to_a
                    strategy = nil
                  end
                  install(flag, args, strategy: strategy)
                end
              when :target
                task flag, [:dir] do |_, args|
                  dir = param_guard(action, flag, args: args, key: :dir)
                  depend(flag, args.extras, target: dir)
                end
              else
                task flag do |_, args|
                  depend flag, args.to_a
                end
              end
            when 'outdated'
              format_desc action, flag, 'eager?'
              task flag do |_, args|
                outdated flag, args.to_a
              end
            when 'build'
              case flag
              when :poetry
                next unless build_backend == 'poetry.core.masonry.api'
              when :pdm
                next unless build_backend == 'pdm.backend'
              when :hatch
                next unless build_backend == 'hatchling.build'
              end
              format_desc(action, flag, 'opts*', after: case flag
                                                        when :python then 'srcdir?'
                                                        when :poetry then 'output?'
                                                        when :pdm then 'dest?'
                                                        when :hatch then 'location?'
                                                        end)
              task flag do |_, args|
                build! flag, args.to_a
              end
              break unless flag == :python
            when 'publish'
              format_desc(action, flag, 'opts*', after: case flag
                                                        when :hatch then 'artifacts?'
                                                        when :twine then 'dist?'
                                                        end)
              task flag do |_, args|
                publish flag, args.to_a
              end
            end
          end
        end
      end
    end
  end
end

#publish(flag, opts = []) ⇒ Object



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

def publish(flag, opts = [])
  case flag
  when :poetry
    poetry_session 'publish'
    list = OPT_POETRY[:publish] + OPT_POETRY[:common]
  when :pdm
    opts = pdm_session('publish', opts: opts).last
    list = OPT_PDM[:publish]
  when :hatch
    opts = hatch_session('publish', opts: opts).last
    list = OPT_HATCH[:publish]
  when :twine
    session 'twine', 'upload'
    list = OPT_TWINE[:publish]
  end
  op = OptionPartition.new(opts, list, @session, project: self, single: singleopt(flag))
  dist = lambda do
    (path + 'dist').tap do |dir|
      raise_error('no source files found', hint: dir) unless dir.directory? && !dir.empty?
    end
  end
  case flag
  when :hatch, :twine
    if op.empty?
      op.extras << "#{dist.call}/*"
    else
      op.map! { |val| path + val }
    end
    op.append
  else
    dist.call unless op.arg?(*(flag == :poetry ? ['dist-dir'] : ['d', 'dest']))
    op.clear(pass: false)
  end
  run(from: :"#{flag}:publish", interactive: "Publish #{sub_style(project, styles: theme[:active])}")
end

#refObject



107
108
109
# File 'lib/squared/workspace/project/python.rb', line 107

def ref
  Python.ref
end

#variable_set(key, *val, &blk) ⇒ Object



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/squared/workspace/project/python.rb', line 560

def variable_set(key, *val, **, &blk)
  if block_given?
    case key
    when :dependfile, :venv, :editable
      val = block_args val, &blk
    end
  end
  case key
  when :dependfile
    req = basepath(*val)
    if (index = DEP_PYTHON.index(req.basename.to_s))
      @dependindex = index
      @dependfile = req
    else
      log.warn "variable_set: @#{key}=#{req} (not supported)"
    end
  when :editable
    editable_set val.first
  when :venv
    instance_variable_set(:"@#{key}", val.empty? ? nil : basepath(*val))
  else
    super
  end
end