Skip to main content

9 posts tagged with "Release Blog"

View All Tags

· 13 min read

Introduction

The KCL team is pleased to announce that KCL v0.10.0 is now available! This release has brought three key updates to everyone

  • Enhance the coding experience and efficiency with a more performant, feature-rich, and less error-prone KCL language, toolchain, and IDE.
  • A more comprehensive and diverse set of standard libraries, third-party libraries, and community ecosystem integrations, covering different application scenarios and requirements.
  • The WASM SDK supports browser running and the new KCL Playground.

KCL is an open-source, constraint-based record and functional language hosted by Cloud Native Computing Foundation (CNCF). KCL improves the writing of numerous complex configurations, such as cloud-native scenarios, through its mature programming language technology and practice. It is dedicated to building better modularity, scalability, and stability around configurations, simpler logic writing, faster automation, and great built-in or API-driven integrations.

❤️ Special Thanks

We would like to extend our heartfelt thanks to all 80 community contributors who participated in the iteration from version v0.9 to v0.10. The following list is in no particular order.

@eshepelyuk, @haarchri, @liangyuanpeng, @logo749, @bilalba, @borgius, @patrick-hermann-sva, @ovk, @east4ming, @wmcnamee-coreweave, @steeling, @sschne, @Jacob Colvin, @Richard Holmes, @Christopher Haar, @Yvan da Silva, @Uladzislau Maher, @Sergey Ryabin, @Lukáš Kubín, @Alexander Fuchs, @Divyansh Choukse, @Vishalk91-4, @DavidChevallier, @dennybaa, @bozaro, @vietanhtwdk, @hoangndst, @patpicos, @metacoma, @karlderkaefer, @kukacz, @Matthew Hodgkins, @Gao Jun, @Zack Zhang, @briheet, @Moulick, @stmcginnis, @Manoramsharma, @NishantBansal2003, @varshith257, @Harsh4902, @Gmin2, @shishir-11, @RehanChalana, @Shruti78, @jianzs, @vinayakjaas, @ChrisK, @Lan Liang, @Endre Karlson, @suin, @v3xro, @soubinan, @juanzolotoochin, @mnacharov, @ron1, @vfarcic, @phisco, @juanique, @zackzhangverkada, @warmuuh, @novohool, @officialasishkumar, @cx2c, @yonas, @shruti2522, @nwmcsween, @trogowski, @johnallen3d, @riven-blade, @gesmit74, @prakhar479, @Peter Boat, @Stéphane Este-Gracias, @Josh West, @Brandon Nason, @Anany, @dansrogers, @diefans, @DrummyFloyd

📚 Key Updates

🔧 Core Features

Language

  • Supports both attribute access and index access in assignment statements.

Now you can change the content of the assigned object through index access.

_a = [0, 1] * 2
_a[0] = 2
_a[1] += 2
a = _a

After compilation, you will get the following result

a:
- 2
- 3
- 0
- 1

Or you can change the content of the assigned object through attribute access.

_a = [{key1.key2 = [0] * 2}, {key3.key4 = [0] * 2}]
_a[0].key1.key2[0] = 1
_a[1].key3.key4[1] += 1
a = _a

After compilation, you will get the following result:

a:
- key1:
key2:
- 1
- 0
- key3:
key4:
- 0
- 1
  • For single constant schema properties, the default value can be omitted.
