Add component to display file size

This commit is contained in:
Julien W
2024-08-11 22:15:00 +02:00
parent 4881f04917
commit 94759c65cd
3 changed files with 75 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
package strutil
import "fmt"
// FormatFileSize pretty prints a file size (in bytes) to a human-readable format
//
// e.g. 1024 -> 1 KB
func FormatFileSize(size int64) string {
if size < 1024 {
return fmt.Sprintf("%d B", size)
}
if size < 1024*1024 {
return fmt.Sprintf("%.2f KB", float64(size)/1024)
}
if size < 1024*1024*1024 {
return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024))
}
return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024))
}
@@ -0,0 +1,29 @@
package strutil
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestFormatFileSize(t *testing.T) {
tests := []struct {
size int64
expected string
}{
{size: 0, expected: "0 B"},
{size: 1, expected: "1 B"},
{size: 1023, expected: "1023 B"},
{size: 1024, expected: "1.00 KB"},
{size: 1024*1024 - 10, expected: "1023.99 KB"},
{size: 1024 * 1024, expected: "1.00 MB"},
{size: 1024*1024*1024 - 10_000, expected: "1023.99 MB"},
{size: 1024 * 1024 * 1024, expected: "1.00 GB"},
{size: 1024*1024*1024*1024 - 10_000_000, expected: "1023.99 GB"},
}
for _, test := range tests {
t.Run(test.expected, func(t *testing.T) {
assert.Equal(t, test.expected, FormatFileSize(test.size))
})
}
}
@@ -0,0 +1,24 @@
package component
import (
"database/sql"
"github.com/eduardolat/pgbackweb/internal/util/strutil"
"github.com/maragudk/gomponents"
"github.com/maragudk/gomponents/html"
)
// PrettyFileSize pretty prints a file size (in bytes) to a human-readable format.
// If the size is not valid, it returns an empty string.
//
// e.g. 1024 -> 1 KB
func PrettyFileSize(
size sql.NullInt64,
) gomponents.Node {
return gomponents.If(
size.Valid,
html.Span(
SpanText(strutil.FormatFileSize(size.Int64)),
),
)
}