Skip to content

Conversation

@ekain-fr
Copy link

@ekain-fr ekain-fr commented Oct 11, 2025

Summary

Enhances the Git segment to display the count of dirty files (modified, staged, untracked) next to the status indicator, providing immediate visibility into repository state without running git commands.

Visual Examples:

  • Clean: 🌿 master ✓
  • Dirty without count: 🌿 feat/branch ●
  • Dirty with count: 🌿 feat/branch ● 11 ← NEW
  • With SHA: 🌿 feat/branch ● 11 a1b2c3d (both options enabled)

Changes

Core Git Segment (src/core/segments/git.rs)

  • Add dirty_count: u32 field to GitInfo struct
  • Modify get_status() to return (GitStatus, u32) tuple
    • Parses git status --porcelain output
    • Counts non-empty lines (1 line = 1 file)
  • Update display logic in collect() method:
    • Format: ● 5 (dirty), ⚠ 3 (conflicts), (clean)
  • Add with_dirty_count() builder method for configuration
  • Store dirty_count in metadata for future use

Statusline Integration (src/core/statusline.rs)

  • Read show_dirty_count option from segment configuration
  • Pass option to GitSegment via builder pattern

Theme Configuration (9 files: src/ui/themes/theme_*.rs)

  • Add show_dirty_count: true to all themes by default
  • Consistent configuration across all theme presets:
    • Cometix, Default, Gruvbox, Minimal, Nord
    • Powerline Dark, Powerline Light, Powerline Rose Pine, Powerline Tokyo Night

TUI Configurator Integration

src/ui/components/segment_list.rs:

  • Add ShowSha and ShowDirtyCount to FieldSelection enum

src/ui/components/settings.rs:

  • Display Git-specific options in Settings panel
  • Show checkbox toggles for both options

src/ui/app.rs:

  • Add GIT_SEGMENT_FIELD_COUNT constant (9 fields)
  • Implement field navigation for Git segment options
  • Add toggle handlers for show_sha and show_dirty_count
  • Update field index mapping

src/ui/components/preview.rs:

  • Update mock data to respect Git segment options
  • Dynamically build secondary status based on configuration
  • Preview now shows real-time updates when toggling options

Configuration

Users can control this feature via config:

[segments.options]
show_sha = false            # Existing option
show_dirty_count = true     # New option (default: enabled)

TUI Navigation

  1. Open configurator: ccline --config
  2. Navigate to Git segment (↑/↓)
  3. Switch to Settings panel (Tab)
  4. Select "Show Dirty Count" (↑/↓)
  5. Toggle with Enter
  6. Preview updates in real-time

Default Behavior

Enabled by default in all themes:

  • Provides valuable repository state information
  • Minimal visual clutter (just a number)
  • Easy to disable if not desired

Testing

  • ✅ Compiles successfully: cargo build --release
  • ✅ Tests pass: cargo test
  • ✅ Accuracy verified: Matches git status --porcelain | wc -l
  • ✅ TUI configurator: Options visible and toggle correctly
  • ✅ Preview updates: Real-time feedback when toggling
  • ✅ All 9 themes updated consistently

Tested scenarios:

  • Clean repository (0 files): Shows
  • Dirty files: Shows ● 11 (11 files)
  • With conflicts: Shows ⚠ 3 (3 conflicted files)
  • Option disabled: Shows (backward compatible)
  • Option enabled: Shows ● 5 (with count)

Implementation Details

Performance: Uses existing git status --porcelain call, just adds line counting
Compatibility: Non-breaking change, maintains backward compatibility
Configuration: Follows existing pattern (show_sha for Git segment)

Files Changed

15 files changed, 198 insertions(+), 25 deletions(-)

Core:

  • src/core/segments/git.rs (+52, -11)
  • src/core/statusline.rs (+9, -1)

TUI:

  • src/ui/app.rs (+58, -3)
  • src/ui/components/preview.rs (+58, -11)
  • src/ui/components/segment_list.rs (+3)
  • src/ui/components/settings.rs (+34)

