| OLD | NEW |
| (Empty) |
| 1 // Copyright 2016 The LUCI Authors. All rights reserved. | |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 | |
| 3 // that can be found in the LICENSE file. | |
| 4 | |
| 5 package main | |
| 6 | |
| 7 import ( | |
| 8 "errors" | |
| 9 "fmt" | |
| 10 "strings" | |
| 11 | |
| 12 "github.com/maruel/subcommands" | |
| 13 "golang.org/x/net/context" | |
| 14 | |
| 15 "github.com/luci/luci-go/common/api/buildbucket/buildbucket/v1" | |
| 16 "github.com/luci/luci-go/common/auth" | |
| 17 "github.com/luci/luci-go/common/logging" | |
| 18 ) | |
| 19 | |
| 20 type baseCommandRun struct { | |
| 21 subcommands.CommandRunBase | |
| 22 serviceAccountJSONPath string | |
| 23 host string | |
| 24 } | |
| 25 | |
| 26 func (r *baseCommandRun) SetDefaultFlags() { | |
| 27 r.Flags.StringVar(&r.serviceAccountJSONPath, "service-account-json", | |
| 28 "", | |
| 29 "path to service account json file.") | |
| 30 r.Flags.StringVar(&r.host, "host", | |
| 31 "cr-buildbucket.appspot.com", | |
| 32 "host for the buildbucket service instance.") | |
| 33 } | |
| 34 | |
| 35 func (r *baseCommandRun) makeService(ctx context.Context, a subcommands.Applicat
ion) (*buildbucket.Service, error) { | |
| 36 if r.host == "" { | |
| 37 return nil, errors.New("a host for the buildbucket service must
be provided") | |
| 38 } | |
| 39 | |
| 40 loginMode := auth.OptionalLogin | |
| 41 if r.serviceAccountJSONPath != "" { | |
| 42 // if service account is specified, the request MUST be authenti
cated | |
| 43 // otherwise it is optional. | |
| 44 loginMode = auth.SilentLogin | |
| 45 } | |
| 46 authenticator := auth.NewAuthenticator(ctx, loginMode, auth.Options{Serv
iceAccountJSONPath: r.serviceAccountJSONPath}) | |
| 47 | |
| 48 client, err := authenticator.Client() | |
| 49 if err != nil { | |
| 50 logging.Errorf(ctx, "could not create client: %s", err) | |
| 51 return nil, err | |
| 52 } | |
| 53 logging.Debugf(ctx, "client created") | |
| 54 | |
| 55 service, err := buildbucket.New(client) | |
| 56 if err != nil { | |
| 57 logging.Errorf(ctx, "could not create service: %s", err) | |
| 58 return nil, err | |
| 59 } | |
| 60 | |
| 61 protocol := "https" | |
| 62 if isLocalHost(r.host) { | |
| 63 protocol = "http" | |
| 64 } | |
| 65 | |
| 66 service.BasePath = fmt.Sprintf("%s://%s/api/buildbucket/v1/", protocol,
r.host) | |
| 67 return service, nil | |
| 68 } | |
| 69 | |
| 70 // TODO(robertocn): Dedup this code copied from grpc/cmd/rpc | |
| 71 func isLocalHost(host string) bool { | |
| 72 switch { | |
| 73 case host == "localhost", strings.HasPrefix(host, "localhost:"): | |
| 74 case host == "127.0.0.1", strings.HasPrefix(host, "127.0.0.1:"): | |
| 75 case host == "[::1]", strings.HasPrefix(host, "[::1]:"): | |
| 76 case strings.HasPrefix(host, ":"): | |
| 77 | |
| 78 default: | |
| 79 return false | |
| 80 } | |
| 81 return true | |
| 82 } | |
| OLD | NEW |