func ImportIdFormats()

in mmv1/api/resource.go [1091:1160]


func ImportIdFormats(importFormat, identity []string, baseUrl string) []string {
	var idFormats []string
	if len(importFormat) == 0 {
		underscoredBaseUrl := baseUrl

		if len(identity) == 0 {
			idFormats = []string{fmt.Sprintf("%s/{{name}}", underscoredBaseUrl)}
		} else {
			var transformedIdentity []string
			for _, id := range identity {
				transformedIdentity = append(transformedIdentity, fmt.Sprintf("{{%s}}", id))
			}
			identityPath := strings.Join(transformedIdentity, "/")
			idFormats = []string{fmt.Sprintf("%s/%s", underscoredBaseUrl, google.Underscore(identityPath))}
		}
	} else {
		idFormats = importFormat
	}

	// short id: {{project}}/{{zone}}/{{name}}
	fieldMarkers := regexp.MustCompile(`{{[[:word:]]+}}`).FindAllString(idFormats[0], -1)
	shortIdFormat := strings.Join(fieldMarkers, "/")

	// short ids without fields with provider-level defaults:

	// without project
	fieldMarkers = slices.DeleteFunc(fieldMarkers, func(s string) bool { return s == "{{project}}" })
	shortIdDefaultProjectFormat := strings.Join(fieldMarkers, "/")

	// without project or location
	fieldMarkers = slices.DeleteFunc(fieldMarkers, func(s string) bool { return s == "{{region}}" })
	fieldMarkers = slices.DeleteFunc(fieldMarkers, func(s string) bool { return s == "{{zone}}" })
	shortIdDefaultFormat := strings.Join(fieldMarkers, "/")

	// If the id format can include `/` characters we cannot allow short forms such as:
	// `{{project}}/{{%name}}` as there is no way to differentiate between
	// project-name/resource-name and resource-name/with-slash
	if !strings.Contains(idFormats[0], "%") {
		idFormats = append(idFormats, shortIdFormat, shortIdDefaultProjectFormat, shortIdDefaultFormat)
	}

	slices.SortFunc(idFormats, func(a, b string) int {
		i := strings.Count(a, "/")
		j := strings.Count(b, "/")
		if i == j {
			return strings.Count(a, "{{") - strings.Count(b, "{{")
		}
		return i - j
	})
	slices.Reverse(idFormats)

	// Remove duplicates from idFormats
	uniq := make([]string, len(idFormats))
	uniq[0] = idFormats[0]
	i := 1
	j := 1
	for j < len(idFormats) {
		format := idFormats[j]
		if format != uniq[i-1] {
			uniq[i] = format
			i++
		}
		j++
	}

	uniq = google.Reject(slices.Compact(uniq), func(i string) bool {
		return i == ""
	})
	return uniq
}