Themes (9 files, +1 line each):

  • All theme files in src/ui/themes/

Commits

  1. feat: add dirty file count display to git segment (30b9778)

    • Core implementation in Git segment
    • Theme configuration updates
  2. feat(tui): add Git segment options to TUI configurator (3aca994)

    • TUI integration for both show_sha and show_dirty_count
    • Field navigation and toggle handlers
  3. fix(tui): update Git segment preview to reflect options (7e6a419)

    • Preview component now respects Git options
    • Real-time feedback when toggling

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

Summary by Sourcery

Introduce dirty file count to the Git segment and add two new usage tracking segments with customizable threshold-based warnings; refactor color and threshold logic into shared utilities, extend TUI and themes to support the new options, and update documentation and versioning.

New Features:

  • Add dirty file count display to Git segment with toggleable option
  • Introduce dedicated Usage5Hour and Usage7Day segments for focused API usage tracking
  • Enable threshold-based warning and critical colors and bold styling for usage segments

Enhancements:

  • Refactor ANSI color conversion into a shared color_utils module
  • Centralize threshold logic in threshold_utils and apply metadata-driven styling overrides in statusline
  • Expose public helpers for reset time formatting and shared API usage cache loading
  • Integrate new Git and usage options into the TUI configurator and extend theme presets accordingly

Build:

  • Bump version to 1.0.9 in Cargo.toml

Documentation:

  • Update README with new usage segments and threshold-based color configuration
  • Add changelog entry for version 1.0.9

ekain-fr and others added 20 commits October 9, 2025 15:00
Add two new usage segments for enhanced API usage monitoring:
- Usage5Hour: Displays 5-hour usage with reset time (24% -> 11am)
- Usage7Day: Displays 7-day usage with reset datetime (12% -> Oct 9, 5am)

Features:
- Efficient shared API cache to minimize redundant calls
- Dynamic circle icons based on utilization level
- Automatic UTC to local timezone conversion
- Both segments disabled by default (opt-in)

Technical changes:
- Updated API cache structure with separate reset time fields
- Added time formatting functions for 5-hour and 7-day displays
- Updated all 9 built-in themes to include new segments
- Enhanced UI components with new segment name mappings
- Made ApiUsageCache public for cross-module access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add comprehensive documentation for developers running a forked version
of CCometixLine, including:
- How to rebuild after pulling updates
- Installation options (local vs system-wide)
- Steps to clear old theme cache when new segments are added
- Note about binary naming (ccometixline -> ccline)

Also includes version bump to 1.0.9 in Cargo.lock.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…segments

Replace ASCII arrow (->) with Unicode rightwards arrow (→) for cleaner
display in the 5-hour and 7-day usage segments.

Changes:
- usage_5hour.rs: Format now shows "24% → 11am"
- usage_7day.rs: Format now shows "12% → Oct 9, 5am"
- README.md: Updated documentation examples to reflect new format

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Change 7-day usage segment format from "Oct 9, 5am" to "Oct 9:5am"
for more compact display by replacing comma-space with colon.

Changes:
- usage.rs: Updated format_7day_reset_time() to use colon separator
- README.md: Updated documentation example to show "Oct 9:5am"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add dynamic color changing for Usage5Hour and Usage7Day segments based on
utilization thresholds. This provides visual warnings when API usage
approaches limits.

Features:
- Configurable warning threshold (default: 60%)
- Configurable critical threshold (default: 80%)
- Custom colors for warning and critical states
- Independent configuration per segment
- Supports c16, c256, and RGB color formats

Changes:
- theme_*.rs: Added threshold options to usage segment definitions
  - warning_threshold: 60
  - critical_threshold: 80
  - warning_color: c256 226 (yellow)
  - critical_color: c256 196 (red)
- usage_5hour.rs: Implemented get_color_for_utilization() to determine
  threshold-based colors and add text_color_override to metadata
- usage_7day.rs: Same threshold logic as usage_5hour
- statusline.rs: Check for text_color_override in metadata and apply
  instead of default segment colors
- README.md: Added comprehensive documentation for threshold configuration

Usage example:
```toml
[[segments]]
id = "usage_5hour"
[segments.options]
warning_threshold = 60
critical_threshold = 80
warning_color.c256 = 226  # Yellow
critical_color.c256 = 196  # Red
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Implement full TUI support for threshold-based warning colors. Users can
now interactively configure warning/critical thresholds and colors directly
in the TUI configurator without editing config files.

Features:
- New threshold fields shown for Usage5Hour and Usage7Day segments
- Interactive threshold editing (cycle through 40/50/60/70/80/90/95%)
- Color picker integration for warning/critical colors
- Dynamic field navigation based on segment type
- Real-time preview updates

Changes:
- segment_list.rs: Extended FieldSelection enum with:
  - WarningThreshold
  - CriticalThreshold
  - WarningColor
  - CriticalColor

- settings.rs: Conditional display of threshold fields
  - Show threshold fields only for usage segments
  - Extract and display current threshold values from options
  - Display warning/critical colors with proper formatting

- app.rs: Full editing support
  - Dynamic field count (11 for usage segments, 7 for others)
  - Navigation logic updated for threshold fields
  - Threshold cycling (Enter to cycle through common values)
  - Color picker opens for WarningColor/CriticalColor
  - apply_selected_color stores colors in segment options

Usage:
1. Open TUI: ccline -c
2. Navigate to Usage5Hour or Usage7Day segment
3. Use Up/Down to select threshold fields
4. Press Enter to cycle threshold values or open color picker
5. Press [S] to save configuration

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Update TUI preview component to reflect the latest changes to usage segments:

Changes:
- Use Unicode arrow (→) instead of ASCII (->)
- Update 7-day format: "Oct 9:5am" instead of "Oct 9, 5am"
- Add get_threshold_color() method to apply threshold-based color overrides
- Update mock utilization values to demonstrate threshold states:
  - Usage5Hour: 65% (triggers warning color - yellow)
  - Usage7Day: 85% (triggers critical color - red)
- Update dynamic icons to match utilization levels

The preview now accurately shows threshold-based coloring in real-time,
allowing users to see how their threshold settings affect the display
before saving the configuration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Update default threshold colors to use 16-color ANSI palette (c16)
instead of 256-color palette (c256) for better terminal compatibility
and consistency with the TUI display.

Changes:
- theme_default.rs: Changed warning_color from c256:226 to c16:11,
  critical_color from c256:196 to c16:9
- theme_gruvbox.rs: Same color updates for both usage segments
- theme_cometix.rs: Same color updates for both usage segments
- All themes: Updated usage_7day default icon/text color from c16:11
  (yellow) to c16:12 (light blue) for visual differentiation
- README.md: Updated documentation to show c16 defaults

Color mappings:
- Warning: c16:11 (Yellow) - equivalent to c256:226
- Critical: c16:9 (Light Red) - equivalent to c256:196

Benefits:
- Better compatibility with terminals that don't support 256 colors
- Matches TUI configurator display format (16:11, 16:9)
- More consistent with other segment color definitions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add warning_bold and critical_bold options to usage segments, allowing text
to become bold when usage exceeds warning or critical thresholds. This provides
additional visual prominence for high usage states.

Features:
- New options: warning_bold (default: false), critical_bold (default: true)
- Automatic bold text when thresholds are exceeded
- Independent control for warning and critical states
- Works alongside threshold color changes

Default behavior:
- Default/Gruvbox themes: warning=normal, critical=bold
- Cometix theme: warning=bold, critical=bold (matches theme style)

Changes:
- usage_5hour.rs: Added should_be_bold() method to check bold options
  and apply text_bold_override to metadata
- usage_7day.rs: Same should_be_bold() logic for 7-day segment
- statusline.rs: Check for text_bold_override in metadata and apply
  instead of default text_bold style
- theme_*.rs: Added warning_bold and critical_bold options to all themes

Usage example:
```toml
[[segments]]
id = "usage_5hour"
[segments.options]
warning_bold = true   # Make text bold at 60% usage
critical_bold = true  # Make text bold at 80% usage
```

Result: Critical usage now displays in bold red text for maximum visibility!

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…ator

Add full TUI support for configuring warning_bold and critical_bold options in Usage (5-hour) and Usage (7-day) segments.

Changes:
- Add WarningBold and CriticalBold to FieldSelection enum
- Display bold toggle fields in settings panel with [✓]/[ ] indicators
- Add color swatches (██) for warning/critical color fields
- Update navigation to handle 13 fields for usage segments (was 11)
- Add Enter key handlers to toggle bold options
- Show status messages when bold settings are changed
- Update preview in real-time when bold options are toggled

Users can now press Enter on "Warning Bold" or "Critical Bold" fields to toggle them on/off, making it easy to configure threshold-based bold text styling without manual TOML editing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Address code review comments by introducing shared helper functions and
clarifying utilization value format:

**New shared utilities (color_utils.rs):**
- serialize_ansi_color_to_json(): Eliminates duplicated color serialization
- c16_to_ratatui_color(): Centralizes 16-color ANSI to ratatui::Color mapping
- ansi_color_to_ratatui(): Handles all color formats (c16, c256, RGB)

**Refactored files:**
- usage_5hour.rs: Use serialize_ansi_color_to_json(), clarify utilization format
- usage_7day.rs: Use serialize_ansi_color_to_json(), clarify utilization format
- settings.rs: Replace 6 duplicated color mappings with color_utils helpers
- app.rs: Use serialize_ansi_color_to_json() for warning/critical colors
- mod.rs: Export new color_utils module

**Documentation improvements:**
- Added comments clarifying utilization values are percentages (0-100)
- Added comments explaining division by 100 converts to normalized values (0-1)
- This addresses reviewer questions about get_circle_icon expectations

**Code quality improvements:**
- Reduced duplication: ~100 lines of repeated color mapping code eliminated
- Single source of truth: Color conversion logic now centralized
- Maintainability: Future color format changes only require updating one place
- Consistency: All color conversions now use the same helper functions

Addresses review comments from PR code review.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fork enhancements: Usage segments with threshold styling and comprehensive improvements
Extend threshold-based color and bold text support to the context window segment,
matching the implementation from usage segments (5-hour/7-day). This provides
visual feedback when context usage exceeds configurable warning (60%) and critical
(80%) thresholds.

Additionally, fix missing threshold options in usage segments for minimal, nord,
and all powerline themes. These themes were missing the threshold configurations
that were already present in default, gruvbox, and cometix themes.

Changes:
- context_window.rs: Add get_color_for_utilization() and should_be_bold() methods
- app.rs, settings.rs: Include ContextWindow in threshold segment checks for TUI
- All 9 themes: Add threshold options to context_window_segment() functions
- minimal, nord, powerline themes: Add missing threshold options to usage segments

Default thresholds:
- Warning: 60% (yellow, normal weight)
- Critical: 80% (red, bold)
- Cometix theme: Both warning and critical use bold text

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add missing warning/critical threshold configurations to usage 5-hour and
7-day segments in minimal, nord, and all powerline themes. These themes were
missing the threshold options that were already present in default, gruvbox,
and cometix themes.

Adds the following threshold options to usage segments:
- warning_threshold: 60% (triggers yellow color)
- critical_threshold: 80% (triggers red color with bold text)
- warning_color: yellow (ANSI c16: 11)
- critical_color: red (ANSI c16: 9)
- warning_bold: false
- critical_bold: true

This ensures all themes have consistent threshold-based visual feedback for
usage tracking segments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Extend threshold-based color and bold text support to the context window segment,
matching the implementation from usage segments (5-hour/7-day). This provides
visual feedback when context usage exceeds configurable warning (60%) and critical
(80%) thresholds.

**Implementation:**
- context_window.rs: Add get_color_for_utilization() and should_be_bold() methods
  - Uses color_utils::serialize_ansi_color_to_json() from PR Haleclipse#41
  - Checks utilization against warning_threshold (default 60%) and critical_threshold (default 80%)
  - Returns appropriate color/bold overrides based on threshold levels
- app.rs, settings.rs: Include ContextWindow in threshold segment checks for TUI
  - Enables threshold configuration UI for context window segment
  - Adds 6 threshold fields (thresholds, colors, bold flags) to segment settings
- All 9 themes: Add threshold options to context_window_segment() functions
  - warning_threshold: 60%, critical_threshold: 80%
  - warning_color: c16=11 (yellow), critical_color: c16=9 (red)
  - Cometix/Gruvbox: Both thresholds use bold (warning_bold/critical_bold: true)
  - Default/Minimal/Nord/Powerline themes: Only critical uses bold

**Dependencies:**
- Requires color_utils module from PR Haleclipse#41 (enhanced-usage-segments)
- This PR should not be merged until PR Haleclipse#41 is merged

**Default behavior:**
- Warning: 60% utilization → yellow text, normal weight (bold in Cometix/Gruvbox)
- Critical: 80% utilization → red text, bold weight
- Below warning: Uses default segment colors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit addresses all feedback from the PR code review by introducing
shared utilities, config caching, and improving code maintainability.

**Changes:**

1. **New threshold_utils module (addresses duplication concerns)**
   - Created src/core/segments/threshold_utils.rs
   - Extracts shared threshold logic from context_window, usage_5hour, usage_7day
   - Implements config caching using once_cell to avoid repeated disk I/O
   - Provides centralized functions:
     * get_thresholds_for_segment(): Extract warning/critical thresholds
     * get_color_for_utilization(): Determine color based on utilization
     * should_be_bold(): Determine bold text based on utilization

2. **Refactored segments to use shared utilities**
   - context_window.rs: Removed duplicated get_color_for_utilization/should_be_bold
   - usage_5hour.rs: Removed duplicated threshold methods
   - usage_7day.rs: Removed duplicated threshold methods
   - All segments now call threshold_utils functions with SegmentId parameter
   - Reduced ~200 lines of duplicated code

3. **Fixed date formatting (Comment 1)**
   - usage.rs: Changed format_7day_reset_time output from "Oct 9:5am" to "Oct 9, 5am"
   - Added comma for better readability and consistency with comment suggestion

4. **Added field count constants (Comment 3)**
   - app.rs: Defined DEFAULT_SEGMENT_FIELD_COUNT (7) and THRESHOLD_SEGMENT_FIELD_COUNT (13)
   - Replaced inline hardcoded values with named constants
   - Improved maintainability and reduced error risk

5. **Fixed potential panic in color picker (Comment 4)**
   - app.rs: Replaced unwrap() with proper error handling using if-let Ok()
   - Prevents panic if serialize_ansi_color_to_json returns unexpected format
   - Safely handles JSON parsing failures for WarningColor and CriticalColor

**Dependencies:**
- Added once_cell = "1.19" to Cargo.toml for config caching

**Testing:**
- ✅ Compiles successfully with cargo build --release
- ✅ All threshold functionality preserved with shared utilities
- ✅ Config caching reduces disk I/O for threshold checks

**Impact:**
- Eliminated ~200 lines of duplicated code
- Improved performance with config caching
- Better maintainability with centralized threshold logic
- Reduced risk of inconsistencies across segments

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This brings the context window threshold feature and code review improvements
into master, including:

- Context window threshold support (warning/critical color/bold)
- Shared threshold utilities with config caching
- Refactored usage segments to use shared utilities
- Improved date formatting for 7-day reset time
- Field count constants instead of hardcoded values
- Safe error handling in color picker

All code review feedback has been addressed.

Conflict resolution: Accepted refactored version from feature branch which
uses shared threshold_utils instead of duplicated methods.
Enhances the Git segment to display the number of dirty (modified, staged, untracked) files next to the status indicator. This provides immediate visibility into repository state.

- Add dirty_count field to GitInfo struct
- Modify get_status() to count files from git status --porcelain output
- Display format: "● 5" (dirty), "⚠ 3" (conflicts), "✓" (clean)
- Add show_dirty_count configuration option (default: true in all themes)
- Add with_dirty_count() builder method for segment configuration
- Maintain backward compatibility when option is disabled

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Adds show_sha and show_dirty_count configuration options to the TUI
configurator for the Git segment. Users can now toggle these options
interactively using the TUI.

Changes:
- Add ShowSha and ShowDirtyCount to FieldSelection enum
- Display Git options in Settings panel (show_sha, show_dirty_count)
- Add GIT_SEGMENT_FIELD_COUNT constant (9 fields)
- Implement field navigation for Git segment options
- Add toggle handlers for show_sha and show_dirty_count
- Update field index mapping for Git segment

TUI Navigation:
- Navigate to Git segment in Segments panel
- Switch to Settings panel (Tab)
- Use ↑/↓ to select "Show SHA" or "Show Dirty Count"
- Press Enter to toggle the option
- Preview updates in real-time

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…ty_count options

The TUI preview was using hardcoded mock data for the Git segment that
didn't respect the show_sha and show_dirty_count configuration options.
This made it appear that toggling these options in the TUI had no effect
on the preview.

Changes:
- Read show_sha and show_dirty_count from segment config in preview
- Dynamically build Git segment secondary status based on options
- Mock data now shows:
  - "● 5" when show_dirty_count is enabled (5 dirty files)
  - "●" when show_dirty_count is disabled
  - "a1b2c3d" SHA appended when show_sha is enabled
  - Proper status parts joining like real Git segment

Preview now displays:
- show_dirty_count OFF, show_sha OFF: "feat/demo ● ↑2"
- show_dirty_count ON, show_sha OFF: "feat/demo ● 5 ↑2"
- show_dirty_count OFF, show_sha ON: "feat/demo ● ↑2 a1b2c3d"
- show_dirty_count ON, show_sha ON: "feat/demo ● 5 ↑2 a1b2c3d"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@sourcery-ai
Copy link

sourcery-ai bot commented Oct 11, 2025

Reviewer's Guide

This PR extends the Git segment to optionally show the count of dirty files, introduces two dedicated usage segments with threshold-based warning/critical colors, adds shared utilities for color and threshold handling, and updates the TUI configurator, theme presets, and documentation to expose and preview these new features.

Class diagram for new and updated segment types

classDiagram
    class GitSegment {
        +bool show_sha
        +bool show_dirty_count
        +with_sha(show_sha: bool) GitSegment
        +with_dirty_count(show_dirty_count: bool) GitSegment
        +collect(input: InputData) Option<SegmentData>
    }
    class GitInfo {
        +String branch
        +GitStatus status
        +u32 ahead
        +u32 behind
        +Option<String> sha
        +u32 dirty_count
    }
    class UsageSegment {
        +collect(input: InputData) Option<SegmentData>
        +static load_usage_cache() Option<ApiUsageCache>
        +static get_circle_icon(utilization: f64) String
        +static format_5hour_reset_time(reset_time_str: Option<&str>) String
        +static format_7day_reset_time(reset_time_str: Option<&str>) String
    }
    class ApiUsageCache {
        +f64 five_hour_utilization
        +f64 seven_day_utilization
        +Option<String> five_hour_resets_at
        +Option<String> seven_day_resets_at
        +String cached_at
    }
    class Usage5HourSegment {
        +collect(input: InputData) Option<SegmentData>
    }
    class Usage7DaySegment {
        +collect(input: InputData) Option<SegmentData>
    }
    Usage5HourSegment --|> Segment
    Usage7DaySegment --|> Segment
    UsageSegment --|> Segment
    GitSegment --|> Segment
    GitSegment --> GitInfo
    UsageSegment --> ApiUsageCache
    Usage5HourSegment --> UsageSegment
    Usage7DaySegment --> UsageSegment
    ApiUsageCache <.. UsageSegment
Loading

File-Level Changes

Change Details Files
Add dirty file count support to Git segment
  • Extend GitInfo with a dirty_count field
  • Change get_status() to return (GitStatus, count)
  • Add with_dirty_count() builder and store count in metadata
  • Update collect() formatting to show “● N” or “⚠ N” when enabled
src/core/segments/git.rs
Integrate show_dirty_count option into segment collection and statusline
  • Read show_dirty_count from config and pass to GitSegment::with_dirty_count
  • Parse metadata.text_color_override and text_bold_override in StatusLineGenerator
  • Apply these overrides when styling primary/secondary text
src/core/statusline.rs
Implement dedicated 5-hour and 7-day usage segments with threshold logic
  • Split API cache struct to store separate reset times
  • Add load_usage_cache(), format_5hour_reset_time(), format_7day_reset_time() helpers
  • Create Usage5HourSegment and Usage7DaySegment modules sharing cache
  • Enhance context_window to support threshold color and bold overrides
src/core/segments/usage.rs
src/core/segments/usage_5hour.rs
src/core/segments/usage_7day.rs
src/core/segments/context_window.rs
Introduce shared utilities for color serialization and threshold lookup
  • Create color_utils.rs to convert AnsiColor↔ratatui Color and serialize to JSON
  • Create threshold_utils.rs to cache config and compute warning/critical color/bold based on utilization
src/core/segments/color_utils.rs
src/core/segments/threshold_utils.rs
Extend TUI configurator and preview to expose Git and threshold options
  • Add ShowSha and ShowDirtyCount to FieldSelection enum
  • Update SettingsComponent to render checkboxes for new options and threshold fields
  • Adjust App navigation, constants and toggle handlers for Git and usage thresholds
  • Enhance preview generator to mock Git dirty count and threshold-based colors
src/ui/components/segment_list.rs
src/ui/components/settings.rs
src/ui/app.rs
src/ui/components/preview.rs
Update themes, presets, and documentation for new features
  • Enable show_dirty_count by default in all 9 theme files
  • Add usage_5hour and usage_7day segments to presets.rs
  • Document Git dirty count and usage segments in README
  • Record new version and features in CHANGELOG
src/ui/themes/theme_*.rs
src/ui/themes/presets.rs
README.md
CHANGELOG.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • The SettingsComponent and App logic for segment‐specific fields (Git vs. usage thresholds) has grown quite large and repetitive—consider refactoring into smaller helper functions or a data-driven table so adding/removing options is easier.
  • All nine theme files contain nearly identical boilerplate for the new usage_5hour and usage_7day segments—extract a shared helper or macro to generate those presets and reduce manual duplication.
  • threshold_utils caches the Config in a global OnceCell without ever invalidating it, so changes to the TOML won’t take effect in the running TUI—consider exposing a cache-invalidate hook or reloading logic when the config is updated.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The SettingsComponent and App logic for segment‐specific fields (Git vs. usage thresholds) has grown quite large and repetitive—consider refactoring into smaller helper functions or a data-driven table so adding/removing options is easier.
- All nine theme files contain nearly identical boilerplate for the new usage_5hour and usage_7day segments—extract a shared helper or macro to generate those presets and reduce manual duplication.
- threshold_utils caches the Config in a global OnceCell without ever invalidating it, so changes to the TOML won’t take effect in the running TUI—consider exposing a cache-invalidate hook or reloading logic when the config is updated.

## Individual Comments

### Comment 1
<location> `src/core/segments/usage.rs:70` </location>
<code_context>

-    fn get_cache_path() -> Option<std::path::PathBuf> {
+    /// Format 5-hour reset time as "11am" or "5pm"
+    pub fn format_5hour_reset_time(reset_time_str: Option<&str>) -> String {
+        if let Some(time_str) = reset_time_str {
+            if let Ok(dt) = DateTime::parse_from_rfc3339(time_str) {
</code_context>

<issue_to_address>
**suggestion:** Consider handling time zone edge cases for reset time formatting.

If time zone differences are possible, please clarify or document how reset times are handled for users in various time zones.
</issue_to_address>

### Comment 2
<location> `src/core/segments/usage.rs:161` </location>
<code_context>
     }

+    /// Public helper to load cache for other usage segments
+    pub fn load_usage_cache() -> Option<ApiUsageCache> {
+        let cache_path = Self::get_cache_path()?;
+        if !cache_path.exists() {
</code_context>

<issue_to_address>
**suggestion (performance):** Repeated file reads may impact performance if called frequently.

Consider caching the loaded usage data in memory during a render cycle, or implementing a cache invalidation strategy to avoid repeated disk reads.

Suggested implementation:

```rust
    use once_cell::sync::OnceCell;
    use std::sync::Mutex;

    static USAGE_CACHE: OnceCell<Mutex<Option<ApiUsageCache>>> = OnceCell::new();

    /// Public helper to load cache for other usage segments
    pub fn load_usage_cache() -> Option<ApiUsageCache> {
        let cache = USAGE_CACHE.get_or_init(|| Mutex::new(None));
        let mut cache_guard = cache.lock().unwrap();

        if cache_guard.is_some() {
            return cache_guard.clone();
        }

        let cache_path = Self::get_cache_path()?;
        if !cache_path.exists() {
            return None;
        }

        let content = std::fs::read_to_string(&cache_path).ok()?;
        let parsed = serde_json::from_str(&content).ok();
        *cache_guard = parsed.clone();
        parsed
    }

