| // Copyright 2020 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package gitiles |
| |
| import ( |
| "context" |
| "fmt" |
| "net/http" |
| |
| "go.chromium.org/luci/common/api/gitiles" |
| "go.chromium.org/luci/common/proto/git" |
| gitilespb "go.chromium.org/luci/common/proto/gitiles" |
| ) |
| |
| // gitilesClientWrapper provides utilities for interacting with a Gitiles project. |
| type gitilesClientWrapper struct { |
| client gitilespb.GitilesClient |
| project string |
| } |
| |
| // NewClient returns a gitilesClientWrapper for a host and project. |
| func NewClient(ctx context.Context, host, project string, httpClient *http.Client) (*gitilesClientWrapper, error) { |
| client, err := gitiles.NewRESTClient(httpClient, host, true) |
| if err != nil { |
| return nil, err |
| } |
| return &gitilesClientWrapper{client: client, project: project}, nil |
| } |
| |
| // LatestCommit returns the revision at refs/heads/master HEAD. |
| func (c *gitilesClientWrapper) LatestCommit(ctx context.Context) (string, error) { |
| log, err := c.Log(ctx, "refs/heads/master", 1) |
| if err != nil { |
| return "", err |
| } |
| return log[0].GetId(), nil |
| } |
| |
| // Log returns a slice of commits of length `numCommits` starting from `committish`. |
| func (c *gitilesClientWrapper) Log(ctx context.Context, committish string, numCommits int32) ([]*git.Commit, error) { |
| resp, err := c.client.Log(ctx, &gitilespb.LogRequest{ |
| Project: c.project, |
| Committish: committish, |
| PageSize: numCommits, |
| }) |
| if err != nil { |
| return nil, fmt.Errorf("failed to get log for project %s: %v", c.project, err) |
| } |
| if len(resp.Log) == 0 { |
| return nil, fmt.Errorf("empty log for project %s", c.project) |
| } |
| return resp.Log, nil |
| } |