Skip to content

Commit 4daf06f

Browse files
committed
📊 Enhance table display and fix help formatting for v2.1.0
This commit includes several improvements for the v2.1.0 release: - Fix compilation issues with help text formatting by replacing backtick concatenation with double quotes - Optimize table display for queries with many labels: - Limit displayed columns to 10 (metric + 8 labels + value) - Truncate long headers and values for better readability - Implement intelligent column limiting for wide tables - Add emojis to feature and tips sections for improved visual appeal - Reorganize tips display to show before Prometheus connection - Update README with v2.1.0 release notes and new features - Improve alignment of command-line options in help output These enhancements make the application more robust and user-friendly, particularly when working with complex metrics containing numerous labels.
1 parent 7a01897 commit 4daf06f

3 files changed

Lines changed: 88 additions & 47 deletions

File tree

README.md

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ A powerful command-line tool for querying Prometheus metrics with advanced autoc
3131
- [📄 License](#-license)
3232
- [📝 Version History](#-version-history)
3333
- [v2.0.0 - Complete Go Rewrite 🚀](#v200---complete-go-rewrite-)
34+
- [v2.1.0 - Enhanced Usability and Display 🚀](#v210---enhanced-usability-and-display-)
3435
- [v1.0.0 - Original Python Implementation](#v100---original-python-implementation)
3536

3637
## 📝 Overview
@@ -64,8 +65,9 @@ Prometheus CLI is a modern, feature-rich tool that allows you to query Prometheu
6465

6566
### ⚙️ Configuration
6667
- **🌐 Custom Prometheus URLs**: Connect to any Prometheus server
67-
- **📝 Command History**: Persistent command history across sessions
68-
- **🎛️ Configurable Options**: Flexible command-line options for all features
68+
- **📝 Command History**: Flexible command history management with options for persistent files and temporary files.
69+
- **🎛️ Configurable Options**: Flexible command-line options for all features, including history and debugging.
70+
- **🐛 Debugging**: Enable verbose output for detailed error diagnosis.
6971

7072
## 📥 Installation
7173

@@ -124,6 +126,10 @@ Prometheus CLI supports the following command line options:
124126
--password Password for basic authentication
125127
--insecure Skip TLS certificate verification
126128
--enable-label-values Enable autocompletion for label values (default: true)
129+
--history-file Path to the command history file. If not set, a temporary file is used.
130+
--persist-history Do not delete the history file on exit. Only applicable if --history-file is set or a temporary file is used.
131+
--debug Enable verbose error output for debugging.
132+
--tips Display detailed feature and usage tips on startup.
127133
--help, -h Show help
128134
--version Show version information
129135
```
@@ -241,12 +247,25 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
241247

242248
**Technical Enhancements:**
243249
- Refactored codebase with proper Go package structure
244-
- Comprehensive documentation following Go best practices
245250
- Automated testing and continuous integration
246251
- Memory-efficient data structures and algorithms
247252
- Robust error handling and user feedback
248253

254+
### v2.1.0 - Enhanced Usability and Display 🚀
255+
**Major Features:**
256+
- **📝 Configurable History**: Added `--history-file` and `--persist-history` flags for flexible command history management.
257+
- **🐛 Improved Debugging**: Enhanced `--debug` flag with more verbose output for initialization and error diagnosis.
258+
- **💡 Optional Tips**: Introduced `--tips` flag to control the display of detailed feature and usage tips on startup.
259+
- **📊 Optimized Table Display**: Improved table rendering for queries with many labels, preventing excessive width issues.
260+
261+
**Technical Enhancements:**
262+
- Refined error handling and logging for better debugging experience.
263+
- Improved command-line option parsing and validation.
264+
- Implemented intelligent column limiting and header truncation for better readability.
265+
- Fixed compilation issues with help text formatting.
266+
249267
### v1.0.0 - Original Python Implementation
250268
- Basic Prometheus querying functionality
251269
- Simple table output
252270
- Basic metric name autocompletion
271+

cmd/prom-cli/main.go

Lines changed: 36 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ package main
55
import (
66
"fmt"
77
"os"
8-
"path/filepath" // Added for filepath.Join
8+
"path/filepath"
99
"strings"
1010

1111
"prometheus-cli/internal/completion"
@@ -19,32 +19,22 @@ import (
1919

2020
// Command-line flags for configuring the application behavior.
2121
var (
22-
// url specifies the Prometheus server URL to connect to.
23-
url = kingpin.Flag("url", "Prometheus server URL.").Default("http://localhost:9090").String()
24-
25-
// username specifies the username for basic authentication.
22+
// Prometheus Connection Flags
23+
url = kingpin.Flag("url", "Prometheus server URL.").Default("http://localhost:9090").String()
2624
username = kingpin.Flag("username", "Username for basic authentication.").String()
27-
28-
// password specifies the password for basic authentication.
2925
password = kingpin.Flag("password", "Password for basic authentication.").String()
30-
31-
// insecure determines whether to skip TLS certificate verification.
3226
insecure = kingpin.Flag("insecure", "Skip TLS certificate verification.").Bool()
3327

34-
// enableLabelValues controls whether label values autocompletion is enabled.
28+
// Autocompletion Flags
3529
enableLabelValues = kingpin.Flag("enable-label-values", "Enable autocompletion for label values.").Default("true").Bool()
3630

37-
// debug enables verbose error output for debugging purposes.
38-
debug = kingpin.Flag("debug", "Enable verbose error output for debugging.").Bool()
39-
40-
// historyFile specifies the path to the command history file.
41-
historyFile = kingpin.Flag("history-file", "Path to the command history file. If not set, a temporary file is used.\n").String()
42-
43-
// persistHistory determines whether the history file should be persisted across sessions.
44-
persistHistory = kingpin.Flag("persist-history", "Do not delete the history file on exit. Only applicable if --history-file is set or a temporary file is used.\n").Bool()
31+
// History Flags
32+
historyFile = kingpin.Flag("history-file", "Path to the command history file.").String()
33+
persistHistory = kingpin.Flag("persist-history", "Do not delete the history file on exit.").Bool()
4534

46-
// tips enables the display of detailed feature and usage tips on startup.
47-
tips = kingpin.Flag("tips", "Display detailed feature and usage tips on startup.").Bool()
35+
// Display and Utility Flags
36+
debug = kingpin.Flag("debug", "Enable verbose error output for debugging.").Bool()
37+
tips = kingpin.Flag("tips", "Display detailed feature and usage tips on startup.").Bool()
4838
)
4939

5040
// main is the entry point of the Prometheus CLI application.
@@ -55,6 +45,13 @@ func main() {
5545
kingpin.HelpFlag.Short('h')
5646
kingpin.Parse()
5747

48+
// Display welcome message and feature information if tips are enabled
49+
if *tips {
50+
printWelcomeMessage()
51+
} else {
52+
fmt.Println("Enter Prometheus queries. Press Ctrl+C to exit.")
53+
}
54+
5855
// Initialize Prometheus client with user-provided configuration
5956
if *debug {
6057
fmt.Printf("Debug: Setting Prometheus URL to %s/api/v1\n", *url)
@@ -67,15 +64,15 @@ func main() {
6764

6865
// Load available metrics from Prometheus for autocompletion
6966
fmt.Print("Loading metrics...")
70-
metrics, err := prometheus.GetMetrics()
71-
if err != nil {
72-
if *debug {
73-
fmt.Printf("\rError getting metrics: %v\n", err)
74-
} else {
75-
fmt.Printf("\rError getting metrics. Use --debug for more details.\n")
76-
}
77-
os.Exit(1)
67+
metrics, err := prometheus.GetMetrics()
68+
if err != nil {
69+
if *debug {
70+
fmt.Printf("\rError getting metrics: %v\n", err)
71+
} else {
72+
fmt.Printf("\rError getting metrics. Use --debug for more details.\n")
7873
}
74+
os.Exit(1)
75+
}
7976
fmt.Printf("\rLoaded %d metrics successfully.\n", len(metrics))
8077

8178
// Initialize the advanced autocompletion system
@@ -164,9 +161,6 @@ func main() {
164161
}
165162
}()
166163

167-
// Display welcome message and feature information
168-
printWelcomeMessage()
169-
170164
// Run the main interactive query loop
171165
runQueryLoop(l)
172166
}
@@ -178,18 +172,18 @@ func printWelcomeMessage() {
178172
if *tips {
179173
fmt.Println(`
180174
✨ Features:
181-
- 📊 Metric Names: Smart autocompletion for all available Prometheus metrics
182-
- 🏷️ Label Names: Context-aware label suggestions when typing ` + "`metric{`" + `
183-
- 💎 Label Values: Real-time label value suggestions with caching for performance
184-
- ⚡ PromQL Expressions: Complete support for operators, built-in functions, time range selectors, and query modifiers
185-
- 🔧 Context-Aware Suggestions: Intelligent suggestions based on cursor position and query context
186-
- 🚀 Navigation Support: Tab completion with arrow key navigation for easy selection
175+
- Metric Names: Smart autocompletion for all available Prometheus metrics
176+
- Label Names: Context-aware label suggestions when typing "metric{"
177+
- Label Values: Real-time label value suggestions with caching for performance
178+
- PromQL Expressions: Complete support for operators, built-in functions, time range selectors, and query modifiers
179+
- Context-Aware Suggestions: Intelligent suggestions based on cursor position and query context
180+
- Navigation Support: Tab completion with arrow key navigation for easy selection
187181
188182
💡 Tips:
189-
- Type 'rat' + Tab 'rate('
190-
- After metric{} + Tab operators and modifiers
191-
- Inside functions + Tab metrics
192-
- After operators + Tab metrics and functions
183+
- Type 'rat' + Tab -> 'rate('
184+
- After metric{} + Tab -> operators and modifiers
185+
- Inside functions + Tab -> metrics
186+
- After operators + Tab -> metrics and functions
193187
`)
194188
}
195189
}
@@ -223,4 +217,4 @@ func runQueryLoop(l *readline.Instance) {
223217

224218
display.DisplayTable(results)
225219
}
226-
}
220+
}

internal/display/table.go

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,28 @@ func DisplayTable(results []prometheus.QueryResult) {
6363
headers := append([]string{"Metric"}, labels...)
6464
headers = append(headers, "Value")
6565

66+
// Limit the number of columns to display to avoid overly wide tables
67+
maxColumns := 10 // Metric + 8 most important labels + Value
68+
69+
if len(headers) > maxColumns {
70+
// Keep only the first few labels
71+
labels = labels[:maxColumns-2] // -2 for Metric and Value columns
72+
// Update headers accordingly
73+
headers = append([]string{"Metric"}, labels...)
74+
headers = append(headers, "Value")
75+
}
76+
77+
// Truncate long headers to improve readability
78+
maxHeaderLength := 20
79+
displayHeaders := make([]string, len(headers))
80+
for i, header := range headers {
81+
if len(header) > maxHeaderLength {
82+
displayHeaders[i] = header[:maxHeaderLength-3] + "..."
83+
} else {
84+
displayHeaders[i] = header
85+
}
86+
}
87+
6688
// Initialize table writer with stdout as destination
6789
table := tablewriter.NewWriter(os.Stdout)
6890

@@ -78,7 +100,13 @@ func DisplayTable(results []prometheus.QueryResult) {
78100
// Fill in label values in the correct column positions
79101
for i, label := range labels {
80102
// Column index is i+1 because metric name is at index 0
81-
row[i+1] = result.Metric[label]
103+
value := result.Metric[label]
104+
// Truncate long values
105+
if len(value) > maxHeaderLength {
106+
row[i+1] = value[:maxHeaderLength-3] + "..."
107+
} else {
108+
row[i+1] = value
109+
}
82110
}
83111

84112
// Extract and format the metric value
@@ -97,7 +125,7 @@ func DisplayTable(results []prometheus.QueryResult) {
97125

98126
// Configure and render the table
99127
// Using Header() and Bulk() methods for automatic formatting with separators
100-
table.Header(headers)
128+
table.Header(displayHeaders)
101129

102130
if err := table.Bulk(rows); err != nil {
103131
fmt.Printf("Error adding bulk data to table: %v\n", err)

0 commit comments

Comments
 (0)