Skip to content

feat/fix/multi battery display #348

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Theoreticallyhugo
Copy link
Collaborator

@Theoreticallyhugo Theoreticallyhugo commented Jul 9, 2025

support multiple batteries

upgrading the battery widget to display an arbitrary amount of detected batteries.

battery label

the battery label can be removed, set at just the leftmost end, or set for each battery individually.
setting multiple battery labels requires separating them with newlines

# setting multiple labels
set -g @dracula-battery-label "1:\n2:"
# setting one label
set -g @dracula-battery-label "bat"
# setting no label
set -g @dracula-battery-label false

battery divider

as soon as there is more than one battery, a divider can be set. with the following being the default setting.

set -g @dracula-battery-separator "; "

nerdfont battery status

the battery status continues to be displayed as nerdfont glyph for each battery individually, as it was for one battery before.

tested under:

  • linux (x86 with two batteries) with and without acpi
  • linux (x86 with one battery) with and without acpi
  • linux (x86 without battery) with and without acpi
  • MacOS (apple silicon with one battery)

Copy link

coderabbitai bot commented Jul 9, 2025

📝 Walkthrough

Walkthrough

The documentation and battery status script were updated to support and clarify handling of multiple batteries. The script now processes arrays of battery data, displays each battery's label, icon, and percentage individually, and introduces a configuration option for custom separators. Documentation was updated to reflect these multi-battery configuration options.

Changes

File(s) Change Summary
docs/CONFIG.md Expanded documentation for the battery plugin to explain multi-battery support, label configuration, and separators.
scripts/battery.sh Refactored to support multiple batteries: renamed main status function, added parsing function, iterates over arrays for per-battery display, and improved configuration handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant BatteryScript
    participant System

    User->>BatteryScript: Run battery.sh
    BatteryScript->>System: Query battery percentages, statuses, and labels
    System-->>BatteryScript: Return percentages, statuses, labels (possibly multiple)
    BatteryScript->>BatteryScript: Split data into arrays
    loop For each battery
        BatteryScript->>BatteryScript: parse_battery_status(percentage, status)
        BatteryScript->>User: Output label, icon, percentage (with separator)
    end
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/battery-status

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Theoreticallyhugo Theoreticallyhugo marked this pull request as ready for review July 20, 2025 10:26
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
scripts/battery.sh (1)

90-150: parse_battery_status recreates the same associative arrays on every call

Declaring the 11-element maps inside the function for every battery is
needless work. Move them to file scope or declare them local -g once, then
index them inside the function. It makes the hot-path loop lighter and easier
to read.

docs/CONFIG.md (1)

212-223: Clarify newline usage in tmux options

The example uses an actual line-break inside the quoted string:

set -g @dracula-battery-label "1:\n2:"

tmux will store the literal “\n”, not a newline.
To embed real newlines you need either:

set -g @dracula-battery-label "1:

or escape with $'...':

set -g @dracula-battery-label $'1:\n2:'

Worth mentioning to prevent confusion.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89d16fd and e3f927b.

📒 Files selected for processing (2)
  • docs/CONFIG.md (1 hunks)
  • scripts/battery.sh (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
scripts/battery.sh (1)
scripts/utils.sh (1)
  • get_tmux_option (3-12)

Comment on lines 174 to 176
bat_perc=$(battery_percent)
bat_perc="${bat_perc%\%}"

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Percent sign removed only from LAST battery – breaks arithmetic for the others

${bat_perc%\%} strips the % at one trailing location.
With multiple batteries (70%\n60%) the result becomes 70%\n60, so the first value still carries % and parse_battery_status later receives 70%, triggering “value too great for base” or “invalid arithmetic” errors.

- bat_perc="${bat_perc%\%}"
+# drop “%” from *every* line
+bat_perc=$(tr -d '%' <<<"$bat_perc")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bat_perc=$(battery_percent)
bat_perc="${bat_perc%\%}"
bat_perc=$(battery_percent)
bat_perc=$(tr -d '%' <<<"$bat_perc")
🤖 Prompt for AI Agents
In scripts/battery.sh around lines 174 to 176, the code removes the percent sign
only from the last battery percentage value, causing errors when multiple
batteries are present. Modify the code to remove the percent signs from all
battery percentage values by processing each value individually or using a
method that strips '%' from every entry before further arithmetic operations.

Comment on lines +183 to +186
IFS=$'\n' read -rd '' -a percs <<<"$bat_perc"
IFS=$'\n' read -rd '' -a stats <<<"$(get_battery_status)"
IFS=$'\n' read -rd '' -a lbls <<<"$bat_label"
show_bat_label=$(get_tmux_option "@dracula-show-battery-status" false)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

read -rd '' is invalid – arrays stay empty

read’s -d expects a single delimiter character; an empty string yields
read: -d: option requires an argument, so the arrays never populate and the
widget silently prints nothing.

A portable Bash way:

-IFS=$'\n' read -rd '' -a percs <<<"$bat_perc"
-IFS=$'\n' read -rd '' -a stats <<<"$(get_battery_status)"
-IFS=$'\n' read -rd '' -a lbls  <<<"$bat_label"
+readarray -t percs <<<"$bat_perc"
+readarray -t stats <<<"$(get_battery_status)"
+readarray -t lbls  <<<"$bat_label"

Alternatively, keep read:

IFS=$'\n' read -r -a percs <<<"$bat_perc"
🤖 Prompt for AI Agents
In scripts/battery.sh around lines 183 to 186, the use of 'read -rd ''' is
invalid because the -d option requires a single delimiter character and an empty
string causes the arrays to remain empty. To fix this, remove the '-d ''' option
and use 'read -r -a' with IFS set to newline to correctly populate the arrays
from the input strings.

Comment on lines +187 to +196
for ((i=0; i<num_bats; i++)); do
if [[ i -gt 0 ]]; then
echo -n "$(get_tmux_option "@dracula-battery-separator" "; ")"
fi
echo -n "${lbls[$i]}"
if $show_bat_label; then
echo -n "$(parse_battery_status "${percs[$i]}" "${stats[$i]}") "
fi
echo -n "${percs[$i]}%"
done
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid per-iteration tmux calls & off-by-one risk

  1. get_tmux_option "@dracula-battery-separator" "; " is executed for every
    battery. Cache once before the loop to halve tmux round-trips.

  2. num_bats=$(wc -l <<<"$bat_perc") undercounts when the last line lacks a
    trailing newline and overcounts if bat_perc was empty.
    You already have percs; just use its length.

- num_bats=$(wc -l <<< "$bat_perc")
+num_bats=${#percs[@]}- if [[ i -gt 0 ]]; then
-   echo -n "$(get_tmux_option "@dracula-battery-separator" "; ")"
+if (( i > 0 )); then
+  echo -n "$bat_sep"
 fi
bat_sep=$(get_tmux_option "@dracula-battery-separator" "; ")
🤖 Prompt for AI Agents
In scripts/battery.sh around lines 187 to 196, avoid calling get_tmux_option
inside the loop by caching its result in a variable before the loop starts.
Also, replace the calculation of num_bats using wc -l on bat_perc with using the
length of the percs array to prevent off-by-one errors and incorrect counts when
bat_perc is empty or lacks a trailing newline. Update the loop to use the cached
separator variable and the corrected num_bats value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant