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