// Package gitea talks to a Gitea server's API (https://gitea.com/api/swagger): // reading a repository and opening and reading pull requests. Supermarket // never merges or pushes to a default branch: merging is the user's call. package gitea import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" ) // ErrUnauthorized means the token was refused. var ErrUnauthorized = errors.New("Gitea refused the token") // Client calls one Gitea with one token. type Client struct { base, token string http *http.Client } // New takes Gitea's address (https://gitea.example.com) and an access token. func New(base, token string) *Client { return &Client{base: strings.TrimRight(base, "/"), token: token, http: &http.Client{Timeout: time.Minute}} } // Base is Gitea's address. func (c *Client) Base() string { return c.base } // Token is the access token, for git over HTTPS. func (c *Client) Token() string { return c.token } func (c *Client) do(ctx context.Context, method, path string, body, out any) error { var rd io.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { return err } rd = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, c.base+"/api/v1"+path, rd) if err != nil { return err } req.Header.Set("Authorization", "token "+c.token) req.Header.Set("Accept", "application/json") if body != nil { req.Header.Set("Content-Type", "application/json") } res, err := c.http.Do(req) if err != nil { return err } defer res.Body.Close() raw, err := io.ReadAll(io.LimitReader(res.Body, 8<<20)) if err != nil { return err } if res.StatusCode == http.StatusUnauthorized { return ErrUnauthorized } if res.StatusCode < 200 || res.StatusCode > 299 { var e struct { Message string `json:"message"` } if json.Unmarshal(raw, &e) == nil && e.Message != "" { return fmt.Errorf("Gitea %s: %s", path, e.Message) } return fmt.Errorf("Gitea %s: HTTP %d", path, res.StatusCode) } if out == nil { return nil } return json.Unmarshal(raw, out) } // Me is the token's user name. func (c *Client) Me(ctx context.Context) (string, error) { var u struct { Login string `json:"login"` } err := c.do(ctx, http.MethodGet, "/user", nil, &u) return u.Login, err } // Repo is a repository. type Repo struct { FullName string `json:"full_name"` DefaultBranch string `json:"default_branch"` CloneURL string `json:"clone_url"` HTMLURL string `json:"html_url"` Permissions struct { Push bool `json:"push"` } `json:"permissions"` } // GetRepo reads a repository, "owner/name". func (c *Client) GetRepo(ctx context.Context, full string) (*Repo, error) { var r Repo if err := c.do(ctx, http.MethodGet, "/repos/"+escapeFull(full), nil, &r); err != nil { return nil, err } return &r, nil } // Pull is a pull request. type Pull struct { Number int64 `json:"number"` State string `json:"state"` // open, closed Merged bool `json:"merged"` MergedAt *time.Time `json:"merged_at"` HTMLURL string `json:"html_url"` } // OpenPull opens a pull request from head into base. func (c *Client) OpenPull(ctx context.Context, full, head, base, title, body string) (*Pull, error) { var p Pull err := c.do(ctx, http.MethodPost, "/repos/"+escapeFull(full)+"/pulls", map[string]string{"head": head, "base": base, "title": title, "body": body}, &p) if err != nil { return nil, err } return &p, nil } // GetPull reads a pull request. func (c *Client) GetPull(ctx context.Context, full string, n int64) (*Pull, error) { var p Pull if err := c.do(ctx, http.MethodGet, fmt.Sprintf("/repos/%s/pulls/%d", escapeFull(full), n), nil, &p); err != nil { return nil, err } return &p, nil } // ClosePull closes a pull request without merging it. func (c *Client) ClosePull(ctx context.Context, full string, n int64) error { return c.do(ctx, http.MethodPatch, fmt.Sprintf("/repos/%s/pulls/%d", escapeFull(full), n), map[string]string{"state": "closed"}, nil) } func escapeFull(full string) string { owner, name, _ := strings.Cut(full, "/") return url.PathEscape(owner) + "/" + url.PathEscape(name) } // ParseRepo turns what the profile holds ("owner/name", or the repository's // web or clone address) into "owner/name", and the Gitea address if the // value had one. func ParseRepo(v string) (base, full string, err error) { v = strings.TrimSpace(v) if v == "" { return "", "", errors.New("no repository") } if !strings.Contains(v, "://") { v = strings.TrimSuffix(v, ".git") if strings.Count(v, "/") != 1 { return "", "", fmt.Errorf("%q isn't owner/name", v) } return "", v, nil } u, err := url.Parse(v) if err != nil { return "", "", err } parts := strings.Split(strings.Trim(strings.TrimSuffix(u.Path, ".git"), "/"), "/") if len(parts) < 2 { return "", "", fmt.Errorf("%q has no owner/name", v) } return u.Scheme + "://" + u.Host, parts[len(parts)-2] + "/" + parts[len(parts)-1], nil }