Skip to content
suit Artifact [6b5e27e2f6]
Login

Artifact [6b5e27e2f6]

Artifact 6b5e27e2f648763cdc07edda9efa4c7f5cfc6706736708a8a0167ed95e9c79ea:


#include "place.h"

#include "exclude.h"
#include "join.h"
#include "platform.h"

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

constexpr size_t PATH_CAP = 4096;
constexpr unsigned LOCK_WAIT_MS = 2000;
constexpr unsigned LOCK_POLL_MS = 50;

static const char REASON_FILE[] = "a real file";
static const char REASON_DIR[] = "a real folder";
static const char REASON_LINK[] = "someone else's link";
static const char REASON_BLOCKED[] = "something in the way";

typedef enum { D_NONE, D_LINK, D_DIR, D_FILE } DestKind;

// What is at DEST, without following a link. For a link, its target too.
static int inspect(const char *dest, DestKind *kind, char *target, size_t cap)
{
    struct stat st;
    if (sys_lstat(dest, &st) != 0) {
        if (errno == ENOENT || errno == ENOTDIR) {
            *kind = D_NONE;
            return 0;
        }
        say(STDERR_FILENO, "suit: cannot look at %s: %s\n", dest, strerror(errno));
        return 1;
    }
    *kind = S_ISDIR(st.st_mode) ? D_DIR : D_FILE;
    if (!S_ISLNK(st.st_mode)) return 0;
    ssize_t n = sys_readlink(dest, target, cap - 1);
    if (n < 0) {
        say(STDERR_FILENO, "suit: cannot read the link %s: %s\n", dest, strerror(errno));
        return 1;
    }
    target[n] = '\0';
    *kind = D_LINK;
    return 0;
}

static const char *reason_for(DestKind kind)
{
    if (kind == D_LINK) return REASON_LINK;
    return kind == D_DIR ? REASON_DIR : REASON_FILE;
}

// ---- folders ----------------------------------------------------------------

static bool have_dir(const Actions *out, const char *path)
{
    for (uint32_t i = 0; i < out->ndirs; i++)
        if (strcmp(out->dirs[i], path) == 0) return true;
    return false;
}

static int add_dir(Actions *out, const char *path)
{
    if (have_dir(out, path)) return 0;
    size_t len = strlen(path) + 1;
    if (out->ndirs == DIR_MAX || out->used + len > sizeof out->text) {
        say(STDERR_FILENO, "suit: too many folders to make (limit %u folders, %zu bytes of names)\n",
            DIR_MAX, DIR_TEXT_MAX);
        return 1;
    }
    char *copy = out->text + out->used;
    memcpy(copy, path, len);
    out->used += len;
    out->dirs[out->ndirs++] = copy;
    return 0;
}

// The folders above DEST that do not exist yet go in OUT, parents first. If one
// of them exists and is not a folder, DEST is BLOCKED.
static int parents(Actions *out, const char *dest, bool *blocked)
{
    *blocked = false;
    bool missing = false;
    for (const char *s = strchr(dest + 1, '/'); s != nullptr; s = strchr(s + 1, '/')) {
        size_t len = (size_t)(s - dest);
        char prefix[PATH_CAP];
        ensure(len < sizeof prefix);
        memcpy(prefix, dest, len);
        prefix[len] = '\0';
        struct stat st;
        if (!missing && sys_stat(prefix, &st) != 0) {
            if (errno != ENOENT) {
                say(STDERR_FILENO, "suit: cannot look at %s: %s\n", prefix, strerror(errno));
                return 1;
            }
            missing = true;
        } else if (!missing && !S_ISDIR(st.st_mode)) {
            *blocked = true;
            return 0;
        }
        if (missing && add_dir(out, prefix) != 0) return 1;
    }
    return 0;
}

// ---- plan -------------------------------------------------------------------

static int cmp_action(const void *pa, const void *pb)
{
    const Action *a = pa;
    const Action *b = pb;
    return strcmp(a->dest, b->dest);
}

static int cmp_dest(const void *key, const void *elem)
{
    const Placement *p = elem;
    return strcmp(key, p->dest);
}

