Module: SimpleCov::CLI::Badge

Extended by:
Badge, CommandHelpers
Included in:
Badge
Defined in:
lib/simplecov/cli/badge.rb,
lib/simplecov/cli/badge/svg.rb

Defined Under Namespace

Modules: Svg

Constant Summary collapse

TOTAL_KEYS =
{line: "lines", branch: "branches", method: "methods"}.freeze

Constants included from CommandHelpers

CommandHelpers::STATS_ROW_FORMAT

Instance Method Summary collapse

Methods included from CommandHelpers

build_parser, command_name, common_options, error, error_nil, on_help, one?, parse_common, quiet_option, recorded_contexts, stats_row

Instance Method Details

#emit(svg, opts, stdout) ⇒ Object



56
57
58
59
# File 'lib/simplecov/cli/badge.rb', line 56

def emit(svg, opts, stdout)
  opts.fetch(:output) ? File.write(opts.fetch(:output), svg) : stdout.puts(svg)
  0
end

#parse(args) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/simplecov/cli/badge.rb', line 32

def parse(args)
  opts = {input: CLI.default_input, criterion: :line,
          label: nil, output: nil} #: Hash[Symbol, untyped]
  build_parser do |parser|
    parser.on("--input PATH") { |v| opts[:input] = v }
    parser.on("--output PATH") { |v| opts[:output] = v }
    parser.on("--criterion C") { |v| opts[:criterion] = v.to_sym }
    parser.on("--label TEXT") { |v| opts[:label] = v }
  end.parse(args)
  opts
end

#percent_for(opts, key, stderr) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/simplecov/cli/badge.rb', line 44

def percent_for(opts, key, stderr)
  document = CoverageFile.load_document(opts.fetch(:input), command: "badge", stderr: stderr)
  return nil unless document

  totals = document["total"]
  percent = totals.dig(key, "percent") if totals.is_a?(Hash)
  return percent if percent.is_a?(Numeric)

  error_nil(stderr, "no #{opts.fetch(:criterion)} totals in #{opts.fetch(:input)} " \
                    "(was the run measuring #{opts.fetch(:criterion)} coverage?)")
end

#run(args, stdout:, stderr:) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/simplecov/cli/badge.rb', line 17

def run(args, stdout:, stderr:)
  opts = parse(args)
  key = TOTAL_KEYS[opts.fetch(:criterion)]
  unless key
    return error(stderr,
      "unknown --criterion #{opts.fetch(:criterion).inspect} (expected line, branch, or method)")
  end

  percent = percent_for(opts, key, stderr)
  return 1 unless percent

  label = opts.fetch(:label) || "#{opts.fetch(:criterion)} coverage"
  emit(Svg.render(label: label, percent: percent), opts, stdout)
end