🌽 A simple and pain-free configuration language.

Overview

🌽 Corn

A simple and pain-free configuration language.

Corn has been designed using inspiration from JSON and Nix to produce a language that's easy and intuitive to write, good for config files, and has a feature-set small enough you can learn it in minutes. It was born out of the following frustrations:

  • JSON is not a config language, despite how often people use it as one
  • TOML is good for flat structures but gets ugly quickly with deeper objects
  • YAML is far too complex and its whitespace rules make it error-prone

What Corn Is Not

Corn is not a full programming language and does not try to be. There are no variables, there is no interpolation and there are no statement blocks.

Likewise, Corn is not a data exchange format. Unlike JSON or YAML or TOML, you cannot serialize code back into Corn.

Usage

As a binary

Corn can be installed as an executable binary to convert files from the .corn format into any supported output format. Currently these are:

  • JSON
  • YAML
  • TOML

Windows, Linux and macOS are currently supported.

Install it using cargo:

cargo install cornfig

Then simply:

cornfig file.corn
cornfig file.corn -t yaml

As a library

Corn can be used as a Rust library to deserialize config files directly without needing to convert to other file formats.

Rust docs can be found here.

use cornfig::parse;

fn main() {
    let corn = "{foo = 42}";

    let config = parse(corn).unwrap();
    let json = serde_json::to_string_pretty(&config.value).unwrap();

    assert_eq!(json, "{\"foo\": 42}");
}

Writing Corn

This section gives all the outputs in JSON format. Remember you can output in any supported format!

All Corn files must contain a top-level object that contains keys/values. Keys must be alphanumeric and do not need quotes around them. Values must be one of the following:

  • String
  • Integer
  • Float
  • Boolean
  • Object
  • Array
  • Null
  • Input

A very basic example therefore would be:

{
    hello = "world"
}

Which of course maps to the following in JSON:

{
  "hello": "world"
}

A more complex example would be something like a package.json. This makes use of inputs, various other data types and key chaining:

let {
    $entry = "dist/index.js"
    $author = { name = "John Smith" email = "[email protected]" }
} in {
    name = "example-package"
    version = "1.0.0"
    main = $entry
    bin.executable = $entry
    private = false
    
    author = $author
    author.url = "https://example.com" 
    
    contributors = [ $author ]
    
    scripts.build = "tsc"
    scripts.run = "node dist"
    
    dependencies = {
        dotenv = "^8.2.0"
        // put the rest of your deps here...
    }
    
    devDependencies.typescript = "^4.5"
}
This output's a bit longer than the others, so click here to expand it and have a look.
{
  "author": {
    "email": "[email protected]",
    "name": "John Smith",
    "url": "https://example.com"
  },
  "bin": {
    "filebrowser": "dist/index.js"
  },
  "contributors": [
    {
      "email": "[email protected]",
      "name": "John smith"
    }
  ],
  "dependencies": {
    "dotenv": "^8.2.0"
  },
  "devDependencies": {
    "typescript": "^4.5"
  },
  "main": "dist/index.js",
  "name": "example-package",
  "private": false,
  "scripts": {
    "build": "tsc",
    "run": "node dist"
  },
  "version": "1.0.0"
}

Types

String

Strings must be surrounded by double quotes. All unicode is supported.

foo = "bar"

Integer

Integers are signed and 64 bit, meaning you can use any value between -9223372036854775808 and 9223372036854775807.

answer = 42

Float

Double precision (64-bit) floats are used.

pi = 3.14159

Boolean

As you'd expect.

not_false = true

Object

Objects use braces to mark the start and end. They contain key/value pairs.

There is no restriction on nesting objects within objects or arrays.

{
  foo = "bar"
  hello = "world"
}

Array

Arrays use square brackets to mark the start and end. Values are space-separated. Like objects, there is no restriction on nesting arrays or objects inside.

    array = [ 1 2 3 ]

You can also include whitespace as you please and mix element types:

{
    array = [ 1 2 3 ]
    array2 = [
        "one"
        2
        true
        { three = 3 }
    ]
}

The above converts to the following JSON:

{
  "array": [
    1,
    2,
    3
  ],
  "array2": [
    "one",
    2,
    true,
    {
      "three": 3
    }
  ]
}

Null

Null values simply use the null keyword:

foo = null

Inputs