schema Deployment:
apiVersion: "apps/v1" = "apps/v1"
schema Deployment:
apiVersion: "apps/v1" # "apps/v1" is the default value
  • Fixed the issue of semantic check time being too long when nesting multiple config blocks in KCL.
  • Removed the unwrap() statement in the semantic parser to reduce panic issues.
  • Fixed the calculation error of the field merge operation with a list index.
  • Fixed the type conversion error when the as keyword exists in an external package.
  • Fixed the type check error when the config is converted to the schema in a lambda function.
  • Optimized the type inference and check of the Dict return value of the optimization function parameter call, which can omit the schema name to simplify the configuration writing.
  • Supported the syntax of _config["key"] = "value" or _config.key = "value" to modify the configuration in place in the assignment statement.
  • Optimized the type check of the configuration merge operator, which can find more type errors at compile time.
  • Fixed the issue of the datetime date format in the built-in API.
  • Fixed the Schema configuration merge parameter parsing error.
  • Optimized the error message.
  • Fixed the unexpected error caused by the circular dependency in the Schema inheritance.
  • Fixed the issue of the automatic merge of the configuration being invalid.
  • KCL optimized the error message of the circular dependency in the Schema inheritance.
  • KCL refactored the code in the compilation entry.
  • KCL added the release of the library under the windows mingw environment.
  • KCL fixed the CI error in the windows environment.
  • Optimized the KCL runtime error message and added some test cases.

Toolchain

  • Added the kcl test tool to support the print function output in test cases.

You can use the print function to output logs in test cases.

test_print = lambda {
print("Test Begin ...")
}

By running the kcl test command to run the test case, you can see the corresponding log:

test_print: PASS (9ms)
Test Begin ...

--------------------------------------------------------------------------------
PASS: 1/1
  • kcl import tool supports importing JSON Schema with AllOf validation fields into KCL Schema.

For JSON Schema containing AllOf validation fields:

{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/schemas/config",
"description": "Schema for representing a config information.",
"type": "object",
"properties": {
"name": {
"type": "string",
"allOf": [
{
"pattern": "198.160"
},
{
"pattern": "198.161"
},
{
"pattern": "198.162"
}
]
},
"price": {
"type": "number",
"minimum": 0
}
},
"required": ["name"]
}

It will generate the corresponding KCL Schema:

"""
This file was generated by the KCL auto-gen tool. DO NOT EDIT.
Editing this file might prove futile when you re-run the KCL auto-gen generate command.
"""
import regex

schema Config:
r"""
Schema for representing a config information.

Attributes
----------
name : str, required
price : float, optional
"""

name: str
price?: float

check:
regex.match(name, r"198.160")
regex.match(name, r"198.161")
regex.match(name, r"198.162")
price >= 0 if price
  • KCL package management tool supports adding a KCL package from a Git repository subdirectory as a third-party library.

By the following command, the KCL package management tool supports adding a KCL package from a Git repository subdirectory as a third-party library.

kcl mod add <package_name> --git <git_url> --commit <commit_id>

Taking https://github.com/kcl-lang/flask-demo-kcl-manifests.git as an example, add the KCL package named cc in the subdirectory of this repository as a dependency:

kcl mod add cc --git https://github.com/kcl-lang/flask-demo-kcl-manifests.git --commit 8308200
  • The kcl-playground based on the WASM backend is online.

kclplayground

  • kcl import tool supports importing the entire Go Package and converting all Go struct definitions into KCL Schema definitions.
  • Fixed the compilation error of kcl import when importing Kubernetes CRD and OpenAPI Schema.
  • Optimized the output format of kcl mod init.
  • kcl fmt tool supports retaining the blank lines between multiple code snippets, which will not delete all of them.
  • Fixed the issue of the package management tool not recognizing the package relative path ${KCL_MOD} in the compilation entry.
  • The package management tool adjusts the plainHttp option to be optional.
  • The package management tool fixes the compilation entry recognition error caused by the wrong root directory.
  • The package management tool adds a cache for login credentials to reduce security risks.
  • The package management tool fixes the compilation failure caused by the virtual compilation entry.
  • The package management tool fixes the missing default dependencies in the kcl.mod.
  • The package management tool fixes the calculation error of the vendor path, which causes the third-party library to be re-downloaded.
  • The package management tool fixes the failure to push the OCI registry with the https protocol.
  • The package management tool fixes the compilation failure when compiling multiple *.k files.
  • The package management added more test cases.
  • The package management tool fixed the circular dependency issue caused by adding the git subpackage multiple times as a dependency.
  • The package management tool fixed the missing dependencies path when use the kcl mod metadata command.
  • The package management tool preloads the MVS version management algorithm in the Add, Update command, controlled by the environment variable SupportMVS=true.
  • KCL tree-sitter adds sequence operations and selector support.
  • KCL tree-sitter optimizes some syntax rules and adds more test cases.
  • Fixed the issue of the kcl fmt tool formatting the Schema index signature comment error.
  • Fixed the issue of kcl import importing the Kubernetes CRD setting the -o parameter to an unexpected error.
  • Fixed the issue of kcl import importing an empty Go struct outputting an unexpected KCL Schema error.
  • Optimized the code structure and document structure of kcl-openapi.
  • Added more test cases and optimized the code structure of kcl-playground.
  • krm-kcl function fixed some errors in the tests and documents.
  • krm-kcl function fixed the issue of dependency download failure.
  • kcl-operator updated and fixed some document content, optimized some code structures.
  • kcl-operator added some test cases and optimized the release process.
  • kcl-operator added automatic authentication when initializing containers.
  • kcl fmt tool provides C API.
  • kcl fmt tool removes redundant blank lines in if blocks.

