Skip to content

Modern Docker Management, Designed for Everyone

refactor: standardize on github.com/docker/go-units (#4377)

Kyle Mendellaafcfb43112d
diff --git a/backend/internal/notification/children/templates/service_test.go b/backend/internal/notification/children/templates/service_test.go
index 469c3f67a..ffa729352 100644
--- a/backend/internal/notification/children/templates/service_test.go
+++ b/backend/internal/notification/children/templates/service_test.go
@@ -99,4 +99,8 @@ func TestService_RenderPruneReportEmailTemplate_IncludesEnvironment(t *testing.T
require.NoError(t, err)
require.Contains(t, htmlBody, "Cluster West")
require.Contains(t, textBody, "Cluster West")
+ for _, size := range []string{"3.6 GiB", "480.0 MiB", "2.3 GiB", "612.0 MiB", "219.5 MiB"} {
+ require.Contains(t, htmlBody, size)
+ require.Contains(t, textBody, size)
+ }
}
diff --git a/backend/pkg/utils/notifications/messages.go b/backend/pkg/utils/notifications/messages.go
index 007b5c313..418e522d2 100644
--- a/backend/pkg/utils/notifications/messages.go
+++ b/backend/pkg/utils/notifications/messages.go
@@ -5,12 +5,12 @@ import (
"fmt"
"maps"
"slices"
- "sort"
"strings"
+ "github.com/docker/go-units"
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
"github.com/getarcaneapp/arcane/types/v2/system"
- kit "go.getarcane.app/kit/pkg"
+ "go.getarcane.app/kit/pkg"
)
type MessageFormat string
@@ -23,7 +23,7 @@ const (
MessageFormatHTML MessageFormat = "html"
)
-func formatNotificationTitleInternal(format MessageFormat, title string) string {
+func formatNotificationTitle(format MessageFormat, title string) string {
switch format {
case MessageFormatPlain:
return title
@@ -38,7 +38,7 @@ func formatNotificationTitleInternal(format MessageFormat, title string) string
}
}
-func formatNotificationLabelInternal(format MessageFormat, label string) string {
+func formatNotificationLabel(format MessageFormat, label string) string {
switch format {
case MessageFormatPlain:
return label + ":"
@@ -53,7 +53,7 @@ func formatNotificationLabelInternal(format MessageFormat, label string) string
}
}
-func formatNotificationCodeInternal(format MessageFormat, value string) string {
+func formatNotificationCode(format MessageFormat, value string) string {
switch format {
case MessageFormatPlain:
return value
@@ -67,8 +67,32 @@ func formatNotificationCodeInternal(format MessageFormat, value string) string {
}
func BuildImageUpdateNotificationMessage(format MessageFormat, environmentName, imageRef string, updateInfo *imageupdate.Response) string {
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyImageUpdateNotificationMessageInternal(environmentName, imageRef, updateInfo)
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n\n", environmentName)
+ fmt.Fprintf(&message, "πŸ“¦ **%s**\n", imageRef)
+
+ if updateInfo == nil {
+ fmt.Fprintln(&message, "ℹ️ Update details unavailable")
+ return message.String()
+ }
+
+ if !updateInfo.HasUpdate {
+ fmt.Fprintln(&message, "βœ… Already up to date")
+ return message.String()
+ }
+
+ current, latest := updateInfo.CurrentVersion, updateInfo.LatestVersion
+ if (updateInfo.UpdateType != "tag" || (current == "" && latest == "")) && (updateInfo.CurrentDigest != "" || updateInfo.LatestDigest != "") {
+ current = shortenNotificationDigest(updateInfo.CurrentDigest)
+ latest = shortenNotificationDigest(updateInfo.LatestDigest)
+ }
+ if !writeNtfyTransition(&message, current, latest, "") {
+ fmt.Fprintln(&message, "⚠️ Update available")
+ }
+
+ return message.String()
}
updateStatus := kit.Ternary(updateInfo != nil && updateInfo.HasUpdate, "Update Available", "No Update")
@@ -76,18 +100,17 @@ func BuildImageUpdateNotificationMessage(format MessageFormat, environmentName,
updateStatus = "⚠️ Update Available"
}
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "πŸ”” Container Image Update Notification"))
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Image"), imageRef)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Status"), updateStatus)
+ fmt.Fprintf(&message, "%s\n\n", formatNotificationTitle(format, "πŸ”” Container Image Update Notification"))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Image"), imageRef)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Status"), updateStatus)
if updateInfo != nil {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Update Type"), updateInfo.UpdateType)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Update Type"), updateInfo.UpdateType)
if updateInfo.CurrentDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Current Digest"), formatNotificationCodeInternal(format, updateInfo.CurrentDigest))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Current Digest"), formatNotificationCode(format, updateInfo.CurrentDigest))
}
if updateInfo.LatestDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Latest Digest"), formatNotificationCodeInternal(format, updateInfo.LatestDigest))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Latest Digest"), formatNotificationCode(format, updateInfo.LatestDigest))
}
}
@@ -95,32 +118,69 @@ func BuildImageUpdateNotificationMessage(format MessageFormat, environmentName,
}
func BuildContainerUpdateNotificationMessage(format MessageFormat, environmentName, containerName, imageRef, oldDigest, newDigest string) string {
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyContainerUpdateNotificationMessageInternal(environmentName, containerName, imageRef, oldDigest, newDigest)
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n\n", environmentName)
+ fmt.Fprintf(&message, "🐳 **%s**\n", containerName)
+ fmt.Fprintf(&message, "πŸ“¦ `%s`\n", imageRef)
+
+ if !writeNtfyTransition(
+ &message,
+ shortenNotificationDigest(oldDigest),
+ shortenNotificationDigest(newDigest),
+ "",
+ ) {
+ fmt.Fprintln(&message, "βœ… Updated successfully")
+ }
+
+ return message.String()
}
status := kit.Ternary(format != MessageFormatPlain, "βœ… Updated Successfully", "Updated Successfully")
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "βœ… Container Successfully Updated"))
+ fmt.Fprintf(&message, "%s\n\n", formatNotificationTitle(format, "βœ… Container Successfully Updated"))
fmt.Fprintf(&message, "Your container has been updated with the latest image version.\n\n")
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Container"), containerName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Image"), imageRef)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Status"), status)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Container"), containerName)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Image"), imageRef)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Status"), status)
if oldDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Previous Version"), formatNotificationCodeInternal(format, oldDigest))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Previous Version"), formatNotificationCode(format, oldDigest))
}
if newDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Current Version"), formatNotificationCodeInternal(format, newDigest))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Current Version"), formatNotificationCode(format, newDigest))
}
return message.String()
}
func BuildBatchImageUpdateNotificationMessage(format MessageFormat, environmentName string, updates map[string]*imageupdate.Response) string {
+ imageRefs := slices.Sorted(maps.Keys(updates))
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyBatchImageUpdateNotificationMessageInternal(environmentName, updates)
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
+
+ for _, imageRef := range imageRefs {
+ update := updates[imageRef]
+
+ fmt.Fprintf(&message, "\nπŸ“¦ **%s**\n", imageRef)
+
+ var current, latest string
+ if update != nil {
+ current, latest = update.CurrentVersion, update.LatestVersion
+ if (update.UpdateType != "tag" || (current == "" && latest == "")) && (update.CurrentDigest != "" || update.LatestDigest != "") {
+ current = shortenNotificationDigest(update.CurrentDigest)
+ latest = shortenNotificationDigest(update.LatestDigest)
+ }
+ }
+ if !writeNtfyTransition(&message, current, latest, " ") {
+ fmt.Fprintln(&message, " ⚠️ Update available")
+ }
+ }
+
+ return message.String()
}
title := "Container Image Updates Available"
@@ -129,11 +189,8 @@ func BuildBatchImageUpdateNotificationMessage(format MessageFormat, environmentN
description = "1 container image has an update available."
}
- imageRefs := slices.Sorted(maps.Keys(updates))
-
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n%s\n", formatNotificationTitleInternal(format, title), description)
- fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s\n\n%s\n", formatNotificationTitle(format, title), description)
+ fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabel(format, "Environment"), environmentName)
for _, imageRef := range imageRefs {
update := updates[imageRef]
@@ -146,18 +203,18 @@ func BuildBatchImageUpdateNotificationMessage(format MessageFormat, environmentN
case MessageFormatMarkdown:
fmt.Fprintf(&message, "**%s**\n", imageRef)
fmt.Fprintf(&message, "β€’ **Type:** %s\n", update.UpdateType)
- fmt.Fprintf(&message, "β€’ **Current:** %s\n", formatNotificationCodeInternal(format, update.CurrentDigest))
- fmt.Fprintf(&message, "β€’ **Latest:** %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest))
+ fmt.Fprintf(&message, "β€’ **Current:** %s\n", formatNotificationCode(format, update.CurrentDigest))
+ fmt.Fprintf(&message, "β€’ **Latest:** %s\n\n", formatNotificationCode(format, update.LatestDigest))
case MessageFormatSlack:
fmt.Fprintf(&message, "*%s*\n", imageRef)
fmt.Fprintf(&message, "β€’ *Type:* %s\n", update.UpdateType)
- fmt.Fprintf(&message, "β€’ *Current:* %s\n", formatNotificationCodeInternal(format, update.CurrentDigest))
- fmt.Fprintf(&message, "β€’ *Latest:* %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest))
+ fmt.Fprintf(&message, "β€’ *Current:* %s\n", formatNotificationCode(format, update.CurrentDigest))
+ fmt.Fprintf(&message, "β€’ *Latest:* %s\n\n", formatNotificationCode(format, update.LatestDigest))
case MessageFormatHTML:
fmt.Fprintf(&message, "<b>%s</b>\n", imageRef)
fmt.Fprintf(&message, "β€’ <b>Type:</b> %s\n", update.UpdateType)
- fmt.Fprintf(&message, "β€’ <b>Current:</b> %s\n", formatNotificationCodeInternal(format, update.CurrentDigest))
- fmt.Fprintf(&message, "β€’ <b>Latest:</b> %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest))
+ fmt.Fprintf(&message, "β€’ <b>Current:</b> %s\n", formatNotificationCode(format, update.CurrentDigest))
+ fmt.Fprintf(&message, "β€’ <b>Latest:</b> %s\n\n", formatNotificationCode(format, update.LatestDigest))
}
}
@@ -174,8 +231,28 @@ type ContainerUpdateBatchEntry struct {
// BuildBatchContainerUpdateNotificationMessage builds a formatted notification for a batch of container updates.
func BuildBatchContainerUpdateNotificationMessage(format MessageFormat, environmentName string, entries []ContainerUpdateBatchEntry) string {
+ sorted := slices.Clone(entries)
+ slices.SortFunc(sorted, func(a, b ContainerUpdateBatchEntry) int { return strings.Compare(a.ContainerName, b.ContainerName) })
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyBatchContainerUpdateNotificationMessageInternal(environmentName, entries)
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
+
+ for _, entry := range sorted {
+ fmt.Fprintf(&message, "\n🐳 **%s**\n", entry.ContainerName)
+ fmt.Fprintf(&message, " πŸ“¦ `%s`\n", entry.ImageRef)
+
+ if !writeNtfyTransition(
+ &message,
+ shortenNotificationDigest(entry.OldDigest),
+ shortenNotificationDigest(entry.NewDigest),
+ " ",
+ ) {
+ fmt.Fprintln(&message, " βœ… Updated successfully")
+ }
+ }
+
+ return message.String()
}
title := "Containers Updated"
@@ -185,13 +262,8 @@ func BuildBatchContainerUpdateNotificationMessage(format MessageFormat, environm
description = "1 container was updated."
}
- sorted := make([]ContainerUpdateBatchEntry, len(entries))
- copy(sorted, entries)
- sort.Slice(sorted, func(i, j int) bool { return sorted[i].ContainerName < sorted[j].ContainerName })
-
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n%s\n", formatNotificationTitleInternal(format, title), description)
- fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s\n\n%s\n", formatNotificationTitle(format, title), description)
+ fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabel(format, "Environment"), environmentName)
for _, entry := range sorted {
switch format {
@@ -206,10 +278,10 @@ func BuildBatchContainerUpdateNotificationMessage(format MessageFormat, environm
}
fmt.Fprintf(&message, "β€’ Image: %s\n", entry.ImageRef)
if entry.OldDigest != "" {
- fmt.Fprintf(&message, "β€’ Previous Version: %s\n", formatNotificationCodeInternal(format, entry.OldDigest))
+ fmt.Fprintf(&message, "β€’ Previous Version: %s\n", formatNotificationCode(format, entry.OldDigest))
}
if entry.NewDigest != "" {
- fmt.Fprintf(&message, "β€’ Current Version: %s\n\n", formatNotificationCodeInternal(format, entry.NewDigest))
+ fmt.Fprintf(&message, "β€’ Current Version: %s\n\n", formatNotificationCode(format, entry.NewDigest))
} else {
fmt.Fprintf(&message, "\n")
}
@@ -219,50 +291,75 @@ func BuildBatchContainerUpdateNotificationMessage(format MessageFormat, environm
}
func BuildVulnerabilitySummaryNotificationMessage(format MessageFormat, environmentName, summaryLabel, overview, fixableCount, severityBreakdown, sampleCVEs string) string {
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyVulnerabilitySummaryNotificationMessageInternal(
- environmentName,
- summaryLabel,
- overview,
- fixableCount,
- severityBreakdown,
- sampleCVEs,
- )
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
+
+ if strings.TrimSpace(summaryLabel) != "" {
+ fmt.Fprintf(&message, "\nπŸ“Š **%s**\n", summaryLabel)
+ }
+ if strings.TrimSpace(overview) != "" {
+ fmt.Fprintf(&message, "πŸ“¦ %s\n", overview)
+ }
+ if strings.TrimSpace(fixableCount) != "" {
+ fmt.Fprintf(&message, "πŸ› οΈ %s\n", fixableCount)
+ }
+ if strings.TrimSpace(severityBreakdown) != "" {
+ severityItems := strings.Fields(severityBreakdown)
+ fmt.Fprintf(&message, "🚨 %s\n", strings.Join(severityItems, " β€’ "))
+ }
+ if strings.TrimSpace(sampleCVEs) != "" {
+ fmt.Fprintf(&message, "πŸ”Ž `%s`\n", sampleCVEs)
+ }
+
+ return message.String()
}
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "πŸ“Š Daily Vulnerability Summary"))
+ fmt.Fprintf(&message, "%s\n\n", formatNotificationTitle(format, "πŸ“Š Daily Vulnerability Summary"))
if strings.TrimSpace(summaryLabel) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Summary"), summaryLabel)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Summary"), summaryLabel)
}
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Environment"), environmentName)
if strings.TrimSpace(overview) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Overview"), overview)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Overview"), overview)
}
if strings.TrimSpace(fixableCount) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Fixable Vulnerabilities"), fixableCount)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Fixable Vulnerabilities"), fixableCount)
}
if strings.TrimSpace(severityBreakdown) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Severity Breakdown"), severityBreakdown)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Severity Breakdown"), severityBreakdown)
}
if strings.TrimSpace(sampleCVEs) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Sample CVEs"), sampleCVEs)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Sample CVEs"), sampleCVEs)
}
return message.String()
}
func BuildPruneReportNotificationMessage(format MessageFormat, environmentName string, result *system.PruneAllResult) string {
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyPruneReportNotificationMessageInternal(environmentName, result)
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
+ fmt.Fprintf(
+ &message,
+ "πŸ’Ύ **%s** reclaimed\n\n",
+ FormatBytes(result.SpaceReclaimed),
+ )
+ fmt.Fprintf(&message, "πŸ“¦ Images: %s\n", FormatBytes(result.ImageSpaceReclaimed))
+ fmt.Fprintf(&message, "🧱 Containers: %s\n", FormatBytes(result.ContainerSpaceReclaimed))
+ fmt.Fprintf(&message, "πŸ’Ώ Volumes: %s\n", FormatBytes(result.VolumeSpaceReclaimed))
+ fmt.Fprintf(&message, "πŸ› οΈ Build cache: %s\n", FormatBytes(result.BuildCacheSpaceReclaimed))
+
+ return message.String()
}
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "🧹 System Prune Report"))
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabelInternal(format, "Total Space Reclaimed"), FormatBytes(result.SpaceReclaimed))
- fmt.Fprintf(&message, "%s\n", formatNotificationLabelInternal(format, "Breakdown"))
+ fmt.Fprintf(&message, "%s\n\n", formatNotificationTitle(format, "🧹 System Prune Report"))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabel(format, "Total Space Reclaimed"), FormatBytes(result.SpaceReclaimed))
+ fmt.Fprintf(&message, "%s\n", formatNotificationLabel(format, "Breakdown"))
fmt.Fprintf(&message, "- Containers: %s\n", FormatBytes(result.ContainerSpaceReclaimed))
fmt.Fprintf(&message, "- Images: %s\n", FormatBytes(result.ImageSpaceReclaimed))
fmt.Fprintf(&message, "- Volumes: %s\n", FormatBytes(result.VolumeSpaceReclaimed))
@@ -271,19 +368,25 @@ func BuildPruneReportNotificationMessage(format MessageFormat, environmentName s
}
func BuildAutoHealNotificationMessage(format MessageFormat, environmentName, containerName string) string {
+ var message strings.Builder
+
if format == MessageFormatNtfyMarkdown {
- return buildNtfyAutoHealNotificationMessageInternal(environmentName, containerName)
+ fmt.Fprintf(&message, "πŸ–₯️ %s\n\n", environmentName)
+ fmt.Fprintf(&message, "🐳 **%s**\n", containerName)
+ fmt.Fprintln(&message, "πŸ”„ Restarted automatically")
+ fmt.Fprintln(&message, "⚠️ Reason: container was unhealthy")
+
+ return message.String()
}
- var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "Auto Heal"))
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Container"), containerName)
- fmt.Fprintf(&message, "%s Automatically restarted because it was unhealthy.\n", formatNotificationLabelInternal(format, "Status"))
+ fmt.Fprintf(&message, "%s\n\n", formatNotificationTitle(format, "Auto Heal"))
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Environment"), environmentName)
+ fmt.Fprintf(&message, "%s %s\n", formatNotificationLabel(format, "Container"), containerName)
+ fmt.Fprintf(&message, "%s Automatically restarted because it was unhealthy.\n", formatNotificationLabel(format, "Status"))
return message.String()
}
-func shortenNotificationDigestInternal(value string) string {
+func shortenNotificationDigest(value string) string {
trimmed := strings.TrimSpace(value)
algorithm, digest, found := strings.Cut(trimmed, ":")
if !found {
@@ -311,24 +414,7 @@ func shortenNotificationDigestInternal(value string) string {
return algorithm + ":" + digest[:6] + "..."
}
-func ntfyUpdateTransitionInternal(update *imageupdate.Response) (string, string) {
- if update == nil {
- return "", ""
- }
-
- if update.UpdateType == "tag" && (update.CurrentVersion != "" || update.LatestVersion != "") {
- return update.CurrentVersion, update.LatestVersion
- }
-
- if update.CurrentDigest != "" || update.LatestDigest != "" {
- return shortenNotificationDigestInternal(update.CurrentDigest),
- shortenNotificationDigestInternal(update.LatestDigest)
- }
-
- return update.CurrentVersion, update.LatestVersion
-}
-
-func writeNtfyTransitionInternal(message *strings.Builder, current, latest, indent string) bool {
+func writeNtfyTransition(message *strings.Builder, current, latest, indent string) bool {
if current == "" && latest == "" {
return false
}
@@ -351,211 +437,12 @@ func writeNtfyTransitionInternal(message *strings.Builder, current, latest, inde
return true
}
-func byteMagnitudeInternal(bytes uint64) (float64, int) {
- const unit = 1024
- if bytes < unit {
- return float64(bytes), -1
- }
-
- div, exp := uint64(unit), 0
- for n := bytes / unit; n >= unit; n /= unit {
- div *= unit
- exp++
- }
-
- return float64(bytes) / float64(div), exp
-}
-
-func formatNtfyBytesInternal(bytes uint64) string {
- value, exp := byteMagnitudeInternal(bytes)
- if exp < 0 {
- return fmt.Sprintf("%d B", bytes)
- }
-
- units := []string{"KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
- return fmt.Sprintf("%.1f %s", value, units[exp])
-}
-
-func buildNtfyImageUpdateNotificationMessageInternal(
- environmentName,
- imageRef string,
- updateInfo *imageupdate.Response,
-) string {
- var message strings.Builder
-
- fmt.Fprintf(&message, "πŸ–₯️ %s\n\n", environmentName)
- fmt.Fprintf(&message, "πŸ“¦ **%s**\n", imageRef)
-
- if updateInfo == nil {
- fmt.Fprintln(&message, "ℹ️ Update details unavailable")
- return message.String()
- }
-
- if !updateInfo.HasUpdate {
- fmt.Fprintln(&message, "βœ… Already up to date")
- return message.String()
- }
-
- current, latest := ntfyUpdateTransitionInternal(updateInfo)
- if !writeNtfyTransitionInternal(&message, current, latest, "") {
- fmt.Fprintln(&message, "⚠️ Update available")
- }
-
- return message.String()
-}
-
-func buildNtfyContainerUpdateNotificationMessageInternal(
- environmentName,
- containerName,
- imageRef,
- oldDigest,
- newDigest string,
-) string {
- var message strings.Builder
-
- fmt.Fprintf(&message, "πŸ–₯️ %s\n\n", environmentName)
- fmt.Fprintf(&message, "🐳 **%s**\n", containerName)
- fmt.Fprintf(&message, "πŸ“¦ `%s`\n", imageRef)
-
- if !writeNtfyTransitionInternal(
- &message,
- shortenNotificationDigestInternal(oldDigest),
- shortenNotificationDigestInternal(newDigest),
- "",
- ) {
- fmt.Fprintln(&message, "βœ… Updated successfully")
- }
-
- return message.String()
-}
-
-func buildNtfyBatchImageUpdateNotificationMessageInternal(
- environmentName string,
- updates map[string]*imageupdate.Response,
-) string {
- imageRefs := slices.Sorted(maps.Keys(updates))
-
- var message strings.Builder
- fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
-
- for _, imageRef := range imageRefs {
- update := updates[imageRef]
-
- fmt.Fprintf(&message, "\nπŸ“¦ **%s**\n", imageRef)
-
- current, latest := ntfyUpdateTransitionInternal(update)
- if !writeNtfyTransitionInternal(&message, current, latest, " ") {
- fmt.Fprintln(&message, " ⚠️ Update available")
- }
- }
-
- return message.String()
-}
-
-func buildNtfyBatchContainerUpdateNotificationMessageInternal(
- environmentName string,
- entries []ContainerUpdateBatchEntry,
-) string {
- sorted := make([]ContainerUpdateBatchEntry, len(entries))
- copy(sorted, entries)
-
- sort.Slice(sorted, func(i, j int) bool {
- return sorted[i].ContainerName < sorted[j].ContainerName
- })
-
- var message strings.Builder
- fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
-
- for _, entry := range sorted {
- fmt.Fprintf(&message, "\n🐳 **%s**\n", entry.ContainerName)
- fmt.Fprintf(&message, " πŸ“¦ `%s`\n", entry.ImageRef)
-
- if !writeNtfyTransitionInternal(
- &message,
- shortenNotificationDigestInternal(entry.OldDigest),
- shortenNotificationDigestInternal(entry.NewDigest),
- " ",
- ) {
- fmt.Fprintln(&message, " βœ… Updated successfully")
- }
- }
-
- return message.String()
-}
-
-func buildNtfyVulnerabilitySummaryNotificationMessageInternal(
- environmentName,
- summaryLabel,
- overview,
- fixableCount,
- severityBreakdown,
- sampleCVEs string,
-) string {
- var message strings.Builder
-
- fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
-
- if strings.TrimSpace(summaryLabel) != "" {
- fmt.Fprintf(&message, "\nπŸ“Š **%s**\n", summaryLabel)
- }
- if strings.TrimSpace(overview) != "" {
- fmt.Fprintf(&message, "πŸ“¦ %s\n", overview)
- }
- if strings.TrimSpace(fixableCount) != "" {
- fmt.Fprintf(&message, "πŸ› οΈ %s\n", fixableCount)
- }
- if strings.TrimSpace(severityBreakdown) != "" {
- severityItems := strings.Fields(severityBreakdown)
- fmt.Fprintf(&message, "🚨 %s\n", strings.Join(severityItems, " β€’ "))
- }
- if strings.TrimSpace(sampleCVEs) != "" {
- fmt.Fprintf(&message, "πŸ”Ž `%s`\n", sampleCVEs)
- }
-
- return message.String()
-}
-
-func buildNtfyPruneReportNotificationMessageInternal(
- environmentName string,
- result *system.PruneAllResult,
-) string {
- var message strings.Builder
-
- fmt.Fprintf(&message, "πŸ–₯️ %s\n", environmentName)
- fmt.Fprintf(
- &message,
- "πŸ’Ύ **%s** reclaimed\n\n",
- formatNtfyBytesInternal(result.SpaceReclaimed),
- )
- fmt.Fprintf(&message, "πŸ“¦ Images: %s\n", formatNtfyBytesInternal(result.ImageSpaceReclaimed))
- fmt.Fprintf(&message, "🧱 Containers: %s\n", formatNtfyBytesInternal(result.ContainerSpaceReclaimed))
- fmt.Fprintf(&message, "πŸ’Ώ Volumes: %s\n", formatNtfyBytesInternal(result.VolumeSpaceReclaimed))
- fmt.Fprintf(&message, "πŸ› οΈ Build cache: %s\n", formatNtfyBytesInternal(result.BuildCacheSpaceReclaimed))
-
- return message.String()
-}
-
-func buildNtfyAutoHealNotificationMessageInternal(
- environmentName,
- containerName string,
-) string {
- var message strings.Builder
-
- fmt.Fprintf(&message, "πŸ–₯️ %s\n\n", environmentName)
- fmt.Fprintf(&message, "🐳 **%s**\n", containerName)
- fmt.Fprintln(&message, "πŸ”„ Restarted automatically")
- fmt.Fprintln(&message, "⚠️ Reason: container was unhealthy")
-
- return message.String()
-}
-
func FormatBytes(bytes uint64) string {
- value, exp := byteMagnitudeInternal(bytes)
- if exp < 0 {
+ if bytes < units.KiB {
return fmt.Sprintf("%d B", bytes)
}
- return fmt.Sprintf("%.1f %cB", value, "KMGTPE"[exp])
+ return units.CustomSize("%.1f %s", float64(bytes), units.KiB, []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"})
}
func BuildEmailSubject(environmentName, subject string) string {
diff --git a/cli/go.mod b/cli/go.mod
index e21dcbb00..aa0a2ae2b 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -13,6 +13,7 @@ require (
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/x/ansi v0.11.9
github.com/charmbracelet/x/term v0.2.2
+ github.com/docker/go-units v0.5.0
github.com/getarcaneapp/arcane/types/v2 v2.14.0
github.com/mattn/go-runewidth v0.0.31
github.com/muesli/cancelreader v0.2.2
@@ -22,7 +23,6 @@ require (
github.com/stretchr/testify v1.12.1
go.getarcane.app/acfs v0.6.2
go.getarcane.app/kit v0.4.0
- go.getarcane.app/sys/bytes v0.3.0
go.yaml.in/yaml/v4 v4.0.0-rc.6
)
@@ -44,7 +44,6 @@ require (
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.8.2 // indirect
- github.com/docker/go-units v0.5.0 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/go-logfmt/logfmt v0.6.1 // indirect
github.com/go-logr/logr v1.4.4 // indirect
diff --git a/cli/go.sum b/cli/go.sum
index c93a2cc5b..8355f1d1b 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -141,8 +141,6 @@ go.getarcane.app/builds v0.4.4 h1:r9e97gmG2vic6kZB1UfTp9vSpqb1nPYA6CBlbaCvH64=
go.getarcane.app/builds v0.4.4/go.mod h1:8B6z4dKZqE36Y+Rpudx7AIL3BXeIoqsMgrJQepRKeds=
go.getarcane.app/kit v0.4.0 h1:3PqyAmBfp07ZOK1ztCwS6vuOzQKFtXeMbk+P0oxhIK4=
go.getarcane.app/kit v0.4.0/go.mod h1:KTjbXTEeC3i9e1QxZowDJWjFyABlD6UF3ISVtoIZs10=
-go.getarcane.app/sys/bytes v0.3.0 h1:hkei6a52Gz/SdezCj7jj14Hc90Tkw4g1dNVZdpYWhMs=
-go.getarcane.app/sys/bytes v0.3.0/go.mod h1:fcMYM7dknLk+KDXYAg6XOfRF22POYxcTnQeypFEjDbE=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
diff --git a/cli/internal/output/tui.go b/cli/internal/output/tui.go
index 32c91bb01..f55d2a17f 100644
--- a/cli/internal/output/tui.go
+++ b/cli/internal/output/tui.go
@@ -1,17 +1,21 @@
package output
import (
+ "cmp"
"context"
"fmt"
"io"
+ "slices"
"strings"
"sync"
"time"
"charm.land/bubbles/v2/progress"
+ "charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
- "go.getarcane.app/sys/bytes"
+ "github.com/docker/go-units"
+ "go.getarcane.app/kit/pkg"
)
var spinnerFrames = []string{"β ‹", "β ™", "β Ή", "β Έ", "β Ό", "β ΄", "β ¦", "β §", "β ‡", "⠏"}
@@ -50,51 +54,100 @@ type tracker struct {
// StartTracker renders a checklist only for interactive text output.
func StartTracker(ctx context.Context, out io.Writer, enabled bool, labels ...string) *tracker {
- if out == nil {
- out = io.Discard
- }
- t := &tracker{out: out, live: enabled && IsTerminal(out) && IsTerminal(Stdout()), current: -1}
+ out = cmp.Or(out, io.Discard)
+ t := &tracker{out: out, live: enabled && IsTerminal(out) && IsTerminal(Stdout()) && ctx.Err() == nil, current: -1}
for _, label := range labels {
t.steps = append(t.steps, trackerStep{label: label, status: stepPending})
}
- if !t.live || ctx.Err() != nil {
- t.live = false
+ if !t.live {
return t
}
+ fd, hasFD := t.out.(interface{ Fd() uintptr })
t.stop, t.done = make(chan struct{}), make(chan struct{})
t.resumeOuter = SuspendProgress()
trackersMu.Lock()
activeTrackers[t] = struct{}{}
trackersMu.Unlock()
- go t.runInternal(ctx)
- return t
-}
-
-func (t *tracker) runInternal(ctx context.Context) {
- defer close(t.done)
- defer func() {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.stopped = true
- t.clearInternal()
- }()
- ticker := time.NewTicker(100 * time.Millisecond)
- defer ticker.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.stop:
- return
- case <-ticker.C:
+ go func() {
+ defer close(t.done)
+ defer func() {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.stopped = true
+ if t.drawn == 0 {
+ return
+ }
+ terminalMu.Lock()
+ defer terminalMu.Unlock()
+ _, _ = io.WriteString(t.out, strings.Repeat("\x1b[A\r\x1b[2K", t.drawn))
+ t.drawn = 0
+ }()
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.stop:
+ return
+ case <-ticker.C:
+ }
t.mu.Lock()
t.frame++
- if t.paused == 0 {
- t.drawInternal()
+ if t.paused > 0 {
+ t.mu.Unlock()
+ continue
}
+ width, height := 80, 24
+ if hasFD {
+ w, h, err := term.GetSize(fd.Fd())
+ width = max(kit.Ternary(err == nil, w, width), 1)
+ height = max(kit.Ternary(err == nil, h, height), 2)
+ }
+ var frame strings.Builder
+ frame.WriteString(kit.Ternary(t.drawn > 0, fmt.Sprintf("\x1b[%dA", t.drawn), ""))
+ start := max(len(t.steps)-max(height-2, 1), 0)
+ icons := [...]string{stepPending: "β—‹", stepRunning: spinnerFrames[t.frame%len(spinnerFrames)], stepSucceeded: "βœ“", stepFailed: "βœ—"}
+ styles := [...]lipgloss.Style{stepPending: statusMutedStyle, stepRunning: infoStyle, stepSucceeded: successStyle, stepFailed: statusOfflineStyle}
+ for _, step := range t.steps[start:] {
+ line := " " + renderForInternal(t.out, styles[step.status], icons[step.status]) + " " + renderForInternal(t.out, valueStyle, step.label)
+ if step.status == stepRunning && step.total > 0 {
+ current := min(step.current, step.total)
+ var count string
+ if step.bytes {
+ count = Bytes(current) + "/" + Bytes(step.total)
+ } else {
+ count = fmt.Sprintf("%d/%d", current, step.total)
+ }
+ barWidth := min(24, max(width-visibleWidthInternal(step.label)-len(count)-7, 1))
+ bar := progress.New(progress.WithWidth(barWidth), progress.WithColors(arcanePurple))
+ showColor := colorEnabledInternal()
+ bar.FullColor = kit.Ternary(showColor, bar.FullColor, nil)
+ bar.EmptyColor = kit.Ternary(showColor, bar.EmptyColor, nil)
+ bar.PercentageStyle = kit.Ternary(showColor, bar.PercentageStyle, tablePlainCell.UnsetPadding())
+ line = fmt.Sprintf(" %s %s %s", renderForInternal(t.out, infoStyle, step.label), bar.ViewAs(float64(current)/float64(step.total)), count)
+ if !showColor {
+ line = ansi.Strip(line)
+ }
+ }
+ frame.WriteString("\r\x1b[2K")
+ frame.WriteString(ansi.Truncate(line, width, "…"))
+ frame.WriteByte('\n')
+ }
+ // Erase rows left over after a terminal resize.
+ count := len(t.steps) - start
+ if extra := t.drawn - count; extra > 0 {
+ frame.WriteString(strings.Repeat("\r\x1b[2K\n", extra))
+ _, _ = fmt.Fprintf(&frame, "\x1b[%dA", extra)
+ }
+ t.drawn = count
+ terminalMu.Lock()
+ _, _ = io.WriteString(t.out, frame.String())
+ terminalMu.Unlock()
t.mu.Unlock()
}
- }
+ }()
+ return t
}
// NextStep completes the active step and starts the next pending step.
@@ -114,16 +167,11 @@ func (t *tracker) NextStep() {
func (t *tracker) SetProgress(key, label string, current, total int64, byteCount bool) {
t.mu.Lock()
defer t.mu.Unlock()
- index := -1
+ var index int
if key == "" && t.current >= 0 && t.current < len(t.steps) {
index = t.current
} else {
- for i := range t.steps {
- if t.steps[i].key == key {
- index = i
- break
- }
- }
+ index = slices.IndexFunc(t.steps, func(step trackerStep) bool { return step.key == key })
}
if index < 0 {
t.steps = append(t.steps, trackerStep{key: key})
@@ -174,7 +222,12 @@ func SuspendProgress() func() {
for _, t := range trackers {
t.mu.Lock()
t.paused++
- t.clearInternal()
+ if t.drawn > 0 {
+ terminalMu.Lock()
+ _, _ = io.WriteString(t.out, strings.Repeat("\x1b[A\r\x1b[2K", t.drawn))
+ t.drawn = 0
+ terminalMu.Unlock()
+ }
t.mu.Unlock()
}
var once sync.Once
@@ -189,82 +242,14 @@ func SuspendProgress() func() {
}
}
-func (t *tracker) clearInternal() {
- if t.drawn == 0 {
- return
- }
- terminalMu.Lock()
- defer terminalMu.Unlock()
- _, _ = io.WriteString(t.out, strings.Repeat("\x1b[A\r\x1b[2K", t.drawn))
- t.drawn = 0
-}
+// Bytes renders a signed byte count in human-readable form.
+func Bytes(value int64) string { return UnsignedBytes(uint64(max(value, 0))) }
-func (t *tracker) drawInternal() {
- width := 80
- height := 24
- if fd, ok := t.out.(interface{ Fd() uintptr }); ok {
- if w, h, err := term.GetSize(fd.Fd()); err == nil {
- width, height = max(w, 1), max(h, 2)
- }
- }
- var frame strings.Builder
- if t.drawn > 0 {
- _, _ = fmt.Fprintf(&frame, "\x1b[%dA", t.drawn)
- }
- start := max(len(t.steps)-max(height-2, 1), 0)
- for _, step := range t.steps[start:] {
- frame.WriteString("\r\x1b[2K")
- frame.WriteString(ansi.Truncate(t.renderStepInternal(step, width), width, "…"))
- frame.WriteByte('\n')
- }
- // Erase rows left over after a terminal resize.
- count := len(t.steps) - start
- for i := count; i < t.drawn; i++ {
- frame.WriteString("\r\x1b[2K\n")
- }
- if t.drawn > count {
- _, _ = fmt.Fprintf(&frame, "\x1b[%dA", t.drawn-count)
+// UnsignedBytes renders an unsigned byte count in human-readable form.
+func UnsignedBytes(value uint64) string {
+ if value < units.KiB {
+ return fmt.Sprintf("%d B", value)
}
- t.drawn = count
- terminalMu.Lock()
- defer terminalMu.Unlock()
- _, _ = io.WriteString(t.out, frame.String())
-}
-func (t *tracker) renderStepInternal(step trackerStep, width int) string {
- icon, style := "β—‹", statusMutedStyle
- switch step.status {
- case stepRunning:
- icon, style = spinnerFrames[t.frame%len(spinnerFrames)], infoStyle
- if step.total > 0 {
- current := min(step.current, step.total)
- count := fmt.Sprintf("%d/%d", current, step.total)
- if step.bytes {
- count = Bytes(current) + "/" + Bytes(step.total)
- }
- barWidth := min(24, max(width-visibleWidthInternal(step.label)-len(count)-7, 1))
- bar := progress.New(progress.WithWidth(barWidth), progress.WithColors(arcanePurple))
- if !colorEnabledInternal() {
- bar.FullColor = nil
- bar.EmptyColor = nil
- bar.PercentageStyle = tablePlainCell.UnsetPadding()
- }
- line := fmt.Sprintf(" %s %s %s", renderForInternal(t.out, infoStyle, step.label), bar.ViewAs(float64(current)/float64(step.total)), count)
- if !colorEnabledInternal() {
- return ansi.Strip(line)
- }
- return line
- }
- case stepSucceeded:
- icon, style = "βœ“", successStyle
- case stepFailed:
- icon, style = "βœ—", warnStyle.Foreground(statusOffline)
- }
- return " " + renderForInternal(t.out, style, icon) + " " + renderForInternal(t.out, valueStyle, step.label)
+ return units.CustomSize("%.1f %s", float64(value), units.KiB, []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"})
}
-
-// Bytes renders a signed byte count in human-readable form.
-func Bytes(value int64) string { return bytes.Capacity(uint64(max(value, 0))).String() }
-
-// UnsignedBytes renders an unsigned byte count in human-readable form.
-func UnsignedBytes(value uint64) string { return bytes.Capacity(value).String() }