-
Notifications
You must be signed in to change notification settings - Fork 0
/
branch.go
67 lines (59 loc) · 2.02 KB
/
branch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package goscm
import (
"errors"
"fmt"
"net/url"
)
type BranchContainer struct {
Embedded struct {
Branches []Branch `json:"branches"`
} `json:"_embedded"`
}
type Branch struct {
Name string `json:"name"`
DefaultBranch bool `json:"defaultBranch"`
Revision string `json:"revision"`
Stale bool `json:"stale"`
LastCommitDate string `json:"lastCommitDate,omitempty"`
LastCommitter LastCommitter `json:"lastCommitter"`
}
type LastCommitter struct {
Name string `json:"name"`
Mail string `json:"mail"`
}
// ListRepoBranches List all branches of the repository
func (c *Client) ListRepoBranches(namespace string, name string) (BranchContainer, error) {
branchContainer := BranchContainer{}
err := c.getJson("/api/v2/repositories/"+namespace+"/"+name+"/branches/", &branchContainer, nil)
if err != nil {
return BranchContainer{}, fmt.Errorf("failed to load branches of %s/%s: %w", namespace, name, err)
}
return branchContainer, nil
}
// GetRepoBranch Get a single branch of the repository by branch name
func (c *Client) GetRepoBranch(namespace string, name string, branchName string) (Branch, error) {
branch := Branch{}
err := c.getJson("/api/v2/repositories/"+namespace+"/"+name+"/branches/"+url.PathEscape(branchName), &branch, nil)
if err != nil {
return Branch{}, fmt.Errorf("failed to load branch %s of %s/%s: %w", branchName, namespace, name, err)
}
return branch, nil
}
var ErrEmptyRepository = errors.New("repository is empty")
var ErrNoDefaultBranchFound = errors.New("no default branch found")
// GetDefaultBranch Get the default branch of the repository
func (c *Client) GetDefaultBranch(namespace string, name string) (Branch, error) {
branches, err := c.ListRepoBranches(namespace, name)
if err != nil {
return Branch{}, err
}
if len(branches.Embedded.Branches) == 0 {
return Branch{}, ErrEmptyRepository
}
for _, b := range branches.Embedded.Branches {
if b.DefaultBranch {
return b, nil
}
}
return Branch{}, ErrNoDefaultBranchFound
}