IDE

  • The IDE adds hints for the schema parameter.

schemaargshint

  • Fixed the semantic highlighting of the schema index signature key.
  • Supported the use of the kcl.work configuration file to divide the IDE workspace.
  • Fixed the issue of the IDE not recognizing the schema instantiation parameters.
  • Fixed auto-complete errors in the IDE schema doc.
  • Fixed the issue of auto-complete failure in the IDE unification attributes.
  • Supported the fine-grained completion of distinguishing attribute and value semantics when instantiating the Schema.
  • KCL vim plugin updates the installation document.
  • KCL vscode plugin removes the response to yaml files.
  • KCL vscode plugin adds Apache 2.0 License.
  • Fix the use of ':' in the Schema merge operator definition attribute instantiation completion.
  • Fixed the unexpected completion in the Schema Doc.
  • Fixed the kcl-language-server command-line version display issue.
  • Supported the IDE to disable the save formatting configuration for NeoVim, VS Code, and other plugins.
  • Removed the default key bindings of the KCL NeoVim plugin and supported user customization.
  • Fixed the code highlighting failure of the first line and first column.
  • Fixed the dead lock issue of the IDE.
  • IDE adds more output logs.
  • IDE optimizes the find ref function.
  • IDE fixed the failure when update kcl.mod.
  • IDE fixed the failure of finding reference.
  • IDE fixed the failure of code highlighting when opening a file.
  • LSD restructured some code structures and adjusted some API scopes.
  • IDE fixed the issue of the IDE does not synchronize after updating dependencies with kpm.
  • IDE fixed the panic caused by circular dependencies.
  • IDE fixed the issue of auto-completion failure in the if expression.
  • IDE fixed the failure of code highlighting for the Schema member with an index signature.
  • KCL intellij IDE plugin supports LSP4IJ.

API

📦️ Standard Libraries and Third-Party Libraries

Standard Libraries

  • Added the file.current() function to get the full path of the current running KCL file.
import file

a = file.current()

After compiling, you can get the following result:

a: /Users/xxx/xxx/main.k
  • KCL added some built-in APIs parameters to support the encoding parameter.
sha512(value: str, encoding: str = "utf-8") -> str
  • KCL has added a new built-in API, crypto.blake3, to support the use of the Blake algorithm for hashing.
import crypto
blake3 = crypto.blake3("ABCDEF")
  • KCL has added a new built-in API, isnullish, to support determining whether a field is empty.
a = [100, 10, 100]
A = isnullish(a)
e = None
E = isnullish(e)
  • KCL has added a new built-in API, datetime.validate, to support validating date content.
import datetime
assert datetime.validate("2024-08-26", "%Y-%m-%d")

