kclvm

package module
v0.8.7 Latest Latest
Warning

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

Go to latest
Published: May 10, 2024 License: Apache-2.0 Imports: 10 Imported by: 4

README

KCL Go SDK

GoDoc Coverage Status license FOSSA Status

KCL is an open-source, constraint-based record and functional language that enhances the writing of complex configurations, including those for cloud-native scenarios. With its advanced programming language technology and practices, KCL is dedicated to promoting better modularity, scalability, and stability for configurations. It enables simpler logic writing and offers ease of automation APIs and integration with homegrown systems.

What is it for?

You can use KCL to

Building & Testing

go test ./...

Run KCL Code with Go SDK

package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	yaml := kcl.MustRun("kubernetes.k", kcl.WithCode(code)).GetRawYamlResult()
	fmt.Println(yaml)
}

const code = `
apiVersion = "apps/v1"
kind = "Deployment"
metadata = {
    name = "nginx"
    labels.app = "nginx"
}
spec = {
    replicas = 3
    selector.matchLabels = metadata.labels
    template.metadata.labels = metadata.labels
    template.spec.containers = [
        {
            name = metadata.name
            image = "${metadata.name}:1.14.2"
            ports = [{ containerPort = 80 }]
        }
    ]
}
`

Run the command:

go run ./examples/kubernetes/main.go

Output:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

Run KCL Code with Go Plugin

package main

import (
	"fmt"

	"kcl-lang.io/kcl-go/pkg/kcl"
	"kcl-lang.io/kcl-go/pkg/native"                // Import the native API
	_ "kcl-lang.io/kcl-go/pkg/plugin/hello_plugin" // Import the hello plugin
)

func main() {
	// Note we use `native.MustRun` here instead of `kcl.MustRun`, because it needs the cgo feature.
	yaml := native.MustRun("main.k", kcl.WithCode(code)).GetRawYamlResult()
	fmt.Println(yaml)
}

const code = `
import kcl_plugin.hello

name = "kcl"
three = hello.add(1,2)  # hello.add is written by Go
`

Documents

See the KCL website

License

Apache License Version 2.0

FOSSA Status

Documentation

Overview

Package kclvm

KCL Go SDK

┌─────────────────┐         ┌─────────────────┐           ┌─────────────────┐
│     kcl files   │         │    KCL-Go-API   │           │  KCLResultList  │
│  ┌───────────┐  │         │                 │           │                 │
│  │    1.k    │  │         │                 │           │                 │
│  └───────────┘  │         │                 │           │  ┌───────────┐  │         ┌───────────────┐
│  ┌───────────┐  │         │  ┌───────────┐  │           │  │ KCLResult │──┼────────▶│x.Get("a.b.c") │
│  │    2.k    │  │         │  │ Run(path) │  │           │  └───────────┘  │         └───────────────┘
│  └───────────┘  │────┐    │  └───────────┘  │           │                 │
│  ┌───────────┐  │    │    │                 │           │  ┌───────────┐  │         ┌───────────────┐
│  │    3.k    │  │    │    │                 │           │  │ KCLResult │──┼────────▶│x.Get("k", &v) │
│  └───────────┘  │    │    │                 │           │  └───────────┘  │         └───────────────┘
│  ┌───────────┐  │    ├───▶│  ┌───────────┐  │──────────▶│                 │
│  │setting.yml│  │    │    │  │RunFiles() │  │           │  ┌───────────┐  │         ┌───────────────┐
│  └───────────┘  │    │    │  └───────────┘  │           │  │ KCLResult │──┼────────▶│x.JSONString() │
└─────────────────┘    │    │                 │           │  └───────────┘  │         └───────────────┘
                       │    │                 │           │                 │
