mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-05-08 04:29:16 -05:00
Add component to display file size
This commit is contained in:
@@ -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)),
|
||||
),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user