Skip to content
suit Artifact [c79b0670d9]
Login

Artifact [c79b0670d9]

Artifact c79b0670d938c19fd2f130f5cbc28e0d326d19766ad35cb7b3cb42441ebb6575:


#include "commands.h"

#include "assets.h"
#include "attention.h"
#include "conf.h"
#include "hook.h"
#include "install.h"
#include "join.h"
#include "ledger.h"
#include "machine.h"
#include "need.h"
#include "place.h"
#include "platform.h"
#include "project.h"
#include "resolve.h"
#include "scan.h"
#include "stamp.h"
#include "store.h"
#include "wardrobes.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

constexpr size_t PATH_CAP = 4096;
constexpr size_t PATH_ROOM = 640;
// What the stamp may list. A path costs the per-minute compare about 4 us (7.4 ms
// for the 1890 paths of the old stamp on the budget's fixture), so 128 keep it
// near half of its 1 ms budget whatever the stores hold.
constexpr uint32_t WATCH_MAX = 128;
// A named path: a store's path, a slash and a line of its config.
constexpr size_t WATCH_PATH_MAX = WARDROBE_PATH_MAX + CONF_LINE_MAX + 2;

static Conf conf;  // every wardrobe's config, as one set
static Wards wards;
static Assets assets;
static Plan plan;
static Ledger ledger;
static Actions acts;
static Roots roots;
static Projects found;
static Projects hand_set;
static char machine[MACHINE_MAX + 1];  // this machine's name, empty if it has none

typedef struct {
    char home[PATH_CAP];       // $HOME
    char suit_home[PATH_CAP];  // $SUIT_HOME
    char store_dir[PATH_CAP];  // $SUIT_HOME/store, which holds a store for each wardrobe
    char ledger_path[PATH_CAP];
    char lock_path[PATH_CAP];
    char machine_path[PATH_CAP];
    char roots_path[PATH_CAP];
    char projects_path[PATH_CAP];
    char set_path[PATH_CAP];
} Paths;

static int find_paths(Paths *p)
{
    size_t len = suit_home_path(p->store_dir, sizeof p->store_dir, "store");
    if (len == 0) return 1;
    const char *home = sys_getenv("HOME");
    if (home == nullptr || strlen(home) >= PATH_CAP) {
        say(STDERR_FILENO, "suit: HOME is not set, or too long\n");
        return 1;
    }
    snprintf(p->home, sizeof p->home, "%s", home);
    // Room for a name of any length under the store, which no folder can exceed.
    if (len + PATH_ROOM > PATH_CAP) {
        say(STDERR_FILENO, "suit: SUIT_HOME is longer than %zu bytes\n", PATH_CAP - PATH_ROOM);
        return 1;
    }
    memcpy(p->suit_home, p->store_dir, len);
    p->suit_home[len] = '\0';
    // The other paths fit too: the home folder left PATH_ROOM bytes.
    [[maybe_unused]] size_t b = suit_home_path(p->ledger_path, sizeof p->ledger_path, "ledger");
    [[maybe_unused]] size_t c = suit_home_path(p->lock_path, sizeof p->lock_path, "lock");
    [[maybe_unused]] size_t d = suit_home_path(p->machine_path, sizeof p->machine_path, "machine");
    [[maybe_unused]] size_t e = suit_home_path(p->roots_path, sizeof p->roots_path, "roots");
    [[maybe_unused]] size_t f = suit_home_path(p->projects_path, sizeof p->projects_path, "projects");
    [[maybe_unused]] size_t g = suit_home_path(p->set_path, sizeof p->set_path, "projects.set");
    ensure(b != 0 && c != 0 && d != 0 && e != 0 && f != 0 && g != 0);
    return 0;
}

// ---- resolve and compare with the disk ----------------------------------------

static int check_source(const char *dest, const char *src)
{
    struct stat st;
    if (sys_lstat(src, &st) == 0) return 0;
    say(STDERR_FILENO, "suit: %s wants %s, which is not in the store\n", dest, src);
    return 1;
}

// The placements' sources are in the store, and so are the sources of the files
// to join, which stand in for the placements' own.
static int check_sources(void)
{
    for (uint32_t i = 0; i < plan.n; i++) {
        bool joined = false;
        for (uint32_t j = 0; j < plan.njoins; j++) joined |= strcmp(plan.joins[j].path, plan.p[i].src) == 0;
        if (!joined && check_source(plan.p[i].dest, plan.p[i].src) != 0) return 1;
    }
    for (uint32_t j = 0; j < plan.njoins; j++) {
        const Join *join = &plan.joins[j];
        for (uint32_t k = 0; k < join->n; k++)
            if (check_source(join->path, join->src[k]) != 0) return 1;
    }
    return 0;
}

static int load_ledger(const Paths *p)
{
    LedgerError err;
    if (ledger_load(&ledger, p->ledger_path, &err)) return 0;
    say(STDERR_FILENO, "%s:%d: %s\n", p->ledger_path, err.line, err.msg);
    return 1;
}

static int load_projects(const char *path, Projects *list, bool with_kind);

static bool wears_personal(void)
{
    for (uint32_t i = 0; i < conf.nsections; i++)
        if (conf.sections[i].kind == KIND_WEAR && strcmp(conf.sections[i].arg[0], "personal") == 0) return true;
    return false;
}

