Luce packages
LuceLuce BaseLuciaOS

dymokomi/luc

Source of release 0.24.3

0.24.3 / src / main.lucb

#==============================================================================================
#
#   luc - The Luce project tool
#
#   DESCRIPTION:
#       One command for a Luce project: build, run, test, check and format it through the Luce
#       compiler, and run the named workflows in its package.prisma tasks. luc finds the project
#       by walking up to the nearest package.prisma, picks the compiler from the package language
#       (luce-base or luce, overridable with LUCE_BASE / LUCE), and forwards the compiler's own
#       output and exit code. This is the MVP surface; scaffolding, dependencies, task
#       dependency graphs and workspaces follow (see README).
#
#==============================================================================================

import c
import io
import os
from luce_std import files, paths
import platform
from luce_std import process
import strings
import memory
from luce_pkg import pkg
import credentials
import checkout
import project_file
import packages
import registry_http
import apps
import progress
import package_tests
import release as releasing
from luce_git import git
from luce_crypto import native as crypto_native


## The only registry account for now; `luc init` writes it as the package owner.
let default_owner = "dymokomi"

## A command-line or manifest problem the user can fix.
pub let usage_error: ErrorCode = ErrorCode.package(1)

# A scratch buffer for one interpolated error message at a time (errors are terminal).
var message_buffer: u8[512]

# mark: The project ===========================================================================

## One `[tasks]` workflow: its name, the shell command it runs, an optional one-line
## description, and the tasks it depends on (run first).
struct Task:
    var name: str
    var command: str
    var description: str
    var depends: str[]

## A loaded project: where it is, the package identity, the chosen entry, and its tasks.
struct Project:
    var root: str
    var name: str
    var language: str
    var entry: str
    ## The source root under `root`, `src` unless the manifest names another.
    var source: str
    var tasks: Task[]
    var task_count: usize

    func close():
        strings.release(self.root)
        strings.release(self.name)
        strings.release(self.language)
        strings.release(self.entry)
        strings.release(self.source)
        for i in 0..<self.task_count:
            strings.release(self.tasks[i].name)
            strings.release(self.tasks[i].command)
            strings.release(self.tasks[i].description)
            for dependency in self.tasks[i].depends: strings.release(dependency)
            if self.tasks[i].depends.length > 0: free(self.tasks[i].depends) in memory.heap
        if self.tasks.length > 0: free(self.tasks) in memory.heap
        self.task_count = 0

    ## The compiler for this project's language, overridable through the environment.
    func compiler() -> str!:
        if self.language == "luce":
            return try toolchain_compiler("luce", "LUCE")
        return try toolchain_compiler("luce-base", "LUCE_BASE")

    ## The entry source: the manifest's `entry`, else the conventional app main, else the
    ## library's starter module (src/<module>.<ext>) so `check` works on a package.
    func entry_path() -> str!:
        let found = try self.starter()
        return found else error(usage_error, "no entry source found (expected src/main or src/<module>, the last word of the package's name); set entry in package.prisma")

    ## The entry source as `entry_path` finds it, or none for a library without a module
    ## named after the package.
    func starter() -> str?!:
        if self.entry.length > 0:
            return try join(self.root, self.entry)
        let suffix = ".luc" if self.language == "luce" else ".lucb"
        let main_name = try join_name("main", suffix)
        defer strings.release(main_name)
        let library = try project_file.library_module(self.name)
        defer strings.release(library)
        let module_name = try join_name(library, suffix)
        defer strings.release(module_name)
        let module = try paths.join("src", module_name)
        defer module.release()
        let application = try paths.join("src", main_name)
        defer application.release()
        for relative in [application.value, main_name, module.value]:
            let candidate = try join(self.root, relative)
            let terminated = try strings.copy(candidate)
            let exists = files.exists((c.str)terminated)
            strings.release(terminated)
            if exists: return candidate
            strings.release(candidate)
        return none

    func find_task(name: str) -> Task?:
        var index: usize = 0
        while index < self.task_count:
            if self.tasks[index].name == name:
                return self.tasks[index]
            index += 1
        return none

# mark: Loading the project ====================================================================

## Find the nearest package.prisma from the current directory upward, load it, and
## remove any stale luce.toml. Absent one, the project is an anonymous
## luce-base app rooted at the current directory.
## `registry` loads a package that was downloaded from the registry, so every dependency,
## including ones its author overrides with a local path, comes from the registry.
func load_project(prepare: bool = true, directory_hint: str = "", registry: bool = false) -> Project!:
    let start = try strings.copy(directory_hint) if directory_hint.length > 0 else try os.cwd()
    defer strings.release(start)
    var project = Project(root = try strings.copy(start), name = try strings.copy("app"),
        language = try strings.copy("luce-base"), entry = try strings.copy(""), source = try strings.copy("src"))
    errdefer project.close()
    project.tasks = try new Task[128] ---
    var directory = start
    while true:
        if try project_file.exists_in(directory):
            strings.release(project.root)
            project.root = try strings.copy(directory)
            try apply_definition(&project)
            if prepare: try packages.prepare(project.root, registry)
            try project_file.generate(project.root, project.root, registry)
            return project
        let parent = paths.directory(directory)
        if parent == directory or parent.length == 0:
            return project
        directory = parent

func apply_definition(project: Project*) -> !:
    var definition = try project_file.read(project.root)
    defer definition.close()
    try replace_text(&project.name, definition.name)
    try replace_text(&project.language, definition.language)
    try replace_text(&project.entry, definition.entry)
    try replace_text(&project.source, definition.source)
    for i in 0..<definition.task_count:
        let declared = try definition.task_at(i)
        let slot = try task_slot(project, declared.name)
        try replace_text(&project.tasks[slot].command, declared.command)
        try replace_text(&project.tasks[slot].description, declared.description)
        var depends: str[]
        for j in 0..<declared.depend_count:
            depends = try append(depends, try strings.copy(declared.depends[j]))
        project.tasks[slot].depends = depends

## Parse the little of luce.toml luc needs: [package] name/language/entry and [tasks]
## name = "command" pairs. Values are quoted strings; comments and blank lines are ignored.
func parse_manifest(project: Project*, text: str) -> !:
    var section = ""
    let lines = try strings.split(text, '\n')
    defer free(lines) in memory.heap
    for raw in lines:
        let line = strings.trim(raw)
        if line.length == 0 or strings.starts_with(line, "#"):
            continue
        if strings.starts_with(line, "["):
            section = strings.trim(strip(line, "[", "]"))
            continue
        let (key_raw, value_raw) = strings.split_once(line, "=") else continue
        let key = strings.trim(key_raw)
        let value = unquote(strings.trim(value_raw))
        if section == "package":
            if key == "name":
                try replace_text(&project.name, value)
            elif key == "language":
                try replace_text(&project.language, value)
            elif key == "entry":
                try replace_text(&project.entry, value)
        elif section == "tasks":
            let slot = try task_slot(project, key)
            try replace_text(&project.tasks[slot].command, value)
        elif strings.starts_with(section, "tasks."):
            let slot = try task_slot(project, (str)section.bytes[6..])
            if key == "cmd":
                try replace_text(&project.tasks[slot].command, value)
            elif key == "description":
                try replace_text(&project.tasks[slot].description, value)
            elif key == "depends":
                let replacement = try string_array(value)
                for dependency in project.tasks[slot].depends: strings.release(dependency)
                if project.tasks[slot].depends.length > 0: free(project.tasks[slot].depends) in memory.heap
                project.tasks[slot].depends = replacement

func replace_text(target: str*, value: str) -> !:
    let replacement = try strings.copy(value)
    strings.release(*target)
    *target = replacement

func unquote(text: str) -> str:
    if text.length >= 2 and strings.starts_with(text, "\"") and strings.ends_with(text, "\""):
        return (str)text.bytes[1..<text.length - 1]
    return text

func strip(text: str, open: str, close: str) -> str:
    var inner = text
    if strings.starts_with(inner, open):
        inner = (str)inner.bytes[open.length..]
    if strings.ends_with(inner, close):
        inner = (str)inner.bytes[..<inner.length - close.length]
    return inner

## The index of the task named `name`, creating an empty one when it is new; a task can be
## introduced by a plain [tasks] line or a [tasks.<name>] subtable, in any order.
func task_slot(project: Project*, name: str) -> usize!:
    var index: usize = 0
    while index < project.task_count:
        if project.tasks[index].name == name:
            return index
        index += 1
    if project.task_count >= project.tasks.length:
        error(usage_error, "too many tasks in package.prisma")
    let owned_name = try strings.copy(name)
    errdefer strings.release(owned_name)
    let command = try strings.copy("")
    errdefer strings.release(command)
    let description = try strings.copy("")
    errdefer strings.release(description)
    project.tasks[project.task_count] = Task(name = owned_name, command = command, description = description)
    project.task_count += 1
    return project.task_count - 1

## Parse a `["a", "b"]` TOML string array into a slice; empty items are dropped.
func string_array(value: str) -> str[]!:
    let inner = strip(strings.trim(value), "[", "]")
    var result: str[]
    let parts = try strings.split(inner, ',')
    defer free(parts) in memory.heap
    for part in parts:
        let item = unquote(strings.trim(part))
        if item.length > 0:
            result = try append(result, try strings.copy(item))
    return result

# mark: Running things =========================================================================

## Run `program` with `arguments`, forwarding its output and returning its exit code. Dynamic
## strings become NUL-terminated copies so they cross the process boundary as `c.str`.
func spawn(program: str, arguments: str[]) -> i32!:
    let program_text = try strings.copy(program)
    defer strings.release(program_text)
    let argv = try new c.str[arguments.length] ---
    var index: usize = 0
    defer release_spawn_arguments(argv, index)
    while index < arguments.length:
        argv[index] = (c.str)try strings.copy(arguments[index])
        index += 1
    let ran = try process.run((c.str)program_text, argv)
    defer ran.release()
    if ran.value.output.length > 0:
        try io.stdout().write(ran.value.output)
    if ran.value.error_output.length > 0:
        try io.stderr().write(ran.value.error_output)
    return ran.value.exit_code

func release_spawn_arguments(arguments: c.str[], count: usize):
    for i in 0..<count: strings.release((str)arguments[i])
    if arguments.length > 0: free(arguments) in memory.heap

## `left` and `right` joined, as text the caller releases with strings.release.
func join(left: str, right: str) -> str!:
    let joined = try paths.join(left, right)
    defer joined.release()
    return try strings.copy(joined.value)

## How `luc build` and `luc run` build: `--release` optimises; `--diagnostic` builds with
## the compiler's diagnostic profile, which fills unwritten storage with 0xAA and makes the
## allocators catch double frees and writes after free.
struct BuildMode:
    var release: bool
    var diagnostic: bool

## The build flags among `words`, `--release` and `--diagnostic`; `command` names the
## command in the usage error any other word gets.
func build_mode(words: str[], command: str) -> BuildMode!:
    var mode = BuildMode(release = false, diagnostic = false)
    for word in words:
        if word == "--release":
            mode.release = true
        elif word == "--diagnostic":
            mode.diagnostic = true
        else:
            error(usage_error, try strings.format(message_buffer[0..], f"usage: luc {command} [--release] [--diagnostic] [-- args]"))
    return mode

## The project's build output path under its root: build/<name>, or build/<name>-diagnostic
## for the diagnostic profile, so the two builds never replace each other.
func output_path(project: Project*, diagnostic: bool) -> str!:
    let directory = try paths.join(project.root, "build")
    defer directory.release()
    if not diagnostic:
        return try join(directory.value, project.name)
    let name = try join_name(project.name, "-diagnostic")
    defer strings.release(name)
    return try join(directory.value, name)

## Build the project's entry into build/<name> under the project root, or with `--diagnostic`
## into build/<name>-diagnostic, which is never bundled as an application.
func build(project: Project*, mode: BuildMode, extra: str[]) -> i32!:
    let entry = try project.entry_path()
    defer strings.release(entry)
    try ensure_build(project)
    let output = try output_path(project, mode.diagnostic)
    defer strings.release(output)
    var arguments: str[]
    defer release_string_array(arguments)
    for word in ["build", entry, "--native", "-o", output]:
        arguments = try append(arguments, word)
    if mode.release:
        arguments = try append(arguments, "--release")
    if mode.diagnostic:
        arguments = try append(arguments, "--profile")
        arguments = try append(arguments, "diagnostic")
    let combined = try concat(arguments, extra)
    defer release_string_array(combined)
    var label: u8[160]
    let status = try progress.run(try strings.format(label, f"compiling {project.name}"), try project.compiler(), combined)
    if status != 0 or mode.diagnostic or not try project_file.exists_in(project.root): return status
    # A declared application is also wrapped as Name.app / Name.AppDir beside the executable.
    var definition = try project_file.read(project.root)
    defer definition.close()
    if definition.is_bundled(): try apps.bundle(project.root, &definition)
    return status

func ensure_build(project: Project*) -> !:
    let directory = try paths.join(project.root, "build")
    defer directory.release()
    if not files.exists((c.str)directory.value):
        try files.create_directory((c.str)directory.value)

## Build, then run the produced binary with `arguments`.
func run_app(project: Project*, mode: BuildMode, arguments: str[]) -> i32!:
    var no_extra: str[]
    let status = try build(project, mode, no_extra)
    if status != 0:
        return status
    let executable = try output_path(project, mode.diagnostic)
    defer strings.release(executable)
    return try spawn(executable, arguments)

## A task run in progress: the tasks already finished (each runs once) and the tasks on the
## current dependency chain (to catch a cycle).
struct Runner:
    var project: Project*
    var done: str[]
    var done_count: usize
    var active: str[]
    var active_count: usize

## Run task `name`, its `depends` first (each at most once), forwarding `passthrough` only to
## the named target. Fails on an unknown task or a dependency cycle.
func run_task(project: Project*, name: str, passthrough: str[]) -> i32!:
    var runner = Runner(project = project)
    runner.done = try new str[project.task_count + 1] ---
    runner.active = try new str[project.task_count + 1] ---
    return try run_graph(&runner, name, passthrough, true)

