git.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. ret = cleanstringutils.GetString(ret)
  30. tagListSrc := strings.Split(ret, "\n")
  31. tagList := make([]string, 0, len(tagListSrc))
  32. for _, tag := range tagListSrc {
  33. tag = strings.TrimSpace(tag)
  34. if tag == "" || (filter != nil && !filter(tag)) {
  35. continue
  36. }
  37. tagList = append(tagList, tag)
  38. }
  39. return tagList, nil
  40. }
  41. func GetTagList() ([]string, error) {
  42. return GetTagListWithFilter(nil)
  43. }
  44. func GetTagCommit(tag string) (string, error) {
  45. return executils.RunOnline("git", "rev-list", "-n", "1", tag)
  46. }
  47. func GetFirstCommit() (string, error) {
  48. return executils.RunOnline("git", "rev-list", "--max-parents=0", "HEAD")
  49. }
  50. func GetPatch(from string, to string, excludes ...string) ([]byte, error) {
  51. args := make([]string, 0, len(excludes)+3)
  52. args = append(args, "diff", from, to, ".")
  53. for _, e := range excludes {
  54. args = append(args, fmt.Sprintf(":(exclude)%s", e))
  55. }
  56. return executils.RunBytes("git", args...)
  57. }