battery_hearts

Crates.iobattery_hearts
lib.rsbattery_hearts
version0.1.3
created_at2025-10-09 14:45:47.918288+00
updated_at2025-10-09 14:45:47.918288+00
descriptionA terminal battery indicator using hearts - supports both nerdfont symbols and emoji
homepagehttps://github.com/djensenius/battery_hearts
repositoryhttps://github.com/djensenius/battery_hearts
max_upload_size
id1875740
size103,524
David Jensenius (djensenius)

documentation

README

Battery Hearts ๐Ÿ”‹โค๏ธ

Test Lint Build Security

A terminal battery indicator using hearts - supports both nerdfont symbols and emoji!

Features

  • ๐Ÿ”‹ Cross-platform battery status detection (macOS, Linux, Windows)
  • โค๏ธ Two display modes: Nerdfont symbols or emoji hearts
  • โšก Charging/discharging indicators with different symbols for each state
  • ๐ŸŽ›๏ธ Customizable number of hearts and percentage display threshold
  • ๐Ÿš€ Fast and lightweight - written in Rust

Installation

From Releases (Recommended)

Download the latest binary for your platform from the releases page.

# Download and make executable
chmod +x battery_hearts-*
./battery_hearts-* --version

From crates.io

cargo install battery_hearts

From Source

git clone https://github.com/djensenius/battery_hearts.git
cd battery_hearts
cargo build --release
./target/release/battery_hearts

Third-Party Integration

battery_hearts is designed to be easily integrated into other applications, scripts, and tools.

Exit Codes

  • 0: Success - battery status retrieved and displayed
  • 1: Error - could not determine battery status
  • 2: Invalid command-line arguments

JSON Output Mode

For programmatic use, enable JSON output with --json:

battery_hearts --json --emoji

Output format:

{
  "percentage": 0.750,
  "charging": false,
  "hearts": "โค๏ธ โค๏ธ ๐Ÿงก",
  "status": "discharging"
}

Error format:

{
  "error": "Could not determine battery status",
  "percentage": null,
  "charging": null,
  "hearts": null,
  "status": "unknown"
}

Silent Mode

Use --quiet to suppress all error messages for clean script integration:

# Script-friendly usage
if battery_hearts --quiet --json > /dev/null; then
    echo "Battery status available"
else
    echo "Battery unavailable"
fi

Integration Examples

Shell Scripts

#!/bin/bash
# Get battery info in JSON format
BATTERY_JSON=$(battery_hearts --json --emoji)
if [ $? -eq 0 ]; then
    # Parse JSON (requires jq)
    PERCENTAGE=$(echo "$BATTERY_JSON" | jq -r '.percentage')
    CHARGING=$(echo "$BATTERY_JSON" | jq -r '.charging')
    HEARTS=$(echo "$BATTERY_JSON" | jq -r '.hearts')
    
    echo "Battery: ${PERCENTAGE} (${HEARTS})"
else
    echo "Battery status unavailable"
fi

Python Integration

import subprocess
import json
import sys

def get_battery_status():
    try:
        result = subprocess.run(
            ['battery_hearts', '--json', '--emoji'], 
            capture_output=True, 
            text=True,
            check=True
        )
        return json.loads(result.stdout)
    except (subprocess.CalledProcessError, json.JSONDecodeError):
        return None

# Usage
battery = get_battery_status()
if battery and 'error' not in battery:
    print(f"Battery: {battery['percentage']:.1%} ({battery['hearts']})")
    print(f"Status: {battery['status']}")
else:
    print("Battery status unavailable")

Node.js Integration

const { execSync } = require('child_process');

function getBatteryStatus() {
    try {
        const output = execSync('battery_hearts --json --emoji', { 
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'] 
        });
        return JSON.parse(output);
    } catch (error) {
        return null;
    }
}

// Usage
const battery = getBatteryStatus();
if (battery && !battery.error) {
    console.log(`Battery: ${(battery.percentage * 100).toFixed(1)}% (${battery.hearts})`);
    console.log(`Status: ${battery.status}`);
} else {
    console.log('Battery status unavailable');
}

Status Bar Integration

tmux:

# Add to .tmux.conf
set -g status-right '#(battery_hearts --emoji) %Y-%m-%d %H:%M'

Waybar (Wayland):

{
    "custom/battery-hearts": {
        "exec": "battery_hearts --emoji",
        "interval": 30,
        "format": "{}",
        "tooltip": false
    }
}

Polybar (X11):

[module/battery-hearts]
type = custom/script
exec = battery_hearts --emoji
interval = 30

Reliability Considerations

  1. Always check exit codes when integrating
  2. Use --quiet mode to avoid stderr pollution in scripts
  3. Handle JSON parsing errors gracefully
  4. Set reasonable timeouts (tool typically runs in <100ms)
  5. Consider caching results for frequently-called integrations

Performance

  • Startup time: ~50-100ms (varies by platform)
  • Memory usage: <2MB
  • No external dependencies required
  • Cross-platform compatible

Usage

Basic Usage

# Show battery with nerdfont hearts (default)
battery_hearts

# Show battery with emoji hearts
battery_hearts --emoji

Visual Examples

Nerdfont mode (requires nerdfont compatible terminal):

๓ฐ‹‘ ๓ฐ‹‘ ๓ฑฑ   # ~67% charging
๓ฐ‹‘ ๓ฐ›ž ๓ฑฒ   # ~50% discharging

Emoji mode (works in any terminal):

โค๏ธ โค๏ธ โšก   # ~67% charging
โค๏ธ ๐Ÿงก ๐Ÿ”‹   # ~50% discharging

Options

# Customize number of hearts
battery_hearts --max-hearts 5 --emoji

# Show percentage when battery is low
battery_hearts --threshold 0.25 --emoji

# Run visual test showing all battery levels
battery_hearts --test --emoji

# Use custom battery command
battery_hearts --cmd "your_custom_battery_command"

# Show help
battery_hearts --help

Symbol Reference

Nerdfont Symbols

  • ๓ฐ‹‘ Full heart
  • ๓ฐ›ž Half heart
  • ๓ฐ‹• Empty heart
  • ๓ฑฑ Empty charging
  • ๓ฑฒ Empty discharging
  • ๓ฑฎ Full charging
  • ๓ฑฏ Full discharging

Emoji Symbols

  • โค๏ธ Full heart
  • ๐Ÿงก Half heart
  • ๐Ÿค Empty heart
  • โšก Empty charging
  • ๐Ÿ”‹ Empty discharging
  • ๐Ÿ’š Full charging
  • ๐Ÿ’” Full discharging

Configuration

Environment Variables

Set BATTERY_CMD to override the default battery detection command:

export BATTERY_CMD="your_custom_command"
battery_hearts

Platform Support

  • macOS: Uses pmset (built-in)
  • Linux: Uses acpi or upower (may need installation)
  • Windows: Uses PowerShell WMI/CIM (built-in)

Development

Prerequisites

Building

cargo build

Testing

# Run unit tests
cargo test

# Run visual tests
cargo run -- --test --emoji

# Lint and format
cargo clippy --all-targets --all-features
cargo fmt --all

CI/CD

This project uses GitHub Actions for:

  • โœ… Linting with rustfmt and clippy
  • โœ… Testing on multiple platforms
  • โœ… Building release binaries
  • ๐Ÿ”’ Security auditing with cargo-audit

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests and linting: cargo test && cargo clippy && cargo fmt
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Credits

Inspired by the need for a simple, cross-platform battery indicator that works well in terminal status bars and tmux configurations.

Commit count: 0

cargo fmt