// Everything plan, apply and status start with: the config, the store, the
// ledger, the plan and what to do about the disk.
static int prepare(const Paths *p, const char *why)
{
    if (wardrobes_load(&wards, &conf) != 0) return 1;
    int rc = assets_load(&wards, &assets);
    if (rc != 0) return rc;
    rc = machine_read(p->machine_path, machine);
    // The list of projects matters only to a config that has something to wear in one.
    found.n = 0;
    if (rc == 0 && wears_personal()) rc = load_projects(p->projects_path, &found, true);
    if (rc != 0) return rc;
    ResolveError rerr;
    bool resolved = why == nullptr
        ? resolve(&conf, &assets, p->home, p->suit_home, &wards, machine, &found, &plan, &rerr)
        : resolve_why(&conf, &assets, p->home, p->suit_home, &wards, machine, &found, why, &plan, &rerr);
    if (!resolved) {
        say(STDERR_FILENO, "suit: %s\n", rerr.msg);
        return 1;
    }
    rc = check_sources();
    if (rc != 0) return rc;
    rc = load_ledger(p);
    if (rc != 0) return rc;
    return place_plan(&plan, &ledger, &acts);
}

// Find the wardrobes that take part, then for each in order, stopping at the
// first that fails, show its version (SHOW) or check that no update was left
// unfinished. A problem with the wardrobes' configs, which find reports as 2,
// is CONFIG_RC.
static int open_wardrobes(const Paths *p, bool show, int config_rc)
{
    int rc = wardrobes_find(&wards, p->suit_home);
    if (rc == 2) return config_rc;
    for (uint32_t i = 0; rc == 0 && i < wards.n; i++)
        rc = show ? store_show_version(wards.w[i].name) : store_check_journal(wards.w[i].name);
    return rc;
}

int cmd_plan(void)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : open_wardrobes(&p, false, 1);
    rc = rc != 0 ? rc : prepare(&p, nullptr);
    if (rc == 0) place_print(&plan, &acts);
    return rc;
}

// ---- the stamp: what the no-change run watches ---------------------------------
//
// The compare stats each path the stamp lists, and the budget (docs/decisions.md,
// "Speed") cannot hold one stat for each file of the stores. So the stamp lists
// what apply reads that can change what it places or a file it writes, and not
// what it only links to: a link shows an edit to its target, or to a file in the
// folder it targets, without an apply. What apply reads, and whether it is watched:
//
//   $SUIT_HOME/store, listed to find the wardrobes   watched: the folder, and each
//       folder in it, so a wardrobe, or a suit.conf in one, appearing or going shows
//   each wardrobe's suit.conf (content)             watched
//   each wardrobe's folder                         watched (its own entries)
//   its skills, agents and commands folders, listed watched: the folder itself,
//       whose time changes when an entry is added, removed or renamed (an editor's
//       save by rename too, a harmless apply), and each entry that is a link,
//       whose target can appear, go or change kind without touching the folder
//   each entry's type (a skill is a folder, an agent a file)  not watched apart:
//       a folder replaced by a file of its name, or the reverse, is an entry
//       removed and one added, which changes the listing folder
//   files in a skill folder, an agent's or a command's content  not watched:
//       apply links to them and never reads them
//   each `instructions`, `file` and `slot` path of every outfit, worn or not
//       watched, whether it exists or not: a source that appears or goes changes
//       the plan, and the two sources of a joined file are read and copied into it
//   each need's prompt (it must exist and be a file)  watched
//   each need's done test (a file in the home folder)  not watched:
//       docs/needs.md, an item stays until the next apply
//   the ledger, the machine's name, the projects list  watched (and roots and
//       projects.set, which a rescan reads, as before)
//   the destinations in the home folder and the joined files  not watched: apply
//       puts back a link or a joined file changed by hand when it next runs
//   $SUIT_HOME/NAME.journal  not watched: an apply it stops changes nothing, and
//       the stamp of the last apply still holds
//   the attention file  not watched: apply rewrites only its need items
//   the upstreams/NAME records  not read by apply
// Nothing is placed by copy; the joined file is the one file whose content comes
// from the store. The paths grow with the wardrobes, the links in their listing
// folders and the paths the configs name, never with the files in a skill.

typedef struct {
    char *paths[WATCH_MAX];
    uint32_t n;
    bool over;  // a path did not fit under WATCH_MAX
    char text[WATCH_MAX * WATCH_PATH_MAX];
    size_t used;
    char dir[WATCH_PATH_MAX];
} Watch;

static Watch watch;

// Add PATH once. Over the limit, remember it for write_stamp to say.
static void watch_add(const char *path)
{
    for (uint32_t i = 0; i < watch.n; i++)
        if (strcmp(watch.paths[i], path) == 0) return;
    if (watch.n == WATCH_MAX) {
        watch.over = true;
        return;
    }
    size_t len = strlen(path) + 1;
    ensure(len <= WATCH_PATH_MAX);  // each fits watch.dir or a named path
    char *copy = watch.text + watch.used;
    memcpy(copy, path, len);
    watch.used += len;
    watch.paths[watch.n++] = copy;
}

// watch.dir with "/ENTRY" after it; the caller cuts it back to LEN.
static size_t watch_push(const char *entry)
{
    size_t len = strlen(watch.dir);
    [[maybe_unused]] int n = snprintf(watch.dir + len, sizeof watch.dir - len, "/%s", entry);
    ensure(n > 0 && (size_t)n < sizeof watch.dir - len);  // the system allows no longer path
    return len;
}

