func convertResourceJson()

in internal/langserver/handlers/command/resource_json_converter.go [34:78]


func convertResourceJson(ctx context.Context, input string, telemetrySender telemetry.Sender) (string, error) {
	var model resourceModel
	err := json.Unmarshal([]byte(input), &model)
	if err != nil {
		return "", fmt.Errorf("unable to unmarshal JSON content: %w", err)
	}

	block, err := ParseResourceJson(input)
	if err != nil {
		return "", err
	}

	label := ""
	if len(block.Labels()) == 2 {
		label = block.Labels()[1]
	}
	apiVersion := ""
	typeValue := string(block.Body().GetAttribute("type").Expr().BuildTokens(nil).Bytes())
	typeValue = strings.Trim(typeValue, " \"")
	if parts := strings.Split(typeValue, "@"); len(parts) == 2 {
		apiVersion = parts[1]
	}

	telemetrySender.SendEvent(ctx, "ConvertJsonToAzapi", map[string]interface{}{
		"status": "completed",
		"kind":   "resource-json",
		"type":   typeValue,
	})

	importBlock := hclwrite.NewBlock("import", nil)
	importBlock.Body().SetAttributeValue("id", cty.StringVal(fmt.Sprintf("%s?api-version=%s", model.ID, apiVersion)))
	importBlock.Body().SetAttributeTraversal("to", hcl.Traversal{hcl.TraverseRoot{Name: "azapi_resource"}, hcl.TraverseAttr{Name: label}})

	result := fmt.Sprintf(`/*
Note: This is a generated HCL content from the JSON input which is based on the latest API version available.
To import the resource, please run the following command:
terraform import azapi_resource.%s %s?api-version=%s

Or add the below config:
%s*/

%s`, label, model.ID, apiVersion, string(hclwrite.Format(importBlock.BuildTokens(nil).Bytes())), string(hclwrite.Format(block.BuildTokens(nil).Bytes())))

	return result, nil
}