cog

package module
v0.0.28 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2025 License: Apache-2.0 Imports: 9 Imported by: 4

README

cog

cog is a Code generator created with the following objectives in mind:

  • Support multiple schema formats: CUE, JSON Schema, OpenAPI, ...
  • Generate code in a wide range of languages: Golang, Java, PHP, Python, Typescript, …
  • Generate types described by schemas
  • Generate developer-friendly builder libraries, allowing the creation of complex objects as-code

Example use-cases

  • The Grafana Foundation SDK is fully generated by cog, from a collection of schemas exposed by Grafana
  • Grafana itself uses cog to enable a schema-first approach where some resources (example: dashboards) are schematized first, then code is generated both for the frontend and backend from those schemas.
  • The grafana-app-sdk uses cog as a library for some of its code generation needs.

[!TIP] While cog is built and maintained by Grafana Labs, it is completely schema-agnostic.

Usage

As a CLI

Download the cog binary from our releases, and run the codegen pipeline:

cog generate --config ./cog-pipeline.yaml
As a Go Library

See the Go documentation for more example and a complete API reference.

package main

import (
    "context"
    "fmt"

    "github.com/grafana/cog"
)

func main() {
    files, err := cog.TypesFromSchema().
        CUEModule("/path/to/cue/module").
        SchemaTransformations(
            cog.AppendCommentToObjects("Transformed by cog."),
            cog.PrefixObjectsNames("Example"),
        ).
        Golang(cog.GoConfig{}).
        Run(context.Background())
    if err != nil {
        panic(err)
    }

    if len(files) != 1 {
        panic("expected a single file :(")
    }

    fmt.Println(string(files[0].Data))
}

Maturity

Cog should be considered as "public preview". While it is used by Grafana Labs in production, it still is under active development.

Additional information can be found in Release life cycle for Grafana Labs.

[!NOTE] Bugs and issues are handled solely by Engineering teams. On-call support or SLAs are not available.

Contributing

See our contributing guide.

Documentation

Overview

Example (CueModule)

ExampleCueModule demonstrates how to generate types from a CUE module living on the filesystem.

files, err := TypesFromSchema().
	CUEModule("/path/to/cue/module").
	Golang(GoConfig{}).
	Run(context.Background())
if err != nil {
	panic(err)
}

if len(files) != 1 {
	panic("expected a single file :(")
}

fmt.Println(string(files[0].Data))
Output:

Example (CueValue)

ExampleCueValue demonstrates how to generate types from a CUE value.

schema := `
// Contains things.
Container: {
    str: string
}

// This is a bar.
Bar: {
       type: "bar"
       foo: string
}
`

cueValue := cuecontext.New().CompileString(schema)
if cueValue.Err() != nil {
	panic(cueValue.Err())
}

files, err := TypesFromSchema().
	CUEValue("sandbox", cueValue).
	Golang(GoConfig{}).
	Run(context.Background())
if err != nil {
	panic(err)
}

if len(files) != 1 {
	panic("expected a single file :(")
}

fmt.Println(string(files[0].Data))
Output:

Example (GoOutput)

ExampleGoOutput demonstrates how to generate Go types from a CUE value.

schema := `
// Contains things.
Container: {
    str: string
}

// This is a bar.
Bar: {
       type: "bar"
       foo: string
}
`

cueValue := cuecontext.New().CompileString(schema)
if cueValue.Err() != nil {
	panic(cueValue.Err())
}

files, err := TypesFromSchema().
	CUEValue("sandbox", cueValue).
	Golang(GoConfig{}).
	Run(context.Background())
if err != nil {
	panic(err)
}

if len(files) != 1 {
	panic("expected a single file :(")
}

fmt.Println(string(files[0].Data))
Output:

Example (SchemaTransformations)

ExampleSchemaTransformations demonstrates how apply transformations to input schemas.

schema := `
// Contains things.
Container: {
    str: string
}

// This is a bar.
Bar: {
       type: "bar"
       foo: string
}
`

cueValue := cuecontext.New().CompileString(schema)
if cueValue.Err() != nil {
	panic(cueValue.Err())
}

files, err := TypesFromSchema().
	CUEValue("sandbox", cueValue).
	Golang(GoConfig{}).
	SchemaTransformations(
		AppendCommentToObjects("Transformed by cog."),
		PrefixObjectsNames("Example"),
	).
	Run(context.Background())
if err != nil {
	panic(err)
}

if len(files) != 1 {
	panic("expected a single file :(")
}

fmt.Println(string(files[0].Data))
Output:

Example (TypescriptOutput)

ExampleTypescriptOutput demonstrates how to generate Typescript types from a CUE value.

schema := `
// Contains things.
Container: {
    str: string
}

// This is a bar.
Bar: {
       type: "bar"
       foo: string
}
`

cueValue := cuecontext.New().CompileString(schema)
if cueValue.Err() != nil {
	panic(cueValue.Err())
}

