Pkl is Apple's new configuration language. Review and comparison with YAML and JSON

Each application requires a certain level of configuration. Using special languages, you can create files that can automate system initialization. These files are usually read and interpreted only once. The most common example is Windows INI configurations that are processed using Microsoft APIs.

The popularity of configurations like INI has varied over the years. As applications have evolved, so has the complexity of configuration. Therefore, it is especially important to choose the right configuration language so as not to complicate life for yourself and your pet project. Below the cut we talk about pickles and Pkl – a new solution from Apple.

Use navigation if you don't want to read the entire text:

Why do we need configuration languages?
More about Pkl
Getting started with a new language
Examples: comparison with other formats
Conclusion

Why do we need configuration languages?


Configuration languages ​​are usually declarative. There are several solutions – each with its own advantages and disadvantages. For example, XML, JSON, YAML and HCL are somewhat compatible, but trade-offs are necessary depending on the language chosen. Or you can use “general-purpose languages” (Kotlin, Ruby, JavaScript and the like), that is, describe system parameters in the form of program code.

The last option is not always acceptable: unnecessary dependencies appear, the described configurations become “tied” to interpreters and compilers. For example, if you describe the application parameters, describe them in Python and transfer them to a virtual environment in which it is not installed, an exception will be thrown. Even if you install Parseltongue, the question of compatibility of the configuration with “root” will arise, which must still count.

What does this have to do with pickles?

To solve the problems described, Apple has developed

Pkl configuration language

(Pickle, “pickles”). The company felt that configuration was best expressed as a mixture of a static language and a programming language.

The developers took the best of both worlds and created a language that is declarative and easy to read and write, but enhanced with features borrowed from general-purpose languages. Pkl version 0.25 launched on February 1, 2024 and is available in the GitHub repository. Let's get to know her better.

More about Pkl


Pkl is designed around a key-value structure similar to JSON, rather than using imperative statements like many other traditional languages. One of the key advantages of this approach is its high compatibility with popular configuration formats such as JSON, XML and YAML.

Pkl uses some ideas from three other languages: Python, Kotlin and Lisp. In addition, it can work on any platform that supports these languages ​​and seamlessly interact with them. Perhaps Pkl stands for Python-Kotlin-Lisp. Or maybe not.

Pkl supports both complex types (lists, maps, sets, and enumerations) and primitive types (integers, strings, booleans, and zero). Additionally, users can perform type checking at build and runtime, and create new types and schemas.

Pkl supports sandboxing, which creates an isolated virtual environment for working with configuration code. The least privilege option, which provides the minimum permissions required to set the configuration, is also supported by the language.

In addition, using Pkl you can configure networks, servers, cloud services, containers and other infrastructure elements. Pkl is designed to be both declarative and easy to read and write, while still incorporating elements commonly found in traditional programming languages: classes, functions, conditionals, and loops. This allows for different levels of abstraction.

Pkl can also create static configuration files in common formats or be embedded as a library into other application runtimes. But these are all words that can be found on the official website. Let's get to practice.

Getting started with a new language


To get started you need to install the interface
command line (CLI) Pkl. Users can create, modify, build, execute, and test Pkl configuration files using this command line interface. Just install pickles dependencies into your project and dive into the Pkl API for configuration. It allows you to read, write, check and execute Pkl configuration files. The interface is available for Java, Kotlin, Swift and Go.

Examples: comparison with other formats

Probably the most popular formats for storing human-readable and machine-readable data are JSON and YAML. Pkl may not be a well-known language, but it has a minimal and consistent syntax that is also easy to understand and write.

pros

Minuses

Examples

Here are some examples of JSON, YAML and Pickle files that define the same configuration data. Compare what seems clearer to you and write your opinion in the comments!

{
  "name": "My application",
  "port": 8080,
  "database": {
    "host": "localhost",
    "user": "root",
    "password": "password"
  }
}

JSON.

name: My application
port: 8080
database:
  host: localhost
  user: root
  password: password

YAML.

module ApplicationConfig
name: String
port: UInt16
database: Database
class Database {
  host: String
  user: String
  password: String(isBetween(8, 40))
}
applicationConfig {
  name = "My application"
  port = 8080
  database {
    host = "localhost"
    user = "root"
    password = "password"
  }
}

Pkl.

The example above defines a module named ApplicationConfig with top-level configuration for the application, including name and port. It also defines the database class, describing the access parameters: host, user and password.

The language provides an applicationConfig instance with actual values ​​corresponding to the provided JSON example. This approach uses the power of Pkl to define structured, secure configurations. And can be extended with additional checks or functions.

The Pickle example is more “expressive” than JSON or YAML. It also includes a check to ensure that the password is at least eight characters long. You can also use operators to validate data:

isEmpty (!isEmpty)

isBetween(a, b)

==, >, <, ≥, ≤

matches(Regex("….")

Some of the Pkl operators. More information – in the documentation.

Here's what the additional validation in the configuration would look like:

module Person
name: String(!isEmpty)
age: Int(isBetween(0, 130))
zipCode: String(matches(Regex("\\d{5}")))

Pkl can interact with other languages ​​in two ways: injection and code generation. The language can be embedded as a library in Java, Kotlin, Swift, Go. For example, this is how you can load a Pkl file and access its values ​​from Java and Golang:

import com.apple.pkl.Pkl;
import com.apple.pkl.PklConfig;
import com.apple.pkl.PklException;
// Загрузка Pkl-файла
PklConfig config = Pkl.load("config.pkl");
// Доступ к значению Pkl
String host = config.getString("host");
// Изменение значения Pkl
config.set("port", 8080);
// Сохранение Pkl-файла
Pkl.dump(config, "config.pkl");
import (
"context"
"github.com/apple/pkl-go"
)
// Загрузка Pkl-файла
config, err := pkl.LoadFromPath(context.Background(), "config.pkl")
if err != nil {
panic(err)
}
// Доступ к значению Pkl
host := config.GetString("host")
// Изменение значения Pkl
config.Set("port", 8080)
// Сохранение Pkl-файла
err = pkl.Dump(config, "config.pkl")
if err != nil {
panic(err)
}

Pkl supports code generation for Java, Kotlin, Swift and Go and can “shape” classes, enums, constants and annotations based on configuration values. For example, this is how you can create a Java class from a Pkl file:

# Define a Pkl value
(def person
(dict
:name "Alice"
:age 25
:gender "female"
)
)
Generate a Java class
(pkl-codegen-java person "Person")

The generated Java class will look like this:

public class Person {
public static final String name = "Alice";
public static final int age = 25;
public static final String gender = "female";
}

Conclusion

Apple Pkl is a new programming language for simple, expressive, and portable customization. It can be useful to use in various scenarios where customization is needed, such as an application. It can also interact with other languages ​​by embedding or code generation. This is an open source project that welcomes everyone's contributions.

What do you think about Pkl? Share your opinion in the comments!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *