computeProjectId function
A convenience wrapper that tries multiple strategies to find the project ID, prioritizing local development strategies over cloud discovery.
The strategies are tried in the following order:
- projectIdFromEnvironmentVariables
- projectIdFromCredentialsFile
- projectIdFromGcloudConfig
- projectIdFromMetadataServer
If client is provided, it is used to make the request to the metadata
server if all other strategies fail.
To understand the behavior of refresh and the caching behavior, see
projectIdFromMetadataServer.
Implementation
Future<String> computeProjectId({
http.Client? client,
bool refresh = false,
}) async =>
projectIdFromEnvironmentVariables() ??
projectIdFromCredentialsFile() ??
await projectIdFromGcloudConfig() ??
await () async {
try {
return await projectIdFromMetadataServer(
client: client,
refresh: refresh,
);
} on MetadataServerException catch (e) {
throw MetadataServerException._(
'''
${e.message}
If not running on Google Cloud, one of these environment variables must be set
to the target Google Project ID:
${projectIdEnvironmentVariableOptions.join('\n')}
Alternatively, set $credentialsPathEnvironmentVariable to point to a service account
JSON file that contains a "project_id" field.
If you are running locally, you can also set the default project in the Google
Cloud SDK by running:
`gcloud config set project <PROJECT_ID>`
''',
innerException: e.innerException,
innerStackTrace: e.innerStackTrace,
);
}
}();