Skip to content
This repository was archived by the owner on Jun 8, 2019. It is now read-only.

Commit 59ddbdc

Browse files
lafrikstechknowlogick
authored andcommitted
Support for git refs listing API (#129)
1 parent 4f96d9a commit 59ddbdc

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

gitea/repo_refs.go

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Copyright 2018 The Gitea 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+
5+
package gitea
6+
7+
import (
8+
"encoding/json"
9+
"errors"
10+
"fmt"
11+
"strings"
12+
)
13+
14+
// Reference represents a Git reference.
15+
type Reference struct {
16+
Ref string `json:"ref"`
17+
URL string `json:"url"`
18+
Object *GitObject `json:"object"`
19+
}
20+
21+
// GitObject represents a Git object.
22+
type GitObject struct {
23+
Type string `json:"type"`
24+
SHA string `json:"sha"`
25+
URL string `json:"url"`
26+
}
27+
28+
// GetRepoRef get one ref's information of one repository
29+
func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, error) {
30+
ref = strings.TrimPrefix(ref, "refs/")
31+
r := new(Reference)
32+
err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r)
33+
if _, ok := err.(*json.UnmarshalTypeError); ok {
34+
// Multiple refs
35+
return nil, errors.New("no exact match found for this ref")
36+
} else if err != nil {
37+
return nil, err
38+
}
39+
40+
return r, nil
41+
}
42+
43+
// GetRepoRefs get list of ref's information of one repository
44+
func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, error) {
45+
ref = strings.TrimPrefix(ref, "refs/")
46+
resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil)
47+
if err != nil {
48+
return nil, err
49+
}
50+
51+
// Attempt to unmarshal single returned ref.
52+
r := new(Reference)
53+
refErr := json.Unmarshal(resp, r)
54+
if refErr == nil {
55+
return []*Reference{r}, nil
56+
}
57+
58+
// Attempt to unmarshal multiple refs.
59+
var rs []*Reference
60+
refsErr := json.Unmarshal(resp, &rs)
61+
if refsErr == nil {
62+
if len(rs) == 0 {
63+
return nil, errors.New("unexpected response: an array of refs with length 0")
64+
}
65+
return rs, nil
66+
}
67+
68+
return nil, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr)
69+
}

0 commit comments

Comments
 (0)