Third-Party Libraries

  • cluster-api-provider-azure updated to v1.16.0
  • cluster-api updated to v1.7.4
  • konfig updated to v0.6.0
  • karmada updated to v0.1.1
  • k8s updated to 1.31
  • gateway-api updated to 0.2.0
  • karpenter updated to 0.2.0
  • crossplane updated to 1.16.0
  • cilium updated to 0.3.0
  • external-secrets updated to 0.1.2
  • The New Module List
    • fluxcd-kcl-controller
    • fluxcd-kustomize-controller
    • fluxcd-helm-controller
    • fluxcd-source-controller
    • fluxcd-image-reflector-controller
    • fluxcd-image-automation-controller
    • fluxcd-notification-controller
    • kwok
    • crossplane-provider-vault 1.0.0
    • outdent 0.1.0
    • kcl_lib 0.1.0

☸️ Ecosystem Integration

  • Flux KCL Controller released v0.4.0 version, aligning with most of the Flux Kustomize Controller functions to meet the needs of directly using KCL to replace Kustomize for Flux GitOps.
  • KRM KCL Specification released v0.10.0 beta version, adding private Git repository pull and ignore TLS check functions.
  • KCL Nix Package released v0.9.8 version.
  • Crossplane KCL Function released v0.9.4 version, see https://github.com/crossplane-contrib/function-kcl
  • KCL Bazel Rules updated to KCL v0.10.0 beta version, see https://github.com/kcl-lang/rules_kcl
  • KCL Flux Controller passed the parameter optimization, added more test cases, and a more complete release and test process.

🧩 Multi-Language SDKs and Plugins

Multi-Language SDKs

  • KCL Go SDK supports interacting with the KCL core Rust API in RPC mode or CGO mode through build tags, with CGO mode enabled by default and RPC mode enabled by -tags rpc.
  • New KCL C/C++ language SDK.
  • Added Go, Java, Python, Rust, .NET, C/C++ and other multi-language API Specs, related documents, test cases, and use cases.
  • Added KCL Kotlin and Swift language SDKs, which have not yet officially released dependency packages. Contributions are welcome.
  • Added KCL WASM lib support for node.js and browser integration.
  • Refactored and optimized the KCL Python/Go/Java code.
  • KCL WASM SDK fixed the issue caused by the '\0' escape character.
  • KCL lib supports cross-platform compilation.
  • KCL WASM SDK adds some test cases.

Multi-Language Plugins

  • KCL Plugin supports development through Rust.
  • Add more test cases for the KCL Plugin.

📖 Documentation Updates

  • Added Python, Java, Node.js, Rust, WASM, .NET, C/C++ and other multi-language API documents.
  • Updated the IDE Quick Start document.
  • New Blog "A Comparative Overview of Jsonnet and KCL".
  • Updated the crd in "Adapt From Kubernetes CRD Resources" in the documentation.
  • Added the KCL review article at kubecon 2024.
  • Added the document for built-in API.
  • Added the document for the integration of the package management tool with OCI registry and Git Repo.
  • Added the document for include and exclude fields in the kcl.mod.
  • Added FAQ about the docker-credential-desktop not found solution.
  • Added reference documents for some resources in the konfig.
  • Add API documentation for KCL WASM.
  • Added API documentation for KCL Rust Plugin Development.
  • Add FAQ document about the mixin and protocol.
  • Fixed some document errors.

🌐 Other Resources

🔥 Check out the KCL Community and join us 🔥

For more resources, refer to:

· 9 min read

Introduction

The KCL team is pleased to announce that KCL v0.9.0 is now available! This release has brought three key updates to everyone

  • Enhance the coding experience and efficiency with a more performant, feature-rich, and less error-prone KCL language, toolchain, and IDE.
  • A more comprehensive and diverse set of standard libraries, third-party libraries, and community ecosystem integrations, covering different application scenarios and requirements.
  • Richer multi-language SDKs and plugins, seamlessly integrating with different programming languages and development environments.