files, err := TypesFromSchema().
	CUEValue("sandbox", cueValue).
	Typescript(TypescriptConfig{}).
	Run(context.Background())
if err != nil {
	panic(err)
}

if len(files) != 1 {
	panic("expected a single file :(")
}

fmt.Println(string(files[0].Data))
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendCommentToObjects

func AppendCommentToObjects(comment string) compiler.Pass

AppendCommentToObjects adds the given comment to every object definition.

func PrefixObjectsNames

func PrefixObjectsNames(prefix string) compiler.Pass

PrefixObjectsNames adds the given prefix to every object's name.

Types

type CUEOption

type CUEOption func(*codegen.CueInput)

func CUEImports added in v0.0.2

func CUEImports(importsMap map[string]string) CUEOption

CUEImports allows referencing additional libraries/modules.

func ForceEnvelope

func ForceEnvelope(envelopeName string) CUEOption

ForceEnvelope decorates the parsed cue Value with an envelope whose name is given. This is useful for dataqueries for example, where the schema doesn't define any suitable top-level object.

func NameFunc

func NameFunc(nameFunc simplecue.NameFunc) CUEOption

NameFunc specifies the naming strategy used for objects and references. It is called with the value passed to the top level method or function and the path to the entity being parsed.

func PreserveExternalReferences added in v0.0.22

func PreserveExternalReferences() CUEOption

PreserveExternalReferences disables the inlining of external references. This should be used in conjunction with "imports maps" on output languages to properly handle external references.

type GoConfig added in v0.0.2

type GoConfig struct {
	// GenerateEqual controls the generation of `Equal()` methods on types.
	GenerateEqual bool

	// AnyAsInterface instructs cog to emit `interface{}` instead of `any`.
	AnyAsInterface bool

	// AllowMarshalEmptyDisjunctions makes generated `MarshalJSON()`
	// ignore errors when marshaling an empty disjunction.
	AllowMarshalEmptyDisjunctions bool
}

GoConfig defines a set of configuration options specific to Go outputs.

type SchemaToTypesPipeline

type SchemaToTypesPipeline struct {
	// contains filtered or unexported fields
}

SchemaToTypesPipeline represents a simplified codegen.Pipeline, meant to take a single input schema and generates types for it in a single output language.

func TypesFromSchema

func TypesFromSchema() *SchemaToTypesPipeline

TypesFromSchema generates types from a single input schema and a single output language.

func (*SchemaToTypesPipeline) CUEModule added in v0.0.2

func (pipeline *SchemaToTypesPipeline) CUEModule(modulePath string, opts ...CUEOption) *SchemaToTypesPipeline

CUEModule sets the pipeline's input to the given cue module.

func (*SchemaToTypesPipeline) CUEValue

func (pipeline *SchemaToTypesPipeline) CUEValue(pkgName string, value cue.Value, opts ...CUEOption) *SchemaToTypesPipeline

CUEValue sets the pipeline's input to the given cue value.

func (*SchemaToTypesPipeline) Debug

func (pipeline *SchemaToTypesPipeline) Debug(enabled bool) *SchemaToTypesPipeline

Debug controls whether debug mode is enabled or not. When enabled, more information is included in the generated output, such as an audit trail of applied transformations.

func (*SchemaToTypesPipeline) Golang

func (pipeline *SchemaToTypesPipeline) Golang(config GoConfig) *SchemaToTypesPipeline

Golang sets the output to Golang types.

func (*SchemaToTypesPipeline) Run

func (pipeline *SchemaToTypesPipeline) Run(ctx context.Context) (codejen.Files, error)

Run executes the codegen pipeline and returns the files generated as a result.

func (*SchemaToTypesPipeline) SchemaTransformations

func (pipeline *SchemaToTypesPipeline) SchemaTransformations(passes ...compiler.Pass) *SchemaToTypesPipeline

SchemaTransformations adds the given transformations to the set of transformations that will be applied to the input schema.

func (*SchemaToTypesPipeline) Typescript

func (pipeline *SchemaToTypesPipeline) Typescript(config TypescriptConfig) *SchemaToTypesPipeline

Typescript sets the output to Typescript types.

type TypescriptConfig added in v0.0.2

type TypescriptConfig struct {
	// ImportsMap associates package names to their import path.
	ImportsMap map[string]string

	// EnumsAsUnionTypes generates enums as a union of values instead of using
	// an actual `enum` declaration.
	// If EnumsAsUnionTypes is false, an enum will be generated as:
	// “`ts
	// enum Direction {
	//   Up = "up",
	//   Down = "down",
	//   Left = "left",
	//   Right = "right",
	// }
	// “`
	// If EnumsAsUnionTypes is true, the same enum will be generated as:
	// “`ts
	// type Direction = "up" | "down" | "left" | "right";
	// “`
	EnumsAsUnionTypes bool `yaml:"enums_as_union_types"`
}

TypescriptConfig defines a set of configuration options specific to Go outputs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL