feat(tools): branch_protection_get

This commit is contained in:
Mathias Bergqvist
2026-05-06 22:44:24 +02:00
parent 9e4251c1a7
commit ddfcc32afd
4 changed files with 178 additions and 0 deletions

View File

@@ -123,6 +123,33 @@ func (c *Client) DeleteBranch(ctx context.Context, owner, repo, branch string) e
return MapStatus(status, body)
}
type BranchProtection struct {
Protected bool `json:"-"`
RequiredApprovals int64 `json:"required_approvals"`
PushWhitelist []string `json:"push_whitelist_usernames"`
MergeWhitelist []string `json:"merge_whitelist_usernames"`
}
func (c *Client) GetBranchProtection(ctx context.Context, owner, repo, branch string) (*BranchProtection, error) {
p := fmt.Sprintf("/api/v1/repos/%s/%s/branch_protections/%s", owner, repo, branch)
body, status, err := c.GetJSON(ctx, p)
if err != nil {
return nil, err
}
if status == 404 {
return &BranchProtection{Protected: false}, nil
}
if err := MapStatus(status, body); err != nil {
return nil, err
}
var bp BranchProtection
if err := json.Unmarshal(body, &bp); err != nil {
return nil, err
}
bp.Protected = true
return &bp, nil
}
// UpsertFile creates a file when args.Sha is empty (POST) or updates an existing
// file when args.Sha is set (PUT). Gitea routes both operations by HTTP method on
// the same /contents/{path} URL, and rejects PUT without a sha.

View File

@@ -164,3 +164,37 @@ func TestDeleteBranchProtected(t *testing.T) {
require.Error(t, err)
assert.ErrorIs(t, err, gitea.ErrPermissionDenied)
}
func TestGetBranchProtectionFound(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/o/r/branch_protections/main", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"required_approvals": 2,
"push_whitelist_usernames": ["alice"],
"merge_whitelist_usernames": ["bob"]
}`))
}))
defer srv.Close()
c := gitea.NewClient(srv.URL, "tok")
bp, err := c.GetBranchProtection(context.Background(), "o", "r", "main")
require.NoError(t, err)
assert.True(t, bp.Protected)
assert.Equal(t, int64(2), bp.RequiredApprovals)
assert.Equal(t, []string{"alice"}, bp.PushWhitelist)
assert.Equal(t, []string{"bob"}, bp.MergeWhitelist)
}
func TestGetBranchProtectionNotFoundReturnsUnprotected(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"not found"}`))
}))
defer srv.Close()
c := gitea.NewClient(srv.URL, "tok")
bp, err := c.GetBranchProtection(context.Background(), "o", "r", "feat/x")
require.NoError(t, err)
assert.False(t, bp.Protected)
}