```

```rust
    fn save_cache(&self, cache: &ApiUsageCache) {
        if let Some(cache_path) = Self::get_cache_path() {
            if let Some(parent) = cache_path.parent() {
                // Invalidate and update the in-memory cache after saving
                if let Some(cell) = USAGE_CACHE.get() {
                    let mut cache_guard = cell.lock().unwrap();
                    *cache_guard = Some(cache.clone());
                }
            }

```

- You may need to add `once_cell = "1.17"` (or latest) to your `Cargo.toml` dependencies.
- Ensure `ApiUsageCache` implements `Clone` if it does not already.
- If you want to support cache invalidation on file changes outside this process, consider adding a timestamp or file watcher.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

}

/// Public helper to load cache for other usage segments
pub fn load_usage_cache() -> Option<ApiUsageCache> {
Copy link

Choose a reason for hiding this comment

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

suggestion (performance): Repeated file reads may impact performance if called frequently.

Consider caching the loaded usage data in memory during a render cycle, or implementing a cache invalidation strategy to avoid repeated disk reads.

Suggested implementation:

    use once_cell::sync::OnceCell;
    use std::sync::Mutex;

    static USAGE_CACHE: OnceCell<Mutex<Option<ApiUsageCache>>> = OnceCell::new();

    /// Public helper to load cache for other usage segments
    pub fn load_usage_cache() -> Option<ApiUsageCache> {
        let cache = USAGE_CACHE.get_or_init(|| Mutex::new(None));
        let mut cache_guard = cache.lock().unwrap();

        if cache_guard.is_some() {
            return cache_guard.clone();
        }

        let cache_path = Self::get_cache_path()?;
        if !cache_path.exists() {
            return None;
        }

        let content = std::fs::read_to_string(&cache_path).ok()?;
        let parsed = serde_json::from_str(&content).ok();
        *cache_guard = parsed.clone();
        parsed
    }
    fn save_cache(&self, cache: &ApiUsageCache) {
        if let Some(cache_path) = Self::get_cache_path() {
            if let Some(parent) = cache_path.parent() {
                // Invalidate and update the in-memory cache after saving
                if let Some(cell) = USAGE_CACHE.get() {
                    let mut cache_guard = cell.lock().unwrap();
                    *cache_guard = Some(cache.clone());
                }
            }
  • You may need to add once_cell = "1.17" (or latest) to your Cargo.toml dependencies.
  • Ensure ApiUsageCache implements Clone if it does not already.
  • If you want to support cache invalidation on file changes outside this process, consider adding a timestamp or file watcher.

ekain-fr and others added 2 commits October 11, 2025 12:47
Display dirty count directly adjacent to status indicator (●5 instead of ● 5) for better visual compactness in the Git segment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Update TUI configurator preview to match actual Git segment behavior - show ●5 instead of ● 5 for better visual consistency.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant