Class: Utils::LineBlamer

Inherits:
Object show all
Defined in:
lib/utils/line_blamer.rb

Overview

A class for analyzing and retrieving git blame information for specific lines of code.

This class provides functionality to initialize with a file path and line number, and then perform git blame operations to obtain information about when and by whom that specific line was last modified. It serves as a utility for developers to quickly access historical context for individual lines of code within their projects.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, lineno = 1) ⇒ LineBlamer

Initializes a new LineBlamer instance to analyze source code line information.

Parameters:

  • file (String)

    the path to the file containing the line of code

  • lineno (Integer) (defaults to: 1)

    the line number within the file (defaults to 1)



16
17
18
# File 'lib/utils/line_blamer.rb', line 16

def initialize(file, lineno = 1)
  @file, @lineno = file, lineno
end

Class Method Details

.for_line(line) ⇒ Utils::LineBlamer?

Finds the source location of a line and creates a new LineBlamer instance.

This method extracts the file path and line number from the given line object using its source_location method. If a valid location is found, it initializes and returns a new LineBlamer instance with the extracted file path and line number.

information

has a valid source location, otherwise nil

Parameters:

  • line (Object)

    the line object to analyze for source location

Returns:



32
33
34
# File 'lib/utils/line_blamer.rb', line 32

def self.for_line(line)
  location = line.source_location and new(*location)
end

Instance Method Details

#perform(options = '') ⇒ String?

Performs git blame on a specific line of code and returns the result.

This method executes a git blame command to analyze the specified file and line number, retrieving information about when and by whom the line was last modified. It handles potential errors from git by suppressing stderr output and returns nil if git is not available or the operation fails.

Parameters:

  • options (String) (defaults to: '')

    additional options to pass to the git blame command

Returns:

  • (String, nil)

    the output of the git blame command if successful, otherwise nil



47
48
49
# File 'lib/utils/line_blamer.rb', line 47

def perform(options = '')
  `git 2>/dev/null blame #{options} -L #@lineno,+1 "#@file"`.full?
end