// One wanted placement against what is on disk and what the ledger says.
static int decide_want(const Placement *w, const Ledger *ledger, Actions *out)
{
    const LedgerEntry *mine = ledger_find_link(ledger, w->dest);
    Action act = {ACT_CLASH, w->dest, w->src, nullptr, nullptr, w, nullptr};
    DestKind kind;
    char target[PATH_CAP];
    int rc = inspect(w->dest, &kind, target, sizeof target);
    if (rc != 0) return rc;
    if (kind == D_NONE) {
        bool blocked;
        rc = parents(out, w->dest, &blocked);
        if (rc != 0) return rc;
        act.kind = blocked ? ACT_CLASH : ACT_CREATE;
        act.reason = blocked ? REASON_BLOCKED : nullptr;
    } else if (kind == D_LINK) {
        // Ours if the ledger has it and it points where we put it, or where we
        // would put it now (a crash between making a link and writing the ledger).
        bool at_want = strcmp(target, w->src) == 0;
        bool ours = mine != nullptr && (at_want || strcmp(target, mine->src) == 0);
        act.kind = !ours ? ACT_CLASH : (at_want ? ACT_KEEP : ACT_REPLACE);
        act.reason = ours ? nullptr : REASON_LINK;
        act.old = mine != nullptr ? mine->src : nullptr;
    } else {
        act.reason = reason_for(kind);
    }
    out->a[out->n++] = act;
    return 0;
}

// A link the ledger has and nothing wants any more.
static int decide_stale(const LedgerEntry *le, Actions *out)
{
    Action act = {ACT_DROP, le->dest, le->src, nullptr, nullptr, nullptr, nullptr};
    DestKind kind;
    char target[PATH_CAP];
    int rc = inspect(le->dest, &kind, target, sizeof target);
    if (rc != 0) return rc;
    bool ours = kind == D_LINK && strcmp(target, le->src) == 0;
    if (kind != D_NONE) {
        act.kind = ours ? ACT_REMOVE : ACT_CLASH;
        act.reason = ours ? nullptr : reason_for(kind);
    }
    out->a[out->n++] = act;
    return 0;
}

static bool ledger_has_file(const Ledger *l, const char *path)
{
    for (uint32_t i = 0; i < l->n; i++)
        if (l->e[i].kind == ENTRY_FILE && strcmp(l->e[i].dest, path) == 0) return true;
    return false;
}

// A joined file against what the ledger and the disk say: write it if it is
// missing or out of date.
static int decide_join(const Join *j, const Ledger *ledger, Actions *out)
{
    int current = join_current(j);
    if (current < 0) return 1;
    bool blocked;  // a folder in the way shows when the file is written
    int rc = current == 1 ? 0 : parents(out, j->path, &blocked);
    if (rc != 0) return rc;
    Action act = {current == 1 ? ACT_FILE : ACT_WRITE, j->path, nullptr, nullptr, nullptr, nullptr, j};
    act.old = ledger_has_file(ledger, j->path) ? j->path : nullptr;
    out->a[out->n++] = act;
    return 0;
}

// A joined file the ledger has and no join wants any more.
static int decide_stale_file(const LedgerEntry *le, Actions *out)
{
    DestKind kind;
    char target[PATH_CAP];
    int rc = inspect(le->dest, &kind, target, sizeof target);
    if (rc == 0 && kind != D_NONE)
        out->a[out->n++] = (Action){ACT_UNWRITE, le->dest, nullptr, nullptr, nullptr, nullptr, nullptr};
    return rc;
}

static bool is_join_path(const Plan *plan, const char *path)
{
    for (uint32_t i = 0; i < plan->njoins; i++)
        if (strcmp(plan->joins[i].path, path) == 0) return true;
    return false;
}

// ---- the blocks that hide a project's links from its version control --------------

typedef struct {
    const char *excl;
    const char *line;
} Pair;

static Pair pairs[PLACE_MAX];
static struct {
    const char *project;
    const char *excl;
} seen[PROJECT_ENTRY_MAX];

static const char *keep_btext(Actions *out, const char *s)
{
    size_t len = strlen(s) + 1;
    ensure(out->bused + len <= sizeof out->btext);  // BLOCK_TEXT_MAX is the most the plan can come to
    const char *copy = memcpy(out->btext + out->bused, s, len);
    out->bused += len;
    return copy;
}

