Module: BruteCLI::Bat

Defined in:
lib/brute_cli/bat.rb

Overview

Thin wrapper around the β€˜bat` command for syntax-highlighted terminal output. Provides two rendering modes: one for unified diffs and one for markdown prose.

Constant Summary collapse

BAT_BIN =
ENV.fetch("BRUTE_BAT_BIN", "bat")
COMMON_FLAGS =
%w[
  --color=always
  --paging=never
].freeze

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns true if the bat binary is found on PATH.

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/brute_cli/bat.rb', line 34

def self.available?
  return @available if defined?(@available)
  @available = ENV["PATH"].to_s.split(File::PATH_SEPARATOR).any? { |dir| File.executable?(File.join(dir, BAT_BIN)) }
end

.diff_mode(text, width: 80) ⇒ Object

Render a unified diff with line numbers and a grid border.

BruteCLI::Bat.diff_mode(patch_text, width: 100)


20
21
22
# File 'lib/brute_cli/bat.rb', line 20

def self.diff_mode(text, width: 80)
  run(text, language: "diff", style: "numbers,grid", width: width)
end

.markdown_mode(text, width: 80) ⇒ Object

Render markdown source with syntax highlighting (headers, bold, fenced code blocks, etc.) β€” no extra decorations so it reads like prose.

BruteCLI::Bat.markdown_mode(md_text, width: 120)


29
30
31
# File 'lib/brute_cli/bat.rb', line 29

def self.markdown_mode(text, width: 80)
  run(text, language: "markdown", style: "plain", width: width)
end

.run(text, language:, style:, width: 80) ⇒ Object

Low-level: pipe text through bat with arbitrary options.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/brute_cli/bat.rb', line 40

def self.run(text, language:, style:, width: 80)
  cmd = [
    BAT_BIN,
    *COMMON_FLAGS,
    "--language=#{language}",
    "--style=#{style}",
    "--terminal-width=#{width}",
  ]

  stdout, status = Open3.capture2(*cmd, stdin_data: text)

  if status.success?
    stdout
  else
    # If bat exits non-zero, return the raw text so we never swallow output.
    text
  end
rescue Errno::ENOENT
  unless @bat_missing_warned
    msg = " bat not found β€” diff syntax highlighting unavailable.\n" \
          " Install: https://github.com/sharkdp/bat#installation "
    $stderr.puts msg.colorize(background: :red, color: :white)
    @bat_missing_warned = true
  end
  text
end