// A folder of the store is watched, whether or not it is a wardrobe that takes part: a
// suit.conf that appears in it makes it one.
static int watch_folder(void *state, const char *entry)
{
    (void)state;
    if (entry[0] == '.') return 0;
    size_t len = watch_push(entry);
    struct stat st = {};
    (void)sys_stat(watch.dir, &st);
    if (S_ISDIR(st.st_mode)) watch_add(watch.dir);
    watch.dir[len] = '\0';
    return 0;
}

// An entry of a skills, agents or commands folder that is a link.
static int watch_link(void *state, const char *entry)
{
    (void)state;
    if (entry[0] == '.') return 0;
    size_t len = watch_push(entry);
    struct stat st = {};
    (void)sys_lstat(watch.dir, &st);
    if (S_ISLNK(st.st_mode)) watch_add(watch.dir);
    watch.dir[len] = '\0';
    return 0;
}

static int watch_wardrobe(const Ward *w)
{
    static const char *const listings[] = {"skills", "agents", "commands"};
    watch_add(w->store);
    watch_add(w->conf);
    for (size_t k = 0; k < sizeof listings / sizeof listings[0]; k++) {
        snprintf(watch.dir, sizeof watch.dir, "%s/%s", w->store, listings[k]);
        watch_add(watch.dir);
        // A folder that is not there holds nothing; it shows when it appears.
        if (sys_listdir(watch.dir, watch_link, nullptr) < 0 && errno != ENOENT) {
            say(STDERR_FILENO, "suit: cannot read %s: %s\n", watch.dir, strerror(errno));
            return 1;
        }
    }
    return 0;
}