┌─────────────────┐    │    │                 │           │  ┌───────────┐  │         ┌───────────────┐
│     Options     │    │    │  ┌───────────┐  │           │  │ KCLResult │──┼────────▶│x.YAMLString() │
│WithOptions      │    │    │  │MustRun()  │  │           │  └───────────┘  │         └───────────────┘
│WithOverrides    │────┘    │  └───────────┘  │           │                 │
│WithWorkDir      │         │                 │           │                 │
│WithDisableNone  │         │                 │           │                 │
└─────────────────┘         └─────────────────┘           └─────────────────┘
Example
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	const k_code = `
name = "kcl"
age = 1

two = 2

schema Person:
    name: str = "kcl"
    age: int = 1

x0 = Person {}
x1 = Person {
	age = 101
}
`

	yaml := kcl.MustRun("testdata/main.k", kcl.WithCode(k_code)).First().YAMLString()
	fmt.Println(yaml)

	fmt.Println("----")

	result := kcl.MustRun("./testdata/main.k").First()
	fmt.Println(result.JSONString())

	fmt.Println("----")
	fmt.Println("x0.name:", result.Get("x0.name"))
	fmt.Println("x1.age:", result.Get("x1.age"))

	fmt.Println("----")

	var person struct {
		Name string
		Age  int
	}
	fmt.Printf("person: %+v\n", result.Get("x1", &person))
}
Output:

Index

Examples

Constants

View Source
const KclvmAbiVersion = scripts.KclvmAbiVersion

KclvmAbiVersion is the current kclvm ABI version.

Variables

This section is empty.

Functions

func FormatCode

func FormatCode(code interface{}) ([]byte, error)

FormatCode returns the formatted code.

Example
package main

import (
	"fmt"
	"log"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	out, err := kcl.FormatCode(`a  =  1+2`)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(out))

}
Output:

a = 1 + 2

func FormatPath

func FormatPath(path string) (changedPaths []string, err error)

FormatPath formats files from the given path path: if path is `.` or empty string, all KCL files in current directory will be formatted, not recursively if path is `path/file.k`, the specified KCL file will be formatted if path is `path/to/dir`, all KCL files in the specified dir will be formatted, not recursively if path is `path/to/dir/...`, all KCL files in the specified dir will be formatted recursively

the returned changedPaths are the changed file paths (relative path)

Example
package main

import (
	"fmt"
	"log"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	changedPaths, err := kcl.FormatPath("testdata/fmt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(changedPaths)
}
Output:

func GetSchemaTypeMapping added in v0.5.1

func GetSchemaTypeMapping(file, code, schemaName string) (map[string]*KclType, error)

GetSchemaTypeMapping returns a <schemaName>:<schemaType> mapping of schema types from a kcl file or code.

file: string

The kcl filename

code: string

The kcl code string

schema_name: string

The schema name got, when the schema name is empty, all schemas are returned.

func InitKclvmPath

func InitKclvmPath(kclvmRoot string)

InitKclvmPath init kclvm path.

func InitKclvmRuntime

func InitKclvmRuntime(n int)

InitKclvmRuntime init kclvm process.

func LintPath

func LintPath(paths []string) (results []string, err error)

LintPath lint files from the given path

Example
package main

import (
	"fmt"
	"log"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	// import a
	// import a # reimport

	results, err := kcl.LintPath([]string{"testdata/lint/import.k"})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range results {
		fmt.Println(s)
	}

}
Output:

Module 'a' is reimported multiple times
Module 'a' imported but unused
Module 'a' imported but unused

func ListDepFiles

func ListDepFiles(workDir string, opt *ListDepFilesOption) (files []string, err error)

ListDepFiles return the depend files from the given path

func ListDownStreamFiles

func ListDownStreamFiles(workDir string, opt *ListDepsOptions) ([]string, error)

ListDownStreamFiles return a list of downstream depend files from the given changed path list.

func ListUpStreamFiles

func ListUpStreamFiles(workDir string, opt *ListDepsOptions) (deps []string, err error)

ListUpStreamFiles return a list of upstream depend files from the given path list

func OverrideFile

func OverrideFile(file string, specs, importPaths []string) (bool, error)

OverrideFile rewrites a file with override spec file: string. The File that need to be overridden specs: []string. List of specs that need to be overridden.

Each spec string satisfies the form: <pkgpath>:<field_path>=<filed_value> or <pkgpath>:<field_path>-
When the pkgpath is '__main__', it can be omitted.

importPaths. List of import statements that need to be added

func Validate added in v0.7.0

func Validate(dataFile, schemaFile string, opts *ValidateOptions) (ok bool, err error)

Validate validates the given data file against the specified schema file with the provided options.

func ValidateCode

func ValidateCode(data, code string, opts *ValidateOptions) (ok bool, err error)

ValidateCode validate data string match code string

Types

type KCLResult

type KCLResult = kcl.KCLResult
Example
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	const k_code = `
name = "kcl"
age = 1
	
two = 2
	
schema Person:
    name: str = "kcl"
    age: int = 1

x0 = Person {name = "kcl-go"}
x1 = Person {age = 101}
`

	result := kcl.MustRun("testdata/main.k", kcl.WithCode(k_code)).First()

	fmt.Println("x0.name:", result.Get("x0.name"))
	fmt.Println("x1.age:", result.Get("x1.age"))

}
Output:

x0.name: kcl-go
x1.age: 101

type KCLResultList

type KCLResultList = kcl.KCLResultList

func MustRun

func MustRun(path string, opts ...Option) *KCLResultList

MustRun is like Run but panics if return any error.

Example
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	yaml := kcl.MustRun("testdata/main.k", kcl.WithCode(`name = "kcl"`)).First().YAMLString()
	fmt.Println(yaml)

}
Output:

name: kcl
Example (RawYaml)
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	const code = `
b = 1
a = 2
`
	yaml := kcl.MustRun("testdata/main.k", kcl.WithCode(code)).GetRawYamlResult()
	fmt.Println(yaml)

	yaml_sorted := kcl.MustRun("testdata/main.k", kcl.WithCode(code), kcl.WithSortKeys(true)).GetRawYamlResult()
	fmt.Println(yaml_sorted)

}
Output:

b: 1
a: 2
a: 2
b: 1
Example (SchemaType)
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	const code = `
schema Person:
	name: str = ""

x = Person()
`
	json := kcl.MustRun("testdata/main.k", kcl.WithCode(code)).First().JSONString()
	fmt.Println(json)

}
Output:

{
    "x": {
        "name": ""
    }
}
Example (Settings)
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	yaml := kcl.MustRun("./testdata/app0/kcl.yaml").First().YAMLString()
	fmt.Println(yaml)
}
Output:

func Run

func Run(path string, opts ...Option) (*KCLResultList, error)

Run evaluates the KCL program with path and opts, then returns the object list.

Example (GetField)
package main

import (
	"fmt"
	"log"

	kcl "kcl-lang.io/kcl-go"
)

func assert(v bool, a ...interface{}) {
	if !v {
		a = append([]interface{}{"assert failed"}, a...)
		log.Panic(a...)
	}
}

func main() {
	// run kcl.yaml
	x, err := kcl.Run("./testdata/app0/kcl.yaml")
	assert(err == nil, err)

	// print deploy_topology[1].zone
	fmt.Println(x.First().Get("deploy_topology.1.zone"))

}
Output:

R000A

func RunFiles

func RunFiles(paths []string, opts ...Option) (*KCLResultList, error)

RunFiles evaluates the KCL program with multi file path and opts, then returns the object list.

Example
package main

import (
	"fmt"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	result, _ := kcl.RunFiles([]string{"./testdata/app0/kcl.yaml"})
	fmt.Println(result.First().YAMLString())
}
Output:

type KclType

type KclType = kcl.KclType

func GetSchemaType

func GetSchemaType(file, code, schemaName string) ([]*KclType, error)