KCL is an open-source, constraint-based record and functional language hosted by Cloud Native Computing Foundation (CNCF). KCL improves the writing of numerous complex configurations, such as cloud-native scenarios, through its mature programming language technology and practice. It is dedicated to building better modularity, scalability, and stability around configurations, simpler logic writing, faster automation, and great built-in or API-driven integrations.

❤️ Special Thanks

We would like to extend our heartfelt thanks to all 120 community contributors who participated in the iteration from version v0.8 to v0.9 over the past 120 days. The following list is in no particular order.

@Shashank Mittal, @MattHodge, @officialasishkumar, @Gmin2, @Akash Kumar, @sfshumaker, @sanzoghenzo, @MOHAMED FAWAS, @bradkwadsworth-mw, @excalq, @Daksh-10, @metacoma, @Wes McNamee, @Stéphane Este-Gracias, @octonawish-akcodes, @zong-zhe, @shashank-iitbhu, @NAVRockClimber, @AkashKumar7902, @Petrosz007, @patrycju, @Korada Vishal, @selfuryon, @tvandinther, @vtomilov, @Peefy, @taylormonacelli, @Tertium, @Stefano Borrelli, @Bishal, @kukacz, @borgius, @steeling, @jheyduk, @HStéphane Este-Gracias, @userxiaosi, @folliehiyuki, @kubernegit, @nizq, @Alexander Fuchs, @ihor-hrytskiv, @Mohamed Asif, @reedjosh, @Wck-iipi, @evensolberg, @aldoborrero@ron18219, @rodrigoalvamat, @mproffitt, @karlhepler, @shruti2522, @leon-andria, @prahaladramji, @Even Solberg, @utnim2, @warjiang, @Asish Kumar, @He1pa, @Emmanuel Alap, @d4v1d03, @Yvan da Silva, @Abhishek, @DavidChevallier, @zargor, @Kim Sondrup, @SamirMarin, @Hai Wu, @MatisseB, @beholdenkey, @nestoralonso, @HAkash Kumar, @olinux, @liangyuanpeng, @ngergs, @Penguin, @ealap, @markphillips100, @Henri Williams, @eshepelyuk, @CC007, @mintu, @M Slane, @zhuxw, @atelsier, @aleeriz, @LinYunling, @YvanDaSilva, @chai2010, @Sergey Ryabin, @vfarcic, @vemoo, @riven-blade, @ibishal, @empath-nirvana, @bozaro, @jgascon-nx, @reckless-huang, @Sergei Iakovlev, @Blarc, @JeevaRamanathan, @dennybaa, @PrettySolution, @east4ming, @nkabir, @sestegra, @XiaoK29, @ricochet1k, @yjsnly, @umaher, @SjuulJanssen, @wilsonwang371, @Lukáš Kubín, @samuel-deal-tisseo, @blakebarnett, @Uladzislau Maher, @ytsarev, @Vishalk91-4, @Stephen C, @Tom van Dinther, @MrGuoRanDuo, @dopesickjam

📚 Key Updates

⚡️ Performance Enhancements

Runtime Performance

In the new KCL v0.9 release, a new fast runtime mode has been introduced. This can be enabled by setting the KCL_FAST_EVAL=1 environment variable, which improves startup and runtime performance. For configurations using Schema (such as the k8s third-party library), this offers approximately a 3x performance boost compared to previous versions. For simple configurations without Schema, output YAML performance has been tested to surpass tools like helm template and kustomize build that use YAML and Go Templates.

IDE Performance

KCL IDE has further optimized incremental compilation and performance for semantic analysis in large projects. For KCL projects with around 400 files, the end-to-end response time has been reduced to 20% of the previous version.

🔧 Core Features

Language

  • String interpolation now supports escaping with \${} similar to Shell to cancel interpolation.
world = "world"
hello_world_0 = "hello ${world}" # hello world
hello_world_1 = "hello \${world}" # hello ${world}
  • Added schema type support to the typeof function for distinguishing schema types from instances.
schema Foo:
bar?: str

