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

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

Constant Summary collapse

OPT_MESON =
{
  build: %w[D=q clearcache debug errorlogs fatal-meson-warnings pkgconfig.relocatable prefer-static
            python.allow-limited-api reconfigure stdsplit strip vsenv werror wipe auto-features=b backend=b
            bindir=p build.cmake-prefix-path=p build.pkg-config-path=p buildtype=b cmake-prefix-path=p
            cross-file=p datadir=p default-library=b default-both-libraries=b force-fallback-for=q genvslite=b
            includedir=p infodir=p install-umask=b layout=b libdir=p libexecdir=p licensedir=p localedir=p
            localstatedir=p mandir=p native-file=p optimization=b pkg-config-path=p prefix=p
            python.bytecompile=i python.platlibdir=p python.purelibdir=p python.install-env=b sbindir=p
            sharedstatedir=p sysconfdir=p unity=b unity-size=i warnlevel=b wrap-mode=b].freeze,
  compile: %w[clean v|verbose j|jobs=i l|load-average=b ninja-args=q vs-args=q xcode-args=q].freeze
}.freeze

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary collapse

Attributes inherited from Base

#children, #dependfile, #exception, #group, #name, #parent, #path, #pipe, #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, #sparse_checkout, #stash, #status, #submodule, #switch, #tag

Methods inherited from Base

#<=>, #==, #add, aliasargs, #allref, #archive, #archive?, #as, #asdf, #basepath, #basepath!, batchargs, #build, #build?, #chain, #clean, #clean?, #copy, #copy?, #dependname, #dependtype, #dev?, #doc, #doc?, #empty?, #enabled?, #error, #event, #exclude?, #exist?, #first, #generate, #global, #global=, #global_set, #graph, #graph?, #has?, #inject, #inspect, #last, #lint, #lint?, #localname, #log, options, populate, #prereqs, #prereqs?, #prod?, ref, #ref?, #rootpath, #run, #scope, #script?, #scriptdata, #scriptname, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #version=, #with

Methods included from Common::Format

emphasize, #enable_aixterm, #enable_drawing, message, raise_error

Constructor Details

#initialize(editable: '.', asdf: 'python', **kwargs) ⇒ Python

Returns a new instance of Python.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/squared/workspace/project/python.rb', line 125

def initialize(*, editable: '.', asdf: 'python', **kwargs)
  super
  if @pass.include?(Python.ref)
    initialize_ref Python.ref
    initialize_logger kwargs[:log]
  else
    initialize_build(Python.ref, **kwargs)
    initialize_env(**kwargs)
  end
  dependfile_set(DEP_PYTHON, default: 2)
  serve_set kwargs[:serve]
  editable_set editable
  venv_set kwargs[:venv]
end

Instance Attribute Details

#editableObject

Returns the value of attribute editable.



123
124
125
# File 'lib/squared/workspace/project/python.rb', line 123

def editable
  @editable
end

#venvObject (readonly)

Returns the value of attribute venv.



122
123
124
# File 'lib/squared/workspace/project/python.rb', line 122

def venv
  @venv
end

Class Method Details

.bannerargsObject



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

def bannerargs
  %i[version dependfile venv].freeze
end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


115
116
117
118
119
# File 'lib/squared/workspace/project/python.rb', line 115

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

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

.tasksObject



103
104
105
# File 'lib/squared/workspace/project/python.rb', line 103

def tasks
  [:outdated].freeze
end

.venv?Boolean

Returns:

  • (Boolean)


111
112
113
# File 'lib/squared/workspace/project/python.rb', line 111

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

Instance Method Details

#build!(flag, opts = [], outdir: nil, srcdir: nil) ⇒ Object



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