static const LedgerEntry *ledger_find_block(const Ledger *l, const char *path)
{
    for (uint32_t i = 0; i < l->n; i++)
        if (l->e[i].kind == ENTRY_BLOCK && strcmp(l->e[i].dest, path) == 0) return &l->e[i];
    return nullptr;
}

// The exclude file for PROJECT, found once.
static int exclude_for(Actions *out, uint32_t *nseen, const char *project, const char **excl)
{
    for (uint32_t i = 0; i < *nseen; i++) {
        if (seen[i].project != project) continue;
        *excl = seen[i].excl;
        return 0;
    }
    ensure(*nseen < PROJECT_ENTRY_MAX);  // a project is listed once, and the list is that long
    char path[EXCLUDE_PATH_MAX];
    if (exclude_path(project, path, sizeof path) != 0) return 1;
    *excl = nullptr;
    for (uint32_t i = 0; i < *nseen; i++)  // a linked worktree has the main repository's file
        if (strcmp(seen[i].excl, path) == 0) *excl = seen[i].excl;
    if (*excl == nullptr) *excl = keep_btext(out, path);
    seen[*nseen].project = project;
    seen[*nseen].excl = *excl;
    (*nseen)++;
    return 0;
}

static int cmp_pair(const void *pa, const void *pb)
{
    const Pair *a = pa;
    const Pair *b = pb;
    int r = strcmp(a->excl, b->excl);
    return r != 0 ? r : strcmp(a->line, b->line);
}

// Decide a block that the plan wants: the file's current bytes against the lines.
static int decide_block(const Ledger *ledger, Actions *out, Block *b)
{
    const LedgerEntry *mine = ledger_find_block(ledger, b->path);
    bool exists;
    if (exclude_edit(b->path, &out->lines[b->first], b->count, false, true, &b->changed, &exists) != 0) return 1;
    b->created = mine != nullptr ? mine->src != nullptr : !exists;
    if (exists) return 0;
    // Reading the file said ENOENT, so nothing in the way is a file: only folders are missing.
    [[maybe_unused]] bool blocked;
    int rc = parents(out, b->path, &blocked);
    ensure(!blocked);
    return rc;
}

// What goes in each exclude file: the owned links in a git project, from the top of
// the project, in the file of the repository the project belongs to. A Fossil or
// zit project has no local exclude file.
static int plan_blocks(const Ledger *ledger, Actions *out)
{
    uint32_t npairs = 0;
    uint32_t nseen = 0;
    for (uint32_t i = 0; i < out->n; i++) {
        const Action *a = &out->a[i];
        bool owned = a->kind == ACT_CREATE || a->kind == ACT_REPLACE || a->kind == ACT_KEEP;
        if (!owned || a->want->project == nullptr || a->want->vcs != KIND_GIT) continue;
        const char *project = a->want->project;
        size_t plen = strlen(project);
        ensure(strncmp(a->dest, project, plen) == 0 && a->dest[plen] == '/');  // resolve built it so
        char line[EXCLUDE_LINE_MAX];
        [[maybe_unused]] bool fits = exclude_line(a->dest + plen + 1, line, sizeof line);
        ensure(fits);
        if (exclude_for(out, &nseen, project, &pairs[npairs].excl) != 0) return 1;
        pairs[npairs++].line = keep_btext(out, line);
    }
    qsort(pairs, npairs, sizeof pairs[0], cmp_pair);
    for (uint32_t i = 0; i < npairs; i++) {
        bool first = i == 0 || strcmp(pairs[i - 1].excl, pairs[i].excl) != 0;
        if (first) {
            ensure(out->nblocks < BLOCK_MAX);  // one for each project at most
            out->blocks[out->nblocks++] = (Block){BL_SET, pairs[i].excl, out->nlines, 0, false, false};
        } else if (strcmp(pairs[i - 1].line, pairs[i].line) == 0) {
            continue;
        }
        out->lines[out->nlines++] = pairs[i].line;
        out->blocks[out->nblocks - 1].count++;
    }
    uint32_t wanted = out->nblocks;
    for (uint32_t i = 0; i < wanted; i++)
        if (decide_block(ledger, out, &out->blocks[i]) != 0) return 1;
    // A block the ledger has and nothing wants any more.
    for (uint32_t i = 0; i < ledger->n; i++) {
        const LedgerEntry *le = &ledger->e[i];
        bool wants = false;
        for (uint32_t b = 0; b < wanted; b++) wants |= strcmp(out->blocks[b].path, le->dest) == 0;
        if (le->kind != ENTRY_BLOCK || wants) continue;
        ensure(out->nblocks < BLOCK_MAX);  // the projects wanting one, and the ledger's entries
        Block *b = &out->blocks[out->nblocks++];
        bool exists;
        *b = (Block){BL_REMOVE, le->dest, 0, 0, le->src != nullptr, false};
        if (exclude_edit(le->dest, nullptr, 0, b->created, true, &b->changed, &exists) != 0) return 1;
    }
    return 0;
}

