blob: 630cc776164efc71b8f69621fb2d37a4cc7ea4df [file] [log] [blame]
// 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 resolves a ref to a revision.
func (c *gitilesClientWrapper) LatestCommit(ctx context.Context, ref string) (string, error) {
log, err := c.Log(ctx, ref, 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
}
// DownloadFile returns the contents of the file at `path` and `ref`.
func (c *gitilesClientWrapper) DownloadFile(ctx context.Context, path, ref string) (string, error) {
resp, err := c.client.DownloadFile(ctx, &gitilespb.DownloadFileRequest{
Project: c.project,
Committish: ref,
Path: path,
Format: gitilespb.DownloadFileRequest_TEXT,
})
if err != nil {
return "", fmt.Errorf("failed to download %s: %v", path, err)
}
return resp.Contents, nil
}