func run_graph(runner: Runner*, name: str, passthrough: str[], target: bool) -> i32!:
    var index: usize = 0
    while index < runner.done_count:
        if runner.done[index] == name:
            return 0
        index += 1
    index = 0
    while index < runner.active_count:
        if runner.active[index] == name:
            error(usage_error, try strings.format(message_buffer[0..], f"task dependency cycle at '{name}'"))
        index += 1
    let task = runner.project.find_task(name) else error(usage_error, try strings.format(message_buffer[0..], f"no task named '{name}'"))
    runner.active[runner.active_count] = name
    runner.active_count += 1
    for dependency in task.depends:
        var none_args: str[]
        let dependency_status = try run_graph(runner, dependency, none_args, false)
        if dependency_status != 0:
            return dependency_status
    var args: str[]
    if target:
        args = passthrough
    let status = try run_command(task.command, args)
    runner.active_count -= 1
    runner.done[runner.done_count] = name
    runner.done_count += 1
    return status

## Run a task's command through the host's shell (so `&&`, pipes and redirects work),
## forwarding `args`. POSIX uses `sh -c`, Windows uses `cmd /c`, so tasks run on either.
func run_command(command: str, args: str[]) -> i32!:
    if platform.windows:
        # cmd has no `$@`; append the arguments to the command line, space separated.
        var windows: str[]
        windows = try append(windows, "/c")
        windows = try append(windows, try join_with(command, args))
        return try spawn("cmd", windows)
    # sh -c "<command> \"$@\"" sh <args>: the args become $1.. so "$@" forwards them.
    var script = command
    if args.length > 0:
        var buffer: u8[2048]
        script = try strings.copy(try strings.format(buffer[0..], f"{command} \"$@\""))
    var argv: str[]
    for word in ["-c", script, "sh"]:
        argv = try append(argv, word)
    return try spawn("sh", try concat(argv, args))

## `command` followed by each argument, space separated, as one command line.
func join_with(command: str, args: str[]) -> str!:
    var parts: str[]
    parts = try append(parts, command)
    return try strings.join(try concat(parts, args), " ")

## A two-word argument list as a slice (fixed-size literals do not coerce to `str[]`).
func two(first: str, second: str) -> str[]!:
    var result: str[]
    result = try append(result, first)
    result = try append(result, second)
    return result

func list_tasks(project: Project*) -> !:
    if project.task_count == 0:
        try io.stdout().write("no tasks are defined in package.prisma\n")
        return
    try io.stdout().write("tasks:\n")
    var index: usize = 0
    while index < project.task_count:
        let task = project.tasks[index]
        if task.description.length > 0:
            try io.stdout().write(f"  {task.name}  -  {task.description}\n")
        else:
            try io.stdout().write(f"  {task.name}\n")
        index += 1

# mark: Dependencies ==========================================================================

# mark: Applications ===========================================================================

## `luc install <owner>/<name>[@<version>]`: fetch, build and install an application.
var owner_buffer: u8[128]
var coordinate_buffer: u8[256]

## `owner/name` as given, or a bare `name` with the owner of the one registry package
## of that name: `luc install luced-2d` when no one else publishes a luced-2d.
func qualified(wanted: str) -> str!:
    if strings.contains(wanted, "/"): return wanted
    let owner = try packages.owner_of(wanted, owner_buffer[0..], message_buffer[0..])
    return try strings.format(coordinate_buffer[0..], f"{owner}/{wanted}")

## `luc latest [owner/]name`: the newest released version, alone on a line, for
## applications that tell their users of an update.
func latest_command(own: str[]) -> i32!:
    if own.length != 1: error(usage_error, "usage: luc latest [<owner>/]<name>")
    let (owner, name) = strings.split_once(try qualified(own[0]), "/") else error(usage_error, "usage: luc latest [<owner>/]<name>")
    var buffer: u8[64]
    let version = try packages.latest(owner, name, buffer)
    try io.stdout().write(f"{version}\n")
    return 0

func install_command(own: str[], updating: bool = false) -> i32!:
    # `--dev` installs the package's whole tree, its tests and dev paths included.
    let development = has(own, "--dev")
    var wanted: str = ""
    var count: usize = 0
    for argument in own:
        if argument != "--dev":
            wanted = argument
            count += 1
    if count != 1: error(usage_error, "usage: luc install [<owner>/]<name>[@<version>] [--dev]")
    let (given, requirement) = strings.split_once(wanted, "@") else (wanted, "")
    let coordinate = try qualified(given)
    let (owner, name) = strings.split_once(coordinate, "/") else error(usage_error, "usage: luc install [<owner>/]<name>[@<version>] [--dev]")
    let home = try apps.home()
    defer strings.release(home)
    let scratch = try apps.child(home, "build")
    defer strings.release(scratch)
    let work_path = try paths.join(scratch, name)
    defer work_path.release()
    let work = work_path.value
    if files.exists((c.str)work): try files.remove_tree((c.str)work)
    defer _ = files.remove_tree((c.str)work) catch: recover ()
    var version_buffer: u8[64]
    try progress.step(f"fetching {coordinate}")
    let version = try packages.download(owner, name, requirement, work, version_buffer, development = development)
    try progress.detail(f"version {version}")

    let installed = try apps.child(home, "apps")
    defer strings.release(installed)
    let application = try apps.child(installed, name)
    defer strings.release(application)
    let placed_path = try paths.join(application, version)
    defer placed_path.release()
    let placed = placed_path.value
    if files.exists((c.str)placed):
        if updating:
            try io.stdout().write(f"{coordinate} {version} is the newest; it is installed\n")
        else:
            try io.stdout().write(f"{coordinate} {version} is already installed\n")
        return 0

    var definition = try project_file.read(work)
    defer definition.close()
    if definition.is_package(): error(usage_error, "that is a package, a library to build on; use 'luc add' inside a project")
    var project = try load_project(directory_hint = work, registry = true)
    defer project.close()
    try progress.step(f"building {coordinate} {version} from source")
    var no_extra: str[]
    let status = try build(&project, BuildMode(release = true, diagnostic = false), no_extra)
    if status != 0: error(usage_error, "the application did not build")

    var plan_buffer: u8[1024]
    var bundle_buffer: u8[96]
    let bundled = try apps.bundle_name(&definition, bundle_buffer) if definition.is_bundled() else ""
    var plan = try strings.format(plan_buffer, f"copy build/{project.name} -> bin/{name}\nlink {name} -> bin/{name}\n")
    if bundled.length > 0 and definition.install.length == 0:
        let built_build = try paths.join(work, "build")
        defer built_build.release()
        let built = try paths.join(built_build.value, bundled)
        defer built.release()
        let status_code = try install_application(&definition, built.value, application, placed, home, name, coordinate, version)
        try remove_other_versions(application, version)
        return status_code
    var scripted = ""
    defer if_release(scripted)
    if definition.install.length > 0:
        scripted = try apps.scripted_plan(try toolchain_compiler("luce", "LUCE"), work, definition.install, name, version)
        plan = scripted

    let staging = try paths.join(application, ".staging")
    defer staging.release()
    if files.exists((c.str)staging.value): try files.remove_tree((c.str)staging.value)
    try files.create_directory((c.str)staging.value)
    errdefer _ = files.remove_tree((c.str)staging.value) catch: recover ()
    var links: u8[16384]
    var links_used: usize
    try apps.apply(plan, work, staging.value, links[0..], &links_used)
    let record = try paths.join(staging.value, ".luc-links")
    defer record.release()
    try files.write((c.str)record.value, links[..<links_used])
    try files.rename((c.str)staging.value, (c.str)placed, replace = false)

    let commands = try apps.child(home, "bin")
    defer strings.release(commands)
    var start: usize
    for end in 0..<links_used:
        if links[end] != '\n': continue
        let (command, relative) = strings.split_once((str)links[start..<end], "\t") else continue
        start = end + 1
        let target = try paths.join(placed, relative)
        defer target.release()
        if not files.exists((c.str)target.value): error(usage_error, "the install plan links a file it did not copy")
        try apps.link_command(commands, command, target.value)
        try io.stdout().write(f"  {command} -> {target.value}\n")
    try remove_other_versions(application, version)
    try io.stdout().write(f"installed {coordinate} {version}\n")
    return 0