int place_plan(const Plan *plan, const Ledger *ledger, Actions *out)
{
    out->n = 0;
    out->ndirs = 0;
    out->used = 0;
    for (uint32_t i = 0; i < plan->n; i++) {
        int rc = decide_want(&plan->p[i], ledger, out);
        if (rc != 0) return rc;
    }
    for (uint32_t i = 0; i < plan->njoins; i++) {
        int rc = decide_join(&plan->joins[i], ledger, out);
        if (rc != 0) return rc;
    }
    for (uint32_t i = 0; i < ledger->n; i++) {
        const LedgerEntry *le = &ledger->e[i];
        int rc = 0;
        if (le->kind == ENTRY_LINK && bsearch(le->dest, plan->p, plan->n, sizeof plan->p[0], cmp_dest) == nullptr)
            rc = decide_stale(le, out);
        if (le->kind == ENTRY_FILE && !is_join_path(plan, le->dest)) rc = decide_stale_file(le, out);
        if (rc != 0) return rc;
    }
    out->nblocks = 0;
    out->nlines = 0;
    out->bused = 0;
    int rc = plan_blocks(ledger, out);
    if (rc != 0) return rc;
    qsort(out->a, out->n, sizeof out->a[0], cmp_action);
    return 0;
}

void place_print(const Plan *plan, const Actions *acts)
{
    for (uint32_t i = 0; i < plan->nskips; i++) say(STDOUT_FILENO, "~ %s\n", plan->skips[i]);
    for (uint32_t i = 0; i < acts->n; i++) {
        const Action *a = &acts->a[i];
        if (a->kind == ACT_CREATE || a->kind == ACT_REPLACE)
            say(STDOUT_FILENO, "+ link %s -> %s\n", a->dest, a->src);
        if (a->kind == ACT_REMOVE) say(STDOUT_FILENO, "- link %s\n", a->dest);
        if (a->kind == ACT_WRITE) say(STDOUT_FILENO, "+ file %s\n", a->dest);
        if (a->kind == ACT_UNWRITE) say(STDOUT_FILENO, "- file %s\n", a->dest);
        if (a->kind == ACT_CLASH) say(STDOUT_FILENO, "! clash %s (%s)\n", a->dest, a->reason);
    }
    for (uint32_t i = 0; i < acts->nblocks; i++) {
        const Block *b = &acts->blocks[i];
        if (b->changed) say(STDOUT_FILENO, "%c block %s\n", b->kind == BL_SET ? '+' : '-', b->path);
    }
}

uint32_t place_missing(const Ledger *ledger, bool print)
{
    uint32_t count = 0;
    for (uint32_t i = 0; i < ledger->n; i++) {
        struct stat st;
        const LedgerEntry *le = &ledger->e[i];
        if (le->kind != ENTRY_LINK || sys_lstat(le->dest, &st) == 0 || errno != ENOENT) continue;
        count++;
        if (print) say(STDOUT_FILENO, "missing %s\n", le->dest);
    }
    return count;
}

// ---- lock -------------------------------------------------------------------

// The pid in the lock file, or 0 if it cannot be told.
static pid_t lock_owner(const char *path)
{
    char text[32] = {};
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) return 0;
    ssize_t n = sys_read(fd, text, sizeof text - 1);
    (void)sys_close(fd);
    return n > 0 ? (pid_t)atol(text) : 0;
}

// A lock whose process is gone is taken over. (Two processes that both find it
// stale both remove it and race for O_EXCL; one wins.)
static bool lock_is_stale(const char *path)
{
    pid_t owner = lock_owner(path);
    return owner > 0 && sys_kill0(owner) != 0 && errno == ESRCH;
}

