...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package detect
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "os"
23
24 "golang.org/x/oauth2/google"
25 "google.golang.org/api/option"
26 "google.golang.org/api/transport"
27 )
28
29 const (
30 projectIDSentinel = "*detect-project-id*"
31 envProjectID = "GOOGLE_CLOUD_PROJECT"
32 )
33
34 var (
35 adcLookupFunc func(context.Context, ...option.ClientOption) (*google.Credentials, error) = transport.Creds
36 envLookupFunc func(string) string = os.Getenv
37 )
38
39
40
41
42
43
44 func ProjectID(ctx context.Context, projectID string, emulatorEnvVar string, opts ...option.ClientOption) (string, error) {
45 if projectID != projectIDSentinel {
46 return projectID, nil
47 }
48
49 if id := envLookupFunc(envProjectID); id != "" {
50 return id, nil
51 }
52
53 creds, err := adcLookupFunc(ctx, opts...)
54 if err != nil {
55 return "", fmt.Errorf("fetching creds: %v", err)
56 }
57
58 if creds.ProjectID == "" && emulatorEnvVar != "" && envLookupFunc(emulatorEnvVar) != "" {
59 return "emulated-project", nil
60 }
61
62 if creds.ProjectID == "" {
63 return "", errors.New("unable to detect projectID, please refer to docs for DetectProjectID")
64 }
65
66 return creds.ProjectID, nil
67 }
68
View as plain text