kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/extractors/gcp/examples/restcheck/rest_auth_check.go (about)

     1  /*
     2   * Copyright 2018 The Kythe Authors. All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *   http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  // Binary rest_auth_check checks whether or not you can access a project via
    18  // cloud build REST API:
    19  // https://cloud.google.com/cloud-build/docs/api/reference/rest/
    20  //
    21  // Usage:
    22  // go build rest_auth_check
    23  // ./rest_auth_check -project_id=some-project-id
    24  //
    25  // For authentication steps, see kythe/extractors/gcp/README.md
    26  package main
    27  
    28  import (
    29  	"context"
    30  	"flag"
    31  	"fmt"
    32  
    33  	"kythe.io/kythe/go/util/log"
    34  
    35  	"golang.org/x/oauth2/google"
    36  	cloudbuild "google.golang.org/api/cloudbuild/v1"
    37  )
    38  
    39  var (
    40  	projectID = flag.String("project_id", "", "The GCP Cloud Build project ID to use")
    41  )
    42  
    43  func checkFlags() {
    44  	if *projectID == "" {
    45  		log.Fatalf("Must specify valid -project_id")
    46  	}
    47  }
    48  
    49  func main() {
    50  	flag.Parse()
    51  	checkFlags()
    52  
    53  	httpClient, err := google.DefaultClient(context.Background(), cloudbuild.CloudPlatformScope)
    54  	if err != nil {
    55  		log.Fatalf("Failed to create oauth client: %q", err)
    56  	}
    57  	cbs, err := cloudbuild.New(httpClient)
    58  	if err != nil {
    59  		log.Fatalf("Failed to dial cloud build: %q", err)
    60  	}
    61  
    62  	pbs := cloudbuild.NewProjectsBuildsService(cbs)
    63  
    64  	pbgc := pbs.List(*projectID)
    65  	r, err := pbgc.Do()
    66  	if err != nil {
    67  		log.Fatalf("Failed to list projects for %s: %q", *projectID, err)
    68  	}
    69  	fmt.Printf("Project %s has %d builds\n", *projectID, len(r.Builds))
    70  }