int place_lock(const char *path, bool quiet)
{
    for (unsigned waited = 0;; waited += LOCK_POLL_MS) {
        int fd = sys_open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);
        if (fd >= 0) {
            char text[32];
            int n = snprintf(text, sizeof text, "%d\n", (int)getpid());
            ensure(n > 0);
            bool ok = sys_write_all(fd, text, (size_t)n);
            (void)sys_close(fd);
            if (ok) return 0;
            (void)sys_unlink(path);
            say(STDERR_FILENO, "suit: cannot write the lock %s: %s\n", path, strerror(errno));
            return 1;
        }
        if (errno != EEXIST) {
            say(STDERR_FILENO, "suit: cannot take the lock %s: %s\n", path, strerror(errno));
            return 1;
        }
        if (lock_is_stale(path)) {
            (void)sys_unlink(path);
            continue;
        }
        if (waited >= LOCK_WAIT_MS) {
            if (!quiet) say(STDERR_FILENO, "suit: another suit holds the lock %s; try again in a moment\n", path);
            return EXIT_BUSY;
        }
        platform_pause_ms(LOCK_POLL_MS);
    }
}

void place_unlock(const char *path)
{
    (void)sys_unlink(path);
}

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

constexpr size_t OP_MAX = PLACE_MAX + LEDGER_ENTRY_MAX + JOIN_MAX;

static Ledger next_ledger;
static bool op_done[OP_MAX];
static bool block_done[BLOCK_MAX];
static bool dir_done[DIR_MAX];

static bool add_entry(Ledger *l, EntryKind kind, const char *dest, const char *src)
{
    if (l->n == LEDGER_ENTRY_MAX) return false;
    l->e[l->n++] = (LedgerEntry){kind, dest, src};
    return true;
}

// The ledger for this moment. INTENT, before anything is done: everything that
// is about to exist and everything about to go, so that a crash leaves the
// ledger a superset of the disk. Final, after: only what was done.
static bool build_ledger(Ledger *l, const Ledger *old, const Actions *acts, bool final)
{
    l->n = 0;
    bool ok = true;
    for (uint32_t i = 0; i < old->n; i++)
        if (old->e[i].kind == ENTRY_DIR) ok &= add_entry(l, ENTRY_DIR, old->e[i].dest, nullptr);
    for (uint32_t i = 0; i < acts->ndirs; i++)
        if (!final || dir_done[i]) ok &= add_entry(l, ENTRY_DIR, acts->dirs[i], nullptr);
    for (uint32_t i = 0; i < acts->n; i++) {
        const Action *a = &acts->a[i];
        bool done = final && op_done[i];
        if (a->kind == ACT_KEEP || (a->kind == ACT_CREATE && !(final && !done)))
            ok &= add_entry(l, ENTRY_LINK, a->dest, a->src);
        if (a->kind == ACT_REPLACE) ok &= add_entry(l, ENTRY_LINK, a->dest, done ? a->src : a->old);
        if (a->kind == ACT_REMOVE && !done) ok &= add_entry(l, ENTRY_LINK, a->dest, a->src);
        // A file is listed before it is written, and while it may still be there.
        if (a->kind == ACT_FILE || (a->kind == ACT_WRITE && !(final && !done && a->old == nullptr)))
            ok &= add_entry(l, ENTRY_FILE, a->dest, nullptr);
        if (a->kind == ACT_UNWRITE && !done) ok &= add_entry(l, ENTRY_FILE, a->dest, nullptr);
    }
    for (uint32_t i = 0; i < acts->nblocks; i++) {
        const Block *b = &acts->blocks[i];
        const char *created = b->created ? LEDGER_CREATED : nullptr;
        // A block is listed before it is written, and while it may still be there.
        if (b->kind == BL_SET && (!final || block_done[i] || ledger_find_block(old, b->path) != nullptr))
            ok &= add_entry(l, ENTRY_BLOCK, b->path, created);
        if (b->kind == BL_REMOVE && !(final && block_done[i])) ok &= add_entry(l, ENTRY_BLOCK, b->path, created);
    }
    return ok;
}