## Once a version is installed it replaces the others: their records go, and with them
## what they copied under ~/.luce. What they placed for the desktop the new version has
## replaced already, so it stays.
func remove_other_versions(application: str, kept: str) -> !:
    let application_z = try strings.copy(application)
    defer strings.release(application_z)
    let versions = try files.list((c.str)application_z)
    defer versions.release()
    for version in versions.value:
        if version == kept or strings.starts_with(version, "."): continue
        let inner = try paths.join(application, version)
        defer inner.release()
        try files.remove_tree((c.str)inner.value)
        try progress.detail(f"removed version {version}")

## Install a desktop application: the bundle goes where the system keeps applications
## (apps.place), ~/.luce/apps/<name>/<version>/ records what was created, and
## ~/.luce/bin/<name> starts it from a terminal.
func install_application(definition: pkg.Definition*, built: str, application: str, placed: str, home: str, name: str, coordinate: str, version: str) -> i32!:
    try progress.step(f"installing {definition.application.name}")
    var record: u8[4096]
    var used: usize
    let executable = try apps.place(definition, built, record, &used)
    defer strings.release(executable)
    let staging = try paths.join(application, ".staging")
    defer staging.release()
    if files.exists((c.str)staging.value): try files.remove_tree((c.str)staging.value)
    try files.create_directory((c.str)staging.value)
    errdefer _ = files.remove_tree((c.str)staging.value) catch: recover ()
    let placed_note = try paths.join(staging.value, ".luc-placed")
    defer placed_note.release()
    try files.write((c.str)placed_note.value, record[..<used])
    var link_line: u8[1200]
    let links_note = try paths.join(staging.value, ".luc-links")
    defer links_note.release()
    try files.write((c.str)links_note.value, (try strings.format(link_line, f"{name}\t{executable}\n")).bytes)
    let placed_z = try strings.copy(placed)
    defer strings.release(placed_z)
    try files.rename((c.str)staging.value, (c.str)placed_z, replace = false)
    let commands = try apps.child(home, "bin")
    defer strings.release(commands)
    try apps.link_command(commands, name, executable)
    var start: usize
    for end in 0..<used:
        if record[end] != '\n': continue
        try progress.detail(f"{(str)record[start..<end]}")
        start = end + 1
    try progress.detail(f"{name} -> {executable}")
    try io.stdout().write(f"installed {coordinate} {version}: open {definition.application.name} from your applications, or run {name}\n")
    return 0

## ~/.luce/session.vault, where `luc login` saves the session unless told otherwise.
func default_vault() -> str!:
    let home = try apps.home()
    defer strings.release(home)
    return try join(home, "session")

func account_file() -> str!:
    let home = try apps.home()
    defer strings.release(home)
    return try join(home, "account")

## Only the real registry's account is remembered: a test or a loopback registry must
## never change who `luc login` logs in as.
func remember_account(origin: str, account: str) -> !:
    if origin != registry_http.production_origin: return
    let path = try account_file()
    defer strings.release(path)
    let terminated = try strings.copy(path)
    defer strings.release(terminated)
    try files.write((c.str)terminated, account.bytes)

## The account last registered or logged in here, or empty.
func remembered_account() -> str!:
    let path = try account_file()
    defer strings.release(path)
    let terminated = try strings.copy(path)
    defer strings.release(terminated)
    if not files.exists((c.str)terminated): return try strings.copy("")
    let bytes = try files.read((c.str)terminated, limit = 128)
    defer bytes.release()
    return try strings.copy(strings.trim((str)bytes.value))

## `luc info`: the project as other tools see it, one `key<TAB>value` per line. Written
## for luced, which asks luc about a project rather than reading package.prisma itself.
## Keys: root, name, owner, version, kind, language, entry, source, dependency (repeated:
## name TAB owner TAB version TAB path-or-empty), locked (repeated: name TAB version),
## generated (repeated: a path luc writes and the editor should hide).
func info_command() -> i32!:
    var project = try load_project(prepare = false)
    defer project.close()
    if not try project_file.exists_in(project.root): error(usage_error, "not in a Luce project (no package.prisma found)")
    var definition = try project_file.read(project.root)
    defer definition.close()
    var out = io.stdout()
    try out.write(f"root\t{project.root}\nname\t{definition.name}\nowner\t{definition.owner}\nversion\t{definition.version}\nkind\t{definition.kind}\nlanguage\t{definition.language}\nentry\t{definition.entry}\nsource\t{definition.source}\n")
    for i in 0..<definition.dependency_count:
        let item = try definition.dependency_at(i)
        try out.write(f"dependency\t{item.name}\t{item.owner}\t{item.version}\t{item.path}\n")
    var graph = packages.read_lock(project.root) catch:
        recover packages.Graph()
    defer graph.close()
    for i in 0..<graph.count:
        try out.write(f"locked\t{graph.packages[i].name}\t{graph.packages[i].version}\n")
    for generated in ["build", ".luc"]:
        try out.write(f"generated\t{generated}\n")
    return 0

func if_release(text: str):
    if text.length > 0: strings.release(text)

## `luc uninstall <name>`: remove an application and the commands it linked. Runs no package code.
func uninstall_command(own: str[]) -> i32!:
    if own.length != 1: error(usage_error, "usage: luc uninstall <name>")
    let name = own[0]
    for byte in name.bytes:
        if byte == '/' or byte == '.' or byte == 0: error(usage_error, "usage: luc uninstall <name>")
    let home = try apps.home()
    defer strings.release(home)
    let installed = try apps.child(home, "apps")
    defer strings.release(installed)
    let application_path = try paths.join(installed, name)
    defer application_path.release()
    let application = application_path.value
    if not files.exists((c.str)application):
        try io.stderr().write(f"luc: {name} is not installed\n")
        return 1
    let commands = try apps.child(home, "bin")
    defer strings.release(commands)
    let commands_z = try strings.copy(commands)
    defer strings.release(commands_z)
    let entries = try files.list((c.str)commands_z)
    defer entries.release()
    for entry in entries.value:
        let link = try paths.join(commands, entry)
        defer link.release()
        let target = files.read_symlink((c.str)link.value) catch: continue
        defer target.release()
        if strings.starts_with(target.value, application) and target.value.length > application.length and target.value.bytes[application.length] == '/':
            try files.remove_file((c.str)link.value)
    # Remove what each installed version placed outside ~/.luce and the commands it linked.
    let versions = try files.list((c.str)application)
    defer versions.release()
    for version in versions.value:
        let inner = try paths.join(application, version)
        defer inner.release()
        try remove_recorded(inner.value, commands)
    try files.remove_tree((c.str)application)
    try io.stdout().write(f"uninstalled {name}\n")
    return 0

