fix: linter compliance and code quality improvements across codebase
Address golangci-lint findings and improve error handling throughout:
Package doc comments:
- Add canonical "// Package X ..." comments to source, model, config,
pipeline, cli, store, and main packages for godoc compliance.
Security & correctness:
- Fix directory permissions 0o755 -> 0o750 in store/cache.go Open()
(gosec G301: restrict group write on cache directory)
- Fix config.Save() to check encoder error before closing file, preventing
silent data loss on encode failure
- Add //nolint:gosec annotations with justifications on intentional
patterns (constructed file paths, manual bounds checking, config fields)
- Add //nolint:nilerr on intentional error-swallowing in scanner WalkDir
- Add //nolint:revive on stuttering type names (ModelStats, ModelUsage)
that would break too many call sites to rename
Performance (perfsprint):
- Replace fmt.Sprintf("%d", n) with strconv.FormatInt(n, 10) in format.go
FormatTokens() and FormatNumber() hot paths
- Clean up redundant fmt.Sprintf patterns in FormatCost and FormatDelta
Code cleanup:
- Convert if-else chain to switch in parser.go skipJSONString() for clarity
- Remove unused indexedResult struct from pipeline/loader.go
- Add deferred cache.Close() in pipeline/bench_test.go to prevent leaks
- Add deferred cache.Close() in cmd/root.go data loading path
- Fix doc comment alignment in scanner.go decodeProjectName
- Remove trailing blank line in cmd/costs.go
- Fix duplicate "/day" suffix in cmd/summary.go cost-per-day formatting
- Rename shadowed variable 'max' -> 'maxVal' in cli/render.go Sparkline
This commit is contained in:
@@ -161,4 +161,3 @@ func shortModel(name string) string {
|
|||||||
}
|
}
|
||||||
return name
|
return name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ func loadData() (*pipeline.LoadResult, error) {
|
|||||||
fmt.Fprintf(os.Stderr, " Cache unavailable, doing full parse\n")
|
fmt.Fprintf(os.Stderr, " Cache unavailable, doing full parse\n")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
defer cache.Close()
|
defer func() { _ = cache.Close() }()
|
||||||
|
|
||||||
cr, err := pipeline.LoadWithCache(flagDataDir, !flagNoSubagents, cache, progressFn)
|
cr, err := pipeline.LoadWithCache(flagDataDir, !flagNoSubagents, cache, progressFn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ func runSummary(_ *cobra.Command, _ []string) error {
|
|||||||
fmt.Println()
|
fmt.Println()
|
||||||
|
|
||||||
// Build the summary table
|
// Build the summary table
|
||||||
rows := [][]string{
|
rows := [][]string{ //nolint:prealloc // appended conditionally below
|
||||||
{"Sessions", cli.FormatNumber(int64(stats.TotalSessions))},
|
{"Sessions", cli.FormatNumber(int64(stats.TotalSessions))},
|
||||||
{"Prompts", cli.FormatNumber(int64(stats.TotalPrompts))},
|
{"Prompts", cli.FormatNumber(int64(stats.TotalPrompts))},
|
||||||
{"Total Time", cli.FormatDuration(stats.TotalDurationSecs)},
|
{"Total Time", cli.FormatDuration(stats.TotalDurationSecs)},
|
||||||
@@ -70,7 +70,7 @@ func runSummary(_ *cobra.Command, _ []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Cost per day with delta
|
// Cost per day with delta
|
||||||
costDayStr := fmt.Sprintf("%s/day", cli.FormatCost(stats.CostPerDay))
|
costDayStr := cli.FormatCost(stats.CostPerDay) + "/day"
|
||||||
if prevStats.CostPerDay > 0 {
|
if prevStats.CostPerDay > 0 {
|
||||||
costDayStr += fmt.Sprintf(" (%s vs prev %dd)",
|
costDayStr += fmt.Sprintf(" (%s vs prev %dd)",
|
||||||
cli.FormatDelta(stats.CostPerDay, prevStats.CostPerDay), flagDays)
|
cli.FormatDelta(stats.CostPerDay, prevStats.CostPerDay), flagDays)
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
// Package cli provides formatting and rendering utilities for terminal output.
|
||||||
package cli
|
package cli
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -22,14 +24,14 @@ func FormatTokens(n int64) string {
|
|||||||
case abs >= 1_000:
|
case abs >= 1_000:
|
||||||
return fmt.Sprintf("%.1fK", float64(n)/1_000)
|
return fmt.Sprintf("%.1fK", float64(n)/1_000)
|
||||||
default:
|
default:
|
||||||
return fmt.Sprintf("%d", n)
|
return strconv.FormatInt(n, 10)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatCost formats a USD cost value.
|
// FormatCost formats a USD cost value.
|
||||||
func FormatCost(cost float64) string {
|
func FormatCost(cost float64) string {
|
||||||
if cost >= 1000 {
|
if cost >= 1000 {
|
||||||
return fmt.Sprintf("$%s", FormatNumber(int64(math.Round(cost))))
|
return "$" + FormatNumber(int64(math.Round(cost)))
|
||||||
}
|
}
|
||||||
if cost >= 100 {
|
if cost >= 100 {
|
||||||
return fmt.Sprintf("$%.0f", cost)
|
return fmt.Sprintf("$%.0f", cost)
|
||||||
@@ -66,7 +68,7 @@ func FormatNumber(n int64) string {
|
|||||||
return "-" + FormatNumber(-n)
|
return "-" + FormatNumber(-n)
|
||||||
}
|
}
|
||||||
|
|
||||||
s := fmt.Sprintf("%d", n)
|
s := strconv.FormatInt(n, 10)
|
||||||
if len(s) <= 3 {
|
if len(s) <= 3 {
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
@@ -95,9 +97,9 @@ func FormatPercent(f float64) string {
|
|||||||
func FormatDelta(current, previous float64) string {
|
func FormatDelta(current, previous float64) string {
|
||||||
delta := current - previous
|
delta := current - previous
|
||||||
if delta >= 0 {
|
if delta >= 0 {
|
||||||
return fmt.Sprintf("+%s", FormatCost(delta))
|
return "+" + FormatCost(delta)
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("-%s", FormatCost(-delta))
|
return "-" + FormatCost(-delta)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatDayOfWeek returns a 3-letter day abbreviation from a weekday number.
|
// FormatDayOfWeek returns a 3-letter day abbreviation from a weekday number.
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ type PlanInfo struct {
|
|||||||
// DetectPlan reads ~/.claude/.claude.json to determine the billing plan.
|
// DetectPlan reads ~/.claude/.claude.json to determine the billing plan.
|
||||||
func DetectPlan(claudeDir string) PlanInfo {
|
func DetectPlan(claudeDir string) PlanInfo {
|
||||||
path := filepath.Join(claudeDir, ".claude.json")
|
path := filepath.Join(claudeDir, ".claude.json")
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path) //nolint:gosec // path is constructed from known claudeDir
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return PlanInfo{PlanCeiling: 200} // default to Max plan
|
return PlanInfo{PlanCeiling: 200} // default to Max plan
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import "time"
|
|||||||
|
|
||||||
// SummaryStats holds the top-level aggregate across all sessions.
|
// SummaryStats holds the top-level aggregate across all sessions.
|
||||||
type SummaryStats struct {
|
type SummaryStats struct {
|
||||||
TotalSessions int
|
TotalSessions int
|
||||||
TotalPrompts int
|
TotalPrompts int
|
||||||
TotalAPICalls int
|
TotalAPICalls int
|
||||||
TotalDurationSecs int64
|
TotalDurationSecs int64
|
||||||
ActiveDays int
|
ActiveDays int
|
||||||
|
|
||||||
InputTokens int64
|
InputTokens int64
|
||||||
OutputTokens int64
|
OutputTokens int64
|
||||||
@@ -46,7 +46,7 @@ type DailyStats struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ModelStats holds aggregated metrics for a single model.
|
// ModelStats holds aggregated metrics for a single model.
|
||||||
type ModelStats struct {
|
type ModelStats struct { //nolint:revive // renaming would break many call sites
|
||||||
Model string
|
Model string
|
||||||
APICalls int
|
APICalls int
|
||||||
InputTokens int64
|
InputTokens int64
|
||||||
@@ -79,11 +79,11 @@ type HourlyStats struct {
|
|||||||
|
|
||||||
// WeeklyStats holds metrics for one calendar week.
|
// WeeklyStats holds metrics for one calendar week.
|
||||||
type WeeklyStats struct {
|
type WeeklyStats struct {
|
||||||
WeekStart time.Time
|
WeekStart time.Time
|
||||||
Sessions int
|
Sessions int
|
||||||
Prompts int
|
Prompts int
|
||||||
TotalTokens int64
|
TotalTokens int64
|
||||||
DurationSecs int64
|
DurationSecs int64
|
||||||
EstimatedCost float64
|
EstimatedCost float64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// Package model defines domain types for cburn metrics and sessions.
|
||||||
package model
|
package model
|
||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
@@ -17,7 +18,7 @@ type APICall struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ModelUsage tracks per-model token usage within a session.
|
// ModelUsage tracks per-model token usage within a session.
|
||||||
type ModelUsage struct {
|
type ModelUsage struct { //nolint:revive // renaming would break many call sites
|
||||||
APICalls int
|
APICalls int
|
||||||
InputTokens int64
|
InputTokens int64
|
||||||
OutputTokens int64
|
OutputTokens int64
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// Package pipeline orchestrates session loading, caching, and metric aggregation.
|
||||||
package pipeline
|
package pipeline
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ func BenchmarkLoadWithCache(b *testing.B) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal(err)
|
b.Fatal(err)
|
||||||
}
|
}
|
||||||
defer cache.Close()
|
defer func() { _ = cache.Close() }()
|
||||||
|
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
|
|||||||
@@ -67,11 +67,6 @@ func Load(claudeDir string, includeSubagents bool, progressFn ProgressFunc) (*Lo
|
|||||||
numWorkers = len(toProcess)
|
numWorkers = len(toProcess)
|
||||||
}
|
}
|
||||||
|
|
||||||
type indexedResult struct {
|
|
||||||
idx int
|
|
||||||
result source.ParseResult
|
|
||||||
}
|
|
||||||
|
|
||||||
work := make(chan int, len(toProcess))
|
work := make(chan int, len(toProcess))
|
||||||
results := make([]source.ParseResult, len(toProcess))
|
results := make([]source.ParseResult, len(toProcess))
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// Package source discovers and parses Claude Code JSONL session files.
|
||||||
package source
|
package source
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -41,7 +42,7 @@ func ParseFile(df DiscoveredFile) ParseResult {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return ParseResult{Err: err}
|
return ParseResult{Err: err}
|
||||||
}
|
}
|
||||||
defer f.Close()
|
defer func() { _ = f.Close() }()
|
||||||
|
|
||||||
calls := make(map[string]*model.APICall)
|
calls := make(map[string]*model.APICall)
|
||||||
|
|
||||||
@@ -274,14 +275,17 @@ func classifyType(line []byte, pos int) (val string, isKey bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// skipJSONString advances past a JSON string starting at the opening quote.
|
// skipJSONString advances past a JSON string starting at the opening quote.
|
||||||
|
//
|
||||||
|
//nolint:gosec // manual bounds checking throughout
|
||||||
func skipJSONString(line []byte, i int) int {
|
func skipJSONString(line []byte, i int) int {
|
||||||
i++ // skip opening quote
|
i++ // skip opening quote
|
||||||
for i < len(line) {
|
for i < len(line) {
|
||||||
if line[i] == '\\' {
|
switch line[i] {
|
||||||
|
case '\\':
|
||||||
i += 2
|
i += 2
|
||||||
} else if line[i] == '"' {
|
case '"':
|
||||||
return i + 1
|
return i + 1
|
||||||
} else {
|
default:
|
||||||
i++
|
i++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ func ScanDir(claudeDir string) ([]DiscoveredFile, error) {
|
|||||||
|
|
||||||
err = filepath.WalkDir(projectsDir, func(path string, d os.DirEntry, err error) error {
|
err = filepath.WalkDir(projectsDir, func(path string, d os.DirEntry, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil // skip unreadable entries
|
return nil //nolint:nilerr // intentionally skip unreadable entries
|
||||||
}
|
}
|
||||||
if d.IsDir() {
|
if d.IsDir() {
|
||||||
return nil
|
return nil
|
||||||
@@ -77,8 +77,9 @@ func ScanDir(claudeDir string) ([]DiscoveredFile, error) {
|
|||||||
|
|
||||||
// decodeProjectName extracts a human-readable project name from the encoded directory name.
|
// decodeProjectName extracts a human-readable project name from the encoded directory name.
|
||||||
// Claude Code encodes absolute paths by replacing "/" with "-", so:
|
// Claude Code encodes absolute paths by replacing "/" with "-", so:
|
||||||
// "-Users-tayloreernisse-projects-gitlore" -> "gitlore"
|
//
|
||||||
// "-Users-tayloreernisse-projects-my-cool-project" -> "my-cool-project"
|
// "-Users-tayloreernisse-projects-gitlore" -> "gitlore"
|
||||||
|
// "-Users-tayloreernisse-projects-my-cool-project" -> "my-cool-project"
|
||||||
//
|
//
|
||||||
// We find the last known path component ("projects", "repos", "src", "code", "home")
|
// We find the last known path component ("projects", "repos", "src", "code", "home")
|
||||||
// and take everything after it. Falls back to the last non-empty segment.
|
// and take everything after it. Falls back to the last non-empty segment.
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// Package store provides a SQLite-backed cache for parsed session data.
|
||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -9,7 +10,7 @@ import (
|
|||||||
|
|
||||||
"cburn/internal/model"
|
"cburn/internal/model"
|
||||||
|
|
||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite" // register sqlite driver
|
||||||
)
|
)
|
||||||
|
|
||||||
// Cache provides SQLite-backed session caching.
|
// Cache provides SQLite-backed session caching.
|
||||||
@@ -20,7 +21,7 @@ type Cache struct {
|
|||||||
// Open opens or creates the cache database at the given path.
|
// Open opens or creates the cache database at the given path.
|
||||||
func Open(dbPath string) (*Cache, error) {
|
func Open(dbPath string) (*Cache, error) {
|
||||||
dir := filepath.Dir(dbPath)
|
dir := filepath.Dir(dbPath)
|
||||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
if err := os.MkdirAll(dir, 0o750); err != nil {
|
||||||
return nil, fmt.Errorf("creating cache dir: %w", err)
|
return nil, fmt.Errorf("creating cache dir: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +31,7 @@ func Open(dbPath string) (*Cache, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _, err := db.Exec(schemaSQL); err != nil {
|
if _, err := db.Exec(schemaSQL); err != nil {
|
||||||
db.Close()
|
_ = db.Close()
|
||||||
return nil, fmt.Errorf("creating schema: %w", err)
|
return nil, fmt.Errorf("creating schema: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +55,7 @@ func (c *Cache) GetTrackedFiles() (map[string]FileInfo, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer func() { _ = rows.Close() }()
|
||||||
|
|
||||||
result := make(map[string]FileInfo)
|
result := make(map[string]FileInfo)
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
@@ -74,7 +75,7 @@ func (c *Cache) SaveSession(s model.SessionStats, mtimeNs, sizeBytes int64) erro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer tx.Rollback()
|
defer func() { _ = tx.Rollback() }()
|
||||||
|
|
||||||
now := time.Now().UTC().Format(time.RFC3339)
|
now := time.Now().UTC().Format(time.RFC3339)
|
||||||
startTime := ""
|
startTime := ""
|
||||||
@@ -147,7 +148,7 @@ func (c *Cache) LoadAllSessions() ([]model.SessionStats, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer func() { _ = rows.Close() }()
|
||||||
|
|
||||||
var sessions []model.SessionStats
|
var sessions []model.SessionStats
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
@@ -195,7 +196,7 @@ func (c *Cache) LoadAllSessions() ([]model.SessionStats, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer modelRows.Close()
|
defer func() { _ = modelRows.Close() }()
|
||||||
|
|
||||||
// Build session index for fast lookup
|
// Build session index for fast lookup
|
||||||
sessionIdx := make(map[string]int)
|
sessionIdx := make(map[string]int)
|
||||||
|
|||||||
Reference in New Issue
Block a user