Writing a Library
A library packages steps for other workspaces to use. It's a directory of GCSL files in a git repository, named by an import path. This page writes a small library that greets someone using a template file of its own, tries it from a workspace, and pins it there.
Before you start #
git.- A workspace to try the library from. This page uses one at
uselib, with an emptyworkspace.gcsl.
Write the library #
-
Make a directory for the library, and a git repository in it. This page names the library
example.org/greeting, and keeps its checkout atlibsrc/example.org/greeting:A library published at
https://example.org/greetingis found there by default, as the Go modules convention has it. -
Save the template as
templates/greeting.txt:Hello, NAME, from a library -
Save the library's code as
greeting.gcsl:# Greets someone with the library's own template. #[track_caller] #[hermetic] def greet(name: String, template: File = file("templates/greeting.txt")) -> File { let made = exec(["/bin/sh", "-c", "sed 's/NAME/{name}/' {template.path} > greeting.txt"]) = working_dir().file("greeting.txt") }A library's public names are its
deffunctions, declared types, and fields;fnandletstay private to their file.#[track_caller]reports an error in the step at the caller's line, where the reader can act on it. The relative path in the default names the library's own file, wherever the library is used. -
Commit it:
Try it from a workspace #
-
In
uselib/build.gcsl, import the library and call it:import "example.org/greeting" def build hello() { = greeting.greet("world") } -
Build with
$GCSL_LIBRARY_PATHnaming the directory that holdsexample.org/:GCSL_LIBRARY_PATH=/path/to/libsrcpekit finds the library in your checkout. Edit it and build again, and pekit uses your edit.
Pin it #
-
Tell
pekit lockwhere the library's repository is. Inuselib/pekit.lock, add a source:A library published at the URL its path names needs no source.
-
Pin it, without
$GCSL_LIBRARY_PATH:
Check the result #
pekit lock prints the commit it pinned:
pinned example.org/greeting at 1b4e27f7c836186a4bfab3f74521ef642b953632
The build after it reports the step found in the store, 0 steps run, 1 found in the store. The step is keyed by the library's path and contents,
not by where pekit found it, so the result from your checkout is reused.
pekit-out/hello/greet/greeting.txt holds Hello, world, from a library.
Ask for a tool #
A library that runs a compiler or another tool should ask for it as a
toolchain, so that each workspace chooses which one. Use an existing kind,
such as Toolchain::C, or declare a kind in the library, and resolve it in
a step's parameter default. Registering
Toolchains
shows both sides.
Keep libraries apart from the workspace #
A library sees nothing of the workspace that imports it: not its
declarations, and not its files. Take anything from the workspace as an
argument. A library can import other libraries, which pekit lock pins
along with it.