encoding/openapi: make API backwards compatible for Istio

This allows a smooth transition for Istio to move from
the old to new API.

Change-Id: If5f6a95a6a3c685a844757fd602974ec39a8969e
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/5320
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/encoding/openapi/openapi.go b/encoding/openapi/openapi.go
index 49f33fd..4f4a92f 100644
--- a/encoding/openapi/openapi.go
+++ b/encoding/openapi/openapi.go
@@ -107,7 +107,20 @@
 	return (*OrderedMap)(top), err
 }
 
-func (c *Config) compose(schemas *ast.StructLit) (*ast.StructLit, error) {
+func toCUE(name string, x interface{}) (v ast.Expr, err error) {
+	b, err := json.Marshal(x)
+	if err == nil {
+		v, err = cuejson.Extract(name, b)
+	}
+	if err != nil {
+		return nil, errors.Wrapf(err, token.NoPos,
+			"openapi: could not encode %s", name)
+	}
+	return v, nil
+
+}
+
+func (c *Config) compose(schemas *ast.StructLit) (x *ast.StructLit, err error) {
 	// Support of OrderedMap is mostly for backwards compatibility.
 	var info ast.Expr
 	switch x := c.Info.(type) {
@@ -120,13 +133,9 @@
 	case OrderedMap:
 		info = (*ast.StructLit)(&x)
 	default:
-		b, err := json.Marshal(x)
-		if err == nil {
-			info, err = cuejson.Extract("info", b)
-		}
+		info, err = toCUE("info section", x)
 		if err != nil {
-			return nil, errors.Wrapf(err, token.NoPos,
-				"openapi: could not encode info section")
+			return nil, err
 		}
 	}