Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Commit 83c0e73

Browse files
authored
Merge pull request #465 from smola/fix-short-ref
fix reference shortening
2 parents b0f7c5b + 61884bb commit 83c0e73

File tree

2 files changed

+23
-18
lines changed

2 files changed

+23
-18
lines changed

plumbing/reference.go

+18-18
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,16 @@ const (
1515
symrefPrefix = "ref: "
1616
)
1717

18-
var (
19-
refPrefixes = []string{
20-
refHeadPrefix,
21-
refTagPrefix,
22-
refRemotePrefix,
23-
refNotePrefix,
24-
refPrefix,
25-
}
26-
)
18+
// refRevParseRules are a set of rules to parse references into short names.
19+
// These are the same rules as used by git in shorten_unambiguous_ref.
20+
// See: https://github.com/git/git/blob/e0aaa1b6532cfce93d87af9bc813fb2e7a7ce9d7/refs.c#L417
21+
var refRevParseRules = []string{
22+
"refs/%s",
23+
"refs/tags/%s",
24+
"refs/heads/%s",
25+
"refs/remotes/%s",
26+
"refs/remotes/%s/HEAD",
27+
}
2728

2829
var (
2930
ErrReferenceNotFound = errors.New("reference not found")
@@ -60,17 +61,16 @@ func (r ReferenceName) String() string {
6061

6162
// Short returns the short name of a ReferenceName
6263
func (r ReferenceName) Short() string {
63-
return r.removeRefPrefix()
64-
}
65-
66-
// Instead of hardcoding a number of components, we should remove the prefixes
67-
// refHeadPrefix, refTagPrefix, refRemotePrefix, refNotePrefix and refPrefix
68-
func (r ReferenceName) removeRefPrefix() string {
6964
s := string(r)
70-
for _, prefix := range refPrefixes {
71-
s = strings.TrimPrefix(s, prefix)
65+
res := s
66+
for _, format := range refRevParseRules {
67+
_, err := fmt.Sscanf(s, format, &res)
68+
if err == nil {
69+
continue
70+
}
7271
}
73-
return s
72+
73+
return res
7474
}
7575

7676
const (

plumbing/reference_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ func (s *ReferenceSuite) TestReferenceNameWithSlash(c *C) {
2323
c.Assert(r.Short(), Equals, "origin/feature/AllowSlashes")
2424
}
2525

26+
func (s *ReferenceSuite) TestReferenceNameNote(c *C) {
27+
r := ReferenceName("refs/notes/foo")
28+
c.Assert(r.Short(), Equals, "notes/foo")
29+
}
30+
2631
func (s *ReferenceSuite) TestNewReferenceFromStrings(c *C) {
2732
r := NewReferenceFromStrings("refs/heads/v4", "6ecf0ef2c2dffb796033e5a02219af86ec6584e5")
2833
c.Assert(r.Type(), Equals, HashReference)

0 commit comments

Comments
 (0)