Korr

CLI apps and the korr command

Docs index

The korr command

Command What it does
korr <file.krr> [args...] Run a script. Arguments after the file go to os.args().
korr run <file.krr> [args...] Same as above.
korr -e "<code>" Run inline code.
korr repl Interactive shell (empty line ends a block, exit quits).
korr check <file.krr> Parse and resolve names without running anything. Great in CI and editors.
korr test [path] Run test_* functions in every *_test.krr file under path (default .).
korr build <file.krr> [-o out] [--runtime bin] Bundle a program and all its imports into one executable.
korr new <name> Create a full-stack starter project.
korr setup [--prefix dir] [--editors-only] [--uninstall] Install this korr on the PATH and add editor support.
korr init / korr add <source> / korr install / korr remove <name> / korr list Manage packages.
korr version / korr help Version / usage.

Exit codes: 0 success, 1 runtime or compile error (or failing tests), 2 usage error. os.exit(n) sets your own.

Environment variables: NO_COLOR=1 disables colours, KORR_DEBUG=1 shows handler error messages in HTTP 500 responses.

Writing a CLI tool

// todo.krr. Usage: korr todo.krr add "Buy milk" | list | done 1
const FILE = "{__dir__}/todos.json"

fn load()
    return fs.exists(FILE) ? json.decode(fs.read(FILE)) : []

fn save(items)
    fs.write(FILE, json.encode(items, true))

let args = os.args()
let items = load()

match args.get(0)
    "add" =>
        let title = args[1..].join(" ")
        if title == ""
            print("usage: todo add <title>")
            os.exit(2)
        items.push({ title, done: false })
        save(items)
        print("added #{len(items)}: {title}")
    "list" =>
        for i, item in items
            print("{i + 1}. [{item.done ? "x" : " "}] {item.title}")
    "done" =>
        let n = int(args.get(1, ""), 0)
        if n < 1 or n > len(items)
            print("no todo #{args.get(1, "?")}")
            os.exit(1)
        items[n - 1].done = true
        save(items)
    _ =>
        print("usage: todo <add TITLE | list | done N>")

Useful building blocks:

Arguments and options

cli.parse turns a short description of your program into a real command-line interface: options with short and long names, typed values, defaults, positional arguments, a generated --help, and clear errors with exit code 2.

// no-check
// count.krr: counts lines in source files
let opts = cli.parse({
    about: "Count lines of code in a folder",
    options: {
        ext: { short: "e", type: "str", default: "krr", help: "file extension to count" },
        top: { short: "n", type: "int", default: 3, help: "how many files to show" },
        quiet: { short: "q", help: "only print the total" },
    },
    args: ["folder?"],
})

let files = fs.glob("{opts.folder ?? "."}/**/*.{opts.ext}")
let counts = files.map(fn(f) => { file: f, lines: len(fs.read(f).lines()) }).sort(fn(c) => -c.lines)
if not opts.quiet
    for c in counts.take(opts.top)
        print(term.cyan(str(c.lines).pad_start(6)), c.file)
print(term.bold("total"), counts.map(fn(c) => c.lines).sum(), "lines in", len(files), "files")
$ korr count.krr --help
Count lines of code in a folder

Usage: count [options] [folder]

Options:
  -e, --ext <text>  file extension to count (default: krr)
  -n, --top <int>   how many files to show (default: 3)
  -q, --quiet       only print the total
  -h, --help        show this help

$ korr count.krr tests -n 2
   358 tests/language_test.krr
   176 tests/stdlib_test.krr
total 849 lines in 5 files
$ korr count.krr -n many
error: --top expects a whole number, got 'many'

Test argument handling by passing the arguments yourself and exit: false, so mistakes become catchable UsageErrors: cli.parse({ ..., exit: false }, ["-n", "2"]).

Colors and terminal output

term.red(text), term.green(text), term.bold(text) and friends style text when the output is a terminal, and leave it plain when it is piped to a file or another program, or when NO_COLOR is set. term.strip removes styles, term.width() gives the terminal width. See term.

korr test

Any file named *_test.krr is a test file. Every top-level function whose name starts with test_ is a test; it passes if it returns without an error.

// math_test.krr
fn test_addition()
    assert_eq(1 + 1, 2)

fn test_division_by_zero_is_an_error()
    let failed = false
    try
        print(1 / 0)
    catch err
        failed = err.kind == "ZeroDivisionError"
    assert(failed, "expected ZeroDivisionError")
$ korr test
./math_test.krr
  PASS test_addition (0.0ms)
  PASS test_division_by_zero_is_an_error (0.0ms)

2 passed, 0 failed (0.00s)

Helper functions must not start with test_. Test files can import the code under test (import "./main.krr" as main); guard server start-up with os.is_main().

korr build: ship a single executable

korr build tool.krr                 # creates ./tool   (tool.exe on Windows)
korr build tool.krr -o bin/tool
./bin/tool add "works without Korr installed"

The bundle contains the Korr runtime plus the source of the entry file and every module it imports (all are compiled first, so a bundle never contains a syntax or name error). Imports must stay inside the project folder. Data files you read with fs and static web folders are not bundled; ship them next to the executable.

To build for another operating system, pass that platform’s korr binary as the runtime (see Building Korr from source):

korr build tool.krr --runtime dist/korr-windows-x86_64.exe -o tool.exe

Previous: Databases Docs index Next: Packages