def build!(flag, opts = [], outdir: nil, srcdir: nil)
  list = case flag
         when :poetry
           cmd = poetry_session 'build'
           OPT_POETRY[:build] + OPT_POETRY[:common]
         when :pdm
           cmd, opts = pdm_session('build', opts: opts)
           OPT_PDM[:build]
         when :hatch
           cmd, opts = hatch_session('build', opts: opts)
           OPT_HATCH[:build]
         when :meson
           cmd = session 'meson', 'setup'
           OPT_MESON[:build]
         else
           cmd, opts = python_session('-m build', opts: opts)
           OPT_PYTHON[:build]
         end
  op = OptionPartition.new(opts, list, cmd, project: self, strict: strict?, single: singleopt(flag))
  case flag
  when :hatch
    op.add_path(outdir) if !ENV['HATCH_BUILD_LOCATION'] && (outdir ||= op.shift)
    srcdir = false
  when :meson
    if outdir
      op.add_path(outdir)
    else
      outdir = op.first
      op.add_first(path: true, expect: 'outdir not specified')
    end
  else
    args = case flag
           when :poetry
             srcdir = false
             %w[o output]
           when :pdm
             srcdir = false
             %w[d dest]
           else
             %w[o outdir]
           end
    outdir = op.shift unless op.arg?(*args)
    op << quote_option(args.last, basepath(outdir)) if outdir
  end
  unless srcdir == false
    if srcdir
      op.add_path(srcdir)
    else
      op.exist?(add: true, first: true)
    end
  end
  from = symjoin flag, 'build'
  if flag == :meson
    cmd = session_output 'meson', 'compile', quote_option('C', basepath(outdir))
    unless op.empty?
      OptionPartition.new(op.extras, OPT_MESON[:compile], cmd, project: self, strict: strict?).append
    end
    run_s(op, cmd.done, from: from)
  else
    op.clear
    run(from: from)
  end
end

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



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/squared/workspace/project/python.rb', line 425

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 && poetry?
      cmd = poetry_session 'install -n'
      cmd << '--no-root' if option('no-root')
    else
      cmd = pip_session 'install'
      cmd << '--upgrade-strategy=eager' if env('UPDATE') || env('PYTHON_UPDATE')
      cmd << '--no-build-isolation' if option('build-isolation', equals: '0')
      if flag
        cmd << case flag
               when :requirement, :target
                 quote_option(flag, basepath(target))
               else
                 shell_option(flag)
               end
        op = append_pip flag, opts, pipopts(:install)
        op.clear
      else
        append_global
      end
      if exist?(DEP_PYTHON[4]) && !session_arg?('r', 'requirement')
        cmd << basic_option('r', DEP_PYTHON[4])
        cmd << basic_option('c', 'constraints.txt') if exist?('constraints.txt')
      end
      append_editable
    end
    run(sync: sync, from: :depend)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


882
883
884
# File 'lib/squared/workspace/project/python.rb', line 882

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

#install(flag, opts = [], packages: [], banner: !silent?)) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# File 'lib/squared/workspace/project/python.rb', line 604

def install(flag, opts = [], packages: [], banner: !silent?)
  if flag == :poetry
    OptionPartition.new(opts, OPT_POETRY[:install] + OPT_POETRY[:common], poetry_session('install'),
                        project: self, strict: strict?, single: singleopt(flag))
  else
    op = append_pip(flag, opts, pipopts(:install), target: pip_session('install'))
  end
  case flag
  when :editable
    op << quote_option('e', op.pop || editable || '.')
    op.clear
  when :user, :upgrade
    op.concat(packages)
    raise_error 'no packages listed', hint: flag if op.empty?
    op << "--#{flag}"
    op.append
    python_session('-m pip', *op.to_a.drop(1)) if workspace.windows?
  end
  run(banner: banner, from: :install)
end

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



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

def outdated(flag = nil, opts = [], sync: invoked_sync?('outdated', flag))
  cmd = pip_session 'list --outdated'
  cmd << if flag
           se = has_value! opts, 's', 'select'
           ia = has_value!(opts, 'i', 'interactive') && !se
           up = has_value! opts, 'u', 'update'
           hide = has_value! opts, 'h', 'hide'
           dryrun = has_value! opts, 'd', 'dry-run'
           if !sync || stdin?
             se = false
             ia = false
           elsif se || ia
             up = true
             items = []
           end
           '--not-required' if opts.include?('no-deps')
         else
           if (up = option('u', 'update'))
             flag = case up
                    when 'major', 'minor'
                      up.to_sym
                    else
                      :patch
                    end
           end
           '--not-required' if option('not-required', notequals: '0') && !env('PYTHON_DEFAULT')
         end
  cmd << '--local' if option('l', 'local')
  append_global
  dryrun ||= dryrun?
  cmd = session_done cmd
  log.info cmd
  on :first, :outdated
  banner = format_banner cmd
  print_item banner if sync
  pwd_set(cmd, dryrun: dryrun) do
    tc = theme[:current]
    start = 0
    found = 0
    col = 0
    major = []
    minor = []
    patch = []
    buffer = []
    out = ->(val) { sync ? puts(val) : buffer << val }
    if workspace.windows?
      (venv ? command(runenv, cmd) : `#{cmd}`).lines(chomp: true)
    else
      IO.popen(runenv || {}, cmd).readlines(chomp: true)
    end
    .each do |line|
      next if line.match?(/^[ -]+$/)

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

          name = line.split(' ', 2).first
          c = cur.join
          l = lat.join
          semver cur
          semver lat
          case (type = semtype(cur, lat))
          when 1
            major << name
          when 2
            minor << name
          else
            patch << name
          end
          next if hide && ((flag == :patch && type < 3) || (flag == :minor && type < 2))

          if type == 3
            styles = color(:yellow)
          else
            styles = color(:green)
            sub_style!(line, if type == 1
                               styles += [:bold]
                               theme[:major]
                             else
                               theme[:active]
                             end, pat: /^(\S+)(.+)$/)
          end
          sub_style!(line, **opt_style(tc, /^(.+)(#{Regexp.escape(c)})(.+)$/, 2)) if tc
          sub_style!(line, **opt_style(styles, /^(.+)(#{Regexp.escape(l)})(.+)$/, 2))
          found += 1
        end
        s = '%2d. %s' % [start, line]
        start += 1
        if ia
          next unless confirm_semver(s.ljust(col + line.size - n), type)
        elsif !se
          out.call(s)
        end
        items&.push([line, name])
      elsif line.start_with?('Package')
        unless stdin?
          col = line.size + 5
          sub = [opt_style(theme[:header], /^(.*)(?<!\dm)(Package|Latest)(.+)$/, 2)] * 2
          out.call(print_footer(" #  #{line}", reverse: true, sub: sub))
        end
        start += 1
      end
    end
    unless sync
      print_item banner
      puts buffer
    end
    if found > 0
      items = if se
                choice('Select a package', items.map(&:first),
                       multiple: true, force: false, index: true, border: true).map { |n| items[n.pred].last }
              elsif ia
                items.map(&:last)
              else
                case flag
                when :major
                  major + minor + patch
                when :minor
                  minor + patch
                else
                  patch
                end
              end
      if up && !items.empty?
        base = %w[eager no-deps]
        base << 'user' unless venv
        opts = (base & opts).map { |val| val == 'eager' ? "upgrade-strategy=#{val}" : val }
        if dryrun
          print_run pip_output('install --upgrade', *opts.map { |val| fill_option(val) }, *items.quote!), false
        else
          install(:upgrade, opts, packages: items, banner: false)
        end
      end
      print_status(major.size, minor.size, patch.size, from: :outdated)
    elsif start == 0 || hide
      puts 'No updates were found'
    end
  end
  on :last, :outdated
end

#outdated?Boolean

Returns:

  • (Boolean)


886
887
888
# File 'lib/squared/workspace/project/python.rb', line 886

def outdated?
  dependtype > 0 && !task_pass?('outdated')
end

#pip(flag, *args, sync: true, banner: verbose?, , with: nil, pass: nil, **kwargs) ⇒ Object



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
790
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
# File 'lib/squared/workspace/project/python.rb', line 757

def pip(flag, *args, sync: true, banner: verbose?, with: nil, pass: nil, **kwargs)
  flag = flag.to_sym
  pass = PASS_PYTHON[:pip].fetch(pip_install?(flag) ? :install : flag, []) + %w[v verbose] if pass.nil?
  opts = session_opts(with, args: args, kwargs: kwargs, pass: pass)
  case flag
  when :freeze, :inspect, :list, :check, :completion, :debug
    opts.concat(args)
  end
  op = append_pip(flag, opts, pipopts(flag), target: pip_session(flag))
  case flag
  when :install, :uninstall, :show, :index
    op.concat(args)
    if op.empty?
      case flag
      when :install, :uninstall
        op << '.' if installable? && !op.arg?('r', 'requirement')
      else
        raise_error 'no packages listed', hint: flag
      end
    elsif flag == :install
      op.append_any
    elsif flag == :index
      op.adjoin('versions', with: 'index')
        .add_first
        .clear
    else
      op.append
    end
  when :freeze
    venv_init
    op << '>'
    ret = kwargs[:requirement] || begin
      file = op.detect { |val| op.exist?(val) }
      op.remove(file) if file
      basepath(file || DEP_PYTHON[4])
    end
    op.add_quote(ret)
      .clear
  when :cache
    op.concat(args)
    raise_error 'no subcommand', hint: flag if op.empty?
    op << (action = op.shift)
    case action
    when 'dir', 'info', 'purge'
      nil
    when 'list', 'remove'
      op.add_first(quote: true)
    else
      raise_error ArgumentError, "unrecognized args: #{action}", hint: flag
    end
    op.clear
  when :config
    op.concat(args)
    raise_error 'no subcommand', hint: flag if op.empty?
    op << (action = op.shift)
    case action
    when 'list', 'edit', 'debug'
      nil
    when 'get', 'unset', 'set'
      op.add_first
      op.add_first(quote: true, expect: true) if action == 'set'
    else
      raise_error ArgumentError, "unrecognized args: #{action}", hint: flag
    end
    op.clear
  when :hash
    op.append(projectmap(op.concat(args), parent: true))
  when :wheel, :lock, :download
    op.concat(args)
    if !op.empty?
      op.append
    elsif installable? && !op.arg?('r', 'requirement')
      op << '.'
    end
  else
    op.clear
  end
  print_run(op, banner, **kwargs)
  run(sync: sync, banner: banner, exception: kwargs.fetch(:exception, exception?), from: symjoin('pip', flag))
    .yield_self { |val| ret || val }
end

#populateObject



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

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

  namespace name do
    Python.subtasks do |action, flags|
      next if task_pass?(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
            %w[tool.poetry.scripts tool.pdm.scripts project.scripts].each_with_index do |table, i|
              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.pred])
                      case i
                      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}".subhint('out of range')
                    end
                  else
                    case i
                    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 "script: #{val}" if exception

                      found |= 2
                      log.warn "run script \"#{val}\"".subhint('not indexed')
                    end
                  end
                end
              end
              break
            end
            next if found.anybits?(1)

            puts log_message(found == 0 ? Logger::INFO : Logger.WARN,
                             "no scripts #{found == 0 ? 'found' : 'executed'}",
                             subject: name, hint: pyprojectfile)
          end
        when 'exec'
          format_desc action, nil, 'command|:,args*'
          task action do |_, args|
            args = args.to_a
            cmd = if (i = args.delete(':')) && !workspace.windows?
                    readline('Enter script', force: true, multiline: %w[## ;])
                  elsif i || args.empty?
                    readline('Enter command', force: true)
                  else
                    command_args(args, min: 1, prefix: 'python')
                    args.join(' ')
                  end
            run(cmd, send: :exec, banner: false)
          end
        end
      else
        namespace action do |ns|
          flags.each do |flag|
            case action
            when 'venv'
              if flag == :create
                format_desc action, flag, 'dir,opts*'
                task flag, [:dir] do |_, args|
                  dir = basepath 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/reate?,d/epend?,opts*'
                  task flag do |_, args|
                    args = args.to_a
                    rm_rf(venv, verbose: true)
                    venv_init if has_value!(args, 'c', 'create')
                    depend :force, args if has_value!(args, 'd', 'depend')
                  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', notequals: '0', prefix: ref)
                      args << readline('Enter arguments', force: false) unless args.first.include?(' ')
                    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 :upgrade
                format_desc action, flag, 'opts*'
                task flag do |_, args|
                  install flag, ['upgrade', *args.to_a, 'pip']
                end
              when :freeze
                format_desc action, flag, "file?=#{DEP_PYTHON[4]},u/uninstall,opts*"
                task flag do |_, args|
                  opts = args.to_a
                  if has_value!(opts, 'u', 'uninstall')
                    unless venv
                      print_error('no venv detected', subject: name)
                      exit 1
                    end
                    require 'tempfile'
                    temp = Tempfile.new("#{name}-")
                    temp.close
                    requirement = Pathname.new(temp)
                  end
                  file = pip(flag, opts: opts, banner: requirement.nil?, requirement: requirement)
                  puts File.read(file) unless silent?
                  if requirement && confirm_basic('Uninstall?', file)
                    pip(:uninstall, opts: ['y', "r=#{shell_quote(file)}"])
                  end
                end
              when :uninstall
                format_desc action, flag, 'package+,opts*'
                task flag do |_, args|
                  pip(flag, opts: args.to_a, banner: true)
                end
              when :wheel
                next unless pyprojectfile || setuptools?

                format_desc action, flag, 'opts*,args*'
                task flag do |_, args|
                  pip(flag, opts: args.to_a, banner: true)
                end
              when :reinstall
                next unless venv && projectpath?(venv)

                format_desc action, flag
                task flag do
                  ns['venv:remove'].invoke('depend')
                end
              end
            when 'install'
              format_desc(action, flag, 'opts*', before: case flag
                                                         when :editable then 'path/url?'
                                                         when :upgrade then 'strategy?,package+'
                                                         when :requirement, :target then 'path'
                                                         else 'package+'
                                                         end)
              case flag
              when :upgrade
                task flag, [:strategy] do |_, args|
                  install flag, (case args.strategy
                                 when 'eager'
                                   'eager'
                                 when /^only-if|needed$/
                                   'only-if-needed'
                                 end.yield_self do |val|
                                   if val
                                     args.extras << "upgrade-strategy=#{val}"
                                   else
                                     args.to_a
                                   end
                                 end)
                end
              when :requirement, :target
                task flag, [:path] do |_, args|
                  path = param_guard(action, flag, args: args, key: :path)
                  depend(flag, args.extras, target: path)
                end
              else
                case flag
                when :user
                  next if venv
                when :poetry
                  next unless poetry?
                end
                task flag do |_, args|
                  install flag, args.to_a
                end
              end
            when 'outdated'
              format_desc(action, flag, "eager?,no-deps?,#{shortname('h', 'i', 's', 'u', 'd')}",
                          before: ('user?' unless venv))
              task flag do |_, args|
                outdated flag, args.to_a
              end
            when 'build'
              next if (be = backend?(flag)) == false

              format_desc(action, flag, 'opts*', after: case flag
                                                        when :poetry then 'output?'
                                                        when :pdm then 'dest?'
                                                        when :hatch then 'location?'
                                                        else 'outdir?,srcdir?'
                                                        end)
              task flag do |_, args|
                build! flag, args.to_a
              end
              break if be
            when 'publish'
              if flag == :twine
                next unless twine?
              elsif (be = backend?(flag)) == false
                next
              end
              format_desc(action, flag, 'test?,opts*', after: case flag
                                                              when :hatch then 'artifacts?'
                                                              when :twine then 'dist?'
                                                              end)
              task flag do |_, args|
                args = args.to_a
                publish(flag, args, test: if args.first == 'test'
                                            args.shift
                                            true
                                          else
                                            false
                                          end)
              end
              break if be
            end
          end
        end
      end
    end
  end
end

#projectObject



843
844
845
846
847
# File 'lib/squared/workspace/project/python.rb', line 843

def project
  return @project unless @project.frozen?

  @project = (read_pyproject('project', 'name') || @project).dup
end

#project=(val) ⇒ Object



151
152
153
# File 'lib/squared/workspace/project/python.rb', line 151

def project=(val)
  @project = val.dup
end

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



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

def publish(flag, opts = [], test: false)
  list = case flag
         when :poetry
           poetry_session 'publish'
           OPT_POETRY[:publish] + OPT_POETRY[:common]
         when :pdm
           opts = pdm_session('publish', opts: opts).last
           OPT_PDM[:publish]
         when :hatch
           opts = hatch_session('publish', opts: opts).last
           OPT_HATCH[:publish]
         else
           session 'twine', 'upload'
           OPT_TWINE[:publish]
         end
  op = OptionPartition.new(opts, list, @session, project: self, strict: strict?, single: singleopt(flag))
  dist = lambda do
    dir = basepath 'dist'
    return dir if dir.directory? && !dir.empty?

    if dir.exist?
      raise_error 'no source to publish', hint: dir
    else
      raise_error Errno::ENOENT, dir, hint: 'publish'
    end
  end
  if test
    if op.arg?('r', flag == :hatch ? 'repo' : 'repository')
      op.push('test')
    else
      op << quote_option('r', 'testpypi')
    end
  end
  case flag
  when :poetry, :pdm
    dist.call unless op.arg?(*(flag == :poetry ? ['dist-dir'] : %w[d dest]))
    op.clear(pass: false)
  else
    if op.empty?
      op << "#{dist.call}/*"
    else
      op.add_path
    end
  end
  run(from: symjoin(flag, 'publish'), interactive: ['Publish', 'N', project])
end

#python(*args, sync: true, banner: verbose?, , with: nil, pass: , **kwargs) ⇒ Object



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/squared/workspace/project/python.rb', line 736

def python(*args, sync: true, banner: verbose?, with: nil, pass: PASS_PYTHON[:python], **kwargs)
  op = OptionPartition.new(session_opts(with, args: args, kwargs: kwargs, pass: pass), OPT_PYTHON[:common],
                           session('python', path: !venv?),
                           project: self, strict: strict?, multiple: [/^-c/], single: singleopt(:python),
                           args: true, stdin: true)
  op.concat(args)
  if op.include?('-')
    op.exist?(add: true)
  else
    op.append_any { |val| OptionPartition.parse_arg!('c', val) }
    if op.arg?('c')
      op.clear
    else
      op.exist?(add: true, first: true) unless op.arg?('m')
      op.append(escape: kwargs.fetch(:escape, false), quote: kwargs.fetch(:quote, false))
    end
  end
  print_run(op, banner, **kwargs)
  run(sync: sync, banner: banner, exception: kwargs.fetch(:exception, exception?), from: :python)
end

#refObject



164
165
166
# File 'lib/squared/workspace/project/python.rb', line 164

def ref
  Python.ref
end

#serve(root, opts = [], bind: 'localhost', port: nil) ⇒ Object



839
840
841
# File 'lib/squared/workspace/project/python.rb', line 839

def serve(root, opts = [], bind: 'localhost', port: nil, **)
  shell(python_session('-m http.server', port, basic_option('b', bind), opts: opts).first.done, chdir: root)
end

#serve?Boolean

Returns:

  • (Boolean)


894
895
896
# File 'lib/squared/workspace/project/python.rb', line 894

def serve?
  @serve != false
end

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



853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'lib/squared/workspace/project/python.rb', line 853

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

#venv?Boolean

Returns:

  • (Boolean)


890
891
892
# File 'lib/squared/workspace/project/python.rb', line 890

def venv?
  !venv.nil? && venv.directory? && !venv.empty?
end

#verbose=(val) ⇒ Object



155
156
157
158
159
160
161
162
# File 'lib/squared/workspace/project/python.rb', line 155

def verbose=(val)
  case val
  when /\Av+\z/
    @verbose = val.size
  else
    super
  end
end

#versionObject



849
850
851
# File 'lib/squared/workspace/project/python.rb', line 849

def version
  @version ||= read_pyproject('project', 'version')
end