Skip to content

Commit c0b0718

Browse files
chuongld20claude
andcommitted
chore: simplify Phase 3 code — deduplicate formatBytes, extract constant
- Consolidate formatBytes(int64) to delegate to formatBytesShort(uint64), eliminating duplicate byte-formatting logic with inconsistent formats - Extract metricsSep constant in metrics collector for the SSH output delimiter Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 4e69e2f commit c0b0718

2 files changed

Lines changed: 10 additions & 18 deletions

File tree

cmd/devbox/main.go

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1230,19 +1230,8 @@ func resolveServer(serverFlag string) (string, error) {
12301230

12311231
// formatBytes returns a human-readable byte size string.
12321232
func formatBytes(b int64) string {
1233-
const (
1234-
kb = 1024
1235-
mb = kb * 1024
1236-
gb = mb * 1024
1237-
)
1238-
switch {
1239-
case b >= gb:
1240-
return fmt.Sprintf("%.1f GB", float64(b)/float64(gb))
1241-
case b >= mb:
1242-
return fmt.Sprintf("%.1f MB", float64(b)/float64(mb))
1243-
case b >= kb:
1244-
return fmt.Sprintf("%.1f KB", float64(b)/float64(kb))
1245-
default:
1246-
return fmt.Sprintf("%d B", b)
1233+
if b < 0 {
1234+
return "0B"
12471235
}
1236+
return formatBytesShort(uint64(b))
12481237
}

internal/metrics/collector.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ import (
1414
// validContainerName matches valid Docker container names.
1515
var validContainerName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]+$`)
1616

17+
// metricsSep is the delimiter used to separate sections in batched SSH output.
18+
const metricsSep = "===METRICS_SEP==="
19+
1720
// dockerStatsJSON mirrors the JSON output of docker stats --format '{{json .}}'.
1821
type dockerStatsJSON struct {
1922
Name string `json:"Name"`
@@ -65,18 +68,18 @@ func (c *sshCollector) CollectWorkspace(ctx context.Context, host, container str
6568
func (c *sshCollector) CollectServer(ctx context.Context, host string) (*ServerMetrics, error) {
6669
// Single SSH command for all container stats + server info.
6770
cmd := "docker stats --no-stream --format '{{json .}}' 2>/dev/null; " +
68-
"echo '===METRICS_SEP==='; " +
71+
"echo '" + metricsSep + "'; " +
6972
"nproc; " +
70-
"echo '===METRICS_SEP==='; " +
73+
"echo '" + metricsSep + "'; " +
7174
"cat /proc/meminfo; " +
72-
"echo '===METRICS_SEP==='; " +
75+
"echo '" + metricsSep + "'; " +
7376
"df -B1 / | tail -1"
7477
stdout, _, err := c.exec.Run(ctx, host, cmd)
7578
if err != nil {
7679
return nil, fmt.Errorf("collecting server metrics on %s: %w", host, err)
7780
}
7881

79-
parts := strings.Split(stdout, "===METRICS_SEP===")
82+
parts := strings.Split(stdout, metricsSep)
8083
if len(parts) < 4 {
8184
return nil, fmt.Errorf("unexpected metrics output from %s (got %d parts)", host, len(parts))
8285
}

0 commit comments

Comments
 (0)