foo = Foo {}
type_schema = typeof(foo) # schema
type_type = typeof(Foo) # type
  • Added a full_pkg keyword argument to the instances() method of Schema to read instances of the corresponding schema from all code.
schema Person:
name: str

alice = Person {name = "Alice"}
all_persons = Person.instances(True)
  • Removed implicit comparison between bool and int types 0 < True.
  • Removed comparison features for the list type [0] < [1].
  • Added type assertion failure functionality to the as keyword.
  • Optimized closure variable capture logic of lambda functions and configuration code blocks {} in different scopes to be more intuitive.

Toolchain

  • kcl run now supports outputting configurations in TOML format with the --format toml option.
  • kcl mod add now supports adding dependencies from private third-party OCI Registries and Git repositories with the --oci and --git options.
  • kcl import now supports importing entire Go Packages as KCL Schemas.
  • kcl import now supports importing files with YAML stream format (---).
  • kcl import now supports importing TOML files as KCL configurations.
  • kcl clean now supports cleaning external dependencies and compile caches.
  • kcl mod init now supports setting the version of a new KCL module with the --version tag.
  • Commands like kcl run, kcl mod add, and kcl mod pull now support accessing private repositories via local Git.

IDE

  • Supports multiple quick fix options.
  • Syntax highlighting for kcl.mod and kcl.mod.lock files.
  • Partial syntax hover highlighting in the IDE.
  • import completion for external dependencies.
  • Function symbol highlighting and Inlay Hints displaying default variable types.

inlayhint

API

  • The Override API now supports setting different attribute operators (:, =, and +=) for configuration overrides.
  • Go API now supports prototext format and KCL schema output as KCL configurations.
  • Go API now supports serializing any Go Type and Go Value to KCL Schema and configurations.

📦️ Standard Libraries and Third-Party Libraries

Standard Libraries

  • Added the file standard library for file IO operations, such as reading configurations from YAML and performing configuration merges.
import file
import yaml
import json_merge_patch as p

config = p.merge(yaml.decode(file.read("deployment.yaml")), {
metadata.name = "override_value"
})

For more functions in the file module, see: https://www.kcl-lang.io/docs/reference/model/file

  • Added the template standard library for writing template configurations.
import template

_data = {
name = "handlebars",
v = [ { a = 1 }, { a = 2 } ],
c = { d = 5 },
g = { b = [ { aa = { bb = 55} }, { aa = { bb = 66} } ] },
people = [ "Yehuda Katz", "Alan Johnson", "Charles Jolley" ]
}

content = template.execute("""\
Hello world from {{name}}

{{#each v}}
{{this.a}}
{{/each}}
{{ c.d }}
{{#each people}}
{{ this }}
{{/each}}
{{#each g.b}}
{{this.aa.bb}}
{{/each}}
""", _data)
  • Added the runtime standard library for capturing runtime exceptions, useful for kcl test tool to test exception cases.
import runtime

schema Person:
name: str
age: int

check:
0 <= age <= 120, "age must be in [1, 120], got ${age}"

test_person_check_error = lambda {
assert runtime.catch(lambda {
p = Person {name = "Alice", age: -1}
}) == "age must be in [1, 120], got -1"
}

Third-Party Libraries

The number of KCL models has increased to 313, including major updates as follows:

  • k8s released version 1.30
  • argo-cd released version 0.1.1
  • argo-workflow released version 0.0.3
  • istio released version 1.21.2
  • victoria-metrics-operator released version 0.45.1
  • cert-manager released version 0.1.2
  • cilium released version 0.1.1
  • Longhorn released version 0.0.1
  • jsonpatch released version 0.0.5, supporting rfc6901Decode
  • Added a new third-party library difflib for comparing configuration differences
  • Added argo-cd-order for sorting argocd sync operation resource order
  • Added models for cluster-api, including cluster-api, cluster-api-provider-metal3, cluster-api-provider-gcp, cluster-api-addon-provider-helm, cluster-api-addon-provider-aws, cluster-api-provider-azure, and more

☸️ Ecosystem Integration

apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
name: example
spec:
compositeTypeRef:
apiVersion: example.crossplane.io/v1beta1
kind: XR
mode: Pipeline
pipeline:
- step: basic
functionRef:
name: function-kcl
input:
apiVersion: krm.kcl.dev/v1alpha1
kind: KCLInput
source: |
# Read the XR
oxr = option("params").oxr
# Patch the XR with the status field
dxr = oxr | {
status.dummy = "cool-status"
}
# Construct a AWS bucket
bucket = {
apiVersion = "s3.aws.upbound.io/v1beta1"
kind = "Bucket"
metadata.annotations: {
"krm.kcl.dev/composition-resource-name" = "bucket"
}
spec.forProvider.region = option("oxr").spec.region
}
# Return the bucket and patched XR
items = [bucket, dxr]
- step: automatically-detect-ready-composed-resources
functionRef:
name: function-auto-ready

Additionally, you can find more real use cases of KCL with other ecosystem projects here:

🧩 Multi-Language SDKs and Plugins

Multi-Language SDKs

The number of KCL multi-language SDKs has increased to 7, currently supporting Rust, Go, Java, .NET, Python, Node.js, and WASM. These can be used without installing additional KCL command-line tools, optimizing the installation size to 90% of previous versions and removing the need for complex system dependencies. Furthermore, each SDK provides the same APIs for code execution, code analysis, type parsing, and adding external dependencies. Here are some examples with the Java and C# SDKs:

  • Java
import com.kcl.api.API;
import com.kcl.api.Spec.ExecProgram_Args;
import com.kcl.api.Spec.ExecProgram_Result;

public class ExecProgramTest {
public static void main(String[] args) throws Exception {
API api = new API();
ExecProgram_Result result = api
.execProgram(ExecProgram_Args.newBuilder().addKFilenameList("path/to/kcl.k").build());
System.out.println(result.getYamlResult());
}
}
  • C#
namespace KclLib.Tests;

using KclLib.API;

public class KclLibAPITest
{
public static void Main()
{
var execArgs = new ExecProgram_Args();
execArgs.KFilenameList.Add("path/to/kcl.k");
var result = new API().ExecProgram(execArgs);
Console.WriteLine(result.YamlResult);
}
}

For more information on installing and using other SDKs, see https://github.com/kcl-lang/lib

Multi-Language Plugins

The number of KCL multi-language plugins has increased to 3, currently supporting Go, Python, and Java. Only basic SDK dependencies are required to achieve seamless interoperation between common languages and KCL. Here are some examples with Python and Java plugins:

Write the following KCL code (main.k)

import kcl_plugin.my_plugin

result = my_plugin.add(1, 1)

Use the Python SDK to register a Python function for calling in KCL

import kcl_lib.plugin as plugin
import kcl_lib.api as api

plugin.register_plugin("my_plugin", {"add": lambda x, y: x + y})

def main():
result = api.API().exec_program(
api.ExecProgram_Args(k_filename_list=["main.k"])
)
assert result.yaml_result == "result: 2"

main()

Use the Java SDK to register a Java function for calling in KCL

package com.kcl;

import com.kcl.api.API;
import com.kcl.api.Spec.ExecProgram_Args;
import com.kcl.api.Spec.ExecProgram_Result;

import java.util.Collections;

public class PluginTest {
public static void main(String[] mainArgs) throws Exception {
API.registerPlugin("my_plugin", Collections.singletonMap("add", (args, kwArgs) -> {
return (int) args[0] + (int) args[1];
}));
ExecProgram_Result result = new API()
.execProgram(ExecProgram_Args.newBuilder().addKFilenameList("main.k").build());
System.out.println(result.getYamlResult());
}
}

For more examples of using other multi-language plugins, see https://www.kcl-lang.io/docs/reference/plugin/overview

Additionally, you can find more real use cases of KCL multi-language plugins here:

🌐 Other Resources

🔥 Check out the KCL Community and join us 🔥

For more resources, refer to: