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.

repo_ref.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "context"
  6. "strings"
  7. "code.gitea.io/gitea/modules/util"
  8. )
  9. // GetRefs returns all references of the repository.
  10. func (repo *Repository) GetRefs() ([]*Reference, error) {
  11. return repo.GetRefsFiltered("")
  12. }
  13. // ListOccurrences lists all refs of the given refType the given commit appears in sorted by creation date DESC
  14. // refType should only be a literal "branch" or "tag" and nothing else
  15. func (repo *Repository) ListOccurrences(ctx context.Context, refType, commitSHA string) ([]string, error) {
  16. cmd := NewCommand(ctx)
  17. if refType == "branch" {
  18. cmd.AddArguments("branch")
  19. } else if refType == "tag" {
  20. cmd.AddArguments("tag")
  21. } else {
  22. return nil, util.NewInvalidArgumentErrorf(`can only use "branch" or "tag" for refType, but got %q`, refType)
  23. }
  24. stdout, _, err := cmd.AddArguments("--no-color", "--sort=-creatordate", "--contains").AddDynamicArguments(commitSHA).RunStdString(&RunOpts{Dir: repo.Path})
  25. if err != nil {
  26. return nil, err
  27. }
  28. refs := strings.Split(strings.TrimSpace(stdout), "\n")
  29. if refType == "branch" {
  30. return parseBranches(refs), nil
  31. }
  32. return parseTags(refs), nil
  33. }
  34. func parseBranches(refs []string) []string {
  35. results := make([]string, 0, len(refs))
  36. for _, ref := range refs {
  37. if strings.HasPrefix(ref, "* ") { // current branch (main branch)
  38. results = append(results, ref[len("* "):])
  39. } else if strings.HasPrefix(ref, " ") { // all other branches
  40. results = append(results, ref[len(" "):])
  41. } else if ref != "" {
  42. results = append(results, ref)
  43. }
  44. }
  45. return results
  46. }
  47. func parseTags(refs []string) []string {
  48. results := make([]string, 0, len(refs))
  49. for _, ref := range refs {
  50. if ref != "" {
  51. results = append(results, ref)
  52. }
  53. }
  54. return results
  55. }