Skip to content

Commit

Permalink
Escape special characters in ref name for update ref (#2454)
Browse files Browse the repository at this point in the history
Fixes: #2453.
  • Loading branch information
shravan1k authored Sep 12, 2022
1 parent 52cc49e commit ae774d0
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
2 changes: 1 addition & 1 deletion github/git_refs.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func (s *GitService) CreateRef(ctx context.Context, owner string, repo string, r
// GitHub API docs: https://docs.github.com/en/rest/git/refs#update-a-reference
func (s *GitService) UpdateRef(ctx context.Context, owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error) {
refPath := strings.TrimPrefix(*ref.Ref, "refs/")
u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refPath)
u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refURLEscape(refPath))
req, err := s.client.NewRequest("PATCH", u, &updateRefRequest{
SHA: ref.Object.SHA,
Force: &force,
Expand Down
52 changes: 52 additions & 0 deletions github/git_refs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,58 @@ func TestGitService_GetRef_pathEscape(t *testing.T) {
})
}

func TestGitService_UpdateRef_pathEscape(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()

args := &updateRefRequest{
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
Force: Bool(true),
}

mux.HandleFunc("/repos/o/r/git/refs/heads/b#1", func(w http.ResponseWriter, r *http.Request) {
v := new(updateRefRequest)
json.NewDecoder(r.Body).Decode(v)

testMethod(t, r, "PATCH")
if !cmp.Equal(v, args) {
t.Errorf("Request body = %+v, want %+v", v, args)
}
fmt.Fprint(w, `
{
"ref": "refs/heads/b#1",
"url": "https://api.github.com/repos/o/r/git/refs/heads/b%231",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
}`)
})

ctx := context.Background()
ref, _, err := client.Git.UpdateRef(ctx, "o", "r", &Reference{
Ref: String("refs/heads/b#1"),
Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")},
}, true)
if err != nil {
t.Errorf("Git.UpdateRef returned error: %v", err)
}

want := &Reference{
Ref: String("refs/heads/b#1"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/b%231"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
}
if !cmp.Equal(ref, want) {
t.Errorf("Git.UpdateRef returned %+v, want %+v", ref, want)
}
}

func TestReference_Marshal(t *testing.T) {
testJSONMarshal(t, &Reference{}, "{}")

Expand Down

0 comments on commit ae774d0

Please sign in to comment.