## Undo an application install recorded in `inner`: every path in .luc-placed, and each
## command in .luc-links that is still a link.
func remove_recorded(inner: str, commands: str) -> !:
    let placed_note = try paths.join(inner, ".luc-placed")
    defer placed_note.release()
    if not files.exists((c.str)placed_note.value): return
    let read_placed = try files.read((c.str)placed_note.value, limit = 4096)
    defer read_placed.release()
    let recorded = read_placed.value
    var start: usize
    for end in 0..<recorded.length:
        if recorded[end] != '\n': continue
        try apps.unplace((str)recorded[start..<end])
        start = end + 1
    let links_note = try paths.join(inner, ".luc-links")
    defer links_note.release()
    if not files.exists((c.str)links_note.value): return
    let read_links = try files.read((c.str)links_note.value, limit = 16384)
    defer read_links.release()
    let links = read_links.value
    start = 0
    for end in 0..<links.length:
        if links[end] != '\n': continue
        let (command, target) = strings.split_once((str)links[start..<end], "\t") else (strings.trim((str)links[start..<end]), "")
        _ = target
        start = end + 1
        try apps.unlink_command(commands, command)

## `luc list`: installed applications and their versions.
func list_command() -> i32!:
    let home = try apps.home()
    defer strings.release(home)
    let installed = try apps.child(home, "apps")
    defer strings.release(installed)
    let installed_z = try strings.copy(installed)
    defer strings.release(installed_z)
    let names = try files.list((c.str)installed_z)
    defer names.release()
    for name in names.value:
        let application = try paths.join(installed, name)
        defer application.release()
        let versions = try files.list((c.str)application.value)
        defer versions.release()
        for version in versions.value:
            if not strings.starts_with(version, "."): try io.stdout().write(f"{name} {version}\n")
    return 0

func add_command(project: Project*, own: str[]) -> i32!:
    let manifest = try require_manifest(project)
    strings.release(manifest)
    var location = ""
    for word in own:
        if not strings.starts_with(word, "--"): location = word
    if location.length == 0:
        error(usage_error, "luc add needs a package: luc add [<owner>/]<name>[@<requirement>] or luc add <path-to-package>")
    if not try project_file.exists_in(location):
        # Not a local package: a registry package. With no requirement it means the newest
        # release (luc.lock records the one chosen); `name@^1.2.0` holds a project back. A
        # bare name is the one registry package of that name, as `luc install` takes it.
        let (wanted, requirement) = strings.split_once(location, "@") else (location, "")
        let coordinate = try qualified(wanted)
        let (owner, name) = strings.split_once(coordinate, "/") else error(usage_error, "no package.prisma at that path, and not a registry package")
        var newest: u8[64]
        let version = try packages.latest(owner, name, newest)
        try project_file.add_registry_dependency(project.root, owner, name, requirement)
        _ = try packages.lock(project.root)
        _ = try packages.sync(project.root)
        try project_file.generate(project.root, project.root)
        if requirement.length > 0:
            try io.stdout().write(f"added dependency {coordinate} {requirement}\n")
        else:
            try io.stdout().write(f"added dependency {coordinate} (newest release, {version})\n")
        return 0
    let name = try project_file.add_dependency(project.root, location)
    defer strings.release(name)
    try project_file.generate(project.root, project.root)
    try io.stdout().write(f"added dependency {name} from {location}\n")
    return 0

## `luc remove <name>` drops a dependency from package.prisma.
func remove_command(project: Project*, own: str[]) -> i32!:
    let manifest = try require_manifest(project)
    strings.release(manifest)
    var name = ""
    for word in own:
        if not strings.starts_with(word, "--"):
            name = word
            break
    if name.length == 0:
        error(usage_error, "luc remove needs a name: luc remove <name>")
    if not try project_file.remove_dependency(project.root, name):
        try io.stderr().write(f"luc: no dependency named '{name}'\n")
        return 1
    try project_file.generate(project.root, project.root)
    try io.stdout().write(f"removed dependency {name}\n")
    return 0

## `luc clean` removes the project's build/ directory (binary and cache); `luc clean cache`
## removes only build/.cache, keeping the built binary.
func clean_command(project: Project*, own: str[]) -> i32!:
    let manifest = try require_manifest(project)
    strings.release(manifest)
    let build_directory = try paths.join(project.root, "build")
    defer build_directory.release()
    let cache_directory = try paths.join(build_directory.value, ".cache")
    defer cache_directory.release()
    var target = build_directory.value
    var label = "build"
    if own.length > 0 and own[0] == "cache":
        target = cache_directory.value
        label = "build/.cache"
    if not files.exists((c.str)target):
        try io.stdout().write(f"nothing to clean ({label} is not present)\n")
        return 0
    try files.remove_tree((c.str)target)
    try io.stdout().write(f"removed {target}\n")
    return 0

## This project's package.prisma, or a usage error when there is no project here.
func require_manifest(project: Project*) -> str!:
    if not try project_file.exists_in(project.root):
        error(usage_error, "not in a Luce project (no package.prisma found); run 'luc init' first")
    return try join(project.root, project_file.file_name)

func package_name_at(manifest: str) -> str!:
    var probe = Project(root = try strings.copy(""), name = try strings.copy(""),
        language = try strings.copy("luce-base"), entry = try strings.copy(""), source = try strings.copy("src"))
    probe.tasks = try new Task[1] ---
    defer probe.close()
    let filename = try strings.copy(manifest)
    defer strings.release(filename)
    let contents = try files.read((c.str)filename)
    defer contents.release()
    try parse_manifest(&probe, (str)contents.value)
    if probe.name.length == 0:
        error(usage_error, try strings.format(message_buffer[0..], f"the package at {manifest} has no [package] name"))
    if probe.name.length > 128: error(usage_error, "dependency package name is too long")
    for i in 0..<probe.name.length:
        let byte = probe.name.bytes[i]
        let letter = byte >= 'a' and byte <= 'z'
        if not letter and byte != '_' and (i == 0 or byte < '0' or byte > '9'):
            error(usage_error, "dependency package name must be a lowercase identifier")
    return try strings.copy(probe.name)

func release_string_array(values: str[]):
    if values.length > 0: free(values) in memory.heap

## Add or replace `name = "value"` under `[dependencies]`, creating the section if absent,
## and preserving the rest of the file line for line.
func upsert_dependency(manifest: str, name: str, value: str) -> !:
    let entry = try toml_line(name, value)
    defer strings.release(entry)
    let filename = try strings.copy(manifest)
    defer strings.release(filename)
    let contents = try files.read((c.str)filename)
    defer contents.release()
    let text = (str)contents.value
    var result: str[]
    defer release_string_array(result)
    var section = ""
    var has_section = false
    let lines = try strings.split(text, '\n')
    defer free(lines) in memory.heap
    for raw in lines:
        let trimmed = strings.trim(raw)
        if strings.starts_with(trimmed, "["):
            section = trimmed
            result = try append(result, raw)
            if trimmed == "[dependencies]":
                has_section = true
                result = try append(result, entry)
            continue
        if section == "[dependencies]" and dependency_key(trimmed) == name:
            continue
        result = try append(result, raw)
    if not has_section:
        result = try append(result, "[dependencies]")
        result = try append(result, entry)
        result = try append(result, "")
    let joined = try strings.join(result, "\n")
    defer strings.release(joined)
    try files.write_text(manifest, joined)

