refactor: deduplicate utility helpers across the codebase (#23338)

Audited exported helpers in `coderd/util/*`, `testutil`, `cryptorand`,
and friends, then replaced duplicated implementations with canonical
versions.

- **fix: `maps.SortedKeys` generic signature** — value type was
hardcoded to `any`, making it impossible to actually call. Added second
type parameter `V any`. Added table-driven tests with `cmp.Diff`.
- **refactor: replace ad-hoc ptr helpers with `ptr.Ref`** — removed
`int64Ptr`, `stringPtr`, `boolPtr`, `i64ptr`, `strPtr`, `PtrInt32`
across 6 files.
- **refactor: replace local `sortedKeys`/`sortKeys` with
`maps.SortedKeys`** — now that the signature is fixed, scripts can use
it.
- **refactor: replace hand-rolled `capitalize` with
`strings.Capitalize`** — the typegen version was also not UTF-8 safe.

> 🤖 This PR was created with the help of Coder Agents, and was reviewed
by my human. 🧑‍💻
This commit is contained in:
Cian Johnston
2026-03-20 15:12:41 +00:00
committed by GitHub
parent 23542cb6af
commit f1d333f0e6
11 changed files with 116 additions and 114 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ func Subset[T, U comparable](a, b map[T]U) bool {
}
// SortedKeys returns the keys of m in sorted order.
func SortedKeys[T constraints.Ordered](m map[T]any) (keys []T) {
func SortedKeys[K constraints.Ordered, V any](m map[K]V) (keys []K) {
for k := range m {
keys = append(keys, k)
}
+44
View File
@@ -4,9 +4,53 @@ import (
"strconv"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/coder/coder/v2/coderd/util/maps"
)
func TestSortedKeys(t *testing.T) {
t.Parallel()
for idx, tc := range []struct {
name string
input map[string]int
expected []string
}{
{
name: "SortsAlphabetically",
input: map[string]int{
"banana": 1,
"apple": 2,
"cherry": 3,
},
expected: []string{"apple", "banana", "cherry"},
},
{
name: "AlreadySorted",
input: map[string]int{
"alpha": 1,
"mango": 2,
"zebra": 3,
},
expected: []string{"alpha", "mango", "zebra"},
},
{
name: "EmptyMap",
input: map[string]int{},
expected: nil,
},
} {
t.Run("#"+strconv.Itoa(idx)+"_"+tc.name, func(t *testing.T) {
t.Parallel()
got := maps.SortedKeys(tc.input)
if diff := cmp.Diff(tc.expected, got); diff != "" {
t.Fatalf("unexpected result (-want +got):\n%s", diff)
}
})
}
}
func TestSubset(t *testing.T) {
t.Parallel()