go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/config_service/internal/clients/gitiles.go (about)

     1  // Copyright 2023 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package clients
    16  
    17  import (
    18  	"context"
    19  	"net/http"
    20  
    21  	"go.chromium.org/luci/common/api/gitiles"
    22  	gitilespb "go.chromium.org/luci/common/proto/gitiles"
    23  	"go.chromium.org/luci/common/proto/gitiles/mock_gitiles"
    24  	"go.chromium.org/luci/server/auth"
    25  )
    26  
    27  var MockGitilesClientKey = "mock gitiles clients key for testing only"
    28  
    29  // NewGitilesClient returns a Gitiles client with the authority of the given
    30  // luciProject or the current service if luciProject is empty.
    31  func NewGitilesClient(ctx context.Context, host, luciProject string) (gitilespb.GitilesClient, error) {
    32  	if mockClient, ok := ctx.Value(&MockGitilesClientKey).(*mock_gitiles.MockGitilesClient); ok {
    33  		return mockClient, nil
    34  	}
    35  
    36  	var t http.RoundTripper
    37  	var err error
    38  	if luciProject != "" {
    39  		t, err = auth.GetRPCTransport(ctx, auth.AsProject, auth.WithProject(luciProject), auth.WithScopes(gitiles.OAuthScope))
    40  	} else {
    41  		t, err = auth.GetRPCTransport(ctx, auth.AsSelf, auth.WithScopes(gitiles.OAuthScope))
    42  	}
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	return gitiles.NewRESTClient(&http.Client{Transport: t}, host, true)
    47  }