Class: HeapProfiler::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/heap_profiler/cli.rb

Constant Summary collapse

SIZE_UNITS =
{
  'B' => 1,
  'K' => 1_000,
  'M' => 1_000_000,
  'G' => 1_000_000_000,
}

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ CLI

Returns a new instance of CLI.



6
7
8
# File 'lib/heap_profiler/cli.rb', line 6

def initialize(argv)
  @argv = argv
end

Instance Method Details

#clean_dump(path) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/heap_profiler/cli.rb', line 50

def clean_dump(path)
  require "json"
  errors = index = 0
  clean_path = "#{path}.clean"
  File.open(clean_path, "w+") do |output|
    File.open(path) do |input|
      input.each_line do |line|
        begin
          JSON.parse(line)
        rescue JSON::ParserError
          errors += 1
          $stderr.puts("Invalid JSON found on line #{index}. Skipping")
        else
          output.print(line)
        end
        index += 1
      end
    end
  end
  $stderr.puts("Processed #{index} lines, removed #{errors} invalid lines")
  $stderr.puts("Clean dump available at #{clean_path}")
end

#parse_byte_size(size_string) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/heap_profiler/cli.rb', line 84

def parse_byte_size(size_string)
  if (match = size_string.match(/\A(\d+)(\w)?B?\z/i))
    digits = Float(match[1])
    base = 1
    unit = match[2]&.upcase
    if unit
      base = SIZE_UNITS.fetch(unit) { raise ArgumentError, "Unknown size unit: #{unit}" }
    end
    size = (digits * base).to_i
    if size > 4_000_000_000
      raise ArgumentError, "Batch size can't be bigger than 4G"
    end
    size
  else
    raise ArgumentError, "#{size_string} is not a valid size"
  end
end


37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/heap_profiler/cli.rb', line 37

def print_report(path)
  results = if File.directory?(path)
    if @retained_only
      DiffResults.new(path, ["retained"])
    else
      DiffResults.new(path)
    end
  else
    HeapResults.new(path)
  end
  results.pretty_print(scale_bytes: true, normalize_paths: true)
end


73
74
75
76
# File 'lib/heap_profiler/cli.rb', line 73

def print_usage
  puts "Usage: #{$PROGRAM_NAME} directory_or_heap_dump"
  puts @parser.help
end

#runObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/heap_profiler/cli.rb', line 10

def run
  parser.parse!(@argv)

  begin
    case @argv.first
    when "clean"
      clean_dump(@argv[1])
      return 0
    when "report"
      print_report(@argv[1])
      return 0
    else
      if @argv.size == 1
        print_report(@argv.first)
        return 0
      end
    end
  rescue CapacityError => error
    STDERR.puts(error.message)
    STDERR.puts("Current size: #{Parser.batch_size}B")
    STDERR.puts("Try increasing it with --batch-size")
    STDERR.puts
  end
  print_usage
  1
end