static int make_link(const char *dest, const char *src)
{
    static unsigned counter;
    const char *slash = strrchr(dest, '/');
    ensure(slash != nullptr);
    char tmp[PATH_CAP + 64];
    [[maybe_unused]] int n = snprintf(tmp, sizeof tmp, "%.*s/" SUIT_TMP_PREFIX "link.%d.%u",
        (int)(slash - dest), dest, (int)getpid(), counter++);
    ensure(n > 0 && (size_t)n < sizeof tmp);
    if (sys_symlink(src, tmp) != 0 || sys_rename(tmp, dest) != 0) {
        int err = errno;
        (void)sys_unlink(tmp);
        return err;
    }
    return 0;
}

static bool in_phase(ActKind kind, int phase)
{
    if (phase == 0) return kind == ACT_WRITE;
    if (phase == 1) return kind == ACT_CREATE || kind == ACT_REPLACE || kind == ACT_REMOVE;
    return kind == ACT_UNWRITE;
}

// Run the actions of one phase, in order: the joined files are written before
// any link can point at them and removed after every link has left them.
static int run_phase(const Actions *acts, int phase)
{
    for (uint32_t i = 0; i < acts->n; i++) {
        const Action *a = &acts->a[i];
        if (!in_phase(a->kind, phase)) continue;
        if (a->kind == ACT_WRITE) {
            if (join_write(a->join) != 0) return 1;
        } else {
            bool removing = a->kind == ACT_REMOVE || a->kind == ACT_UNWRITE;
            int err = removing ? (sys_unlink(a->dest) == 0 ? 0 : errno) : make_link(a->dest, a->src);
            if (err != 0) {
                say(STDERR_FILENO, "suit: cannot %s %s: %s\n", removing ? "remove" : "link", a->dest,
                    strerror(err));
                return 1;
            }
        }
        op_done[i] = true;
    }
    return 0;
}

// Make the exclude files hold their blocks (SET) or hold none (REMOVE). The
// blocks go in before the links they hide, and out after the links have gone.
static int run_blocks(const Actions *acts, BlockKind kind)
{
    for (uint32_t i = 0; i < acts->nblocks; i++) {
        const Block *b = &acts->blocks[i];
        if (b->kind != kind) continue;
        bool changed, exists;
        uint32_t n = kind == BL_SET ? b->count : 0;
        if (exclude_edit(b->path, &acts->lines[b->first], n, b->created, false, &changed, &exists) != 0) return 1;
        block_done[i] = true;
    }
    return 0;
}

static int run_actions(const Actions *acts)
{
    for (uint32_t i = 0; i < acts->ndirs; i++) {
        if (sys_mkdir(acts->dirs[i], 0755) != 0 && errno != EEXIST) {
            say(STDERR_FILENO, "suit: cannot make the folder %s: %s\n", acts->dirs[i], strerror(errno));
            return 1;
        }
        dir_done[i] = true;
    }
    for (int phase = 0; phase < 3; phase++) {
        int rc = phase == 1 ? run_blocks(acts, BL_SET) : 0;
        rc = rc != 0 ? rc : run_phase(acts, phase);
        rc = rc != 0 || phase != 2 ? rc : run_blocks(acts, BL_REMOVE);
        if (rc != 0) return rc;
    }
    return 0;
}

static int write_ledger(const Ledger *l, const char *path)
{
    int err = ledger_write(l, path);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write the ledger %s: %s\n", path, strerror(err));
    return err == 0 ? 0 : 1;
}

int place_apply(const Ledger *old, const Actions *acts, const char *ledger_path)
{
    memset(op_done, 0, sizeof op_done);
    memset(dir_done, 0, sizeof dir_done);
    memset(block_done, 0, sizeof block_done);
    if (!build_ledger(&next_ledger, old, acts, false)) {
        say(STDERR_FILENO, "suit: the ledger would hold more than %u entries\n", LEDGER_ENTRY_MAX);
        return 1;
    }
    int rc = write_ledger(&next_ledger, ledger_path);
    if (rc != 0) return rc;
    int failed = run_actions(acts);
    // The limit was checked for the first ledger; the final one is never larger.
    [[maybe_unused]] bool fits = build_ledger(&next_ledger, old, acts, true);
    ensure(fits);
    rc = write_ledger(&next_ledger, ledger_path);
    return failed != 0 ? failed : rc;
}

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

