Sort stdin by semver
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
892 B

3 years ago
  1. // command svsort sorts lines of text by semver at beginning of line
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "log"
  7. "os"
  8. "sort"
  9. "strings"
  10. "github.com/blang/semver"
  11. )
  12. type line struct {
  13. v semver.Version
  14. line string
  15. }
  16. type lines []line
  17. func (l lines) Len() int { return len(l) }
  18. func (l lines) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
  19. func (l lines) Less(i, j int) bool { return l[i].v.LT(l[j].v) }
  20. func main() {
  21. s := bufio.NewScanner(os.Stdin)
  22. ls := lines{}
  23. for s.Scan() {
  24. f := strings.Fields(s.Text())
  25. if len(f) < 2 {
  26. continue
  27. }
  28. v, err := semver.ParseTolerant(f[0])
  29. if err != nil {
  30. log.Printf("%v: %q", err, s.Text())
  31. continue
  32. }
  33. l := line{
  34. v: v,
  35. line: s.Text(),
  36. }
  37. ls = append(ls, l)
  38. }
  39. if err := s.Err(); err != nil {
  40. log.Fatalf("scan: %v")
  41. }
  42. sort.Sort(ls)
  43. for _, l := range ls {
  44. fmt.Printf("%v\n", l.line)
  45. }
  46. }