main

square/leakcanary

Last updated at: 29/12/2023 09:39

AnalyzeCommand.kt

TLDR

The provided file (AnalyzeCommand.kt) is part of the Shark CLI project and contains the AnalyzeCommand class. This class extends the CliktCommand class and is responsible for analyzing a heap dump.

Methods

There are no additional methods in the code.

Classes

AnalyzeCommand

The AnalyzeCommand class extends the CliktCommand class and represents the command for analyzing a heap dump. It contains the run function, which retrieves the necessary parameters and calls the analyze function.

The analyze function is a companion function of the CliktCommand class. It takes a heapDumpFile and an optional proguardMappingFile as parameters. It reads the Proguard mapping file if it exists, initializes a list of object inspectors, sets up an analysis progress listener, and performs the heap analysis using the HeapAnalyzer class. Finally, it outputs the heap analysis results using the echo function.

package shark

import com.github.ajalt.clikt.core.CliktCommand
import shark.SharkCliCommand.Companion.echo
import shark.SharkCliCommand.Companion.retrieveHeapDumpFile
import shark.SharkCliCommand.Companion.sharkCliParams
import java.io.File

class AnalyzeCommand : CliktCommand(
  name = "analyze",
  help = "Analyze a heap dump."
) {

  override fun run() {
    val params = context.sharkCliParams
    analyze(retrieveHeapDumpFile(params), params.obfuscationMappingPath)
  }

  companion object {
    fun CliktCommand.analyze(
      heapDumpFile: File,
      proguardMappingFile: File?
    ) {
      val proguardMapping = proguardMappingFile?.let {
        ProguardMappingReader(it.inputStream()).readProguardMapping()
      }
      val objectInspectors = AndroidObjectInspectors.appDefaults.toMutableList()

      val listener = OnAnalysisProgressListener { step ->
        SharkLog.d { "Analysis in progress, working on: ${step.name}" }
      }

      val heapAnalyzer = HeapAnalyzer(listener)
      SharkLog.d { "Analyzing heap dump $heapDumpFile" }

      val heapAnalysis = heapAnalyzer.analyze(
        heapDumpFile = heapDumpFile,
        leakingObjectFinder = FilteringLeakingObjectFinder(
          AndroidObjectInspectors.appLeakingObjectFilters
        ),
        referenceMatchers = AndroidReferenceMatchers.appDefaults,
        computeRetainedHeapSize = true,
        objectInspectors = objectInspectors,
        proguardMapping = proguardMapping,
        metadataExtractor = AndroidMetadataExtractor
      )
      echo(heapAnalysis)
    }
  }
}