Skip to content

chore: Replace sort package with slices and cmp packages - #986

Open
dongjiang1989 wants to merge 1 commit into
prometheus:mainfrom
dongjiang1989:sort-slices
Open

chore: Replace sort package with slices and cmp packages#986
dongjiang1989 wants to merge 1 commit into
prometheus:mainfrom
dongjiang1989:sort-slices

Conversation

@dongjiang1989

Copy link
Copy Markdown
Member

Replace all usage of Go's sort package with the modern slices and cmp packages (Go 1.21+) for more concise and readable sorting code.

Changes

  • Remove sort.Interface methods (Len/Less/Swap) from LabelNames, LabelValues, LabelPairs, Fingerprints, Alerts, Samples, Vector, and Matrix types.
  • Add Compare methods on *Sample, *SampleStream, *Alert, and *LabelPair for use with slices.SortFunc, eliminating duplicated comparator code at call sites.
  • Replace sort.Sort calls with slices.SortFunc (using the new Compare methods or cmp.Compare for simple ordered types), and sort.Strings with slices.Sort.
  • Add a depguard rule in .golangci.yml to forbid the sort package and prevent future regressions.
  • Fix pre-existing gofumpt formatting issues in config and route packages (uncovered by make lint).

Note

The original Alerts.Less was not a proper strict weak ordering (it used StartsBefore || EndsBefore || FPLess). The new (*Alert).Compare implements a correct hierarchical comparison (StartsAt → EndsAt → Fingerprint). TestSortAlerts expected values were updated accordingly.

Verification

  • go build ./...
  • go vet ./...
  • make lint
  • go test ./model/... ./expfmt/...

Replace all usage of Go's sort package with the modern slices and cmp
packages (Go 1.21+) for more concise and readable sorting code.

- Remove sort.Interface methods (Len/Less/Swap) from LabelNames,
  LabelValues, LabelPairs, Fingerprints, Alerts, Samples, Vector, and
  Matrix types.
- Add Compare methods on *Sample, *SampleStream, *Alert, and *LabelPair
  for use with slices.SortFunc.
- Replace sort.Sort calls with slices.SortFunc using the new Compare
  methods, and sort.Strings with slices.Sort.
- Add depguard rule in .golangci.yml to forbid the sort package and
  prevent future regressions.
- Fix pre-existing gofumpt formatting issues in config and route
  packages.

Signed-off-by: dongjiang1989 <dongjiang1989@126.com>
@dongjiang1989 dongjiang1989 changed the title Replace sort package with slices and cmp packages chore: Replace sort package with slices and cmp packages Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant