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
+3 -12
View File
@@ -5,12 +5,12 @@ import (
"flag"
"log"
"os"
"sort"
"strconv"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/util/maps"
"github.com/coder/coder/v2/enterprise/audit"
"github.com/coder/coder/v2/scripts/atomicwrite"
)
@@ -96,7 +96,7 @@ func readAuditDoc() ([]byte, error) {
// Writes a markdown table of audit log resources to a buffer
func updateAuditDoc(doc []byte, auditableResourcesMap AuditableResourcesMap) ([]byte, error) {
// We must sort the resources to ensure table ordering
sortedResourceNames := sortKeys(auditableResourcesMap)
sortedResourceNames := maps.SortedKeys(auditableResourcesMap)
i := bytes.Index(doc, generatorPrefix)
if i < 0 {
@@ -135,7 +135,7 @@ func updateAuditDoc(doc []byte, auditableResourcesMap AuditableResourcesMap) ([]
_, _ = buffer.WriteString("|" + readableResourceName + "<br><i>" + auditActionsString + "</i>|<table><thead><tr><th>Field</th><th>Tracked</th></tr></thead><tbody>" + "|")
// We must sort the field names to ensure sub-table ordering
sortedFieldNames := sortKeys(auditableResourcesMap[resourceName])
sortedFieldNames := maps.SortedKeys(auditableResourcesMap[resourceName])
for _, fieldName := range sortedFieldNames {
isTracked := auditableResourcesMap[resourceName][fieldName]
@@ -153,12 +153,3 @@ func updateAuditDoc(doc []byte, auditableResourcesMap AuditableResourcesMap) ([]
func writeAuditDoc(doc []byte) error {
return atomicwrite.File(auditDocFile, doc)
}
func sortKeys[T any](stringMap map[string]T) []string {
var keyNames []string
for key := range stringMap {
keyNames = append(keyNames, key)
}
sort.Strings(keyNames)
return keyNames
}