GetSchemaType returns schema types from a kcl file or code.

file: string

The kcl filename

code: string

The kcl code string

schema_name: string

The schema name got, when the schema name is empty, all schemas are returned.

type ListDepFilesOption

type ListDepFilesOption = list.Option

type ListDepsOptions

type ListDepsOptions = list.DepOptions

type Option

type Option = kcl.Option

func WithCode

func WithCode(codes ...string) Option

WithCode returns a Option which hold a kcl source code list.

func WithDisableNone

func WithDisableNone(disableNone bool) Option

WithDisableNone returns a Option which hold a disable none switch.

func WithExternalPkgs

func WithExternalPkgs(externalPkgs ...string) Option

WithExternalPkgs returns a Option which hold a external package list.

func WithFullTypePath added in v0.8.0

func WithFullTypePath(fullTypePath bool) Option

WithFullTypePath returns a Option which hold a include full type string in the `_type` attribute.

func WithIncludeSchemaTypePath added in v0.5.4

func WithIncludeSchemaTypePath(includeSchemaTypePath bool) Option

WithIncludeSchemaTypePath returns a Option which hold a include schema type path switch.

func WithKFilenames

func WithKFilenames(filenames ...string) Option

WithKFilenames returns a Option which hold a filenames list.

func WithLogger added in v0.7.0

func WithLogger(l io.Writer) Option

WithLogger returns a Option which hold a logger.

func WithOptions

func WithOptions(key_value_list ...string) Option

WithOptions returns a Option which hold a key=value pair list for option function.

Example
package main

import (
	"fmt"
	"log"

	kcl "kcl-lang.io/kcl-go"
)

func main() {
	const code = `
name = option("name")
age = option("age")
`
	x, err := kcl.Run("hello.k", kcl.WithCode(code),
		kcl.WithOptions("name=kcl", "age=1"),
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(x.First().YAMLString())

}
Output:

age: 1
name: kcl

func WithOverrides

func WithOverrides(override_list ...string) Option

WithOverrides returns a Option which hold a override list.

func WithPrintOverridesAST

func WithPrintOverridesAST(printOverridesAST bool) Option

WithPrintOverridesAST returns a Option which hold a printOverridesAST switch.

func WithSelectors added in v0.7.0

func WithSelectors(selectors ...string) Option

WithSelectors returns a Option which hold a path selector list.

func WithSettings

func WithSettings(filename string) Option

WithSettings returns a Option which hold a settings file.

func WithShowHidden added in v0.8.0

func WithShowHidden(showHidden bool) Option

WithShowHidden returns a Option which holds a showHidden switch.

func WithSortKeys

func WithSortKeys(sortKeys bool) Option

WithSortKeys returns a Option which holds a sortKeys switch.

func WithWorkDir

func WithWorkDir(workDir string) Option

WithWorkDir returns a Option which hold a work dir.

type TestCaseInfo added in v0.7.0

type TestCaseInfo = testing.TestCaseInfo

type TestOptions added in v0.7.0

type TestOptions = testing.TestOptions

type TestResult added in v0.7.0

type TestResult = testing.TestResult

func Test added in v0.7.0

func Test(testOpts *TestOptions, opts ...Option) (TestResult, error)

Test calls the test tool to run uni tests in packages.

type ValidateOptions

type ValidateOptions = validate.ValidateOptions

Directories

Path Synopsis
examples
pkg
3rdparty/dlopen
Package dlopen provides some convenience functions to dlopen a library and get its symbols.
Package dlopen provides some convenience functions to dlopen a library and get its symbols.
env
kcl
Package kcl defines the top-level interface for KCL.
Package kcl defines the top-level interface for KCL.
path
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
tools/list
Package list extracts information by parsing KCL source code and return it as list.
Package list extracts information by parsing KCL source code and return it as list.

Jump to

Keyboard shortcuts

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