// The paths a section names in its wardrobe's store.
static void watch_named(const Section *s)
{
    for (uint32_t i = 0; i < s->count; i++) {
        const Entry *e = &conf.entries[s->first + i];
        bool source = strcmp(e->key, "instructions") == 0 || strncmp(e->key, "file ", 5) == 0 ||
            strncmp(e->key, "slot ", 5) == 0;
        bool named = s->kind == KIND_OUTFIT ? source : s->kind == KIND_NEED && strcmp(e->key, "prompt") == 0;
        if (!named) continue;
        char path[WATCH_PATH_MAX];
        [[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", wards.w[s->ward].store, e->val);
        ensure(n > 0 && (size_t)n < sizeof path);  // a store's path and a line of the config
        watch_add(path);
    }
}

// Stamp what apply reads (above): a change to any of it is a reason to run apply.
static int write_stamp(const Paths *p)
{
    watch.n = 0;
    watch.over = false;
    watch.used = 0;
    // The list is empty, so these six always fit.
    const char *const fixed[] = {p->store_dir, p->ledger_path, p->machine_path, p->roots_path, p->projects_path,
        p->set_path};
    for (size_t i = 0; i < sizeof fixed / sizeof fixed[0]; i++) watch_add(fixed[i]);
    snprintf(watch.dir, sizeof watch.dir, "%s", p->store_dir);
    if (sys_listdir(p->store_dir, watch_folder, nullptr) < 0) {
        say(STDERR_FILENO, "suit: cannot read %s: %s\n", p->store_dir, strerror(errno));
        return 1;
    }
    int rc = 0;
    for (uint32_t i = 0; rc == 0 && i < wards.n; i++) rc = watch_wardrobe(&wards.w[i]);
    for (uint32_t i = 0; i < conf.nsections; i++) watch_named(&conf.sections[i]);
    if (rc == 0 && watch.over) {
        say(STDERR_FILENO, "suit: more than %u paths for the no-change run to watch: the configs name too many "
            "files, or the stores hold too many wardrobes or linked assets\n", WATCH_MAX);
        rc = 1;
    }
    return rc != 0 ? rc : stamp_write((int)watch.n, watch.paths);
}

// ---- needs ---------------------------------------------------------------------

typedef struct {
    const char *harness;
    const char *name;
    const char *prompt;  // in the store of its wardrobe
    uint32_t ward;
    DoneTest test;
    NeedState state;
    char why[DONE_WHY_MAX];
} Need;

static Need needs[CONF_NEED_MAX];
static uint32_t nneeds;

constexpr size_t NEED_BLOCK = 65536;
constexpr size_t NEED_NAME_CAP = 2 * CONF_NAME_MAX + 2;
constexpr size_t NEED_HEADER_CAP = 2 * NEED_NAME_CAP + 32;

static const Entry *need_entry(const Section *s, const char *key)
{
    for (uint32_t i = 0; i < s->count; i++)
        if (strcmp(conf.entries[s->first + i].key, key) == 0) return &conf.entries[s->first + i];
    return nullptr;
}

static int need_error(int line, const Need *n, const char *what, const char *why)
{
    say(STDERR_FILENO, "%s:%d: need %s %s: %s%s\n", wards.w[n->ward].conf, line, n->harness, n->name, what, why);
    return 1;
}

static int cmp_need(const void *pa, const void *pb)
{
    const Need *a = pa;
    const Need *b = pb;
    int r = strcmp(a->harness, b->harness);
    return r != 0 ? r : strcmp(a->name, b->name);
}

static void prompt_path(const Need *n, char *path, size_t cap, bool *fits)
{
    int len = snprintf(path, cap, "%s/%s", wards.w[n->ward].store, n->prompt);
    ensure(len > 0);
    *fits = (size_t)len < cap;
}

// Check every need of the config in CONF and read its test, sorted by harness
// and name. Returns 1 after saying which need is wrong and where.
static int load_needs(const Paths *p)
{
    nneeds = 0;
    for (uint32_t i = 0; i < conf.nsections; i++) {
        const Section *s = &conf.sections[i];
        if (s->kind != KIND_NEED) continue;
        Need *n = &needs[nneeds++];
        n->harness = s->arg[0];
        n->name = s->arg[1];
        n->ward = s->ward;
        const Entry *prompt = need_entry(s, "prompt");
        const Entry *done = need_entry(s, "done");
        if (prompt == nullptr) return need_error(s->line, n, "has no prompt", "");
        if (done == nullptr) return need_error(s->line, n, "has no done", "");
        n->prompt = prompt->val;
        if (!need_prompt_ok(prompt->val)) return need_error(prompt->line, n, "prompt is not a path inside the store: ", prompt->val);
        char path[PATH_CAP];
        bool fits;
        prompt_path(n, path, sizeof path, &fits);
        if (!fits) return need_error(prompt->line, n, "prompt path is too long: ", prompt->val);
        struct stat st;
        if (sys_stat(path, &st) != 0) return need_error(prompt->line, n, "cannot read the prompt: ", strerror(errno));
        if (!S_ISREG(st.st_mode)) return need_error(prompt->line, n, "the prompt is not a file: ", prompt->val);
        char why[DONE_WHY_MAX];
        if (!done_parse(&n->test, p->home, done->val, why, sizeof why))
            return need_error(done->line, n, "cannot read the test: ", why);
    }
    qsort(needs, nneeds, sizeof needs[0], cmp_need);
    return 0;
}

static void eval_needs(void)
{
    for (uint32_t i = 0; i < nneeds; i++) needs[i].state = done_eval(&needs[i].test, needs[i].why, sizeof needs[i].why);
}

// The config and its needs, for the commands that only read them. Exit 2 on an error.
static int read_needs(const Paths *p)
{
    if (wardrobes_load(&wards, &conf) != 0) return 2;
    return load_needs(p) != 0 ? 2 : 0;
}

int cmd_needs(void)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : open_wardrobes(&p, false, 2);
    rc = rc != 0 ? rc : read_needs(&p);
    if (rc != 0) return rc;
    eval_needs();
    int worst = 0;
    for (uint32_t i = 0; i < nneeds; i++) {
        const Need *n = &needs[i];
        if (n->state == NEED_DONE) say(STDOUT_FILENO, "%s %s: done\n", n->harness, n->name);
        else if (n->state == NEED_NOT_DONE) say(STDOUT_FILENO, "%s %s: not done\n", n->harness, n->name);
        else say(STDOUT_FILENO, "%s %s: cannot tell (%s)\n", n->harness, n->name, n->why);
        worst |= n->state != NEED_DONE;
    }
    return worst;
}

int cmd_need(const char *harness, const char *name)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : open_wardrobes(&p, false, 2);
    rc = rc != 0 ? rc : read_needs(&p);
    if (rc != 0) return rc;
    const Need *n = nullptr;
    for (uint32_t i = 0; i < nneeds; i++)
        if (strcmp(needs[i].harness, harness) == 0 && strcmp(needs[i].name, name) == 0) n = &needs[i];
    if (n == nullptr) {
        say(STDERR_FILENO, "suit: no need %s %s in the wardrobes under %s\n", harness, name, p.store_dir);
        return 1;
    }
    char path[PATH_CAP];
    bool fits;
    prompt_path(n, path, sizeof path, &fits);
    ensure(fits);  // load_needs checked
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) {
        say(STDERR_FILENO, "suit: cannot open %s: %s\n", path, strerror(errno));
        return 1;
    }
    static char block[NEED_BLOCK];
    ssize_t got = 1;
    int err = 0;
    while (got > 0 && err == 0) {
        got = sys_read(fd, block, sizeof block);
        if (got < 0 && errno == EINTR) got = 1;
        else if (got < 0) err = errno;
        else if (got > 0 && !sys_write_all(STDOUT_FILENO, block, (size_t)got)) err = errno;
    }
    (void)sys_close(fd);
    if (err != 0) say(STDERR_FILENO, "suit: cannot print %s: %s\n", path, strerror(err));
    return err != 0;
}

// Bring the need items of the attention file up to date with the needs now.
static int sync_needs_attention(void)
{
    static char names[CONF_NEED_MAX][NEED_NAME_CAP];
    static char headers[CONF_NEED_MAX][NEED_HEADER_CAP];
    static const char *name_at[CONF_NEED_MAX];
    static const char *header_at[CONF_NEED_MAX];
    eval_needs();
    size_t n = 0;
    for (uint32_t i = 0; i < nneeds; i++) {
        if (needs[i].state == NEED_DONE) continue;
        snprintf(names[n], sizeof names[n], "%s %s", needs[i].harness, needs[i].name);
        snprintf(headers[n], sizeof headers[n], "need %s: run suit need %s", names[n], names[n]);
        name_at[n] = names[n];
        header_at[n] = headers[n];
        n++;
    }
    char path[PATH_CAP];
    [[maybe_unused]] size_t home = suit_home_path(path, sizeof path, "attention");
    ensure(home != 0);  // the same folder find_paths found
    return attention_sync(path, "need", n, name_at, header_at);
}

// ---- apply ---------------------------------------------------------------------