Sometimes it may be useful to store some values at the top of the config file, and use or re-use them later on, or even use them to compose more complex values. Corn supports config inputs, akin to variables but they don't change.

All input names start with a dollar sign $ followed by an alphabetic ASCII character or an underscore _. This can then be followed by any amount of alphanumeric ASCII characters or underscores.

Inputs can be used to store any value type, or inside strings.

To declare inputs, you must include a let { } in block at the start of your config.

let { 
    $firstName = "John"
    $lastName = "Smith" 
    
    $birthday = {
        day = 1
        month = 1
        year = 1970
    }
    
} in {
    name = {
        first = $firstName
        last = $lastName
    }
    
    dob = $birthday
}

As well as declaring your own inputs, you can also access any environment variables by prefixing input names with $env_. For example, to use the system PATH:

{
    path = $env_PATH
}

Will output something similar to:

{
  "path": "/home/jake/.cargo/bin:/home/jake/.local/bin:/usr/local/bin:/usr/bin"
}

Environment variable inputs will fall back to regular inputs of the same name, allowing you to create defaults.

Inputs are intentionally quite limited as to what they can do - if you need more power you should use a full language. That said, they hopefully provide a way of quickly viewing/changing values without needing to trawl through the whole file.

Comments

At any point you can start a comment using //. A comment is terminated by a newline \n character. Comments are entirely ignored and not included in the output.

{
    // this is a single-line comment
    foo = bar // this is a mixed-line comment
}

Nesting Keys

Throughout the page, we've created objects within objects using a syntax like this:

{
    foo = {
        bar = "baz"
    }
}

While this is okay for short cases, it can get tiresome very fast and the braces add a lot of noise when reading.

To solve this, keys can be chained to create deep objects instantly:

{
    foo.bar = "baz"
}

Which in JSON is:

{
  "foo": {
    "bar": "baz"
  }
}

You can mix and match chained keys with nested objects at any time:

{
    foo = {
        bar.baz = 42
        qux = true
    }
    
    foo.quux = [ "green eggs" "ham" ]
}

JSON:

{
  "foo": {
    "bar": {
      "baz": 42
    },
    "qux": true,
    "quux": ["green eggs", "ham"]
  }
}

Whitespace

Almost all whitespace in Corn is optional, since keywords and types end as soon as they end. There are only a few exceptions to this:

  • An integer or float following an integer or float must be whitespace separated to tell where one ends and the next starts.
  • References to inputs must terminate with whitespace as otherwise the parser cannot tell where the name ends.

This means the below is perfectly valid (although for general consistency and readability this is strongly not recommended):

{
    one={foo="bar"bar="foo"}
    two={foo=1bar=2}
    three={foo=1.0bar=2.0}
    four={foo=truebar=false}
    five={foo=nullbar=null}
    six={foo={}bar={}}
    seven={foo=[]bar=[]}

    eight=["foo""bar"]
    nine=[truefalse]
    ten=[nullnull]
    eleven=[[][]]
    twelve=[{}{}]
}

And in fact, we could even go as far as to reduce that to a single line:

{one={foo="bar"bar="foo"}two={foo=1bar=2}three={foo=1.0bar=2.0}four={foo=truebar=false}five={foo=nullbar=null}six={foo={}bar={}}seven={foo=[]bar=[]}eight=["foo""bar"]nine=[truefalse]ten=[nullnull]eleven=[[][]]twelve=[{}{}]}

Syntax Highlighting

Contributing

Contributions are very welcome, although please do open an issue first as not every potential feature will get merged.

At the moment Corn is in very early stages. If you'd like to help out, I'd absolutely love to see the following:

  • More output formats
  • Improvements and fixes to existing features
  • More tests
  • Better documentation

Running Tests

You must set CORN_TEST=foobar as this is required for the environment variable tests.

You might also like...
hosts file parsing, modification library, and some derivatives.

hosts-rs hosts: Hosts file parsing, modification library resolve-github: Use Cloudflare DoH to resolve GitHub domains and generate hosts files github-

Kusion Configuration Language (KCL) is an open source configuration language mainly used in Kusion Stack

Kusion Configuration Language (KCL) is an open source configuration language mainly used in Kusion Stack. KCL is a statically typed language for configuration and policy scenarios, based on concepts such as declarative and Object-Oriented Programming (OOP) paradigms.

(WIP) Taking the pain away from file (de)compression

Ouch! ouch loosely stands for Obvious Unified Compression files Helper and aims to be an easy and intuitive way of compressing and decompressing files

Maniplate `&'static str` (e.g., `concat!`, `format!`) in Rust without pain!

static_str_ops The static_str_ops crate solves a longstanding issue about how to perform non-const string operations, e.g., format!(), concat!(), etc.

Sero is a web server that allows you to easily host your static sites without pain. The idea was inspired by surge.sh but gives you full control.

sero Lightning-fast, static web publishing with zero configuration and full control 📖 Table Of Contents 📖 Table Of Contents 🔧 Tools ❓ About The Pro

A systemd-boot configuration and boot entry configuration parser library

A systemd-boot configuration and boot entry configuration parser library

A rust layered configuration loader with zero-boilerplate configuration management.

salak A layered configuration loader with zero-boilerplate configuration management. About Features Placeholder Key Convension Cargo Features Default

wireguard tool to manage / generate configuration. Maintain one yaml configuration file to quickly build wireguard network.

wgx wireguard tool to manage / generate configuration. Maintain one yaml configuration file to quickly build wireguard network. Usage wgx --h USAGE:

A Rust crate for hassle-free Corosync's configuration file parsing

corosync-config-parser A Rust crate for hassle-free Corosync's configuration file parsing. Inspired by Kilobyte22/config-parser. Usage extern crate co

Use free svg icons in your Dioxus projects easily with dioxus-free-icons.

dioxus-free-icons Use free svg icons in your Dioxus projects easily with dioxus-free-icons. More information about this crate can be found in the crat

A lock-free, partially wait-free, eventually consistent, concurrent hashmap.
A lock-free, partially wait-free, eventually consistent, concurrent hashmap.

A lock-free, partially wait-free, eventually consistent, concurrent hashmap. This map implementation allows reads to always be wait-free on certain pl

Provide free GPT-3.5 API service by reverse engineering the login-free ChatGPT website.

ChatGPT Free API Provide free GPT-3.5 API service by reverse engineering the login-free ChatGPT website. Note: This service requires the IP to be able

A dead simple configuration language.

Rakh! A dead simple configuration language. No seriously, it's simple. With only 26 lines of code, it's one of the tiniest configuration languages the

Swayidle alternative to handle wayland idle notifications, sleep and lock events in Rust with Lua scripting based configuration language

swayidle-rs This is intended as a replacement of sway's idle management daemon. I use it as a tool to understand rust message passing and state manage

Rust API Server: A versatile template for building RESTful interfaces, designed for simplicity in setup and configuration using the Rust programming language.
Rust API Server: A versatile template for building RESTful interfaces, designed for simplicity in setup and configuration using the Rust programming language.

RUST API SERVER Introduction Welcome to the Rust API Server! This server provides a simple REST interface for your applications. This README will guid

Ryan: a configuration language for the practical programmer
Ryan: a configuration language for the practical programmer

Ryan: a configuration language for the practical programmer Say hello to Ryan! Ryan is a minimal programming language that produces JSON (and therefor

Zap - A simple cross-platform configuration management and orchestration tool

Zap - A simple cross-platform orchestration and configuration management tool. The main goal for Zap is to a simple mechanism for managing groups of com

zzhack-cli is a Command Tool to help you quickly generate a WASM WebApp with simple configuration and zero code
zzhack-cli is a Command Tool to help you quickly generate a WASM WebApp with simple configuration and zero code

English | 中文文档 zzhack-cli is a Command Tool that can help you quickly generate a WASM WebApp with simple configuration and zero code. It's worth menti

A simple configuration-based module for inter-network RPC in Holochain hApps.

DNA Auth Resolver A simple configuration-based module for inter-network RPC in Holochain hApps. About Usage In the origin zome In the destination DNA

Comments
  • Allow for more characters in keys

    Allow for more characters in keys

    Lots of things need more than alphanumeric strings in keys. Hyphens would be especially useful. Full unicode should maybe be allowed if keys are quoted.

    This is currently limiting Corn's use in ironbar.

    enhancement 
    opened by JakeStanger 1
  • Ability to deserialize into a struct

    Ability to deserialize into a struct

    Currently cornfig::parse returns the a tree of parsed values which isn't super useful for library use. A serde::Deserializer implementation should be written to attempt to deserialize into structs.

    It's possible to serialize the Corn output using serde then deserialize it again, but this comes with a lot of overhead and requires shipping another format library.

    enhancement 
    opened by JakeStanger 1
  • TOML output support

    TOML output support

    The #[serde(untagged)] attribute causes the TOML serializer to fail, but is required to produce valid JSON/YAML. TOML also does not support any kind of null value so serde fails to serialize None values. At the moment this means TOML is not supported.

    opened by JakeStanger 0
  • Improved error handling

    Improved error handling

    The error code is a little messy at the moment, and the library makes heavy use of unwrap. Error code should be refactored and the parser/deserializer should not panic anywhere.

    enhancement 
    opened by JakeStanger 0
Releases(v0.6.1)
  • v0.6.1(Dec 12, 2022)

    :bug: Bug Fixes

    • b6e93b2 - lib: deserializer not handling invalid inputs (commit by @JakeStanger)

    :recycle: Refactors

    • 21e1ee0 - tidy error handling (commit by @JakeStanger)

    :memo: Documentation Changes

    • 9dbb9d6 - update CHANGELOG.md for v0.6.0 [skip ci] (commit by @JakeStanger)
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Nov 28, 2022)

    :sparkles: New Features

    • 7a2f7b5 - de: from_slice func (commit by @JakeStanger)

    :bug: Bug Fixes

    • e6c8e90 - de: from_str panicking instead of returning result (commit by @JakeStanger)
    • 7ea024d - parser: panic when input references another input (commit by @JakeStanger)
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Nov 27, 2022)

    :sparkles: New Features

    • 9fbf1b0 - serde deserialization support (commit by @JakeStanger)

    :white_check_mark: Tests

    • d035fa2 - update test assets (commit by @JakeStanger)

    :memo: Documentation Changes

    • d4e283c - update CHANGELOG.md for v0.5.0 [skip ci] (commit by @JakeStanger)
    Source code(tar.gz)
    Source code(zip)
Owner
Jake Stanger
I mostly do web development. Front and back end. I also do lots of Linux stuff.
Jake Stanger
A systemd-boot configuration and boot entry configuration parser library

A systemd-boot configuration and boot entry configuration parser library

Kaiyang Wu 2 May 22, 2022
Zap - A simple cross-platform configuration management and orchestration tool

Zap - A simple cross-platform orchestration and configuration management tool. The main goal for Zap is to a simple mechanism for managing groups of com

R. Tyler Croy 50 Oct 29, 2022
Just-config is a configuration library for rust

Config Library for Rust Just-config is a configuration library for rust. It strives for the old Unix mantra "Do one thing and to it well".

FlashSystems 7 Apr 15, 2022
Uclicious is a flexible reduced boilerplate configuration framework.

Uclicious What is Uclicious Usage Raw API Derive-driven Validators Type Mapping Supported attributes (#[ucl(..)]) Structure level Field level Addition

Andrey Cherkashin 14 Aug 12, 2022
A Rust library for processing application configuration easily

Configure me A Rust library for processing application configuration easily About This crate aims to help with reading configuration of application fr

Martin Habovštiak 48 Dec 18, 2022
⚙️ Layered configuration system for Rust applications (with strong support for 12-factor applications).

config-rs Layered configuration system for Rust applications (with strong support for 12-factor applications). Set defaults Set explicit values (to pr

Ryan Leckey 1.8k Jan 9, 2023
cfg-rs: A Configuration Library for Rust Applications

cfg-rs: A Configuration Library for Rust Applications Major Features One method to get all config objects, see get. Automatic derive config object, se

Daniel YU 20 Dec 16, 2022
Next-GEN Confguration Template Generation Language

Sap lang yet another configuration oriented language name comes from Sapphire which is the birthstone of september Language Feature the last expr of t

LemonHX 12 Aug 8, 2022
Next-GEN Confguration Template Generation Language

Sap lang yet another configuration oriented language name comes from Sapphire which is the birthstone of september Language Feature the last expr of t

Sap-Lang 12 Aug 8, 2022
[Proof of Concept] Embedded functional scripting language with YAML ¯\_(ツ)_/¯

[YAML, fun] Just an experimental project implementing embedded functional scripting language based on YAML syntax. API docs for the standard library:

Arijit Basu 12 Aug 15, 2022