Class: Bolt::Outputter::Human

Inherits:
Bolt::Outputter show all
Defined in:
lib/bolt/outputter/human.rb

Direct Known Subclasses

Rainbow

Constant Summary collapse

COLORS =
{
  dim:    "2", # Dim, the other color of the rainbow
  red:    "31",
  green:  "32",
  yellow: "33",
  cyan:   "36"
}.freeze

Instance Method Summary collapse

Methods inherited from Bolt::Outputter

for_format, #indent, #spin

Constructor Details

#initialize(color, verbose, trace, spin, stream = $stdout) ⇒ Human

Returns a new instance of Human.



20
21
22
23
24
25
26
27
# File 'lib/bolt/outputter/human.rb', line 20

def initialize(color, verbose, trace, spin, stream = $stdout)
  super
  # Plans and without_default_logging() calls can both be nested, so we
  # track each of them with a "stack" consisting of an integer.
  @plan_depth = 0
  @disable_depth = 0
  @pinwheel = %w[- \\ | /]
end

Instance Method Details

#colorize(color, string) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/bolt/outputter/human.rb', line 29

def colorize(color, string)
  if @color && @stream.isatty
    "\033[#{COLORS[color]}m#{string}\033[0m"
  else
    string
  end
end

#duration_to_string(duration) ⇒ Object



943
944
945
946
947
948
949
950
951
952
953
954
955
# File 'lib/bolt/outputter/human.rb', line 943

def duration_to_string(duration)
  hrs = (duration / 3600).floor
  mins = ((duration % 3600) / 60).floor
  secs = (duration % 60)
  if hrs > 0
    "#{hrs} hr, #{mins} min, #{secs.round} sec"
  elsif mins > 0
    "#{mins} min, #{secs.round} sec"
  else
    # Include 2 decimal places if the duration is under a minute
    "#{secs.round(2)} sec"
  end
end

#enabled?Boolean

Returns:

  • (Boolean)


112
113
114
# File 'lib/bolt/outputter/human.rb', line 112

def enabled?
  @disable_depth == 0
end

#fatal_error(err) ⇒ Object



880
881
882
883
884
885
886
887
888
889
890
891
# File 'lib/bolt/outputter/human.rb', line 880

def fatal_error(err)
  @stream.puts(colorize(:red, err.message))
  if err.is_a? Bolt::RunFailure
    @stream.puts ::JSON.pretty_generate(err.result_set)
  end

  if @trace && err.backtrace
    err.backtrace.each do |line|
      @stream.puts(colorize(:red, "\t#{line}"))
    end
  end
end

#format_log(log) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/bolt/outputter/human.rb', line 206

def format_log(log)
  color = case log['level']
          when 'warn'
            :yellow
          when 'err'
            :red
          end
  source = "#{log['source']}: " if log['source']
  message = "#{log['level'].capitalize}: #{source}#{log['message']}"
  message = colorize(color, message) if color
  message
end

#format_table(results, padding_left = 0, padding_right = 3) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/bolt/outputter/human.rb', line 296

def format_table(results, padding_left = 0, padding_right = 3)
  # lazy-load expensive gem code
  require 'terminal-table'

  Terminal::Table.new(
    rows: results,
    style: {
      border_x: '',
      border_y: '',
      border_i: '',
      padding_left: padding_left,
      padding_right: padding_right,
      border_top: false,
      border_bottom: false
    }
  )
end

#handle_event(event) ⇒ Object



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
# File 'lib/bolt/outputter/human.rb', line 74

def handle_event(event)
  case event[:type]
  when :enable_default_output
    @disable_depth -= 1
  when :disable_default_output
    @disable_depth += 1
  when :message
    print_message(event[:message])
  when :verbose
    print_message(event[:message]) if @verbose
  end

  if enabled?
    case event[:type]
    when :node_start
      print_start(event[:target]) if @verbose
    when :node_result
      print_result(event[:result]) if @verbose
    when :step_start
      print_step_start(**event) if plan_logging?
    when :step_finish
      print_step_finish(**event) if plan_logging?
    when :plan_start
      print_plan_start(event)
    when :plan_finish
      print_plan_finish(event)
    when :container_start
      print_container_start(event) if plan_logging?
    when :container_finish
      print_container_finish(event) if plan_logging?
    when :start_spin
      start_spin
    when :stop_spin
      stop_spin
    end
  end
end

#plan_logging?Boolean

Returns:

  • (Boolean)


116
117
118
# File 'lib/bolt/outputter/human.rb', line 116

def plan_logging?
  @plan_depth > 0
end


930
931
932
933
934
935
936
937
938
939
940
941
# File 'lib/bolt/outputter/human.rb', line 930

def print_action_error(error)
  # Running everything through 'wrap' messes with newlines. Separating
  # into lines and wrapping each individually ensures separate errors are
  # distinguishable.
  first, *remaining = error.lines
  first = colorize(:red, indent(2, "#{wrap(first, 76)}"))
  wrapped = remaining.map { |l| wrap(l) }
  to_print = wrapped.map { |line| colorize(:red, indent(4, line)) }
  step = [first, *to_print, "\n"].join

  @stream.puts(step)
end


920
921
922
923
924
925
926
927
928
# File 'lib/bolt/outputter/human.rb', line 920

def print_action_step(step)
  first, *remaining = wrap(step, 76).lines

  first     = indent(2, "#{first}")
  remaining = remaining.map { |line| indent(4, line) }
  step      = [first, *remaining, "\n"].join

  @stream.puts(step)
end

Parameters:

  • apply_result (Bolt::ResultSet)

    A ResultSet object representing the result of a ‘bolt apply`



838
839
840
# File 'lib/bolt/outputter/human.rb', line 838

def print_apply_result(apply_result)
  print_summary(apply_result, apply_result.elapsed_time)
end


901
902
903
904
905
906
907
908
909
910
# File 'lib/bolt/outputter/human.rb', line 901

def print_bolt_error(msg:, details:, **_kwargs)
  err = msg
  if (f = details[:file])
    err += "\n  (file: #{f}"
    err += ", line: #{details[:line]}" if details[:line]
    err += ", column: #{details[:column]}" if details[:column]
    err += ")"
  end
  @stream.puts(colorize(:red, err))
end


239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/bolt/outputter/human.rb', line 239

def print_container_finish(event)
  result = if event[:result].is_a?(Bolt::ContainerFailure)
             event[:result].result
           else
             event[:result]
           end

  if result.success?
    @stream.puts(colorize(:green, "Finished: run container '#{result.object}' succeeded."))
  else
    @stream.puts(colorize(:red, "Finished: run container '#{result.object}' failed."))
  end
  print_container_result(result) if @verbose
end


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
# File 'lib/bolt/outputter/human.rb', line 124

def print_container_result(result)
  if result.success?
    @stream.puts(colorize(:green, "Finished running container #{result.object}:"))
  else
    @stream.puts(colorize(:red, "Failed running container #{result.object}:"))
  end

  if result.error_hash
    @stream.puts(colorize(:red, remove_trail(indent(2, result.error_hash['msg']))))
    return 0
  end

  # Only print results if there's something other than empty string and hash
  safe_value = result.safe_value
  if safe_value['stdout'].strip.empty? && safe_value['stderr'].strip.empty?
    @stream.puts(indent(2, "Running container #{result.object} completed successfully with no result"))
  else
    unless safe_value['stdout'].strip && safe_value['stdout'].strip.empty?
      @stream.puts(indent(2, "STDOUT:"))
      @stream.puts(indent(4, safe_value['stdout']))
    end
    unless safe_value['stderr'].strip.empty?
      @stream.puts(indent(2, "STDERR:"))
      @stream.puts(indent(4, safe_value['stderr']))
    end
  end
end


235
236
237
# File 'lib/bolt/outputter/human.rb', line 235

def print_container_start(image:, **_kwargs)
  @stream.puts(colorize(:green, "Starting: run container '#{image}'"))
end


897
898
899
# File 'lib/bolt/outputter/human.rb', line 897

def print_error(message)
  @stream.puts(colorize(:red, message))
end

Print inventory group information.

Parameters:

  • count (Integer)

    Number of groups in the inventory.

  • groups (Array)

    Names of groups in the inventory.

  • inventory (Hash)

    Where the inventory was loaded from.



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# File 'lib/bolt/outputter/human.rb', line 819

def print_groups(count:, groups:, inventory:)
  info = +''

  # Add group list
  info << colorize(:cyan, "Groups\n")
  info << indent(2, groups.join("\n"))
  info << "\n\n"

  # Add inventory file source
  info << format_inventory_source(inventory[:source], inventory[:default])

  # Add group count summary
  info << colorize(:cyan, "Group count\n")
  info << indent(2, "#{count} total")

  @stream.puts info
end

Print the guide for the specified topic.

Parameters:

  • guide (String)

    The guide.



496
497
498
499
500
501
502
503
504
505
506
# File 'lib/bolt/outputter/human.rb', line 496

def print_guide(topic:, guide:, documentation: nil, **_kwargs)
  info = +"#{colorize(:cyan, topic)}\n"
  info << indent(2, guide)

  if documentation
    info << "\n#{colorize(:cyan, 'Documentation')}\n"
    info << indent(2, documentation.join("\n"))
  end

  @stream.puts info
end


18
# File 'lib/bolt/outputter/human.rb', line 18

def print_head; end


893
894
895
# File 'lib/bolt/outputter/human.rb', line 893

def print_message(message)
  @stream.puts(Bolt::Util::Format.stringify(message))
end

Prints detailed module information.

Parameters:

  • name (String)

    The module’s short name.

  • metadata (Hash)

    The module’s metadata.

  • path (String)

    The path to the module.

  • plans (Array)

    The module’s plans.

  • tasks (Array)

    The module’s tasks.



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
609
610
611
612
613
614
615
616
617
618
# File 'lib/bolt/outputter/human.rb', line 558

def print_module_info(name:, metadata:, path:, plans:, tasks:, **_kwargs)
  info = +''

  info << colorize(:cyan, name)

  info << colorize(:dim, " [#{['version']}]") if ['version']
  info << "\n"

  info << if ['summary']
            indent(2, wrap(['summary'].strip, 76))
          else
            indent(2, "No description available.\n")
          end
  info << "\n"

  if tasks.any?
    length = tasks.map(&:first).map(&:length).max
    data   = tasks.map { |task, desc| [task, truncate(desc, 76 - length)] }
    info << colorize(:cyan, "Tasks\n")
    info << format_table(data, 2).to_s
    info << "\n\n"
  end

  if plans.any?
    length = plans.map(&:first).map(&:length).max
    data   = plans.map { |plan, desc| [plan, truncate(desc, 76 - length)] }
    info << colorize(:cyan, "Plans\n")
    info << format_table(data, 2).to_s
    info << "\n\n"
  end

  if ['operatingsystem_support']&.any?
    supported = ['operatingsystem_support'].map do |os|
      [os['operatingsystem'], os['operatingsystemrelease']&.join(', ')]
    end

    info << colorize(:cyan, "Operating system support\n")
    info << format_table(supported, 2).to_s
    info << "\n\n"
  end

  if ['dependencies']&.any?
    dependencies = ['dependencies'].map do |dep|
      [dep['name'], dep['version_requirement']]
    end

    info << colorize(:cyan, "Dependencies\n")
    info << format_table(dependencies, 2).to_s
    info << "\n\n"
  end

  info << colorize(:cyan, "Path\n")
  info << if path.start_with?(Bolt::Config::Modulepath::MODULES_PATH) ||
             path.start_with?(Bolt::Config::Modulepath::BOLTLIB_PATH)
            indent(2, 'built-in module')
          else
            indent(2, path)
          end

  @stream.puts info
end


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
# File 'lib/bolt/outputter/human.rb', line 512

def print_module_list(module_list)
  info = +''

  module_list.each do |path, modules|
    info << if (mod = modules.find { |m| m[:internal_module_group] })
              colorize(:cyan, mod[:internal_module_group])
            else
              colorize(:cyan, path)
            end

    info << "\n"

    if modules.empty?
      info << '(no modules installed)'
    else
      module_info = modules.map do |m|
        version = if m[:version].nil?
                    m[:internal_module_group].nil? ? '(no metadata)' : '(built-in)'
                  else
                    m[:version]
                  end

        [m[:name], version]
      end

      info << format_table(module_info, 2, 1).to_s
    end

    info << "\n\n"
  end

  command = Bolt::Util.powershell? ? 'Get-BoltModule -Name <MODULE>' : 'bolt module show <MODULE>'
  info << colorize(:cyan, "Additional information\n")
  info << indent(2, "Use '#{command}' to view details for a specific module.")

  @stream.puts info
end


648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'lib/bolt/outputter/human.rb', line 648

def print_new_plan(name:, path:)
  if Bolt::Util.powershell?
    show_command = 'Get-BoltPlan -Name '
    run_command  = 'Invoke-BoltPlan -Name '
  else
    show_command = 'bolt plan show'
    run_command  = 'bolt plan run'
  end

  print_message(<<~OUTPUT)
    Created plan '#{name}' at '#{path}'
  
    Show this plan with:
        #{show_command} #{name}
    Run this plan with:
        #{run_command} #{name}
  OUTPUT
end


667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'lib/bolt/outputter/human.rb', line 667

def print_new_policy(name:, path:)
  if Bolt::Util.powershell?
    apply_command = "Invoke-BoltPolicy -Name #{name} -Targets <TARGETS>"
    show_command  = 'Get-BoltPolicy'
  else
    apply_command = "bolt policy apply #{name} --targets <TARGETS>"
    show_command  = 'bolt policy show'
  end

  print_message(<<~OUTPUT)
    Created policy '#{name}' at '#{path}'
    
    Apply this policy with:
        #{apply_command}
    Show available policies with:
        #{show_command}
  OUTPUT
end


264
265
266
267
268
269
# File 'lib/bolt/outputter/human.rb', line 264

def print_plan_finish(event)
  @plan_depth -= 1
  plan = event[:plan]
  duration = event[:duration]
  @stream.puts(colorize(:green, "Finished: plan #{plan} in #{duration_to_string(duration)}"))
end

Parameters:

  • plan (Hash)

    A hash representing the plan



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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/bolt/outputter/human.rb', line 402

def print_plan_info(plan)
  params = plan['parameters'].sort

  info = +''

  # Add plan name and description
  info << colorize(:cyan, "#{plan['name']}\n")

  description = +''
  description << "#{plan['summary']}\n\n" if plan['summary']
  description << plan['docstring'] if plan['docstring']

  info << if description.empty?
            indent(2, 'No description available.')
          else
            indent(2, description.strip)
          end
  info << "\n\n"

  # Build the usage string
  usage = +''
  usage << if Bolt::Util.powershell?
             "Invoke-BoltPlan -Name #{plan['name']}"
           else
             "bolt plan run #{plan['name']}"
           end
  params.each do |name, data|
    usage << (data.include?('default_value') ? " [#{name}=<value>]" : " #{name}=<value>")
  end

  # Add usage
  info << colorize(:cyan, "Usage\n")
  info << indent(2, wrap(usage))
  info << "\n"

  # Add parameters, if any
  if params.any?
    info << colorize(:cyan, "Parameters\n")

    params.each do |name, data|
      info << indent(2, "#{colorize(:yellow, name)}  #{colorize(:dim, data['type'])}\n")
      info << indent(4, "#{wrap(data['description']).chomp}\n") if data['description']
      info << indent(4, "Default: #{data['default_value']}\n") unless data['default_value'].nil?
      info << "\n"
    end
  end

  # Add module location
  info << colorize(:cyan, "Module\n")
  info << if plan['module'].start_with?(Bolt::Config::Modulepath::MODULES_PATH)
            indent(2, 'built-in module')
          else
            indent(2, plan['module'])
          end

  @stream.puts info
end


508
509
510
# File 'lib/bolt/outputter/human.rb', line 508

def print_plan_lookup(value)
  @stream.puts(value)
end

Parameters:



843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
# File 'lib/bolt/outputter/human.rb', line 843

def print_plan_result(plan_result)
  value = plan_result.value
  case value
  when nil
    @stream.puts("Plan completed successfully with no result")
  when Bolt::ApplyFailure, Bolt::RunFailure
    print_result_set(value.result_set)
  when Bolt::ContainerResult
    print_container_result(value)
  when Bolt::ContainerFailure
    print_container_result(value.result)
  when Bolt::ResultSet
    print_result_set(value)
  when Bolt::Result
    print_result(value)
  when Bolt::ApplyResult
    print_apply_result(value)
  when Bolt::Error
    print_bolt_error(**value.to_h.transform_keys(&:to_sym))
  else
    @stream.puts(::JSON.pretty_generate(plan_result, quirks_mode: true))
  end
end


254
255
256
257
258
259
260
261
262
# File 'lib/bolt/outputter/human.rb', line 254

def print_plan_start(event)
  @plan_depth += 1
  # We use this event to both mark the start of a plan _and_ to enable
  # plan logging for `apply`, so only log the message if we were called
  # with a plan
  if event[:plan]
    @stream.puts(colorize(:green, "Starting: plan #{event[:plan]}"))
  end
end


460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/bolt/outputter/human.rb', line 460

def print_plans(plans:, modulepath:)
  command = Bolt::Util.powershell? ? 'Get-BoltPlan -Name <PLAN NAME>' : 'bolt plan show <PLAN NAME>'

  plans = plans.map do |name, description|
    description = truncate(description, 72)
    [name, description]
  end

  @stream.puts colorize(:cyan, 'Plans')
  @stream.puts plans.any? ? format_table(plans, 2) : indent(2, 'No available plans')
  @stream.puts

  @stream.puts colorize(:cyan, 'Modulepath')
  @stream.puts indent(2, modulepath.join(File::PATH_SEPARATOR))
  @stream.puts

  @stream.puts colorize(:cyan, 'Additional information')
  @stream.puts indent(2, "Use '#{command}' to view details and parameters for a specific plan.")
end


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
645
646
# File 'lib/bolt/outputter/human.rb', line 620

def print_plugin_list(plugins:, modulepath:)
  info   = +''
  length = plugins.values.map(&:keys).flatten.map(&:length).max + 4

  plugins.each do |hook, plugin|
    next if plugin.empty?
    next if hook == :validate_resolve_reference

    info << colorize(:cyan, "#{hook}\n")

    plugin.each do |name, description|
      info << indent(2, name.ljust(length))
      info << truncate(description, 80 - length) if description
      info << "\n"
    end

    info << "\n"
  end

  info << colorize(:cyan, "Modulepath\n")
  info << indent(2, "#{modulepath.join(File::PATH_SEPARATOR)}\n\n")

  info << colorize(:cyan, "Additional information\n")
  info << indent(2, "For more information about using plugins see https://pup.pt/bolt-plugins")

  @stream.puts info.chomp
end

Print policies and the modulepath they are loaded from.

Parameters:

  • policies (Array)

    The list of available policies.

  • modulepath (Array)

    The project’s modulepath.



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/bolt/outputter/human.rb', line 691

def print_policy_list(policies:, modulepath:)
  info = +''

  info << colorize(:cyan, "Policies\n")

  if policies.any?
    policies.sort.each { |policy| info << indent(2, "#{policy}\n") }
  else
    info << indent(2, "No available policies\n")
  end

  info << "\n"

  info << colorize(:cyan, "Modulepath\n")
  info << indent(2, modulepath.join(File::PATH_SEPARATOR).to_s)

  @stream.puts info.chomp
end


912
913
914
# File 'lib/bolt/outputter/human.rb', line 912

def print_prompt(prompt)
  @stream.print(colorize(:cyan, indent(4, prompt)))
end


916
917
918
# File 'lib/bolt/outputter/human.rb', line 916

def print_prompt_error(message)
  @stream.puts(colorize(:red, indent(4, message)))
end


872
873
874
875
876
877
878
# File 'lib/bolt/outputter/human.rb', line 872

def print_puppetfile_result(success, puppetfile, moduledir)
  if success
    @stream.puts("Successfully synced modules from #{puppetfile} to #{moduledir}")
  else
    @stream.puts(colorize(:red, "Failed to sync modules from #{puppetfile} to #{moduledir}"))
  end
end


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
# File 'lib/bolt/outputter/human.rb', line 152

def print_result(result)
  if result.success?
    @stream.puts(colorize(:green, "Finished on #{result.target.safe_name}:"))
  else
    @stream.puts(colorize(:red, "Failed on #{result.target.safe_name}:"))
  end

  if result.error_hash
    @stream.puts(colorize(:red, remove_trail(indent(2, result.error_hash['msg']))))
  end

  if result.is_a?(Bolt::ApplyResult) && @verbose
    result.resource_logs.each do |log|
      # Omit low-level info/debug messages
      next if %w[info debug].include?(log['level'])
      message = format_log(log)
      @stream.puts(indent(2, message))
    end
  end

  # Only print results if there's something other than empty string and hash
  if result.value.empty? || (result.value.keys == ['_output'] && !result.message?)
    @stream.puts(indent(2, "#{result.action.capitalize} completed successfully with no result"))
  else
    # Only print messages that have something other than whitespace
    if result.message?
      @stream.puts(remove_trail(indent(2, result.message)))
    end
    case result.action
    when 'command', 'script'
      safe_value = result.safe_value
      if safe_value["merged_output"]
        @stream.puts(indent(2, safe_value['merged_output'])) unless safe_value['merged_output'].strip.empty?

      else # output stdout or stderr
        unless safe_value['stdout'].nil? || safe_value['stdout'].strip.empty?
          @stream.puts(indent(2, "STDOUT:"))
          @stream.puts(indent(4, safe_value['stdout']))
        end
        unless safe_value['stderr'].nil? || safe_value['stderr'].strip.empty?
          @stream.puts(indent(2, "STDERR:"))
          @stream.puts(indent(4, safe_value['stderr']))
        end
      end
    when 'lookup'
      @stream.puts(indent(2, Bolt::Util::Format.stringify(result['value'])))
    else
      if result.generic_value.any?
        @stream.puts(indent(2, ::JSON.pretty_generate(result.generic_value)))
      end
    end
  end
end


867
868
869
870
# File 'lib/bolt/outputter/human.rb', line 867

def print_result_set(result_set)
  result_set.each { |result| print_result(result) }
  print_summary(result_set)
end


120
121
122
# File 'lib/bolt/outputter/human.rb', line 120

def print_start(target)
  @stream.puts(colorize(:green, "Started on #{target.safe_name}..."))
end


228
229
230
231
232
233
# File 'lib/bolt/outputter/human.rb', line 228

def print_step_finish(description:, result:, duration:, **_kwargs)
  failures = result.error_set.length
  plural = failures == 1 ? '' : 's'
  message = "Finished: #{description} with #{failures} failure#{plural} in #{duration.round(2)} sec"
  @stream.puts(colorize(:green, message))
end


219
220
221
222
223
224
225
226
# File 'lib/bolt/outputter/human.rb', line 219

def print_step_start(description:, targets:, **_kwargs)
  target_str = if targets.length > 5
                 "#{targets.count} targets"
               else
                 targets.map(&:safe_name).join(', ')
               end
  @stream.puts(colorize(:green, "Starting: #{description} on #{target_str}"))
end


271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/bolt/outputter/human.rb', line 271

def print_summary(results, elapsed_time = nil)
  ok_set = results.ok_set
  unless ok_set.empty?
    @stream.puts format('Successful on %<size>d target%<plural>s: %<names>s',
                        size: ok_set.size,
                        plural: ok_set.size == 1 ? '' : 's',
                        names: ok_set.targets.map(&:safe_name).join(','))
  end

  error_set = results.error_set
  unless error_set.empty?
    @stream.puts colorize(:red,
                          format('Failed on %<size>d target%<plural>s: %<names>s',
                                 size: error_set.size,
                                 plural: error_set.size == 1 ? '' : 's',
                                 names: error_set.targets.map(&:safe_name).join(',')))
  end

  total_msg = format('Ran on %<size>d target%<plural>s',
                     size: results.size,
                     plural: results.size == 1 ? '' : 's')
  total_msg << " in #{duration_to_string(elapsed_time)}" unless elapsed_time.nil?
  @stream.puts total_msg
end

Print detailed target information.

Parameters:

  • adhoc (Hash)

    Adhoc targets provided on the command line.

  • inventory (Hash)

    Targets provided from the inventory.

  • flag (Boolean)

    Whether a targeting command-line option was used.



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/bolt/outputter/human.rb', line 746

def print_target_info(adhoc:, inventory:, flag:, **_kwargs)
  targets = (adhoc[:targets] + inventory[:targets]).sort_by { |t| t['name'] }

  info = +''

  if targets.any?
    adhoc_text = colorize(:yellow, " (Not found in inventory file)")

    targets.each do |target|
      info << colorize(:cyan, target['name'])
      info << adhoc_text if adhoc[:targets].include?(target)
      info << "\n"
      info << indent(2, target.to_yaml.lines.drop(1).join)
      info << "\n"
    end
  else
    info << colorize(:cyan, "Targets\n")
    info << indent(2, "No targets\n\n")
  end

  info << format_inventory_source(inventory[:file], inventory[:default])
  info << format_target_summary(inventory[:count], adhoc[:count], flag, true)

  @stream.puts info
end

Print target names and where they came from.

Parameters:

  • adhoc (Hash)

    Adhoc targets provided on the command line.

  • inventory (Hash)

    Targets provided from the inventory.

  • flag (Boolean)

    Whether a targeting command-line option was used.



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/bolt/outputter/human.rb', line 716

def print_targets(adhoc:, inventory:, flag:, **_kwargs)
  adhoc_text = colorize(:yellow, "(Not found in inventory file)")

  targets  = []
  targets += inventory[:targets].map { |target| [target['name'], nil] }
  targets += adhoc[:targets].map { |target| [target['name'], adhoc_text] }

  info = +''

  # Add target list
  info << colorize(:cyan, "Targets\n")
  info << if targets.any?
            format_table(targets, 2, 2).to_s
          else
            indent(2, 'No targets')
          end
  info << "\n\n"

  info << format_inventory_source(inventory[:file], inventory[:default])
  info << format_target_summary(inventory[:count], adhoc[:count], flag, false)

  @stream.puts info
end

Print information about a task.

Parameters:



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
# File 'lib/bolt/outputter/human.rb', line 343

def print_task_info(task:)
  params = (task.parameters || []).sort

  info = +''

  # Add task name and description
  info << colorize(:cyan, "#{task.name}\n")
  info << if task.description
            indent(2, task.description.chomp)
          else
            indent(2, 'No description available.')
          end
  info << "\n\n"

  # Build usage string
  usage = +''
  usage << if Bolt::Util.powershell?
             "Invoke-BoltTask -Name #{task.name} -Targets <targets>"
           else
             "bolt task run #{task.name} --targets <targets>"
           end
  usage << (Bolt::Util.powershell? ? ' [-Noop]' : ' [--noop]') if task.supports_noop
  params.each do |name, data|
    usage << if data['type']&.start_with?('Optional') || data.key?('default')
               " [#{name}=<value>]"
             else
               " #{name}=<value>"
             end
  end

  # Add usage
  info << colorize(:cyan, "Usage\n")
  info << indent(2, wrap(usage))
  info << "\n"

  # Add parameters, if any
  if params.any?
    info << colorize(:cyan, "Parameters\n")
    params.each do |name, data|
      info << indent(2, "#{colorize(:yellow, name)}  #{colorize(:dim, data['type'] || 'Any')}\n")
      info << indent(4, "#{wrap(data['description']).chomp}\n") if data['description']
      info << indent(4, "Default: #{data['default'].inspect}\n") if data.key?('default')
      info << "\n"
    end
  end

  # Add module location
  path = task.files.first['path'].chomp("/tasks/#{task.files.first['name']}")
  info << colorize(:cyan, "Module\n")
  info << if path.start_with?(Bolt::Config::Modulepath::MODULES_PATH)
            indent(2, 'built-in module')
          else
            indent(2, path)
          end

  @stream.puts info
end

List available tasks.

Parameters:

  • tasks (Array)

    A list of task names and descriptions.

  • modulepath (Array)

    The modulepath.



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/bolt/outputter/human.rb', line 319

def print_tasks(tasks:, modulepath:)
  command = Bolt::Util.powershell? ? 'Get-BoltTask -Name <TASK NAME>' : 'bolt task show <TASK NAME>'

  tasks = tasks.map do |name, description|
    description = truncate(description, 72)
    [name, description]
  end

  @stream.puts colorize(:cyan, 'Tasks')
  @stream.puts tasks.any? ? format_table(tasks, 2) : indent(2, 'No available tasks')
  @stream.puts

  @stream.puts colorize(:cyan, 'Modulepath')
  @stream.puts indent(2, modulepath.join(File::PATH_SEPARATOR))
  @stream.puts

  @stream.puts colorize(:cyan, 'Additional information')
  @stream.puts indent(2, "Use '#{command}' to view details and parameters for a specific task.")
end

Print available guide topics.

Parameters:

  • topics (Array)

    The available topics.



484
485
486
487
488
489
490
# File 'lib/bolt/outputter/human.rb', line 484

def print_topics(topics:, **_kwargs)
  info = +"#{colorize(:cyan, 'Topics')}\n"
  info << indent(2, topics.join("\n"))
  info << "\n\n#{colorize(:cyan, 'Additional information')}\n"
  info << indent(2, "Use 'bolt guide <TOPIC>' to view a specific guide.")
  @stream.puts info
end

#remove_trail(string) ⇒ Object



55
56
57
# File 'lib/bolt/outputter/human.rb', line 55

def remove_trail(string)
  string.sub(/\s\z/, '')
end

#start_spinObject



37
38
39
40
41
42
43
44
45
46
# File 'lib/bolt/outputter/human.rb', line 37

def start_spin
  return unless @spin && @stream.isatty && !@spinning
  @spinning = true
  @spin_thread = Thread.new do
    loop do
      sleep(0.1)
      @stream.print(colorize(:cyan, @pinwheel.rotate!.first + "\b"))
    end
  end
end

#stop_spinObject



48
49
50
51
52
53
# File 'lib/bolt/outputter/human.rb', line 48

def stop_spin
  return unless @spin && @stream.isatty && @spinning
  @spinning = false
  @spin_thread.terminate
  @stream.print("\b")
end

#truncate(string, width = 80) ⇒ Object

Trims a string to a specified width, adding an ellipsis if it’s longer.



69
70
71
72
# File 'lib/bolt/outputter/human.rb', line 69

def truncate(string, width = 80)
  return string unless string.is_a?(String) && string.length > width
  string.lines.first[0...width].gsub(/\s\w+\s*$/, '...')
end

#wrap(string, width = 80) ⇒ Object

Wraps a string to the specified width. Lines only wrap at whitespace.



62
63
64
65
# File 'lib/bolt/outputter/human.rb', line 62

def wrap(string, width = 80)
  return string unless string.is_a?(String)
  string.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n")
end