## Remove `name = ...` under `[dependencies]`; answers whether a line was removed.
func remove_dependency(manifest: str, name: str) -> bool!:
    let filename = try strings.copy(manifest)
    defer strings.release(filename)
    let contents = try files.read((c.str)filename)
    defer contents.release()
    let text = (str)contents.value
    var result: str[]
    defer release_string_array(result)
    var section = ""
    var removed = false
    let lines = try strings.split(text, '\n')
    defer free(lines) in memory.heap
    for raw in lines:
        let trimmed = strings.trim(raw)
        if strings.starts_with(trimmed, "["):
            section = trimmed
            result = try append(result, raw)
            continue
        if section == "[dependencies]" and dependency_key(trimmed) == name:
            removed = true
            continue
        result = try append(result, raw)
    if removed:
        let joined = try strings.join(result, "\n")
        defer strings.release(joined)
        try files.write_text(manifest, joined)
    return removed

## The key of a `key = value` line, or empty for anything else.
func dependency_key(line: str) -> str:
    if line.length == 0 or strings.starts_with(line, "#"):
        return ""
    let (key, _) = strings.split_once(line, "=") else return ""
    return strings.trim(key)

func toml_line(key: str, value: str) -> str!:
    var buffer: u8[1024]
    return try strings.copy(try strings.format(buffer[0..], f"{key} = \"{value}\""))

# mark: Updating the toolchain ================================================================

## `luc update` (alias `upgrade`): the whole toolset (luce, luce-base and luc, one release
## archive) through the Luce installer, which replaces the tree this luc runs from, where
## it was installed, and leaves the shell's startup files as they are unless that is the
## installer's default place. LUC_HOME, where luc keeps what it installs, is named in the
## installer's command when it is not the default ~/.luce.
## `--dry-run` prints the command without running it. `luc update [owner/]name`: that
## application or tool at its newest version, replacing what is installed.
func update_command(own: str[]) -> i32!:
    for word in own:
        if not strings.starts_with(word, "--"):
            return try install_command(own, updating = true)
    let root = try toolchain_root()
    let command = try installer_command("luce", root)
    if has(own, "--dry-run"):
        try io.stdout().write(f"{command}\n")
        return 0
    try progress.step(f"updating luce, luce-base and luc at {root} from https://luce.luciaos.com")
    if platform.windows:
        # Windows will not replace a running luc.exe: the installer runs in its own window
        # once this process has exited and released it
        let detached = try strings.join(["Start-Process powershell -ArgumentList '-NoExit','-NoProfile','-Command','Start-Sleep 1; ", command, "'"], "")
        if try run_shell(detached) != 0:
            try io.stderr().write("luc: could not start the installer\n")
            return 1
        try io.stdout().write("the update continues in a new PowerShell window\n")
        return 0
    if try run_shell(command) != 0:
        try io.stderr().write("luc: the update did not complete\n")
        return 1
    return 0

## The release tree this luc runs from, as the installer laid it out: the directory whose
## `bin` holds luc and whose `share/luce/VERSION` names the release. Links to luc, such as
## a `bin` of their own on the PATH, are followed to the tree.
func toolchain_root() -> str!:
    let exe = try os.executable()
    let real = try files.canonical((c.str)exe)
    defer real.release()
    let root = paths.directory(paths.directory(real.value))
    let marker = try paths.join(root, "share/luce/VERSION")
    defer marker.release()
    if root.length == 0 or not files.exists((c.str)marker.value):
        error(usage_error, "this luc is not part of an installed Luce release, so there is nothing to update in place; install one with the installer at https://luce.luciaos.com")
    if strings.contains(root, "'"):
        error(usage_error, "the Luce release's path holds a quote, which the installer's command cannot carry")
    return try strings.copy(root)

## The one-line installer pipeline for a site, installing into `root`: curl|sh on POSIX,
## irm|iex on Windows, whose command `update_command` passes on inside single quotes. A
## LUC_HOME other than the default is named in it, so the command means the same when it
## is run from a shell that does not have it set.
func installer_command(site: str, root: str) -> str!:
    var buffer: u8[2048]
    let chosen = try apps.chosen_home()
    let home = chosen else ""
    if strings.contains(home, "'") or strings.contains(home, "\""):
        error(usage_error, "LUC_HOME holds a quote, which the installer's command cannot carry")
    if platform.windows:
        let setting = try strings.join(["$env:LUC_HOME=\"", home, "\"; "], "") if home.length > 0 else ""
        return try strings.copy(try strings.format(buffer[0..], f"$env:LUCE_INSTALL_DIR=\"{root}\"; {setting}irm https://{site}.luciaos.com/install.ps1 | iex"))
    let setting = try strings.join(["LUC_HOME='", home, "' "], "") if home.length > 0 else ""
    return try strings.copy(try strings.format(buffer[0..], f"curl -fsSL https://{site}.luciaos.com/install.sh | LUCE_INSTALL_DIR='{root}' {setting}sh"))

## Run a shell pipeline through the host shell.
func run_shell(command: str) -> i32!:
    if platform.windows:
        var windows: str[]
        for word in ["-NoProfile", "-Command", command]:
            windows = try append(windows, word)
        return try spawn("powershell", windows)
    return try spawn("sh", try two("-c", command))

# mark: Scaffolding ===========================================================================

## `luc new <path>` creates a project in a new directory; `luc init` in the current one.
## Flags: --package (a library) or --app (default); --luce or --luce-base (default).
func scaffold_command(command: str, own: str[]) -> i32!:
    # One of three kinds: a package (library), an application (desktop window) or a tool
    # (terminal program, the default). --lib is the older spelling of --package.
    var kind = "tool"
    if has(own, "--package") or has(own, "--lib"): kind = "package"
    elif has(own, "--application") or has(own, "--app"): kind = "application"
    elif has(own, "--tool"): kind = "tool"
    let language = "luce" if has(own, "--luce") or kind == "application" else "luce-base"
    var target = try os.cwd()
    if command == "new":
        var chosen = ""
        for word in own:
            if not strings.starts_with(word, "--"):
                chosen = word
        if chosen.length == 0:
            error(usage_error, "usage: luc new <dir> [--package | --application | --tool] [--luce]")
        target = chosen
    let name = paths.base(target)
    if try project_file.exists_in(target):
        error(usage_error, "a package.prisma already exists here; refusing to overwrite it")
    try scaffold(target, name, language, kind)
    try io.stdout().write(f"created {language} {kind} '{name}' in {target}\n")
    return 0