// The per-minute run: busy is said by nothing, since the next minute tries again.
static bool run_quietly;

int cmd_apply(void)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : open_wardrobes(&p, false, 1);
    if (rc != 0) return rc;
    rc = place_lock(p.lock_path, run_quietly);
    if (rc != 0) return rc;
    rc = prepare(&p, nullptr);
    rc = rc != 0 ? rc : load_needs(&p);
    rc = rc != 0 ? rc : place_apply(&ledger, &acts, p.ledger_path);
    if (rc == 0) place_print(&plan, &acts);
    // The links are in place; the stamp waits, so the next run tries the attention file again.
    if (rc == 0 && sync_needs_attention() != 0) {
        say(STDERR_FILENO, "suit: the links are in place, but the attention file is not up to date\n");
        rc = 1;
    }
    rc = rc != 0 ? rc : write_stamp(&p);
    place_unlock(p.lock_path);
    return rc;
}

// ---- status --------------------------------------------------------------------

typedef struct {
    const char *project;  // nullptr for the User scope
    const char *harness;
    AssetKind kind;
    uint32_t count;
} Tally;

static int cmp_tally(const void *pa, const void *pb)
{
    const Tally *a = pa;
    const Tally *b = pb;
    // The User scope's tallies (no project) come first, then each project's by folder.
    int r = (a->project != nullptr) - (b->project != nullptr);
    r = r != 0 || a->project == nullptr ? r : strcmp(a->project, b->project);
    r = r != 0 ? r : strcmp(a->harness, b->harness);
    return r != 0 ? r : (int)a->kind - (int)b->kind;
}

// The links in place, grouped by scope: the User scope's first, then each project's.
static void print_links(void)
{
    static Tally tally[PLACE_MAX];
    uint32_t n = 0;
    for (uint32_t i = 0; i < acts.n; i++) {
        const Action *a = &acts.a[i];
        if (a->kind != ACT_KEEP) continue;
        uint32_t t = 0;
        while (t < n && !(tally[t].project == a->want->project &&
                          strcmp(tally[t].harness, a->want->harness) == 0 && tally[t].kind == a->want->kind))
            t++;
        if (t == n) tally[n++] = (Tally){a->want->project, a->want->harness, a->want->kind, 0};
        tally[t].count++;
    }
    qsort(tally, n, sizeof tally[0], cmp_tally);
    for (uint32_t i = 0; i < n; i++) {
        if (tally[i].project != nullptr) say(STDOUT_FILENO, "personal %s ", tally[i].project);
        say(STDOUT_FILENO, "links %s %s %u\n", tally[i].harness, asset_kind_name(tally[i].kind), tally[i].count);
    }
}

// The projects whose links nothing hides: a project that is not git has no local exclude file.
static void print_visible(void)
{
    static const char *shown[PROJECT_ENTRY_MAX];
    uint32_t n = 0;
    for (uint32_t i = 0; i < plan.n; i++) {
        const Placement *w = &plan.p[i];
        if (w->project == nullptr || w->vcs == KIND_GIT) continue;
        bool done = false;
        for (uint32_t k = 0; k < n; k++) done |= shown[k] == w->project;
        if (done) continue;
        shown[n++] = w->project;
        say(STDOUT_FILENO, "links in %s are visible to its version control (%s has no local exclude file)\n",
            w->project, project_kind_name(w->vcs));
    }
}

// One line for each personal wear whose key no project in the list has.
static void print_unmatched_keys(void)
{
    for (uint32_t i = 0; i < conf.nsections; i++) {
        const Section *s = &conf.sections[i];
        if (s->kind != KIND_WEAR || strcmp(s->arg[0], "personal") != 0) continue;
        bool known = false;
        for (uint32_t k = 0; k < found.n; k++) known |= strcmp(found.e[k].key, s->arg[1]) == 0;
        bool again = false;  // [wear personal KEY] and [wear personal KEY machine=NAME] say it once
        for (uint32_t k = 0; k < i; k++)
            again |= conf.sections[k].kind == KIND_WEAR && strcmp(conf.sections[k].arg[0], "personal") == 0 &&
                strcmp(conf.sections[k].arg[1], s->arg[1]) == 0;
        if (!known && !again) say(STDOUT_FILENO, "personal %s: no project with this key\n", s->arg[1]);
    }
}

// One line for each wear, User or personal, limited to a machine that is not this one.
static void print_ignored_limits(void)
{
    for (uint32_t i = 0; i < conf.nsections; i++) {
        const Section *s = &conf.sections[i];
        if (s->kind != KIND_WEAR) continue;
        if (s->arg[2][0] == '\0' || strcmp(s->arg[2], machine) == 0) continue;
        if (machine[0] == '\0')
            say(STDOUT_FILENO, "machine %s: not this machine (this machine has no name)\n", s->arg[2]);
        else
            say(STDOUT_FILENO, "machine %s: not this machine (this is %s)\n", s->arg[2], machine);
    }
}

int cmd_status(void)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : open_wardrobes(&p, true, 1);
    rc = rc != 0 ? rc : prepare(&p, nullptr);
    if (rc != 0) return rc;
    print_links();
    print_visible();
    print_unmatched_keys();
    for (uint32_t i = 0; i < acts.n; i++)
        if (acts.a[i].kind == ACT_CLASH)
            say(STDOUT_FILENO, "clash %s (%s)\n", acts.a[i].dest, acts.a[i].reason);
    (void)place_missing(&ledger, true);
    for (uint32_t i = 0; i < plan.nskips; i++) say(STDOUT_FILENO, "%s\n", plan.skips[i]);
    print_ignored_limits();
    if (install_print_state() != 0) return 1;
    char attention[4096];
    [[maybe_unused]] size_t home = suit_home_path(attention, sizeof attention, "attention");
    ensure(home != 0);  // the same folder prepare() found
    return attention_print(attention);
}

// ---- why -----------------------------------------------------------------------

// The longest project folder that holds DIR, or null.
static const ProjectEntry *project_of(const char *dir)
{
    const ProjectEntry *best = nullptr;
    size_t best_len = 0;
    for (uint32_t i = 0; i < found.n; i++) {
        const char *path = found.e[i].path;
        size_t len = strlen(path);
        bool inside = strncmp(dir, path, len) == 0 && (dir[len] == '\0' || dir[len] == '/');
        if (inside && len >= best_len) {
            best = &found.e[i];
            best_len = len;
        }
    }
    return best;
}

static const char *clash_reason(const char *dest)
{
    for (uint32_t i = 0; i < acts.n; i++)
        if (acts.a[i].kind == ACT_CLASH && strcmp(acts.a[i].dest, dest) == 0) return acts.a[i].reason;
    return nullptr;
}

static void say_state(const Supplier *s)
{
    const char *clash = s->fate == FATE_PLACED || s->fate == FATE_JOINED ? clash_reason(s->dest) : nullptr;
    if (clash != nullptr) say(STDOUT_FILENO, "clash (%s)\n", clash);
    else if (s->fate == FATE_PLACED) say(STDOUT_FILENO, "placed\n");
    else if (s->fate == FATE_JOINED) say(STDOUT_FILENO, "joined\n");
    else if (s->fate == FATE_DROPPED) say(STDOUT_FILENO, "dropped (the machine-limited outfit wins)\n");
    else if (s->fate == FATE_OTHER_MACHINE) say(STDOUT_FILENO, "not applied (not this machine)\n");
    else if (s->fate == FATE_NO_PROJECT) say(STDOUT_FILENO, "not applied (no project with this key here)\n");
    else say(STDOUT_FILENO, "skipped (no folder)\n");
}

// Whether the place concerns the folder DIR is in: the User scope always, a
// personal one for the project DIR is in, and one with no project for its key
// when DIR is in no project that has a key.
static bool concerns(const Supplier *s, const ProjectEntry *here)
{
    if (strcmp(s->scope, "user") == 0) return true;
    if (s->project != nullptr) return here != nullptr && strcmp(s->project, here->path) == 0;
    return here == nullptr || here->key[0] == '\0';
}

int cmd_why(const char *name)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : open_wardrobes(&p, false, 1);
    rc = rc != 0 ? rc : prepare(&p, name);
    if (rc != 0) return rc;
    char dir[PATH_CAP];
    if (sys_getcwd(dir, sizeof dir) == nullptr) {
        say(STDERR_FILENO, "suit: cannot read the current folder: %s\n", strerror(errno));
        return 1;
    }
    const ProjectEntry *here = project_of(dir);
    uint32_t shown = 0;
    for (uint32_t i = 0; i < plan.nsuppliers; i++) {
        const Supplier *s = &plan.sup[i];
        if (!concerns(s, here)) continue;
        shown++;
        say(STDOUT_FILENO, "%s", s->scope);
        if (s->key[0] != '\0') say(STDOUT_FILENO, " %s", s->key);
        if (s->machine[0] != '\0') say(STDOUT_FILENO, " machine=%s", s->machine);
        say(STDOUT_FILENO, ": outfit %s", s->outfit);
        if (wards.n > 1) say(STDOUT_FILENO, " (wardrobe %s)", s->ward);
        say(STDOUT_FILENO, ", %s, %s: ", s->harness, s->dest);
        say_state(s);
    }
    if (shown == 0) {
        say(STDOUT_FILENO, "nothing supplies %s here\n", name);
        return 1;
    }
    // A harness reads its project's folder before its user's.
    for (uint32_t i = 0; i < plan.nsuppliers; i++) {
        const Supplier *mine = &plan.sup[i];
        bool in_effect = mine->fate == FATE_PLACED || mine->fate == FATE_JOINED;
        if (!concerns(mine, here) || !in_effect || strcmp(mine->scope, "personal") != 0 || strcmp(mine->harness, "-") == 0)
            continue;
        bool both = false;
        bool again = false;  // said already, for an earlier personal place of this harness and kind
        for (uint32_t k = 0; k < plan.nsuppliers; k++) {
            const Supplier *o = &plan.sup[k];
            bool same = strcmp(o->harness, mine->harness) == 0 && o->kind == mine->kind &&
                (o->fate == FATE_PLACED || o->fate == FATE_JOINED);
            both |= same && strcmp(o->scope, "user") == 0;
            again |= same && k < i && strcmp(o->scope, "personal") == 0 && concerns(o, here);
        }
        if (both && !again) say(STDOUT_FILENO, "%s reads the project's before the user's\n", mine->harness);
    }
    return 0;
}

// ---- check ---------------------------------------------------------------------

int cmd_check_set(void)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : wardrobes_find(&wards, p.suit_home);
    if (rc != 0) return rc;
    if (wardrobes_load(&wards, &conf) != 0) return 2;
    if (!conf_dump(&conf, STDOUT_FILENO)) {
        say(STDERR_FILENO, "suit: cannot write the dump: %s\n", strerror(errno));
        return 1;
    }
    return 0;
}

// ---- machine -------------------------------------------------------------------

int cmd_machine(const char *name)
{
    Paths p;
    int rc = find_paths(&p);
    if (rc != 0) return rc;
    if (name != nullptr) {
        if (!machine_name_ok(name, strlen(name))) {
            say(STDERR_FILENO, "suit: '%s' is not a machine name (1 to %zu letters, digits, - _ .)\n", name,
                MACHINE_MAX);
            return 2;
        }
        return machine_write(p.machine_path, name);
    }
    rc = machine_read(p.machine_path, machine);
    if (rc == 0 && machine[0] == '\0') {
        say(STDERR_FILENO, "suit: this machine has no name (suit machine NAME sets one)\n");
        return 1;
    }
    if (rc == 0) say(STDOUT_FILENO, "%s\n", machine);
    return rc;
}

// ---- roots and projects --------------------------------------------------------

static int load_roots(const Paths *p)
{
    ProjectError err;
    if (roots_load(&roots, p->roots_path, &err)) return 0;
    say(STDERR_FILENO, "%s:%d: %s\n", p->roots_path, err.line, err.msg);
    return 1;
}

static int load_projects(const char *path, Projects *list, bool with_kind)
{
    ProjectError err;
    if (projects_load(list, path, with_kind, &err)) return 0;
    say(STDERR_FILENO, "%s:%d: %s\n", path, err.line, err.msg);
    return 1;
}

static int write_failed(const char *path, int err)
{
    say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
    return 1;
}

// PATH as the files keep it: absolute, with no trailing slash. Says what is wrong if not.
static bool clean_path(char *path, size_t max)
{
    size_t len = strlen(path);
    while (len > 1 && path[len - 1] == '/') path[--len] = '\0';
    if (project_path_ok(path) && len <= max) return true;
    say(STDERR_FILENO, "suit: '%.200s' is not an absolute path of at most %zu bytes with no control character\n", path,
        max);
    return false;
}

int cmd_roots(const char *verb, char *arg)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : load_roots(&p);
    if (rc != 0) return rc;
    if (verb == nullptr) {
        for (uint32_t i = 0; i < roots.n; i++) say(STDOUT_FILENO, "%s\n", roots.path[i]);
        return 0;
    }
    if (!clean_path(arg, PROJECT_ROOT_MAX)) return 2;
    if (strcmp(verb, "rm") == 0) {
        if (!roots_remove(&roots, arg)) {
            say(STDERR_FILENO, "suit: %s is not a root\n", arg);
            return 1;
        }
    } else {
        struct stat st;
        if (sys_stat(arg, &st) != 0 || !S_ISDIR(st.st_mode)) {
            say(STDERR_FILENO, "suit: %s is not a folder\n", arg);
            return 1;
        }
        AddResult a = roots_add(&roots, arg);
        if (a == ADD_DUPLICATE) {
            say(STDERR_FILENO, "suit: %s is a root already\n", arg);
            return 1;
        }
        if (a == ADD_FULL) {
            say(STDERR_FILENO, "suit: there are %zu roots, the most there can be\n", ROOTS_MAX);
            return 1;
        }
    }
    int err = roots_write(&roots, p.roots_path);
    return err == 0 ? 0 : write_failed(p.roots_path, err);
}

int cmd_projects(bool scan)
{
    Paths p;
    int rc = find_paths(&p);
    if (rc != 0) return rc;
    if (!scan) {
        rc = load_projects(p.projects_path, &found, true);
        for (uint32_t i = 0; rc == 0 && i < found.n; i++)
            say(STDOUT_FILENO, "%s %s %s\n", found.e[i].key[0] != '\0' ? found.e[i].key : "-", found.e[i].path,
                project_kind_name(found.e[i].kind));
        return rc;
    }
    rc = load_roots(&p);
    rc = rc != 0 ? rc : load_projects(p.set_path, &hand_set, false);
    if (rc != 0) return rc;
    if (scan_projects(&roots, &hand_set, &found) != 0) return 1;
    int err = projects_write(&found, p.projects_path, true);
    if (err != 0) return write_failed(p.projects_path, err);
    say(STDOUT_FILENO, "%u projects in %u roots\n", found.n, roots.n);
    return 0;
}

int cmd_project(char *path, const char *key)
{
    Paths p;
    int rc = find_paths(&p);
    rc = rc != 0 ? rc : load_projects(p.set_path, &hand_set, false);
    if (rc != 0) return rc;
    if (!clean_path(path, PROJECT_PATH_MAX - 1)) return 2;
    if (key != nullptr) {
        if (!project_key_ok(key)) {
            say(STDERR_FILENO, "suit: '%.200s' is not a remote key: host/path, with a lower-case host, as in github.com/Owner/Name\n", key);
            return 2;
        }
        (void)projects_remove(&hand_set, path);
        if (projects_add(&hand_set, key, path, KIND_NONE) == ADD_FULL) {
            say(STDERR_FILENO, "suit: too many hand-set keys (limit %u, or %zu bytes of text)\n", PROJECT_ENTRY_MAX,
                sizeof hand_set.buf);
            return 1;
        }
    } else if (!projects_remove(&hand_set, path)) {
        say(STDERR_FILENO, "suit: no key was set for %s\n", path);
        return 1;
    }
    int err = projects_write(&hand_set, p.set_path, false);
    return err == 0 ? 0 : write_failed(p.set_path, err);
}

// ---- off -----------------------------------------------------------------------

int cmd_off(void)
{
    Paths p;
    int rc = find_paths(&p);
    if (rc != 0) return rc;
    rc = place_lock(p.lock_path, false);
    if (rc != 0) return rc;
    rc = load_ledger(&p);
    rc = rc != 0 ? rc : place_off(&ledger, p.ledger_path);
    if (rc == 0) {
        // Nothing is applied, so there is nothing for the timer to watch.
        char stamp[PATH_CAP];
        [[maybe_unused]] size_t home = suit_home_path(stamp, sizeof stamp, "stamp");
        ensure(home != 0);
        (void)sys_unlink(stamp);
        char attention[PATH_CAP];
        [[maybe_unused]] size_t at = suit_home_path(attention, sizeof attention, "attention");
        ensure(at != 0);
        rc = attention_sync(attention, "need", 0, nullptr, nullptr);
    }
    place_unlock(p.lock_path);
    return rc;
}

// ---- hooks ---------------------------------------------------------------------

// One line for one program of an event. False after a message if its link
// cannot be read.
static bool hook_line(Out *o, const char *event, const char *slot, const char *name)
{
    char path[PATH_CAP + HOOK_NAME_MAX + 2];
    bool single = name[0] == '\0';
    size_t n = strlen(slot);
    memcpy(path, slot, n + 1);
    if (!single) {
        path[n] = '/';
        memcpy(path + n + 1, name, strlen(name) + 1);
    }
    char target[PATH_CAP + 1];
    struct stat st;
    if (sys_lstat(path, &st) == 0 && S_ISLNK(st.st_mode)) {
        ssize_t len = sys_readlink(path, target, PATH_CAP);
        if (len < 0) {
            say(STDERR_FILENO, "suit: cannot read the link %s: %s\n", path, strerror(errno));
            return false;
        }
        target[len] = '\0';
    } else {
        memcpy(target, path, strlen(path) + 1);
    }
    out_str(o, event);
    out_str(o, " ");
    out_str(o, single ? "-" : name);
    out_str(o, " -> ");
    out_str(o, target);
    if (sys_stat(path, &st) < 0) out_str(o, " (missing)");
    else if (!S_ISREG(st.st_mode) || (st.st_mode & 0111) == 0) out_str(o, " (not executable)");
    out_str(o, "\n");
    return true;
}

int cmd_hooks(void)
{
    char dir[PATH_CAP];
    if (suit_home_path(dir, sizeof dir, "slots/hook") == 0) return 1;
    char events[HOOK_PROGRAMS_MAX][HOOK_NAME_MAX + 1];
    int n;
    int rc = hook_collect(dir, events, HOOK_PROGRAMS_MAX, &n);
    if (rc < 0 && errno == ENOENT) return 0;
    if (rc < 0) {
        say(STDERR_FILENO, "suit: cannot read %s: %s\n", dir, strerror(errno));
        return 1;
    }
    if (rc > 0) {
        say(STDERR_FILENO, "suit: more than %d events in %s\n", HOOK_PROGRAMS_MAX, dir);
        return 1;
    }
    Out o;
    out_init(&o, STDOUT_FILENO);
    int status = 0;
    for (int i = 0; i < n; i++) {
        if (!hook_event_ok(events[i])) continue;
        char slot[PATH_CAP];
        HookSet set;
        HookForm form = hook_probe(events[i], slot, sizeof slot);
        if (form == HOOK_FAILED || hook_programs(events[i], slot, form, &set) != 0) {
            status = 1;
            continue;
        }
        for (int j = 0; j < set.count; j++)
            if (!hook_line(&o, events[i], slot, set.names[j])) status = 1;
    }
    if (!out_finish(&o)) {
        say(STDERR_FILENO, "suit: cannot write the list: %s\n", strerror(errno));
        return 1;
    }
    return status;
}

// ---- for `suit curate apply` -----------------------------------------------------

int commands_home(char *suit_home, char *lock_path)
{
    Paths p;
    int rc = find_paths(&p);
    if (rc != 0) return rc;
    memcpy(suit_home, p.suit_home, strlen(p.suit_home) + 1);
    memcpy(lock_path, p.lock_path, strlen(p.lock_path) + 1);
    return 0;
}

int commands_resolve(const Conf *c, const Wards *w, const Assets *a, Plan *out)
{
    Paths p;
    [[maybe_unused]] int home = find_paths(&p);
    ensure(home == 0);  // commands_home found them
    int rc = machine_read(p.machine_path, machine);
    found.n = 0;
    bool personal = false;
    for (uint32_t i = 0; i < c->nsections; i++)
        personal |= c->sections[i].kind == KIND_WEAR && strcmp(c->sections[i].arg[0], "personal") == 0;
    if (rc == 0 && personal) rc = load_projects(p.projects_path, &found, true);
    if (rc != 0) return rc;
    ResolveError rerr;
    if (resolve(c, a, p.home, p.suit_home, w, machine, &found, out, &rerr)) return 0;
    say(STDERR_FILENO, "suit: %s\n", rerr.msg);
    return 1;
}

// ---- run -----------------------------------------------------------------------

int cmd_run(void)
{
    int rc = stamp_check(false);
    run_quietly = true;
    return rc == EXIT_CHANGED ? cmd_apply() : rc;
}