git.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "fmt"
  7. "github.com/SongZihuan/BackendServerTemplate/tool/utils/cleanstringutils"
  8. "github.com/SongZihuan/BackendServerTemplate/tool/utils/executils"
  9. "github.com/SongZihuan/BackendServerTemplate/tool/utils/filesystemutils"
  10. "strings"
  11. "sync"
  12. )
  13. var hasGitOnce sync.Once
  14. var hasGit = false
  15. func HasGit() bool {
  16. hasGitOnce.Do(func() {
  17. hasGit = filesystemutils.IsDir("./.git")
  18. })
  19. return hasGit
  20. }
  21. func GetLastCommit() (string, error) {
  22. return executils.RunOnline("git", "rev-parse", "HEAD")
  23. }
  24. func GetTagListWithFilter(filter func(string) bool) ([]string, error) {
  25. ret, err := executils.Run("git", "for-each-ref", "--sort=-creatordate", "--format", "%(refname:short)", "refs/tags/")
  26. if err != nil {
  27. return nil, err
  28. }
  29. fmt.Printf("\n=1=\n%s\n=1=\n", ret)
  30. ret = cleanstringutils.GetString(ret)
  31. fmt.Printf("\n=2=\n%s\n=2=\n", ret)
  32. tagListSrc := strings.Split(ret, "\n")
  33. fmt.Printf("tagListSrc length=%d\n", len(tagListSrc))
  34. tagList := make([]string, 0, len(tagListSrc))
  35. for _, tag := range tagListSrc {
  36. tag = strings.TrimSpace(tag)
  37. if tag == "" || (filter != nil && !filter(tag)) {
  38. fmt.Printf("generate: skip tag %s\n", tag)
  39. continue
  40. }
  41. tagList = append(tagList, tag)
  42. }
  43. return tagList, nil
  44. }
  45. func GetTagList() ([]string, error) {
  46. return GetTagListWithFilter(nil)
  47. }
  48. func GetTagCommit(tag string) (string, error) {
  49. return executils.RunOnline("git", "rev-list", "-n", "1", tag)
  50. }
  51. func GetFirstCommit() (string, error) {
  52. return executils.RunOnline("git", "rev-list", "--max-parents=0", "HEAD")
  53. }