func populateScratchBucketGcsPath()

in cli_tools/common/utils/param/param_utils.go [53:107]


func populateScratchBucketGcsPath(scratchBucketGcsPath *string, zone string, mgce domain.MetadataGCEInterface,
	scratchBucketCreator domain.ScratchBucketCreatorInterface, file string, project *string,
	storageClient domain.StorageClientInterface, removeFileWhenScratchNotOwned bool) (string, error) {

	scratchBucketRegion := ""
	if *scratchBucketGcsPath == "" {
		fallbackZone := zone
		if fallbackZone == "" && mgce.OnGCE() {
			var err error
			if fallbackZone, err = mgce.Zone(); err != nil {
				// reset fallback zone if failed to get zone from running GCE
				fallbackZone = ""
			}
		}

		scratchBucketName, sbr, err := scratchBucketCreator.CreateScratchBucket(file, *project, fallbackZone)
		scratchBucketRegion = sbr
		if err != nil {
			return "", daisy.Errf("failed to create scratch bucket: %v", err)
		}

		*scratchBucketGcsPath = fmt.Sprintf("gs://%v/", scratchBucketName)
	} else {
		scratchBucketName, err := storage.GetBucketNameFromGCSPath(*scratchBucketGcsPath)
		if err != nil {
			return "", daisy.Errf("invalid scratch bucket GCS path %v", scratchBucketGcsPath)
		}

		if !scratchBucketCreator.IsBucketInProject(*project, scratchBucketName) {
			anonymizedErrorMessage := "Scratch bucket %q is not in project %q"

			substitutions := []interface{}{scratchBucketName, *project}

			if removeFileWhenScratchNotOwned && strings.HasPrefix(file, fmt.Sprintf("gs://%s/", scratchBucketName)) {
				err := storageClient.DeleteObject(file)
				if err == nil {
					anonymizedErrorMessage += ". Deleted %q"
					substitutions = append(substitutions, file)
				} else {
					anonymizedErrorMessage += ". Failed to delete %q: %v. " +
						"Check with the owner of gs://%q for more information"
					substitutions = append(substitutions, file, err, scratchBucketName)
				}
			}

			return "", daisy.Errf(anonymizedErrorMessage, substitutions...)
		}

		scratchBucketAttrs, err := storageClient.GetBucketAttrs(scratchBucketName)
		if err == nil {
			scratchBucketRegion = scratchBucketAttrs.Location
		}
	}
	return scratchBucketRegion, nil
}