-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathstatusline.sh
More file actions
executable file
·1524 lines (1346 loc) · 58.3 KB
/
statusline.sh
File metadata and controls
executable file
·1524 lines (1346 loc) · 58.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# ============================================================================
# Bash Compatibility Check and Auto-Upgrade
# ============================================================================
# Wrapped in function to satisfy ShellCheck SC2168 (local only valid in functions)
_upgrade_bash_if_needed() {
# Check if we need modern bash for associative arrays (bash 4.0+)
[[ "${BASH_VERSION%%.*}" -ge 4 ]] && return 0
# Try to find and use modern bash automatically - platform-aware
local bash_candidates=()
# Platform-aware bash candidate prioritization
if [[ "$(uname -s)" == "Darwin" ]]; then
# macOS: try system bash first, then Homebrew installations
bash_candidates=($(command -v bash 2>/dev/null | head -5) /opt/homebrew/bin/bash /usr/local/bin/bash /opt/local/bin/bash)
else
# Linux: try system paths first
bash_candidates=($(command -v bash 2>/dev/null | head -5) /usr/bin/bash /bin/bash /usr/local/bin/bash)
fi
for bash_candidate in "${bash_candidates[@]}"; do
[[ -z "$bash_candidate" ]] && continue # Skip empty entries
if [[ -x "$bash_candidate" ]] && [[ "$("$bash_candidate" -c 'echo ${BASH_VERSION%%.*}' 2>/dev/null)" -ge 4 ]]; then
# Re-execute script with modern bash
exec "$bash_candidate" "$0" "$@"
fi
done
# If no modern bash found, warn but continue with degraded functionality
echo "WARNING: Bash ${BASH_VERSION} detected. Advanced caching features disabled." >&2
# Platform-specific installation suggestion
if [[ "$(uname -s)" == "Darwin" ]]; then
echo "For full functionality, install bash 4+: brew install bash" >&2
else
echo "For full functionality, install bash 4+: sudo apt install bash (or equivalent)" >&2
fi
export STATUSLINE_COMPATIBILITY_MODE=true
}
_upgrade_bash_if_needed "$@"
# ============================================================================
# Claude Code Enhanced Statusline - Main Orchestrator (v2.1.0-refactored)
# ============================================================================
#
# This is the main orchestrator for the modularized Claude Code statusline.
# It loads and coordinates all modules to provide a comprehensive 4-line
# statusline display with git status, MCP monitoring, cost tracking, and
# beautiful themes.
#
# Refactored from monolithic 3930-line script to modular architecture.
# Original functionality preserved with improved maintainability.
# ============================================================================
# Set script directory for module loading
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Define critical paths for configuration management
CONFIG_PATH="$HOME/.claude/statusline/Config.toml"
EXAMPLES_DIR="$HOME/.claude/statusline/examples"
SAMPLE_CONFIGS_DIR="$EXAMPLES_DIR/sample-configs"
# ============================================================================
# CORE MODULE LOADING
# ============================================================================
# Load core module first (provides module loading infrastructure)
if [[ -f "$SCRIPT_DIR/lib/core.sh" ]]; then
source "$SCRIPT_DIR/lib/core.sh"
else
echo "FATAL ERROR: Core module not found at $SCRIPT_DIR/lib/core.sh" >&2
echo "Please ensure the lib/ directory is present with all required modules." >&2
exit 1
fi
# Verify core module loaded successfully
if [[ "${STATUSLINE_CORE_LOADED:-}" != "true" ]]; then
echo "FATAL ERROR: Core module failed to initialize properly" >&2
exit 1
fi
# Enable strict mode for fail-fast behavior (Issue #77)
# This enables: set -euo pipefail with ERR trap for better debugging
enable_strict_mode
# ============================================================================
# MODULE LOADING SEQUENCE
# ============================================================================
# Load modules in dependency order
debug_log "Starting module loading sequence..." "INFO"
start_timer "module_loading"
# Load security module (required by most other modules)
# Security-first sanitization and validation for all inputs
load_module "security" || {
handle_error "Failed to load security module - statusline disabled. Check lib/security.sh exists and is readable." 1 "main"
exit 1
}
# Load JSON field access abstraction layer (v2.1.66+ path migration)
# Must load early - provides get_json_field() with current_usage path migration
load_module "json_fields" || {
handle_warning "JSON fields module failed to load - using direct jq extraction" "main"
}
# Load universal caching module (provides performance optimization for all external commands)
# Secure file operations via create_secure_cache_file for all cache management
load_module "cache" || {
handle_warning "Cache module failed to load - performance optimizations disabled. All commands will run directly." "main"
}
# Load configuration module
# Performance optimization: single-pass jq config extraction
load_module "config" || {
handle_error "Failed to load config module - configuration parsing disabled. Check lib/config.sh and TOML dependencies." 1 "main"
exit 1
}
# Load profiles module (Issue #84)
# Must load after config but before themes (profiles can affect theme selection)
load_module "profiles" || {
handle_warning "Profiles module failed to load - profile switching disabled." "main"
}
# Load theme module
load_module "themes" || {
handle_error "Failed to load themes module - theme system disabled. Check lib/themes.sh for color support." 1 "main"
exit 1
}
# Load git integration module
load_module "git" || {
handle_warning "Git module failed to load - git features disabled. Repository status unavailable." "main"
}
# Load GitHub integration module (Issue #92)
# Must load after git module (depends on git remote detection)
load_module "github" || {
handle_warning "GitHub module failed to load - GitHub integration disabled." "main"
}
# Load MCP monitoring module
load_module "mcp" || {
handle_warning "MCP module failed to load - MCP monitoring disabled. Server status unavailable." "main"
}
# Load cost tracking module
load_module "cost" || {
handle_warning "Cost module failed to load - cost tracking disabled." "main"
}
# Load prayer times and Hijri calendar module
load_module "prayer" || {
handle_warning "Prayer module failed to load - prayer times and Hijri calendar disabled." "main"
}
# Load wellness mode module (break reminders)
load_module "wellness" || {
handle_warning "Wellness module failed to load - break reminders disabled." "main"
}
# Load component system module (required for modular display)
load_module "components" || {
handle_warning "Components module failed to load - modular display disabled. Falling back to legacy display." "main"
}
# Initialize the component system after loading the module
if is_module_loaded "components"; then
init_component_system
fi
# Load plugins module (Issue #90)
# Must load after components (plugins can register custom components)
load_module "plugins" || {
handle_warning "Plugins module failed to load - custom plugins disabled." "main"
}
# Load responsive module (width-aware component filtering)
load_module "responsive" || {
handle_warning "Responsive module failed to load - width filtering disabled." "main"
}
# Load display/formatting module
load_module "display" || {
handle_error "Failed to load display module - output formatting disabled. Check lib/display.sh." 1 "main"
exit 1
}
module_load_time=$(end_timer "module_loading")
debug_log "Module loading completed in ${module_load_time}s" "INFO"
# ============================================================================
# CONFIGURATION INITIALIZATION
# ============================================================================
debug_log "Initializing configuration..." "INFO"
start_timer "config_init"
# Load configuration from all sources (defaults -> TOML -> env overrides)
load_configuration || {
handle_warning "Configuration loading failed, using defaults" "main"
}
# Apply theme
apply_theme || {
handle_warning "Theme application failed, using defaults" "main"
}
config_time=$(end_timer "config_init")
debug_log "Configuration initialization completed in ${config_time}s" "INFO"
# ============================================================================
# COMMAND-LINE INTERFACE
# ============================================================================
# Handle command-line arguments (preserved from original)
show_usage() {
cat <<'EOF'
Claude Code Statusline (Refactored v2.1.0)
==========================================
USAGE:
statusline.sh [options] - Run statusline (default)
statusline.sh --help - Show this help message
statusline.sh --version - Show version information
statusline.sh --json - Output JSON for IDE integrations
statusline.sh --test-display - Test display formatting
statusline.sh --modules - Show loaded modules
statusline.sh --health - Show system health status
statusline.sh --health=json - Show health status (JSON format)
statusline.sh --metrics - Show performance metrics (JSON)
statusline.sh --metrics=prometheus - Show metrics (Prometheus format)
statusline.sh --upgrade - Upgrade to latest version
statusline.sh --validate - Validate Config.toml schema
statusline.sh --validate=strict - Strict validation (exit on errors)
statusline.sh --list-themes - List available themes
statusline.sh --preview-theme <name> - Preview a theme's colors
statusline.sh --check-updates - Check for new versions
statusline.sh --setup-wizard - Interactive setup wizard
REPORTS:
statusline.sh --json - Unified JSON export (pretty-printed)
statusline.sh --json --compact - Compact JSON (single line)
statusline.sh --daily - Today's cost report (ASCII table)
statusline.sh --daily --json - Today's cost report (JSON)
statusline.sh --weekly - Last 7 days report (ASCII table)
statusline.sh --weekly --json - Last 7 days report (JSON)
statusline.sh --monthly - Last 30 days report (ASCII table)
statusline.sh --monthly --json - Last 30 days report (JSON)
statusline.sh --breakdown - Model cost breakdown (ASCII table)
statusline.sh --breakdown --json - Model cost breakdown (JSON)
statusline.sh --instances - Multi-project cost summary
statusline.sh --instances --json - Multi-project cost summary (JSON)
statusline.sh --burn-rate - Cost/token velocity analysis
statusline.sh --burn-rate --json - Burn rate analysis (JSON)
statusline.sh --commits - Cost per commit attribution
statusline.sh --commits --json - Commit costs (JSON)
statusline.sh --mcp-costs - MCP server cost attribution
statusline.sh --mcp-costs --json - MCP server costs (JSON)
statusline.sh --recommendations - Smart cost optimization tips
statusline.sh --recommendations --json - Cost recommendations (JSON)
statusline.sh --watch - Live monitoring mode (10s refresh)
statusline.sh --watch --refresh 5 - Custom refresh interval
statusline.sh --trends - Historical cost trends (ASCII chart)
statusline.sh --trends --period 7d - Cost trends for last 7 days
statusline.sh --trends --json - Cost trends (JSON)
statusline.sh --limits - System limit warnings status
statusline.sh --limits --json - Limit warnings (JSON)
statusline.sh --focus start - Start focus session
statusline.sh --focus stop - Stop and show summary
statusline.sh --focus status - Current session info
statusline.sh --focus history - Session history
statusline.sh --focus history --json - History (JSON)
OUTPUT FORMAT:
--csv - Output in CSV format
--json - Output in JSON format
--compact - Compact output (single line JSON)
FILTERS:
--since DATE - Filter from date (inclusive)
--until DATE - Filter to date (inclusive)
--project NAME - Filter to specific project
Date formats: YYYYMMDD, YYYY-MM-DD, today, yesterday, 7d, 30d, week, month
Examples:
statusline.sh --daily --since 20260101
statusline.sh --monthly --since 2025-12-01 --until 2025-12-31
statusline.sh --breakdown --since 7d
statusline.sh --daily --project my-app
statusline.sh --monthly --project statusline --since 7d
THEMES:
Available: classic, garden, catppuccin, ocean, custom
ENV_CONFIG_THEME=classic ./statusline.sh - Use classic theme
ENV_CONFIG_THEME=garden ./statusline.sh - Use garden theme
ENV_CONFIG_THEME=catppuccin ./statusline.sh - Use catppuccin theme
ENV_CONFIG_THEME=ocean ./statusline.sh - Use ocean theme
DEBUGGING:
STATUSLINE_DEBUG=true ./statusline.sh - Enable debug logging
STATUSLINE_LOG_FORMAT=json STATUSLINE_DEBUG=true ./statusline.sh - JSON logs
FEATURES:
- 4-line statusline with git status, MCP monitoring, and cost tracking
- TOML configuration support (Config.toml)
- 3 built-in themes + custom theme support
- Intelligent caching for performance
- Modular architecture for maintainability
For detailed configuration, see: https://github.com/rz1989s/claude-code-statusline
EOF
}
# Show health status for diagnostics and monitoring
show_health_status() {
local format="${1:-human}"
local status="healthy"
local exit_code=0
local issues=()
# Collect dependency versions
local bash_version="${BASH_VERSION%%(*}"
local jq_version
local curl_version
local git_version
jq_version=$(jq --version 2>/dev/null | sed 's/jq-//')
curl_version=$(curl --version 2>/dev/null | head -1 | awk '{print $2}')
git_version=$(git --version 2>/dev/null | awk '{print $3}')
# Check critical dependencies
local deps_ok=true
[[ -z "$jq_version" ]] && deps_ok=false && issues+=("jq not found")
[[ -z "$curl_version" ]] && deps_ok=false && issues+=("curl not found")
[[ "${BASH_VERSINFO[0]}" -lt 4 ]] && deps_ok=false && issues+=("bash < 4.0")
# Check modules
local modules_loaded=${#STATUSLINE_MODULES_LOADED[@]}
local modules_failed=${#STATUSLINE_MODULES_FAILED[@]}
[[ $modules_failed -gt 0 ]] && issues+=("$modules_failed module(s) failed to load")
# Check config file
local config_status="valid"
local config_path="${CONFIG_PATH:-$HOME/.claude/statusline/Config.toml}"
if [[ ! -f "$config_path" ]]; then
config_status="missing"
issues+=("Config.toml not found")
fi
# Check cache directory
local cache_status="writable"
local cache_dir="${CLAUDE_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/claude-code-statusline}"
if [[ ! -d "$cache_dir" ]]; then
cache_status="missing"
elif [[ ! -w "$cache_dir" ]]; then
cache_status="read-only"
issues+=("Cache directory not writable")
fi
# Determine overall status
[[ ${#issues[@]} -gt 0 ]] && status="degraded"
[[ "$deps_ok" == "false" ]] && status="unhealthy" && exit_code=1
# Output based on format
if [[ "$format" == "json" ]]; then
# Properly quote string values, handle null for missing deps
local jq_val="${jq_version:-null}"
local curl_val="${curl_version:-null}"
local git_val="${git_version:-null}"
[[ "$jq_val" != "null" ]] && jq_val="\"$jq_val\""
[[ "$curl_val" != "null" ]] && curl_val="\"$curl_val\""
[[ "$git_val" != "null" ]] && git_val="\"$git_val\""
cat <<EOF
{
"status": "$status",
"version": "$STATUSLINE_VERSION",
"modules_loaded": $modules_loaded,
"modules_failed": $modules_failed,
"dependencies": {
"bash": "$bash_version",
"jq": $jq_val,
"curl": $curl_val,
"git": $git_val
},
"config": "$config_status",
"cache": "$cache_status"
}
EOF
else
# Human-readable output
echo "Claude Code Statusline Health Check"
echo "===================================="
echo ""
echo "Status: $status"
echo "Version: ${STATUSLINE_VERSION:-unknown}"
echo ""
echo "Dependencies:"
[[ -n "$bash_version" && "${BASH_VERSINFO[0]}" -ge 4 ]] && echo " ✓ bash $bash_version" || echo " ✗ bash ${bash_version:-unknown} (requires 4.0+)"
[[ -n "$jq_version" ]] && echo " ✓ jq $jq_version" || echo " ✗ jq not found"
[[ -n "$curl_version" ]] && echo " ✓ curl $curl_version" || echo " ✗ curl not found"
[[ -n "$git_version" ]] && echo " ✓ git $git_version" || echo " ⚠ git not found (optional)"
echo ""
echo "Modules: $modules_loaded loaded, $modules_failed failed"
echo "Config: $config_status"
echo "Cache: $cache_status"
if [[ ${#issues[@]} -gt 0 ]]; then
echo ""
echo "Issues:"
for issue in "${issues[@]}"; do
echo " • $issue"
done
fi
fi
return $exit_code
}
# Show performance metrics for monitoring and analytics
show_metrics() {
local format="${1:-json}"
local timestamp
timestamp=$(date +%s)
# Module stats
local modules_loaded=${#STATUSLINE_MODULES_LOADED[@]}
local modules_failed=${#STATUSLINE_MODULES_FAILED[@]}
# Cache stats
local cache_hits=0
local cache_misses=0
local cache_hit_rate="0.00"
local cache_size_bytes=0
local cache_file_count=0
if [[ "${STATUSLINE_CACHE_LOADED:-}" == "true" ]]; then
# Aggregate cache stats from tracking arrays
if declare -p CACHE_STATS_HITS &>/dev/null 2>&1; then
for key in "${!CACHE_STATS_HITS[@]}"; do
cache_hits=$((cache_hits + ${CACHE_STATS_HITS[$key]:-0}))
done
fi
if declare -p CACHE_STATS_MISSES &>/dev/null 2>&1; then
for key in "${!CACHE_STATS_MISSES[@]}"; do
cache_misses=$((cache_misses + ${CACHE_STATS_MISSES[$key]:-0}))
done
fi
local total=$((cache_hits + cache_misses))
if [[ $total -gt 0 ]]; then
cache_hit_rate=$(awk "BEGIN {printf \"%.2f\", ($cache_hits / $total) * 100}")
fi
# Get cache directory stats
local cache_dir="${CLAUDE_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/claude-code-statusline}"
if [[ -d "$cache_dir" ]]; then
cache_file_count=$(find "$cache_dir" -type f 2>/dev/null | wc -l | tr -d ' ')
# Use du -sk for cross-platform compatibility, convert to bytes
local size_kb
size_kb=$(du -sk "$cache_dir" 2>/dev/null | cut -f1 || echo "0")
cache_size_bytes=$((size_kb * 1024))
fi
fi
# Component stats
local components_enabled=0
local components_total=0
if [[ "${STATUSLINE_COMPONENTS_LOADED:-}" == "true" ]]; then
if declare -p STATUSLINE_COMPONENT_REGISTRY &>/dev/null 2>&1; then
components_total=${#STATUSLINE_COMPONENT_REGISTRY[@]}
fi
if declare -p COMPONENT_ENABLED &>/dev/null 2>&1; then
for comp in "${!COMPONENT_ENABLED[@]}"; do
[[ "${COMPONENT_ENABLED[$comp]}" == "true" ]] && components_enabled=$((components_enabled + 1))
done
fi
fi
# Output based on format
case "$format" in
json)
cat <<EOF
{
"timestamp": $timestamp,
"version": "$STATUSLINE_VERSION",
"modules": {
"loaded": $modules_loaded,
"failed": $modules_failed
},
"cache": {
"hits": $cache_hits,
"misses": $cache_misses,
"hit_rate_percent": $cache_hit_rate,
"file_count": $cache_file_count,
"size_bytes": $cache_size_bytes
},
"components": {
"enabled": $components_enabled,
"total": $components_total
}
}
EOF
;;
prometheus|prom)
cat <<EOF
# HELP statusline_info Statusline version info
# TYPE statusline_info gauge
statusline_info{version="$STATUSLINE_VERSION"} 1
# HELP statusline_modules_loaded Number of successfully loaded modules
# TYPE statusline_modules_loaded gauge
statusline_modules_loaded $modules_loaded
# HELP statusline_modules_failed Number of failed modules
# TYPE statusline_modules_failed gauge
statusline_modules_failed $modules_failed
# HELP statusline_cache_hits_total Total cache hits
# TYPE statusline_cache_hits_total counter
statusline_cache_hits_total $cache_hits
# HELP statusline_cache_misses_total Total cache misses
# TYPE statusline_cache_misses_total counter
statusline_cache_misses_total $cache_misses
# HELP statusline_cache_hit_rate Cache hit rate percentage
# TYPE statusline_cache_hit_rate gauge
statusline_cache_hit_rate $cache_hit_rate
# HELP statusline_cache_size_bytes Cache directory size in bytes
# TYPE statusline_cache_size_bytes gauge
statusline_cache_size_bytes $cache_size_bytes
# HELP statusline_cache_file_count Number of cache files
# TYPE statusline_cache_file_count gauge
statusline_cache_file_count $cache_file_count
# HELP statusline_components_enabled Number of enabled components
# TYPE statusline_components_enabled gauge
statusline_components_enabled $components_enabled
# HELP statusline_components_total Total number of components
# TYPE statusline_components_total gauge
statusline_components_total $components_total
EOF
;;
*)
echo "Unknown format: $format" >&2
echo "Supported formats: json, prometheus" >&2
return 1
;;
esac
return 0
}
# Check for updates against GitHub releases
check_for_updates() {
local current_version="$STATUSLINE_VERSION"
local repo="rz1989s/claude-code-statusline"
local api_url="https://api.github.com/repos/${repo}/releases/latest"
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ Claude Code Statusline - Update Check ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo "Current version: v$current_version"
echo ""
# Check if curl is available
if ! command -v curl &>/dev/null; then
echo "Error: curl is required to check for updates" >&2
return 1
fi
echo "Checking for updates..."
echo ""
# Fetch latest release from GitHub API
local response
response=$(curl -fsSL --connect-timeout 10 "$api_url" 2>/dev/null)
if [[ -z "$response" ]]; then
echo "Error: Could not connect to GitHub API" >&2
echo "Check your internet connection and try again." >&2
return 1
fi
# Extract version and release info
local latest_version release_url published_at release_notes
latest_version=$(echo "$response" | jq -r '.tag_name // empty' 2>/dev/null | sed 's/^v//')
release_url=$(echo "$response" | jq -r '.html_url // empty' 2>/dev/null)
published_at=$(echo "$response" | jq -r '.published_at // empty' 2>/dev/null | cut -d'T' -f1)
release_notes=$(echo "$response" | jq -r '.body // empty' 2>/dev/null | head -5)
if [[ -z "$latest_version" ]]; then
echo "Error: Could not parse version from GitHub API" >&2
return 1
fi
echo "Latest version: v$latest_version (released $published_at)"
echo ""
# Compare versions (simple string comparison works for semver)
if [[ "$current_version" == "$latest_version" ]]; then
echo "✓ You are running the latest version!"
return 0
fi
# Check if current is newer (dev version)
if [[ "$(printf '%s\n' "$current_version" "$latest_version" | sort -V | tail -1)" == "$current_version" ]]; then
echo "✓ You are running a development version (ahead of latest release)"
return 0
fi
# New version available
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ New Version Available: v$latest_version"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
if [[ -n "$release_notes" ]]; then
echo "Release notes:"
echo "$release_notes" | sed 's/^/ /'
echo ""
fi
echo "To upgrade, run:"
echo ""
echo " curl -sSfL https://raw.githubusercontent.com/${repo}/main/install.sh | bash"
echo ""
echo "Or visit: $release_url"
echo ""
return 0
}
# Interactive setup wizard for new users
run_setup_wizard() {
local config_file="$HOME/.claude/statusline/Config.toml"
clear
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ Claude Code Statusline - Setup Wizard ║"
echo "║ v$STATUSLINE_VERSION ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo "Welcome! This wizard will help you configure your statusline."
echo ""
echo "Press Enter to continue or Ctrl+C to exit..."
read -r
# Step 1: Dependency Check
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Step 1/4: Checking Dependencies"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
local deps_ok=true
# Required
if command -v jq &>/dev/null; then
echo " ✓ jq $(jq --version 2>/dev/null | sed 's/jq-//')"
else
echo " ✗ jq (REQUIRED - install with: brew install jq)"
deps_ok=false
fi
if command -v git &>/dev/null; then
echo " ✓ git $(git --version 2>/dev/null | awk '{print $3}')"
else
echo " ✗ git (REQUIRED)"
deps_ok=false
fi
if command -v curl &>/dev/null; then
echo " ✓ curl $(curl --version 2>/dev/null | head -1 | awk '{print $2}')"
else
echo " ✗ curl (REQUIRED)"
deps_ok=false
fi
if [[ "$deps_ok" == "false" ]]; then
echo ""
echo " ⚠ Some required dependencies are missing."
echo " Please install them and run the wizard again."
return 1
fi
echo ""
echo "Press Enter to continue..."
read -r
# Step 2: Theme Selection
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Step 2/4: Choose Your Theme"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo " 1) catppuccin - Catppuccin Mocha (warm, cozy colors)"
echo " 2) ocean - Deep sea blues and teals"
echo " 3) garden - Soft pastel colors"
echo " 4) classic - Traditional ANSI colors"
echo ""
local theme_choice theme_name="catppuccin"
echo -n " Select theme [1-4, default=1]: "
read -r theme_choice
case "$theme_choice" in
2) theme_name="ocean" ;;
3) theme_name="garden" ;;
4) theme_name="classic" ;;
*) theme_name="catppuccin" ;;
esac
echo ""
echo " Selected: $theme_name"
echo ""
echo " Preview:"
apply_theme "$theme_name"
echo -e " ${CONFIG_BLUE}■ Blue${CONFIG_RESET} ${CONFIG_GREEN}■ Green${CONFIG_RESET} ${CONFIG_RED}■ Red${CONFIG_RESET} ${CONFIG_YELLOW}■ Yellow${CONFIG_RESET} ${CONFIG_CYAN}■ Cyan${CONFIG_RESET}"
echo ""
echo "Press Enter to continue..."
read -r
# Step 3: Feature Configuration
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Step 3/4: Configure Features"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
local enable_prayer="false"
local enable_cost="true"
local display_lines="5"
echo -n " Enable Islamic prayer times? [y/N]: "
read -r prayer_choice
[[ "$prayer_choice" =~ ^[Yy] ]] && enable_prayer="true"
echo -n " Enable cost tracking? [Y/n]: "
read -r cost_choice
[[ "$cost_choice" =~ ^[Nn] ]] && enable_cost="false"
echo -n " Number of display lines [1-9, default=5]: "
read -r lines_choice
[[ "$lines_choice" =~ ^[1-9]$ ]] && display_lines="$lines_choice"
echo ""
echo "Press Enter to continue..."
read -r
# Step 4: Summary and Apply
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Step 4/4: Configuration Summary"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo " Theme: $theme_name"
echo " Display lines: $display_lines"
echo " Prayer times: $enable_prayer"
echo " Cost tracking: $enable_cost"
echo ""
echo " Config file: $config_file"
echo ""
echo -n " Apply these settings? [Y/n]: "
read -r apply_choice
if [[ "$apply_choice" =~ ^[Nn] ]]; then
echo ""
echo " Setup cancelled. No changes made."
return 0
fi
# Apply settings to Config.toml
if [[ -f "$config_file" ]]; then
# Update existing config
sed -i.bak "s/^name = \".*\"/name = \"$theme_name\"/" "$config_file" 2>/dev/null || true
sed -i.bak "s/^lines = .*/lines = $display_lines/" "$config_file" 2>/dev/null || true
sed -i.bak "s/^enabled = .* # prayer/enabled = $enable_prayer # prayer/" "$config_file" 2>/dev/null || true
rm -f "${config_file}.bak" 2>/dev/null
echo ""
echo " ✓ Configuration updated!"
else
echo ""
echo " ⚠ Config file not found. Settings will be applied via environment."
echo ""
echo " Add to your shell profile:"
echo " export ENV_CONFIG_THEME=$theme_name"
echo " export ENV_CONFIG_DISPLAY_LINES=$display_lines"
fi
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ Setup Complete! ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo " Your statusline is now configured."
echo ""
echo " Quick commands:"
echo " ./statusline.sh --help Show all options"
echo " ./statusline.sh --list-themes List available themes"
echo " ./statusline.sh --check-updates Check for updates"
echo ""
return 0
}
# ============================================================================
# JSON API OUTPUT (Issue #95)
# ============================================================================
# Provides structured JSON output for IDE integrations (VS Code, Vim, Emacs)
# Usage: ./statusline.sh --json
output_json_api() {
local json_output=""
# Get current directory (for context)
local current_dir="${PWD}"
# Repository info
local repo_name=""
local repo_branch=""
local repo_status="not_git"
local repo_commits_today="0"
local repo_has_submodules="false"
if is_module_loaded "git" && is_git_repository; then
repo_name=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null)
repo_branch=$(get_git_branch 2>/dev/null)
repo_status=$(get_git_status 2>/dev/null)
repo_commits_today=$(get_commits_today 2>/dev/null)
[[ -f ".gitmodules" ]] && repo_has_submodules="true"
fi
# Cost info
local cost_session="0.00"
local cost_daily="0.00"
local cost_weekly="0.00"
local cost_monthly="0.00"
if is_module_loaded "cost"; then
cost_session=$(get_session_cost 2>/dev/null || echo "0.00")
cost_daily=$(get_daily_cost 2>/dev/null || echo "0.00")
cost_weekly=$(get_weekly_cost 2>/dev/null || echo "0.00")
cost_monthly=$(get_monthly_cost 2>/dev/null || echo "0.00")
fi
# MCP info
local mcp_connected="0"
local mcp_total="0"
local mcp_servers="[]"
if is_module_loaded "mcp" && is_claude_cli_available; then
local mcp_status
mcp_status=$(get_mcp_status 2>/dev/null)
if [[ "$mcp_status" =~ ^([0-9]+)/([0-9]+)$ ]]; then
mcp_connected="${BASH_REMATCH[1]}"
mcp_total="${BASH_REMATCH[2]}"
fi
# Get server names as JSON array
local servers_raw
servers_raw=$(get_all_mcp_servers 2>/dev/null)
if [[ -n "$servers_raw" && "$servers_raw" != "none" ]]; then
mcp_servers=$(echo "$servers_raw" | tr ',' '\n' | jq -R . | jq -s .)
fi
fi
# GitHub info
local github_ci_status=""
local github_pr_count="0"
local github_release=""
if is_module_loaded "github" && is_github_enabled; then
github_ci_status=$(get_ci_status 2>/dev/null)
github_pr_count=$(get_open_pr_count 2>/dev/null || echo "0")
github_release=$(get_latest_release 2>/dev/null)
fi
# Prayer info (if enabled)
local prayer_enabled="false"
local prayer_next=""
local prayer_time=""
if is_module_loaded "prayer" && [[ "${CONFIG_PRAYER_ENABLED:-false}" == "true" ]]; then
prayer_enabled="true"
# Get next prayer info if available
if declare -f get_next_prayer_info &>/dev/null; then
local prayer_info
prayer_info=$(get_next_prayer_info 2>/dev/null)
prayer_next=$(echo "$prayer_info" | cut -d'|' -f1)
prayer_time=$(echo "$prayer_info" | cut -d'|' -f2)
fi
fi
# System info
local theme_name
theme_name=$(get_current_theme 2>/dev/null || echo "default")
local modules_count="${#STATUSLINE_MODULES_LOADED[@]}"
# Build JSON output using jq for proper escaping
cat <<EOF | jq -c .
{
"version": "$STATUSLINE_VERSION",
"timestamp": $(date +%s),
"repository": {
"name": "$repo_name",
"branch": "$repo_branch",
"status": "$repo_status",
"commits_today": $repo_commits_today,
"has_submodules": $repo_has_submodules,
"path": "$current_dir"
},
"cost": {
"session": $cost_session,
"daily": $cost_daily,
"weekly": $cost_weekly,
"monthly": $cost_monthly,
"currency": "USD"
},
"mcp": {
"connected": $mcp_connected,
"total": $mcp_total,
"servers": $mcp_servers
},
"github": {
"enabled": $(is_github_enabled && echo "true" || echo "false"),
"ci_status": "$github_ci_status",
"open_prs": $github_pr_count,
"latest_release": "$github_release"
},
"prayer": {
"enabled": $prayer_enabled,
"next": "$prayer_next",
"time": "$prayer_time"
},
"system": {
"theme": "$theme_name",
"modules_loaded": $modules_count,
"platform": "$(uname -s)"
}
}
EOF
return 0
}
# ============================================================================
# CLI REPORTS MODULE
# ============================================================================
# Load CLI reports module for --json, --daily, --weekly, --monthly commands
if [[ -d "$SCRIPT_DIR/lib/cli" ]]; then
source "$SCRIPT_DIR/lib/cli/reports.sh" 2>/dev/null || true
fi
# ============================================================================
# SOURCE GUARD - Allow tests to source the script for function access
# ============================================================================
# When sourced (not executed directly), return after loading modules/functions
# This enables testing individual functions without triggering stdin reads
if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
debug_log "Script sourced - returning after module initialization" "INFO"
return 0 2>/dev/null || true
fi
# Parse command-line arguments (multi-arg parser for report flags)
if [[ $# -gt 0 ]]; then
_cli_command=""
_cli_format=""
_cli_compact=false
_cli_since=""
_cli_until=""
_cli_project=""
_cli_refresh=""
_cli_period=""
_cli_focus_action=""
while [[ $# -gt 0 ]]; do
case "$1" in
# Immediate-exit flags (backward compatible, single-arg)
"--help"|"-h")
show_usage
exit 0
;;
"--version"|"-v")
echo "Claude Code Statusline v$STATUSLINE_VERSION"
echo "Architecture: $STATUSLINE_ARCHITECTURE_VERSION (modular refactor)"
echo "Compatible with original v$STATUSLINE_COMPATIBILITY_VERSION"
echo "Modules loaded: ${#STATUSLINE_MODULES_LOADED[@]}"
echo "Current theme: $(get_current_theme)"