## Write the project's directories and starter files.
func scaffold(target: str, name: str, language: str, kind: str) -> !:
    try ensure_dir(target)
    let source_path = try paths.join(target, "src")
    defer source_path.release()
    let source = source_path.value
    try ensure_dir(source)
    let suffix = ".luc" if language == "luce" else ".lucb"
    var definition: u8[2048]
    try write_file(target, project_file.file_name, try project_file.scaffold(name, default_owner, language, kind, definition))
    try write_file(target, ".gitignore", "build/\n.luc/\n")
    if kind == "package":
        # luce-json's starter module is src/json, imported as `from luce_json import json`
        let module = try project_file.library_module(name)
        defer strings.release(module)
        try write_file(source, try join_name(module, suffix), try library_source(module, language))
    elif kind == "application":
        var window: u8[1024]
        try write_file(source, "main.luc", try strings.format(window, f"from luce_ui.ui import Application, Button, Text, VStack\n\npub func main(arguments: list[str]) -> int!:\n    let button = Button(\"Continue\")\n    let content = VStack([Text(\"Hello from {name}\"), button], padding = 24.0)\n    let app = Application(content, title = \"{name}\")\n    app.run()\n    return 0\n"))
    else:
        try write_file(source, try join_name("main", suffix), try program_source(name, language))

func ensure_dir(path: str) -> !:
    let terminated = try strings.copy(path)
    defer strings.release(terminated)
    if not files.exists((c.str)terminated):
        try files.create_directory((c.str)terminated)

## Write `content` to the file `name` in `directory`.
func write_file(directory: str, name: str, content: str) -> !:
    let path = try paths.join(directory, name)
    defer path.release()
    try files.write((c.str)path.value, content.bytes)

func join_name(stem: str, suffix: str) -> str!:
    var buffer: u8[128]
    return try strings.copy(try strings.format(buffer[0..], f"{stem}{suffix}"))

func program_source(name: str, language: str) -> str!:
    var buffer: u8[512]
    if language == "luce":
        return try strings.copy(try strings.format(buffer[0..], f"pub func main(arguments: list[str]) -> int!:\n    print(\"hello from {name}\")\n    return 0\n"))
    return try strings.copy(try strings.format(buffer[0..], f"pub func main(arguments: str[]) -> i32:\n    print(\"hello from {name}\")\n    return 0\n"))

func library_source(name: str, language: str) -> str!:
    var buffer: u8[512]
    return try strings.copy(try strings.format(buffer[0..], f"## The {name} package.\npub func greeting() -> str:\n    return \"hello from {name}\"\n"))

# mark: The command line =======================================================================

func append(items: str[], value: str) -> str[]!:
    let grown = try new str[items.length + 1] ---
    var index: usize = 0
    while index < items.length:
        grown[index] = items[index]
        index += 1
    grown[items.length] = value
    if items.length > 0: free(items) in memory.heap
    return grown

func concat(left: str[], right: str[]) -> str[]!:
    let grown = try new str[left.length + right.length] ---
    var index: usize = 0
    while index < left.length:
        grown[index] = left[index]
        index += 1
    var offset: usize = 0
    while offset < right.length:
        grown[left.length + offset] = right[offset]
        offset += 1
    return grown

## Split the arguments after the command into its own words and the passthrough after `--`.
func partition(arguments: c.str[], start: usize) -> (str[], str[])!:
    var own: str[]
    var passthrough: str[]
    var index = start
    var seen_dashes = false
    while index < arguments.length:
        let word = (str)arguments[index]
        if word == "--" and not seen_dashes:
            seen_dashes = true
        elif seen_dashes:
            passthrough = try append(passthrough, word)
        else:
            own = try append(own, word)
        index += 1
    return (own, passthrough)

func has(words: str[], flag: str) -> bool:
    for word in words:
        if word == flag:
            return true
    return false

pub func main(arguments: c.str[]) -> i32!:
    with memory.heap:
        if arguments.length < 2:
            try usage(io.stdout())
            return 0
        let command = (str)arguments[1]
        if command == "--version":
            # the version package.prisma names, which the compiler writes in (platform)
            try io.stdout().write(f"luc {platform.program_version}\n")
            return 0
        if command == "--help" or command == "help":
            try usage(io.stdout())
            return 0
        if command == "git-credential":
            if arguments.length != 3: return 0
            let session = try default_vault()
            defer strings.release(session)
            return try releasing.credential_helper((str)arguments[2], session)
        if command == "publish":
            var notes = ""
            var index: usize = 2
            while index < arguments.length:
                let word = (str)arguments[index]
                index += 1
                if (word == "-m" or word == "--notes") and index < arguments.length:
                    notes = (str)arguments[index]
                    index += 1
                else:
                    error(usage_error, "usage: luc publish -m \"what changed in this version\"")
            var project = try load_project(prepare = false)
            defer project.close()
            let manifest = try require_manifest(&project)
            strings.release(manifest)
            let session = try default_vault()
            defer strings.release(session)
            return try releasing.publish(project.root, packages.origin(), session, notes)
        # Secrets are prompted for at a terminal and read from a pipe otherwise, so the
        # old --*-stdin flags are accepted and ignored. The session vault defaults to
        # ~/.luce/session.vault.
        if command == "login" or command == "register" or command == "repo-create" or command == "git-token":
            var words: str[]
            defer release_string_array(words)
            var vault = ""
            var index: usize = 2
            while index < arguments.length:
                let word = (str)arguments[index]
                index += 1
                if word == "--secrets-stdin" or word == "--passwords-stdin" or word == "--password-stdin": continue
                if word == "--vault" and index < arguments.length:
                    vault = (str)arguments[index]
                    index += 1
                    continue
                words = try append(words, word)
            let fallback = try default_vault()
            defer strings.release(fallback)
            # The origin may be omitted: it is the Lucia OS registry unless one is given.
            var origin = packages.origin()
            var first: usize = 0
            if words.length > 0 and strings.starts_with(words[0], "http"):
                origin = words[0]
                first = 1
            let rest = words[first..]
            if command == "register":
                if rest.length != 1: error(usage_error, "usage: luc register <account>")
                let status = try credentials.register(origin, rest[0])
                if status == 0: try remember_account(origin, rest[0])
                return status
            if command == "login":
                if rest.length > 1: error(usage_error, "usage: luc login [<account>]")
                let remembered = try remembered_account()
                defer strings.release(remembered)
                let account = rest[0] if rest.length > 0 else remembered
                if account.length == 0: error(usage_error, "usage: luc login <account>   (the account is remembered afterwards)")
                let status = try credentials.login_session(origin, account, fallback)
                if status == 0: try remember_account(origin, account)
                return status
            if command == "repo-create":
                if rest.length != 1: error(usage_error, "usage: luc repo-create <name>")
                return try credentials.create_repository(origin, rest[0], vault if vault.length > 0 else fallback)
            if rest.length != 1: error(usage_error, "usage: luc git-token <repository>")
            return try credentials.issue_git_token(origin, rest[0], vault if vault.length > 0 else fallback)
        if command == "checkout-pack":
            # `--install` leaves the development paths out, as an install does.
            let install = arguments.length == 6 and (str)arguments[5] == "--install"
            if arguments.length != 5 and not install: error(usage_error, "usage: luc checkout-pack <pack-path> <commit-id> <new-directory> [--install]")
            return try checkout.from_pack((str)arguments[2], (str)arguments[3], (str)arguments[4], development = not install)
        let (own, passthrough) = try partition(arguments, 2)
        defer release_string_array(own)
        defer release_string_array(passthrough)
        if command == "info":
            return try info_command()
        if command == "latest":
            return try latest_command(own)
        if command == "install":
            return try install_command(own)
        if command == "uninstall":
            return try uninstall_command(own)
        if command == "list":
            return try list_command()
        if command == "new" or command == "init":
            return try scaffold_command(command, own)
        if command == "update" or command == "upgrade":
            return try update_command(own)
        let manages = command == "lock" or command == "sync" or command == "add" or command == "remove" or command == "clean"
        var project = try load_project(prepare = not manages)
        defer project.close()
        if command == "lock" or command == "sync":
            if passthrough.length != 0: error(usage_error, "lock and sync do not accept passthrough arguments")
            let manifest = try require_manifest(&project)
            strings.release(manifest)
            if command == "lock":
                if own.length != 0: error(usage_error, "usage: luc lock")
                let count = try packages.lock(project.root)
                try io.stdout().write(f"locked {count} registry package(s) in luc.lock\n")
            let offline = command == "sync" and own.length == 1 and own[0] == "--offline"
            if command == "sync" and own.length != 0 and not offline: error(usage_error, "usage: luc sync [--offline]")
            let count = try packages.sync(project.root, offline)
            try project_file.generate(project.root, project.root)
            try io.stdout().write(f"synced {count} registry package(s) into .luc/deps\n")
            return 0
        if command == "add":
            return try add_command(&project, own)
        if command == "remove":
            return try remove_command(&project, own)
        if command == "clean":
            return try clean_command(&project, own)
        if command == "build":
            return try build(&project, try build_mode(own, "build"), passthrough)
        if command == "test":
            # every module of the package, imported by the entry or not (§16.5, Luce §17.3),
            # and every test program under tests/
            var diagnostic = false
            var listing = false
            var jobs: usize = 0
            var index: usize = 0
            while index < own.length:
                let word = own[index]
                index += 1
                if word == "--diagnostic": diagnostic = true
                elif word == "--list": listing = true
                elif word == "--jobs" and index < own.length:
                    let count = strings.parse_u64(own[index]) else error(usage_error, "luc test: --jobs takes a number of programs, at least 1")
                    if count == 0: error(usage_error, "luc test: --jobs takes a number of programs, at least 1")
                    jobs = (usize)count
                    index += 1
                else: error(usage_error, "usage: luc test [--diagnostic] [--list] [--jobs N] [-- args]")
            let starter = try project.starter()
            let entry = starter else try strings.copy("")
            defer strings.release(entry)
            let luce = try toolchain_compiler("luce", "LUCE")
            let base = try toolchain_compiler("luce-base", "LUCE_BASE")
            return try package_tests.run(package_tests.Request(root = project.root, source = project.source,
                entry = entry, luce = luce, base = base,
                diagnostic = diagnostic, passthrough = passthrough, list = listing, jobs = jobs))
        if command == "check":
            # every module of the package, imported by the entry or not, for every target
            if own.length != 0: error(usage_error, "usage: luc check [-- args]")
            let starter = try project.starter()
            let entry = starter else try strings.copy("")
            defer strings.release(entry)
            let luce = try toolchain_compiler("luce", "LUCE")
            let base = try toolchain_compiler("luce-base", "LUCE_BASE")
            return try package_tests.check(project.root, project.source, entry, luce, base, passthrough)
        if command == "fmt":
            var formatted = try two("fmt", try project.entry_path())
            if has(own, "--check"):
                formatted = try append(formatted, "--check")
            return try spawn(try project.compiler(), formatted)
        if command == "run":
            if own.length == 0 or own[0] == "--release" or own[0] == "--diagnostic":
                return try run_app(&project, try build_mode(own, "run"), passthrough)
            if project.find_task(own[0]) != none:
                return try run_task(&project, own[0], passthrough)
            try io.stderr().write(f"luc: no task named '{own[0]}'\n")
            list_tasks(&project) catch failure:
                _ = failure
            return 1
        try io.stderr().write(f"luc: unknown command '{command}'; run 'luc help'\n")
        return 1

func usage(out: io.Writer) -> !:
    try out.write("luc - the project tool for Luce and Luce Base\n\n")
    try out.write("Projects\n")
    try out.write("  new <dir> [--package|--tool|--application] [--luce]   create a project\n")
    try out.write("  init [same options]    create one in this directory\n\n")
    try out.write("Building and running\n")
    try out.write("  build [--release] [--diagnostic]   build into build/<name>\n")
    try out.write("  run [--release] [--diagnostic] [-- args]   build and run\n")
    try out.write("  run <task> [-- args]   run a task from package.prisma\n")
    try out.write("  test [--diagnostic] [--jobs N]   run the test blocks and the test programs (tests/<name>/main)\n")
    try out.write("  test --list            name the tests without running them\n")
    try out.write("                         --jobs N: build and run N test programs at once (default: half\n")
    try out.write("                         the processors); a program with a tests/<name>/serial file\n")
    try out.write("                         runs alone, after the others\n")
    try out.write("                         --diagnostic: the diagnostic profile, which fills unwritten\n")
    try out.write("                         storage with 0xAA and traps on double frees and writes\n")
    try out.write("                         after free; it builds into build/<name>-diagnostic\n")
    try out.write("  check [-- args]        type-check every module, for every target, without building\n")
    try out.write("  fmt [--check]          format the sources\n")
    try out.write("  clean [cache]          remove build/, or only its cache\n\n")
    try out.write("Dependencies\n")
    try out.write("  add [owner/]name       add a registry package\n")
    try out.write("  add ../path            add a package checked out beside this one\n")
    try out.write("  remove <name>          remove a dependency\n")
    try out.write("  lock                   resolve everything and write luc.lock\n")
    try out.write("  sync [--offline]       make .luc/deps match luc.lock\n\n")
    try out.write("Installing\n")
    try out.write("  install [owner/]name[@version] [--dev]   download, build and install a tool or application;\n")
    try out.write("                         --dev keeps its tests/, dev/ and other development paths\n")
    try out.write("  list                   what is installed\n")
    try out.write("  latest [owner/]name    the newest released version\n")
    try out.write("  uninstall <name>       remove it\n\n")
    try out.write("Other\n")
    try out.write("  update                 reinstall the latest luce, luce-base and luc\n")
    try out.write("  --version, help\n")

## The compiler `name` (`luce` or `luce-base`): the one `variable` names, else the one
## installed beside luc, since a release puts luc, luce and luce-base in one `bin/` that
## belong together, else `name` on the path. Beside luc before the path, so an older
## luce-base elsewhere on the path (a build from source) is never picked up by mistake.
## A copy of the variable's value: on Windows the next `os.env` call overwrites it.
func toolchain_compiler(name: str, variable: str) -> str!:
    if let chosen = os.env((c.str)variable):
        return try strings.copy(chosen)
    let exe = os.executable() catch failure:
        _ = failure
        return name
    let joined = try paths.join(paths.directory(exe), name)
    defer joined.release()
    # a copy, so the path ends in the zero the file system call reads
    let candidate = try strings.join([joined.value, ".exe" if os.windows else ""], "")
    let info = files.metadata((c.str)candidate) catch failure:
        _ = failure
        strings.release(candidate)
        return name
    if info.kind == files.FileKind.regular:
        return candidate
    strings.release(candidate)
    return name