go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/api/gerrit/demo/main.go (about) 1 // Copyright 2020 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 // This is a bare bone script that interact with Gerrit using Gerrit REST 16 // client for testing purpose. It calls GetChange with ChangeId 1111 by 17 // default. Modify the api to call and the input to the api in 18 // `callAndPrintResp` func to test your change. 19 20 package main 21 22 import ( 23 "context" 24 "fmt" 25 "net/http" 26 "os" 27 "os/signal" 28 29 "go.chromium.org/luci/common/api/gerrit" 30 "go.chromium.org/luci/common/errors" 31 gerritpb "go.chromium.org/luci/common/proto/gerrit" 32 "google.golang.org/protobuf/encoding/protojson" 33 ) 34 35 const gerritHost = "chromium-review.googlesource.com" 36 37 func main() { 38 ctx, cancel := context.WithCancel(context.Background()) 39 defer cancel() 40 interrupt := make(chan os.Signal, 1) 41 signal.Notify(interrupt, os.Interrupt) 42 go func() { 43 <-interrupt 44 cancel() 45 }() 46 47 runWithCtx(ctx) 48 } 49 50 func runWithCtx(ctx context.Context) { 51 client, err := gerrit.NewRESTClient(&http.Client{}, gerritHost, false) 52 if err != nil { 53 fmt.Fprintf(os.Stderr, "error while creating gerrit REST client: %s\n", err) 54 os.Exit(1) 55 } 56 errC := make(chan error) 57 go func() { 58 errC <- callAndPrintResp(ctx, client) 59 }() 60 select { 61 case <-ctx.Done(): 62 fmt.Fprintln(os.Stderr, ctx.Err()) 63 os.Exit(1) 64 case err := <-errC: 65 if err != nil { 66 fmt.Fprintln(os.Stderr, err) 67 os.Exit(1) 68 } 69 } 70 } 71 72 func callAndPrintResp(ctx context.Context, client gerritpb.GerritClient) error { 73 resp, err := client.GetChange(ctx, &gerritpb.GetChangeRequest{ 74 Number: 2653292, 75 Options: []gerritpb.QueryOption{ 76 gerritpb.QueryOption_DETAILED_LABELS, 77 gerritpb.QueryOption_DETAILED_ACCOUNTS, 78 }, 79 }) 80 if err != nil { 81 return errors.Annotate(err, "calling gerrit").Err() 82 } 83 84 m := &protojson.MarshalOptions{ 85 Indent: " ", 86 } 87 b, err := m.Marshal(resp) 88 if err != nil { 89 return errors.Annotate(err, "marshal response proto").Err() 90 } 91 _, err = os.Stdout.Write(b) 92 return err 93 }