git.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2025 BackendServerTemplate Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package gitutils
  5. import (
  6. "github.com/SongZihuan/BackendServerTemplate/tool/utils/cleanstringutils"
  7. "github.com/SongZihuan/BackendServerTemplate/tool/utils/executils"
  8. "github.com/SongZihuan/BackendServerTemplate/tool/utils/filesystemutils"
  9. "strings"
  10. "sync"
  11. )
  12. var hasGitOnce sync.Once
  13. var hasGit = false
  14. func HasGit() bool {
  15. hasGitOnce.Do(func() {
  16. hasGit = filesystemutils.IsDir("./.git")
  17. })
  18. return hasGit
  19. }
  20. func GetLastCommit() (string, error) {
  21. return executils.RunOnline("git", "rev-parse", "HEAD")
  22. }
  23. func GetTagListWithFilter(filter func(string) bool) ([]string, error) {
  24. ret, err := executils.Run("git", "for-each-ref", "--sort=-creatordate", "--format", "%(refname:short)", "refs/tags/")
  25. if err != nil {
  26. return nil, err
  27. }
  28. ret = cleanstringutils.GetString(ret)
  29. tagListSrc := strings.Split(ret, "\n")
  30. tagList := make([]string, 0, len(tagListSrc))
  31. for _, tag := range tagListSrc {
  32. tag = strings.TrimSpace(tag)
  33. if tag == "" || (filter != nil && !filter(tag)) {
  34. continue
  35. }
  36. tagList = append(tagList, tag)
  37. }
  38. return tagList, nil
  39. }
  40. func GetTagList() ([]string, error) {
  41. return GetTagListWithFilter(nil)
  42. }
  43. func GetTagCommit(tag string) (string, error) {
  44. return executils.RunOnline("git", "rev-list", "-n", "1", tag)
  45. }
  46. func GetFirstCommit() (string, error) {
  47. return executils.RunOnline("git", "rev-list", "--max-parents=0", "HEAD")
  48. }