static bool off_gone[LEDGER_ENTRY_MAX];

// Remove one link if it is still ours. -1 left alone, 0 removed or already gone,
// 1 error.
static int off_link(const LedgerEntry *le)
{
    DestKind kind;
    char target[PATH_CAP];
    int rc = inspect(le->dest, &kind, target, sizeof target);
    if (rc != 0) return rc;
    if (kind == D_NONE) return 0;
    if (kind != D_LINK || strcmp(target, le->src) != 0) {
        say(STDOUT_FILENO, "left %s (%s)\n", le->dest, reason_for(kind));
        return 0;
    }
    if (sys_unlink(le->dest) != 0) {
        say(STDERR_FILENO, "suit: cannot remove %s: %s\n", le->dest, strerror(errno));
        return 1;
    }
    say(STDOUT_FILENO, "- link %s\n", le->dest);
    return 0;
}

// Remove one joined file. It is suit's own, so it goes whatever it holds.
static int off_file(const LedgerEntry *le)
{
    if (sys_unlink(le->dest) == 0) {
        say(STDOUT_FILENO, "- file %s\n", le->dest);
        return 0;
    }
    if (errno == ENOENT) return 0;
    say(STDERR_FILENO, "suit: cannot remove %s: %s\n", le->dest, strerror(errno));
    return 1;
}

static int off_dir(const LedgerEntry *le)
{
    if (sys_rmdir(le->dest) == 0) {
        say(STDOUT_FILENO, "- dir %s\n", le->dest);
        return 0;
    }
    if (errno == ENOENT) return 0;
    if (errno == ENOTEMPTY || errno == EEXIST) {
        say(STDOUT_FILENO, "left %s (not empty)\n", le->dest);
        return 0;
    }
    say(STDERR_FILENO, "suit: cannot remove the folder %s: %s\n", le->dest, strerror(errno));
    return 1;
}

// Take suit's block out of one exclude file.
static int off_block(const LedgerEntry *le)
{
    bool changed, exists;
    if (exclude_edit(le->dest, nullptr, 0, le->src != nullptr, false, &changed, &exists) != 0) return 1;
    if (changed) say(STDOUT_FILENO, "- block %s\n", le->dest);
    return 0;
}

int place_off(const Ledger *old, const char *ledger_path)
{
    memset(off_gone, 0, sizeof off_gone);
    int failed = 0;
    for (uint32_t i = 0; i < old->n && failed == 0; i++) {
        if (old->e[i].kind != ENTRY_LINK) continue;
        failed = off_link(&old->e[i]);
        off_gone[i] = failed == 0;
    }
    for (uint32_t i = 0; i < old->n && failed == 0; i++) {
        if (old->e[i].kind != ENTRY_FILE) continue;
        failed = off_file(&old->e[i]);
        off_gone[i] = failed == 0;
    }
    for (uint32_t i = 0; i < old->n && failed == 0; i++) {
        if (old->e[i].kind != ENTRY_BLOCK) continue;
        failed = off_block(&old->e[i]);
        off_gone[i] = failed == 0;
    }
    // Folders go deepest first, so a folder goes before the one that holds it.
    static uint32_t dirs[LEDGER_ENTRY_MAX];
    uint32_t ndirs = 0;
    for (uint32_t i = 0; i < old->n; i++)
        if (old->e[i].kind == ENTRY_DIR) dirs[ndirs++] = i;
    for (uint32_t i = 1; i < ndirs; i++) {  // insertion sort, longest path first
        uint32_t cur = dirs[i];
        uint32_t j = i;
        while (j > 0 && strcmp(old->e[dirs[j - 1]].dest, old->e[cur].dest) < 0) {
            dirs[j] = dirs[j - 1];
            j--;
        }
        dirs[j] = cur;
    }
    for (uint32_t i = 0; i < ndirs && failed == 0; i++) {
        failed = off_dir(&old->e[dirs[i]]);
        off_gone[dirs[i]] = failed == 0;
    }
    next_ledger.n = 0;
    for (uint32_t i = 0; i < old->n; i++)
        if (!off_gone[i]) next_ledger.e[next_ledger.n++] = old->e[i];
    int rc = write_ledger(&next_ledger, ledger_path);
    return failed != 0 ? failed : rc;
}