#include "assets.h"
#include "commands.h"
#include "conf.h"
#include "curate.h"
#include "lint.h"
#include "place.h"
#include "platform.h"
#include "resolve.h"
#include "store.h"
#include "wardrobes.h"
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
// `suit curate apply FILE [--yes]` (docs/curate.md, "Applying the choices"). The choices are worked out
// on the text of each wardrobe's suit.conf, in memory: every step changes the text and parses and checks the
// whole set again, so what is decided next is decided on what the earlier steps made. Nothing is written
// until the whole plan is made, and then only with --yes.
static_assert((int)AK_SKILL == 0 && (int)AK_AGENT == 1 && (int)AK_COMMAND == 2);
constexpr uint32_t NO = 0xffffffffu;
constexpr uint32_t SEC_WORDS = (CONF_SECTION_MAX + 63) / 64;
// A little room beyond the limit of a file, for what one step adds before the parser can say it is too big.
constexpr size_t TEXT_CAP = CONF_FILE_MAX + 2 * CONF_LINE_MAX + 1024;
constexpr size_t WORDS_MAX = 2100; // a line of at most 4096 bytes holds fewer words
constexpr size_t WKEY_MAX = 2 * CONF_WEAR_MAX;
typedef uint64_t Bits[SEC_WORDS];
static bool bit_get(const uint64_t *b, uint32_t i)
{
return (b[i / 64] >> (i % 64) & 1) != 0;
}
static void bit_set(uint64_t *b, uint32_t i)
{
b[i / 64] |= 1ull << (i % 64);
}
static bool bits_any(const uint64_t *b)
{
uint64_t any = 0;
for (uint32_t i = 0; i < SEC_WORDS; i++) any |= b[i];
return any != 0;
}
typedef struct {
CurateChoice c;
int line;
uint32_t ward;
uint32_t aidx; // in the assets of its kind; NO if it is not there and the line is skipped
uint32_t next; // the next choice of the same asset (personal lines for other projects), or NO
bool later; // a placing choice of the same asset comes before this one in the file
uint64_t have; // call and auto: which of the harnesses' `skills.call` lines its front matter holds
bool effective;
Bits listed; // the outfits (sections of `before`) that list it
Bits reach; // the wears (sections of `before`) that reach it, outfits named attic excepted
Bits after; // the same wears, in the set after the changes (sections of `cur`)
} Choice;
static Choice choices[CURATE_ASSETS_MAX];
static uint32_t nchoices;
static uint32_t choice_of[AK_COMMAND + 1][ASSET_MAX];
static char file_buf[CHOICES_FILE_MAX + 1];
static const char *file_arg;
static Wards wards;
static Assets assets;
static Conf before; // the set as it is on disk
static Conf cur; // the set as the changes made so far leave it
static Conf part;
static char orig[WARDROBE_MAX][TEXT_CAP];
static size_t orig_len[WARDROBE_MAX];
static char text[WARDROBE_MAX][TEXT_CAP];
static size_t text_len[WARDROBE_MAX];
static unsigned gen[WARDROBE_MAX]; // how many times a wardrobe's text was changed
static unsigned counts[CHOICE_AUTO + 1][WARDROBE_MAX]; // the choices that changed a wardrobe, by act
static bool front_todo[WARDROBE_MAX]; // a skill's front matter in the wardrobe changes
// The `skills.call` lines of the harnesses, each once, and the buffers a SKILL.md is read and edited in.
static const char *call_line[CURATE_CALL_LINES_MAX];
static size_t ncall;
static char front_in[LINT_FILE_MAX + 1];
static char front_out[LINT_FILE_MAX + CURATE_CALL_LINES_MAX * (CONF_HEADER_MAX + 2)];
static bool expanded[CONF_SECTION_MAX][3]; // `before`'s outfit and kind whose `*` or pattern was made a list
static Bits user_outfits;
// The outfits made in this run and the wardrobe each is in; and which wardrobes need which checked in first:
// dep[u][v] means v has a wear that names an outfit made in u.
typedef struct {
char name[CONF_NAME_MAX + 1];
uint32_t ward;
} Made;
static Made made[CONF_OUTFIT_MAX];
static uint32_t nmade;
static bool dep[WARDROBE_MAX][WARDROBE_MAX]; // the outfits of `before` that a user wear reaches
static int fail_rc;
static Out out;
static const char *const kind_word[AK_COMMAND + 1] = {"skill", "agent", "command"};
static int read_file(const char *path, char *buf, size_t limit, size_t *len);
static const char *const kind_key[AK_COMMAND + 1] = {"skills", "agents", "commands"};
__attribute__((format(printf, 1, 2))) static void emit(const char *fmt, ...)
{
char line[2 * CONF_LINE_MAX + 256];
va_list ap;
va_start(ap, fmt);
[[maybe_unused]] int n = vsnprintf(line, sizeof line, fmt, ap);
va_end(ap);
ensure(n > 0 && (size_t)n < sizeof line); // a path and the words around it
out_str(&out, line);
}
// ---- looking in a Conf -------------------------------------------------------------------------------
static const Entry *find_entry(const Conf *c, const Section *s, const char *key)
{
for (uint32_t i = 0; i < s->count; i++)
if (strcmp(c->entries[s->first + i].key, key) == 0) return &c->entries[s->first + i];
return nullptr;
}
static uint32_t find_outfit(const Conf *c, const char *name, size_t len)
{
for (uint32_t i = 0; i < c->nsections; i++) {
const Section *s = &c->sections[i];
if (s->kind == KIND_OUTFIT && strlen(s->arg[0]) == len && memcmp(s->arg[0], name, len) == 0) return i;
}
return NO;
}
// The wear section SCOPE and TARGET with no machine limit.
static uint32_t find_wear(const Conf *c, const char *scope, const char *target)
{
for (uint32_t i = 0; i < c->nsections; i++) {
const Section *s = &c->sections[i];
if (s->kind == KIND_WEAR && strcmp(s->arg[0], scope) == 0 && strcmp(s->arg[1], target) == 0 && s->arg[2][0] == '\0')
return i;
}
return NO;
}
static void wear_text(const Section *s, char *out_text, size_t cap)
{
[[maybe_unused]] int n = snprintf(out_text, cap, "%s%s%s%s%s", s->arg[0], s->arg[1][0] != '\0' ? " " : "", s->arg[1],
s->arg[2][0] != '\0' ? " machine=" : "", s->arg[2]);
ensure(n > 0 && (size_t)n < cap); // a header is one line
}
// Mark the outfits the list VAL names.
static void seed_names(const Conf *c, const char *val, Bits seen)
{
const char *w;
size_t len;
while (conf_list_next(&val, &w, &len)) {
uint32_t o = find_outfit(c, w, len);
ensure(o != NO); // the config was checked
bit_set(seen, o);
}
}
static void seed_wear(const Conf *c, uint32_t wear, Bits seen)
{
const Entry *en = find_entry(c, &c->sections[wear], "outfits");
if (en != nullptr) seed_names(c, en->val, seen);
}
// Add what the marked outfits include, and so on.
static void spread(const Conf *c, Bits seen)
{
bool grew;
do {
grew = false;
for (uint32_t i = 0; i < c->nsections; i++) {
if (c->sections[i].kind != KIND_OUTFIT || !bit_get(seen, i)) continue;
const Entry *inc = find_entry(c, &c->sections[i], "include");
if (inc == nullptr) continue;
const char *v = inc->val;
const char *w;
size_t len;
while (conf_list_next(&v, &w, &len)) {
uint32_t o = find_outfit(c, w, len);
ensure(o != NO);
if (!bit_get(seen, o)) {
bit_set(seen, o);
grew = true;
}
}
}
} while (grew);
}
// Whether the wears of SCOPE and TARGET with no machine limit reach OUTFIT, which exists.
static bool plain_reaches(const Conf *c, const char *scope, const char *target, const char *outfit)
{
Bits seen = {};
for (uint32_t i = 0; i < c->nsections; i++) {
const Section *s = &c->sections[i];
if (s->kind == KIND_WEAR && strcmp(s->arg[0], scope) == 0 && strcmp(s->arg[1], target) == 0 && s->arg[2][0] == '\0')
seed_wear(c, i, seen);
}
spread(c, seen);
uint32_t o = find_outfit(c, outfit, strlen(outfit));
ensure(o != NO);
return bit_get(seen, o);
}
// Whether a plain wear of the project PROJECT names OUTFIT itself.
static bool personal_names(const Conf *c, const char *project, const char *outfit)
{
uint32_t wi = find_wear(c, "personal", project);
if (wi == NO) return false;
const Entry *en = find_entry(c, &c->sections[wi], "outfits");
if (en == nullptr) return false;
const char *v = en->val;
const char *w;
size_t len;
while (conf_list_next(&v, &w, &len))
if (strlen(outfit) == len && memcmp(outfit, w, len) == 0) return true;
return false;
}
// ---- the text of the wardrobes ---------------------------------------------------------------------------
// Parse every wardrobe's text and check the set as one. False after a message.
static bool rebuild(Conf *dst, char (*t)[TEXT_CAP], const size_t *len)
{
ConfError e;
conf_merge_init(dst);
for (uint32_t i = 0; i < wards.n; i++) {
if (!conf_parse_part(&part, t[i], len[i], &e)) {
say(STDERR_FILENO, "%s:%d: %s\n", wards.w[i].conf, e.line, e.msg);
return false;
}
if (!conf_merge(dst, &part, i, &wards, &e)) {
say(STDERR_FILENO, "%s:%d: %s\n", wards.w[e.ward].conf, e.line, e.msg);
return false;
}
}
if (conf_check(dst, &e)) return true;
say(STDERR_FILENO, "%s:%d: %s\n", wards.w[e.ward].conf, e.line, e.msg);
return false;
}
// WARD's text was changed: parse and check the set again.
static bool changed(uint32_t ward)
{
gen[ward]++;
if (rebuild(&cur, text, text_len)) return true;
say(STDERR_FILENO, "suit: the changes make the config of the wardrobes invalid; nothing is changed\n");
fail_rc = 1;
return false;
}
static bool finish_edit(EditResult r, uint32_t ward, const char *what)
{
if (r == EDIT_LONG) {
say(STDERR_FILENO, "suit: %s would have a line of more than %zu bytes; split it by hand and run this again\n", what,
CONF_LINE_MAX);
fail_rc = 2;
return false;
}
ensure(r == EDIT_OK); // TEXT_CAP has room for what one step adds
return changed(ward);
}
// Split the list VAL into words in BUF (CONF_LINE_MAX + 1 bytes); the number of words.
static size_t split_list(const char *val, char *buf, const char **words)
{
size_t n = 0;
const char *v = val;
const char *w;
size_t len;
while (conf_list_next(&v, &w, &len)) {
memcpy(buf, w, len);
buf[len] = '\0';
words[n++] = buf;
buf += len + 1;
}
return n;
}
// The place of WORD in the WORDS, where the list is in byte order and WORD goes in order; else the end.
static size_t insert_at(const char *const *words, size_t n, const char *word)
{
for (size_t i = 1; i < n; i++)
if (strcmp(words[i - 1], words[i]) >= 0) return n;
size_t at = 0;
while (at < n && strcmp(words[at], word) < 0) at++;
return at;
}
// Add WORD to the list KEY of section SI of `cur`, in the text of its wardrobe; make the entry if it has none.
// WHAT names the section in a message.
static bool add_word(uint32_t si, const char *key, const char *word, const char *what)
{
const Section *s = &cur.sections[si];
uint32_t w = s->ward;
const Entry *en = find_entry(&cur, s, key);
if (en == nullptr) {
char line[CONF_NAME_MAX + 32];
[[maybe_unused]] int n = snprintf(line, sizeof line, "%s = %s", key, word);
ensure(n > 0 && (size_t)n < sizeof line);
int after = s->count > 0 ? cur.entries[s->first + s->count - 1].line : s->line;
return finish_edit(curate_edit_insert(text[w], &text_len[w], TEXT_CAP, after, line), w, what);
}
char buf[CONF_LINE_MAX + 1];
const char *words[WORDS_MAX + 1];
size_t n = split_list(en->val, buf, words);
for (size_t i = 0; i < n; i++)
if (glob_match(words[i], word)) return true; // it is there already
size_t at = insert_at(words, n, word);
memmove(words + at + 1, words + at, (n - at) * sizeof words[0]);
words[at] = word;
return finish_edit(curate_edit_value(text[w], &text_len[w], TEXT_CAP, en->line, words, n + 1), w, what);
}
// ---- one choice -----------------------------------------------------------------------------------------
static bool other_ward(const Choice *ch, const char *outfit, uint32_t where)
{
say(STDERR_FILENO,
"%s:%d: the outfit %s is defined in wardrobe %s, and an outfit lists only the assets of its own wardrobe: the %s %s of wardrobe %s "
"cannot go in it\n",
file_arg, ch->line, outfit, wards.w[where].name, kind_word[ch->c.kind], ch->c.name, ch->c.ward);
fail_rc = 2;
return false;
}
// The outfit NAME exists, in the wardrobe of the asset of CH.
static bool ensure_outfit(const Choice *ch, const char *name)
{
uint32_t si = find_outfit(&cur, name, strlen(name));
if (si != NO) {
if (cur.sections[si].ward == ch->ward) return true;
return other_ward(ch, name, cur.sections[si].ward);
}
char header[CONF_NAME_MAX + 16];
[[maybe_unused]] int n = snprintf(header, sizeof header, "[outfit %s]", name);
ensure(n > 0 && (size_t)n < sizeof header);
emit(" outfit %s: create in %s\n", name, wards.w[ch->ward].name);
if (!finish_edit(curate_edit_append(text[ch->ward], &text_len[ch->ward], TEXT_CAP, header, nullptr), ch->ward, name)) return false;
ensure(nmade < CONF_OUTFIT_MAX); // the set would have been refused
memcpy(made[nmade].name, name, strlen(name) + 1);
made[nmade++].ward = ch->ward;
return true;
}
static bool name_too_long(const Choice *ch, const char *what)
{
say(STDERR_FILENO, "%s:%d: the name of wardrobe %s is too long for a curation outfit (%s.%s is over %zu bytes)\n", file_arg, ch->line,
ch->c.ward, what, ch->c.ward, CONF_NAME_MAX);
fail_rc = 2;
return false;
}
// The outfit of the asset of CH that is called BASE here (attic, kept): BASE.WARDROBE if it is there; else a plain
// BASE of this wardrobe, made by hand; else BASE.WARDROBE, to be made. False after a message if that name is too long.
static bool home_outfit(const Choice *ch, const char *base, char *name)
{
if (curate_home_outfit(base, ch->c.ward, name) == 0) return name_too_long(ch, base);
if (find_outfit(&cur, name, strlen(name)) != NO) return true;
uint32_t plain = find_outfit(&cur, base, strlen(base));
if (plain != NO && cur.sections[plain].ward == ch->ward) memcpy(name, base, strlen(base) + 1);
return true;
}
// The wear in the wardrobe WARD now names OUTFIT: if it was made in another wardrobe, that one is checked in first.
static void note_ref(uint32_t ward, const char *outfit)
{
for (uint32_t i = 0; i < nmade; i++)
if (strcmp(made[i].name, outfit) == 0 && made[i].ward != ward) dep[made[i].ward][ward] = true;
}
static bool add_to(const Choice *ch, const char *outfit)
{
uint32_t si = find_outfit(&cur, outfit, strlen(outfit));
ensure(si != NO); // ensure_outfit made it
char what[CONF_NAME_MAX + 16];
snprintf(what, sizeof what, "outfit %s", outfit);
emit(" outfit %s: add %s\n", outfit, ch->c.name);
return add_word(si, kind_key[ch->c.kind], ch->c.name, what);
}
static void note_expanded(const char *outfit, int kind)
{
uint32_t b = find_outfit(&before, outfit, strlen(outfit));
ensure(b != NO);
expanded[b][kind] = true;
}
// Take the asset of CH out of the outfit OUTFIT, which lists it. A `*` or a pattern that reaches it is
// made the explicit list of the names it reaches, byte-ordered, less this one.
static bool remove_from(const Choice *ch, const char *outfit)
{
uint32_t si = find_outfit(&cur, outfit, strlen(outfit));
ensure(si != NO);
const Section *s = &cur.sections[si];
const Entry *en = find_entry(&cur, s, kind_key[ch->c.kind]);
ensure(en != nullptr); // it lists the asset, so it has the key
char buf[CONF_LINE_MAX + 1];
const char *in[WORDS_MAX + 1];
const char *words[WORDS_MAX + 1];
size_t nin = split_list(en->val, buf, in);
size_t n = 0;
size_t bytes = 0;
bool grew = false;
const NameList *have = &assets.list[ch->c.kind];
char what[CONF_NAME_MAX + 16];
snprintf(what, sizeof what, "outfit %s", outfit);
for (size_t i = 0; i < nin; i++) {
bool glob = strchr(in[i], '*') != nullptr;
if (!glob || !glob_match(in[i], ch->c.name)) {
if (!glob && strcmp(in[i], ch->c.name) == 0) continue;
bytes += strlen(in[i]) + 1; // a line that was whole holds these
words[n++] = in[i];
continue;
}
grew = true;
for (uint32_t a = 0; a < have->n; a++) {
if (have->ward[a] != s->ward || !glob_match(in[i], have->name[a]) || strcmp(have->name[a], ch->c.name) == 0) continue;
if (!conf_name_ok(have->name[a], strlen(have->name[a]), false)) {
say(STDERR_FILENO, "suit: outfit %s: `%s = %s` reaches the name '%s', which a list cannot hold; rename it first\n",
outfit, kind_key[ch->c.kind], in[i], have->name[a]);
fail_rc = 2;
return false;
}
bool seen = false;
for (size_t j = 0; j < n; j++) seen |= strcmp(words[j], have->name[a]) == 0;
for (size_t j = i + 1; j < nin; j++) seen |= strcmp(in[j], have->name[a]) == 0;
if (seen) continue;
bytes += strlen(have->name[a]) + 1;
if (bytes > CONF_LINE_MAX + 1) return finish_edit(EDIT_LONG, s->ward, what);
words[n++] = have->name[a];
}
}
if (grew) note_expanded(outfit, ch->c.kind);
emit(" outfit %s: remove %s\n", outfit, ch->c.name);
return finish_edit(curate_edit_value(text[s->ward], &text_len[s->ward], TEXT_CAP, en->line, words, n), s->ward, what);
}
// The wear SCOPE and TARGET (a plain one) reaches OUTFIT: add it to its `outfits`, or make the wear, in
// the wardrobe that holds `[wear user]` if the wear is a personal one, else in the wardrobe of CH.
static bool ensure_wear(const Choice *ch, const char *scope, const char *target, const char *outfit)
{
if (plain_reaches(&cur, scope, target, outfit)) return true;
uint32_t wi = find_wear(&cur, scope, target);
char shown[CHOICE_PROJECT_MAX + 16];
snprintf(shown, sizeof shown, "%s%s%s", scope, target[0] != '\0' ? " " : "", target);
if (wi == NO) {
uint32_t home = ch->ward;
uint32_t user = find_wear(&cur, "user", "");
if (target[0] != '\0' && user != NO) home = cur.sections[user].ward;
char header[CHOICE_PROJECT_MAX + 32];
[[maybe_unused]] int n = snprintf(header, sizeof header, "[wear %s]", shown);
ensure(n > 0 && (size_t)n < sizeof header);
emit(" wear %s: create in %s\n", shown, wards.w[home].name);
if (!finish_edit(curate_edit_append(text[home], &text_len[home], TEXT_CAP, header, nullptr), home, shown)) return false;
wi = find_wear(&cur, scope, target);
ensure(wi != NO);
}
emit(" wear %s: add outfit %s\n", shown, outfit);
char what[CHOICE_PROJECT_MAX + 32];
snprintf(what, sizeof what, "wear %s", shown);
uint32_t wear_ward = cur.sections[wi].ward;
if (!add_word(wi, "outfits", outfit, what)) return false;
note_ref(wear_ward, outfit);
return true;
}
static bool do_keep(const Choice *ch)
{
char kept[CONF_NAME_MAX + 1];
if (!home_outfit(ch, "kept", kept)) return false;
if (!ensure_outfit(ch, kept)) return false;
for (uint32_t s = 0; s < before.nsections; s++) {
if (before.sections[s].kind != KIND_OUTFIT || !bit_get(ch->listed, s) || !curate_is_attic(before.sections[s].arg[0])) continue;
if (!remove_from(ch, before.sections[s].arg[0])) return false;
}
return add_to(ch, kept) && ensure_wear(ch, "user", "", kept);
}
static bool do_retire(const Choice *ch)
{
bool in_attic = false;
for (uint32_t s = 0; s < before.nsections; s++)
in_attic |= before.sections[s].kind == KIND_OUTFIT && bit_get(ch->listed, s) && curate_is_attic(before.sections[s].arg[0]);
char attic[CONF_NAME_MAX + 1];
if (!home_outfit(ch, "attic", attic)) return false;
if (!in_attic && !ensure_outfit(ch, attic)) return false;
for (uint32_t s = 0; s < before.nsections; s++) {
if (before.sections[s].kind != KIND_OUTFIT || !bit_get(ch->listed, s) || curate_is_attic(before.sections[s].arg[0])) continue;
if (!remove_from(ch, before.sections[s].arg[0])) return false;
}
return in_attic || add_to(ch, attic);
}
// The outfit of the project of CH: the first of the names personal-SLUG, personal-SLUG-2, ... that is not
// there, or is there and is worn by this project's own wear.
static bool pick_personal(const Choice *ch, char *name)
{
for (unsigned k = 1;; k++) {
if (curate_personal_outfit(ch->c.ward, ch->c.project, k, name) == 0) return name_too_long(ch, "personal");
uint32_t si = find_outfit(&cur, name, strlen(name));
if (si == NO) return true;
if (!personal_names(&cur, ch->c.project, name)) continue;
if (cur.sections[si].ward == ch->ward) return true;
return other_ward(ch, name, cur.sections[si].ward);
}
}
static bool do_personal(const Choice *ch)
{
char outfit[CONF_NAME_MAX + 1];
if (!pick_personal(ch, outfit) || !ensure_outfit(ch, outfit)) return false;
// Taking it out of what the User scope wears is done once, by the first line of the asset: when a user wear reaches it,
// every personal line of it changes something, so the first one runs.
for (uint32_t s = 0; !ch->later && s < before.nsections; s++) {
if (before.sections[s].kind != KIND_OUTFIT || !bit_get(ch->listed, s) || !bit_get(user_outfits, s)) continue;
if (!remove_from(ch, before.sections[s].arg[0])) return false;
}
return add_to(ch, outfit) && ensure_wear(ch, "personal", ch->c.project, outfit);
}
// ---- how a skill is invoked: call and auto (docs/curate.md, "call and auto") ------------------------------------
static bool invocation(const Choice *ch)
{
return ch->c.act == CHOICE_CALL || ch->c.act == CHOICE_AUTO;
}
// The `skills.call` line of every harness, each line once, in the order of the sections.
static void collect_calls(void)
{
ncall = 0;
for (uint32_t s = 0; s < before.nsections; s++) {
const Section *h = &before.sections[s];
const Entry *en = h->kind == KIND_HARNESS ? find_entry(&before, h, "skills.call") : nullptr;
if (en == nullptr) continue;
size_t k = 0;
while (k < ncall && strcmp(call_line[k], en->val) != 0) k++;
ensure(k < CURATE_CALL_LINES_MAX); // one line for each harness at most
if (k == ncall) call_line[ncall++] = en->val;
}
}
constexpr size_t SKILL_PATH_CAP = WARDROBE_PATH_MAX + CONF_NAME_MAX + 32;
// Read the SKILL.md of CH (its path into PATH) and make in front_out the text with the change of CH (FORWARD, which
// also sets CH->have) or with that change undone. 0 with the length in *OLEN; 1 after a message when it cannot be read;
// 2 when it has no SKILL.md or no front matter, saying nothing.
static int front_make(Choice *ch, bool forward, char *path, size_t *olen)
{
[[maybe_unused]] int n = snprintf(path, SKILL_PATH_CAP, "%s/skills/%s/SKILL.md", wards.w[ch->ward].store, ch->c.name);
ensure(n > 0 && (size_t)n < SKILL_PATH_CAP);
size_t len = 0;
int rc = read_file(path, front_in, LINT_FILE_MAX, &len);
if (rc == 1 && errno == ENOENT) return 2;
if (rc == 1) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", path, strerror(errno));
return 1;
}
if (rc == 2) {
say(STDERR_FILENO, "suit: %s is over %zu bytes\n", path, LINT_FILE_MAX);
return 1;
}
if (forward) (void)curate_front_has(front_in, len, call_line, ncall, &ch->have);
// Forward, every line: call adds those missing, auto takes out those there. Undone, only what the change did: the lines a call
// added (those it did not have) are taken out, and the lines an auto took out (those it had) go back after `name:`.
bool add = (ch->c.act == CHOICE_CALL) == forward;
const char *lines[CURATE_CALL_LINES_MAX];
size_t nl = 0;
for (size_t k = 0; k < ncall; k++)
if (forward || ((ch->have >> k & 1) != 0) == add) lines[nl++] = call_line[k];
FrontResult r = curate_front_edit(front_in, len, lines, nl, add, front_out, sizeof front_out, olen);
ensure(r != FRONT_FULL); // front_out has room for every line
return r == FRONT_OK ? 0 : 2;
}
// Find which `skills.call` lines the skill of each call and auto choice holds, and whether the choice changes something.
// 0; 1 after a message; 2 when a call names a skill with no front matter (each one is said).
static int scan_invocations(void)
{
collect_calls();
uint64_t all = 0;
for (size_t k = 0; k < ncall; k++) all |= 1ull << k;
unsigned errors = 0;
bool warned = false;
for (uint32_t i = 0; i < nchoices; i++) {
Choice *ch = &choices[i];
if (!invocation(ch) || ch->aidx == NO) continue;
if (ncall == 0) {
if (!warned) say(STDERR_FILENO, "%s:%d: warning: no harness has skills.call, so call and auto change nothing\n", file_arg, ch->line);
warned = true;
continue;
}
char path[SKILL_PATH_CAP];
size_t olen = 0;
int rc = front_make(ch, true, path, &olen);
if (rc == 1) return 1;
if (rc == 2 && ch->c.act == CHOICE_CALL) {
say(STDERR_FILENO, "%s:%d: the skill %s of wardrobe %s has no front matter in %s to make it call-only\n", file_arg, ch->line,
ch->c.name, ch->c.ward, path);
errors++;
continue;
}
ch->effective = rc == 0 && (ch->c.act == CHOICE_CALL ? ch->have != all : ch->have != 0);
}
return errors > 0 ? 2 : 0;
}
// The names of the harnesses that have a `skills.call` line (WITH) or none, joined by ", ", into OUT.
static void harness_names(bool with, char *out_names, size_t cap)
{
size_t at = 0;
out_names[0] = '\0';
for (uint32_t s = 0; s < before.nsections; s++) {
const Section *h = &before.sections[s];
if (h->kind != KIND_HARNESS || (find_entry(&before, h, "skills.call") != nullptr) != with) continue;
at += (size_t)snprintf(out_names + at, cap - at, "%s%s", at > 0 ? ", " : "", h->arg[0]);
ensure(at < cap); // 64 harnesses of short names
}
}
static bool run_invocation(const Choice *ch)
{
char on[CONF_HARNESS_MAX * (CONF_NAME_MAX + 2) + 1];
char off[CONF_HARNESS_MAX * (CONF_NAME_MAX + 2) + 1];
harness_names(true, on, sizeof on);
harness_names(false, off, sizeof off);
emit(" skill %s %s: %s in %s%s%s%s\n", ch->c.ward, ch->c.name, ch->c.act == CHOICE_CALL ? "call-only" : "automatic", on,
off[0] != '\0' ? "; no effect in " : "", off, off[0] != '\0' ? " (no skills.call)" : "");
front_todo[ch->ward] = true;
return true;
}
// Write the SKILL.md of CH with its change (FORWARD) or with the change undone. False after a message.
static bool write_front(Choice *ch, bool forward)
{
char path[SKILL_PATH_CAP];
size_t olen = 0;
if (front_make(ch, forward, path, &olen) != 0) {
say(STDERR_FILENO, "suit: cannot change the front matter of %s\n", path);
return false;
}
int err = sys_write_atomic(path, front_out, olen);
if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
return err == 0;
}
static void describe(const Choice *ch, char *line, size_t cap)
{
static const char *const act_word[] = {"keep", "personal", "retire", "call", "auto"};
[[maybe_unused]] int n = snprintf(line, cap, "%s %s %s %s%s%s", act_word[ch->c.act], kind_word[ch->c.kind], ch->c.ward, ch->c.name,
ch->c.act == CHOICE_PERSONAL ? " " : "", ch->c.project);
ensure(n > 0 && (size_t)n < cap);
}
static bool run_choice(const Choice *ch)
{
unsigned before_gen[WARDROBE_MAX];
memcpy(before_gen, gen, sizeof gen);
char line[CHOICE_PROJECT_MAX + 2 * CONF_NAME_MAX + 64];
describe(ch, line, sizeof line);
emit("%s\n", line);
if (invocation(ch)) {
counts[ch->c.act][ch->ward]++;
return run_invocation(ch);
}
bool ok = ch->c.act == CHOICE_KEEP ? do_keep(ch) : ch->c.act == CHOICE_RETIRE ? do_retire(ch) : do_personal(ch);
if (!ok) return false;
for (uint32_t v = 0; v < wards.n; v++)
if (gen[v] != before_gen[v]) counts[ch->c.act][v]++;
return true;
}
// ---- state: which choices change something ----------------------------------------------------------------
static void on_reach(void *state, const Section *wear, const Section *outfit, AssetKind kind, uint32_t index)
{
bool after = *(const bool *)state;
const Conf *c = after ? &cur : &before;
for (uint32_t ci = choice_of[kind][index]; ci != NO; ci = choices[ci].next) {
Choice *ch = &choices[ci];
if (wear == nullptr) {
if (!after) bit_set(ch->listed, (uint32_t)(outfit - c->sections));
continue;
}
if (curate_is_attic(outfit->arg[0])) continue;
bit_set(after ? ch->after : ch->reach, (uint32_t)(wear - c->sections));
}
}
// Whether another personal line of the asset of CH names PROJECT.
static bool sibling_names(const Choice *ch, const char *project)
{
for (uint32_t ci = choice_of[ch->c.kind][ch->aidx]; ci != NO; ci = choices[ci].next)
if (&choices[ci] != ch && strcmp(choices[ci].c.project, project) == 0) return true;
return false;
}
static void evaluate(Choice *ch)
{
bool listed = bits_any(ch->listed);
bool worn = bits_any(ch->reach);
bool user = false;
bool mine = false; // a personal wear of this project reaches it
bool other = false; // some other wear does, not counting those of the projects of its other personal lines
for (uint32_t s = 0; s < before.nsections; s++) {
if (!bit_get(ch->reach, s)) continue;
const Section *w = &before.sections[s];
if (strcmp(w->arg[0], "user") == 0) user = true;
else if (ch->c.act == CHOICE_PERSONAL && strcmp(w->arg[0], "personal") == 0 && strcmp(w->arg[1], ch->c.project) == 0) mine = true;
else if (ch->c.act == CHOICE_PERSONAL && strcmp(w->arg[0], "personal") == 0 && sibling_names(ch, w->arg[1])) continue;
else other = true;
}
if (ch->c.act == CHOICE_KEEP) ch->effective = !worn;
else if (ch->c.act == CHOICE_RETIRE) ch->effective = !listed || worn;
else ch->effective = user || other || !mine;
}
// ---- the choices file ---------------------------------------------------------------------------------------
// 0, 1 (errno set), or 2 for a file that is over LIMIT bytes.
static int read_file(const char *path, char *buf, size_t limit, size_t *len)
{
int fd = sys_open(path, O_RDONLY, 0);
if (fd < 0) return 1;
size_t n = 0;
for (;;) {
ssize_t r = sys_read(fd, buf + n, limit + 1 - n);
if (r < 0 && errno == EINTR) continue;
if (r < 0) {
int err = errno;
(void)sys_close(fd);
errno = err;
return 1;
}
if (r == 0) break;
n += (size_t)r;
if (n > limit) break;
}
(void)sys_close(fd);
*len = n;
return n > limit ? 2 : 0;
}
// Read and parse the choices file. 0, 1 if it cannot be read, 2 if it is refused (every problem is said).
static int parse_choices(const char *path)
{
size_t len = 0;
int rc = read_file(path, file_buf, CHOICES_FILE_MAX, &len);
if (rc == 1) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", path, strerror(errno));
return 1;
}
if (rc == 2) {
say(STDERR_FILENO, "%s:0: the file is over %zu bytes\n", path, CHOICES_FILE_MAX);
return 2;
}
unsigned errors = 0;
bool over = false;
int ln = 0;
for (size_t pos = 0; pos < len;) {
const char *nl = memchr(file_buf + pos, '\n', len - pos);
size_t end = nl != nullptr ? (size_t)(nl - file_buf) : len;
const char *line = file_buf + pos;
size_t n = end - pos;
pos = end + 1;
ln++;
if (ln == 1) {
if (!curate_choices_header(line, n)) {
say(STDERR_FILENO, "%s:1: not a suit choices file: the first line must be `# suit choices 1`\n", path);
errors++;
}
continue;
}
CurateChoice c;
char msg[256];
ChoiceLine kind = curate_choice_parse(line, n, &c, msg, sizeof msg);
if (kind == CHOICE_NONE) continue;
if (kind == CHOICE_BAD) {
say(STDERR_FILENO, "%s:%d: %s\n", path, ln, msg);
errors++;
continue;
}
if (kind == CHOICE_FOLDER) {
say(STDERR_FILENO, "%s:%d: warning: %s: skipped\n", path, ln, msg);
continue;
}
if (nchoices == CURATE_ASSETS_MAX) {
if (!over) say(STDERR_FILENO, "%s:%d: more than %u choices\n", path, ln, CURATE_ASSETS_MAX);
over = true;
errors++;
continue;
}
// One asset may have its placing lines (keep, retire, or one personal line for each project) and one call or auto line, but
// not call or auto with retire. Any other second line for it is refused.
bool dup = false;
bool later = false;
bool inv = c.act >= CHOICE_CALL;
for (uint32_t j = 0; j < nchoices; j++) {
const CurateChoice *o = &choices[j].c;
if (o->kind != c.kind || strcmp(o->ward, c.ward) != 0 || strcmp(o->name, c.name) != 0) continue;
bool oinv = o->act >= CHOICE_CALL;
bool retired = inv != oinv && (o->act == CHOICE_RETIRE || c.act == CHOICE_RETIRE);
if (inv != oinv && !retired) continue; // a placing line and an invocation line go together
later |= !inv;
bool both = o->act == CHOICE_PERSONAL && c.act == CHOICE_PERSONAL;
if (both && strcmp(o->project, c.project) != 0) continue;
if (both) say(STDERR_FILENO, "%s:%d: the %s %s of wardrobe %s is also limited to %s on line %d\n", path, ln, kind_word[c.kind], c.name,
c.ward, c.project, choices[j].line);
else if (retired && inv) say(STDERR_FILENO, "%s:%d: the skill %s of wardrobe %s is retired on line %d, so it cannot also be made %s\n",
path, ln, c.name, c.ward, choices[j].line, c.act == CHOICE_CALL ? "call-only" : "automatic");
else if (retired) say(STDERR_FILENO, "%s:%d: the skill %s of wardrobe %s is made %s on line %d, so it cannot also be retired\n", path, ln,
c.name, c.ward, o->act == CHOICE_CALL ? "call-only" : "automatic", choices[j].line);
else say(STDERR_FILENO, "%s:%d: the %s %s of wardrobe %s is also chosen on line %d\n", path, ln, kind_word[c.kind], c.name, c.ward,
choices[j].line);
errors++;
dup = true;
break;
}
if (dup) continue;
choices[nchoices] = (Choice){.c = c, .line = ln, .aidx = NO, .next = NO, .later = later};
nchoices++;
}
if (ln == 0) {
say(STDERR_FILENO, "%s:1: not a suit choices file: the first line must be `# suit choices 1`\n", path);
errors++;
}
return errors > 0 ? 2 : 0;
}
// Find the asset of each choice; a line whose wardrobe or asset is not there is a warning and is left out.
static uint32_t find_assets(void)
{
memset(choice_of, 0xff, sizeof choice_of);
uint32_t skipped = 0;
for (uint32_t i = 0; i < nchoices; i++) {
Choice *ch = &choices[i];
uint32_t w = NO;
for (uint32_t v = 0; v < wards.n; v++)
if (strcmp(wards.w[v].name, ch->c.ward) == 0) w = v;
const NameList *l = &assets.list[ch->c.kind];
uint32_t a = NO;
for (uint32_t k = 0; w != NO && k < l->n; k++)
if (l->ward[k] == w && strcmp(l->name[k], ch->c.name) == 0) a = k;
if (a == NO) {
say(STDERR_FILENO, "%s:%d: warning: no %s %s in wardrobe %s: skipped\n", file_arg, ch->line, kind_word[ch->c.kind], ch->c.name,
ch->c.ward);
skipped++;
continue;
}
ch->ward = w;
ch->aidx = a;
if (invocation(ch)) continue; // it changes no outfit, so nothing that reaches the asset concerns it
uint32_t *link = &choice_of[ch->c.kind][a];
while (*link != NO) link = &choices[*link].next;
*link = i;
}
return skipped;
}
// ---- what the plan says about the placements and the wears --------------------------------------------------------
typedef struct {
const char *project; // nullptr for the User scope
char sign;
const char *dest;
const char *src;
} Diff;
static Plan plan_before;
static Plan plan_after;
static Diff diffs[2 * PLACE_MAX];
static int diff_cmp(const void *pa, const void *pb)
{
const Diff *a = pa;
const Diff *b = pb;
const char *pa_s = a->project != nullptr ? a->project : "";
const char *pb_s = b->project != nullptr ? b->project : "";
int c = (a->project != nullptr) - (b->project != nullptr);
c = c != 0 ? c : strcmp(pa_s, pb_s);
return c != 0 ? c : strcmp(a->dest, b->dest);
}
static void print_placements(void)
{
if (commands_resolve(&before, &wards, &assets, &plan_before) != 0 || commands_resolve(&cur, &wards, &assets, &plan_after) != 0) {
emit("placements: not shown, the config does not place\n");
return;
}
uint32_t nd = 0;
uint32_t i = 0;
uint32_t j = 0;
while (i < plan_before.n || j < plan_after.n) {
int c = i == plan_before.n ? 1 : j == plan_after.n ? -1 : strcmp(plan_before.p[i].dest, plan_after.p[j].dest);
const Placement *b = &plan_before.p[i];
const Placement *a = &plan_after.p[j];
if (c < 0) diffs[nd++] = (Diff){b->project, '-', b->dest, nullptr};
else if (c > 0) diffs[nd++] = (Diff){a->project, '+', a->dest, a->src};
else if (strcmp(a->src, b->src) != 0) diffs[nd++] = (Diff){a->project, '+', a->dest, a->src};
if (c <= 0) i++;
if (c >= 0) j++;
}
if (nd == 0) {
emit("placements: none change\n");
return;
}
qsort(diffs, nd, sizeof diffs[0], diff_cmp);
emit("placements:\n");
for (uint32_t d = 0; d < nd; d++) {
const Diff *x = &diffs[d];
bool first = d == 0 || (diffs[d - 1].project == nullptr) != (x->project == nullptr) ||
(x->project != nullptr && strcmp(diffs[d - 1].project, x->project) != 0);
if (first && x->project == nullptr) emit(" user\n");
if (first && x->project != nullptr) emit(" personal %s\n", x->project);
if (x->sign == '+') emit(" + link %s -> %s\n", x->dest, x->src);
else emit(" - link %s\n", x->dest);
}
}
static char wkey[WKEY_MAX][CONF_LINE_MAX + 16];
static uint32_t nwkey;
static uint32_t key_before[CONF_SECTION_MAX];
static uint32_t key_after[CONF_SECTION_MAX];
static uint32_t key_gone[WKEY_MAX];
static uint32_t key_came[WKEY_MAX];
static uint32_t key_of(const Section *wear)
{
char t[CONF_LINE_MAX + 16];
wear_text(wear, t, sizeof t);
for (uint32_t k = 0; k < nwkey; k++)
if (strcmp(wkey[k], t) == 0) return k;
ensure(nwkey < WKEY_MAX); // at most 256 wears in each set
memcpy(wkey[nwkey], t, strlen(t) + 1);
return nwkey++;
}
// Whether CH is the first line of its asset that changes something: the lines of one asset share what reaches it, so
// only that one is counted.
static bool first_effective(const Choice *ch)
{
uint32_t ci = choice_of[ch->c.kind][ch->aidx];
while (!choices[ci].effective) ci = choices[ci].next;
return &choices[ci] == ch;
}
// For each wear that reaches more or fewer of the chosen assets than before.
static void print_wears(void)
{
for (uint32_t s = 0; s < before.nsections; s++)
if (before.sections[s].kind == KIND_WEAR) key_before[s] = key_of(&before.sections[s]);
for (uint32_t s = 0; s < cur.nsections; s++)
if (cur.sections[s].kind == KIND_WEAR) key_after[s] = key_of(&cur.sections[s]);
for (uint32_t ci = 0; ci < nchoices; ci++) {
const Choice *ch = &choices[ci];
if (!ch->effective || invocation(ch) || !first_effective(ch)) continue;
Bits kb = {};
Bits ka = {};
for (uint32_t s = 0; s < before.nsections; s++)
if (bit_get(ch->reach, s)) bit_set(kb, key_before[s]);
for (uint32_t s = 0; s < cur.nsections; s++)
if (bit_get(ch->after, s)) bit_set(ka, key_after[s]);
for (uint32_t k = 0; k < nwkey; k++) {
if (bit_get(kb, k) && !bit_get(ka, k)) key_gone[k]++;
if (bit_get(ka, k) && !bit_get(kb, k)) key_came[k]++;
}
}
bool any = false;
for (uint32_t k = 0; k < nwkey; k++) {
if (key_gone[k] == 0 && key_came[k] == 0) continue;
if (!any) emit("wears:\n");
any = true;
emit(" wear %s: %u leave, %u arrive\n", wkey[k], key_gone[k], key_came[k]);
}
if (!any) emit("wears: none change\n");
}
static void print_expansions(void)
{
for (uint32_t b = 0; b < before.nsections; b++) {
for (int k = 0; k < 3; k++) {
if (!expanded[b][k]) continue;
const Section *s = &before.sections[b];
const Entry *was = find_entry(&before, s, kind_key[k]);
uint32_t ci = find_outfit(&cur, s->arg[0], strlen(s->arg[0]));
const Entry *now = find_entry(&cur, &cur.sections[ci], kind_key[k]);
unsigned names = 0;
const char *v = now != nullptr ? now->val : "";
const char *w;
size_t len;
while (conf_list_next(&v, &w, &len)) names++;
emit("outfit %s: `%s = %s` becomes an explicit list of %u names\n", s->arg[0], kind_key[k], was->val, names);
}
}
}
// ---- the check-in comment ------------------------------------------------------------------------------------
static void comment_of(uint32_t w, char *comment, size_t cap)
{
static const char *const act_word[] = {"kept", "limited", "retired", "call-only", "automatic"};
static const ChoiceAct order[] = {CHOICE_KEEP, CHOICE_PERSONAL, CHOICE_RETIRE, CHOICE_CALL, CHOICE_AUTO};
size_t at = (size_t)snprintf(comment, cap, "Curate:");
const char *sep = " ";
for (int i = 0; i < 5; i++) {
if (counts[order[i]][w] == 0) continue;
at += (size_t)snprintf(comment + at, cap - at, "%s%u %s", sep, counts[order[i]][w], act_word[i]);
sep = ", ";
}
ensure(at < cap);
}
static bool differs(uint32_t w)
{
return front_todo[w] || text_len[w] != orig_len[w] || memcmp(text[w], orig[w], text_len[w]) != 0;
}
// Put wardrobe W back as it was: its suit.conf, and the front matter of the first UPTO choices that changed one of its skills.
static void put_back(uint32_t w, uint32_t upto)
{
int err = sys_write_atomic(wards.w[w].conf, orig[w], orig_len[w]);
if (err != 0) say(STDERR_FILENO, "suit: cannot put %s back as it was: %s\n", wards.w[w].conf, strerror(err));
for (uint32_t i = 0; i < upto; i++)
if (choices[i].effective && invocation(&choices[i]) && choices[i].ward == w) (void)write_front(&choices[i], false);
}
// ---- making the changes ---------------------------------------------------------------------------------------------
static void say_progress(const bool *done, const bool *todo)
{
char have[WARDROBE_MAX * (CONF_NAME_MAX + 2) + 8] = "";
char left[WARDROBE_MAX * (CONF_NAME_MAX + 2) + 8] = "";
for (uint32_t w = 0; w < wards.n; w++) {
if (!todo[w]) continue;
char *to = done[w] ? have : left;
size_t at = strlen(to);
snprintf(to + at, sizeof have - at, "%s%s", at > 0 ? ", " : "", wards.w[w].name);
}
// The wardrobe that failed is one of those not changed, so that list is never empty.
say(STDERR_FILENO, "suit: wardrobes changed: %s; not changed: %s\n", have[0] != '\0' ? have : "none", left);
}
// The order to check the changed wardrobes in: a wardrobe that made an outfit before any that names it in a wear, and in
// byte order of name among the rest. False after a message if each of some wardrobes needs another first.
static bool order_wards(const bool *todo, uint32_t *order, uint32_t count)
{
bool pending[WARDROBE_MAX];
memcpy(pending, todo, sizeof pending);
for (uint32_t n = 0; n < count; n++) {
uint32_t pick = NO;
for (uint32_t w = 0; w < wards.n && pick == NO; w++) {
if (!pending[w]) continue;
bool ready = true;
for (uint32_t u = 0; u < wards.n; u++) ready &= !(pending[u] && dep[u][w]);
if (ready) pick = w;
}
if (pick == NO) {
char left[WARDROBE_MAX * (CONF_NAME_MAX + 2) + 8] = "";
for (uint32_t w = 0; w < wards.n; w++) {
if (!pending[w]) continue;
size_t at = strlen(left);
snprintf(left + at, sizeof left - at, "%s%s", at > 0 ? ", " : "", wards.w[w].name);
}
say(STDERR_FILENO,
"suit: the wardrobes %s each name an outfit that another of them makes, so none can be checked in first; apply the choices of one wardrobe, then the other's\n",
left);
fail_rc = 2;
return false;
}
pending[pick] = false;
order[n] = pick;
}
return true;
}
// Write each changed wardrobe's suit.conf and check it in, in ORDER.
static int write_wardrobes(const bool *todo, const uint32_t *order, uint32_t count)
{
for (uint32_t k = 0; k < count; k++) {
uint32_t w = order[k];
int rc = store_check_journal(wards.w[w].name);
if (rc != 0) return rc;
unsigned n = 0;
rc = store_changes(wards.w[w].name, &n);
if (rc != 0) return rc;
if (n > 0) {
say(STDERR_FILENO, "suit: wardrobe %s has local changes: run `suit commit %s -m TEXT` or `suit tend %s` first\n", wards.w[w].name,
wards.w[w].name, wards.w[w].name);
return EXIT_LOCAL_CHANGES;
}
}
bool done[WARDROBE_MAX] = {};
for (uint32_t k = 0; k < count; k++) {
uint32_t w = order[k];
int err = sys_write_atomic(wards.w[w].conf, text[w], text_len[w]);
if (err != 0) {
say(STDERR_FILENO, "suit: cannot write %s: %s\n", wards.w[w].conf, strerror(err));
say_progress(done, todo);
return 1;
}
for (uint32_t i = 0; i < nchoices; i++) {
if (!choices[i].effective || !invocation(&choices[i]) || choices[i].ward != w || write_front(&choices[i], true)) continue;
put_back(w, i);
say_progress(done, todo);
return 1;
}
char comment[160];
comment_of(w, comment, sizeof comment);
int rc = store_commit(wards.w[w].name, comment, false);
if (rc != 0) {
// Put the files back, so that the working copy is as it was and not left with an edit nobody checked in.
put_back(w, nchoices);
say(STDERR_FILENO, "suit: the check-in of wardrobe %s failed (exit %d)\n", wards.w[w].name, rc);
say_progress(done, todo);
return 1;
}
done[w] = true;
say(STDOUT_FILENO, "wardrobe %s: %s\n", wards.w[w].name, comment);
}
return 0;
}
// ---- the command ----------------------------------------------------------------------------------------------------------
static int usage_error(void)
{
say(STDERR_FILENO, "usage: suit curate apply FILE [--yes]\n");
return 2;
}
// Load the wardrobes, their configs and the assets. 0, or the exit status after a message.
static int load_all(const char *suit_home)
{
int rc = wardrobes_find(&wards, suit_home);
if (rc != 0) return rc;
for (uint32_t w = 0; w < wards.n; w++) {
rc = read_file(wards.w[w].conf, orig[w], CONF_FILE_MAX, &orig_len[w]);
if (rc == 1) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", wards.w[w].conf, strerror(errno));
return 1;
}
if (rc == 2) {
say(STDERR_FILENO, "%s:0: file is over %zu bytes\n", wards.w[w].conf, CONF_FILE_MAX);
return 2;
}
memcpy(text[w], orig[w], orig_len[w]);
text_len[w] = orig_len[w];
}
if (!rebuild(&before, orig, orig_len)) return 2;
[[maybe_unused]] bool same = rebuild(&cur, text, text_len); // the same text again
ensure(same);
return assets_load(&wards, &assets);
}
// Whether a wear reaches the outfit attic: the first, as text, or nullptr.
static const char *attic_worn(char *shown, size_t cap)
{
for (uint32_t s = 0; s < before.nsections; s++) {
if (before.sections[s].kind != KIND_WEAR) continue;
Bits seen = {};
seed_wear(&before, s, seen);
spread(&before, seen);
for (uint32_t o = 0; o < before.nsections; o++) {
if (before.sections[o].kind != KIND_OUTFIT || !curate_is_attic(before.sections[o].arg[0]) || !bit_get(seen, o)) continue;
wear_text(&before.sections[s], shown, cap);
return shown;
}
}
return nullptr;
}
static int apply(bool yes)
{
char suit_home[COMMANDS_PATH_CAP];
char lock_path[COMMANDS_PATH_CAP];
int rc = commands_home(suit_home, lock_path);
if (rc != 0) return rc;
if (yes) {
rc = place_lock(lock_path, false);
if (rc != 0) return rc;
}
rc = parse_choices(file_arg);
rc = rc != 0 ? rc : load_all(suit_home);
if (rc != 0) {
if (yes) place_unlock(lock_path);
return rc;
}
uint32_t skipped = find_assets();
bool phase = false;
resolve_reach(&before, &assets, on_reach, &phase);
for (uint32_t s = 0; s < before.nsections; s++)
if (before.sections[s].kind == KIND_WEAR && strcmp(before.sections[s].arg[0], "user") == 0) seed_wear(&before, s, user_outfits);
spread(&before, user_outfits);
rc = scan_invocations();
if (rc != 0) {
if (yes) place_unlock(lock_path);
return rc;
}
uint32_t effective = 0;
uint32_t retiring = 0;
for (uint32_t i = 0; i < nchoices; i++) {
if (choices[i].aidx == NO) continue;
if (!invocation(&choices[i])) evaluate(&choices[i]);
if (choices[i].effective) effective++;
if (choices[i].effective && choices[i].c.act == CHOICE_RETIRE) retiring++;
}
char shown[CONF_LINE_MAX + 16];
const char *worn = retiring > 0 ? attic_worn(shown, sizeof shown) : nullptr;
if (worn != nullptr) {
say(STDERR_FILENO, "suit: an attic outfit is worn by [wear %s], so nothing can be retired into it; take it out of that wear first\n",
worn);
if (yes) place_unlock(lock_path);
return 2;
}
out_init(&out, STDOUT_FILENO);
emit("plan: %u choices, %u change something, %u already true, %u skipped\n", nchoices, effective,
nchoices - effective - skipped, skipped);
bool ok = true;
for (uint32_t i = 0; ok && i < nchoices; i++)
if (choices[i].aidx != NO && choices[i].effective) ok = run_choice(&choices[i]);
bool todo[WARDROBE_MAX] = {};
uint32_t nchanged = 0;
if (ok) {
for (uint32_t w = 0; w < wards.n; w++) {
todo[w] = differs(w);
if (todo[w]) nchanged++;
}
if (nchanged == 0) emit("nothing to change\n");
}
uint32_t order[WARDROBE_MAX];
if (ok && nchanged > 0) ok = order_wards(todo, order, nchanged);
if (ok && nchanged > 0) {
phase = true;
resolve_reach(&cur, &assets, on_reach, &phase);
print_expansions();
print_placements();
print_wears();
emit("check-ins, in this order:\n");
for (uint32_t k = 0; k < nchanged; k++) {
uint32_t w = order[k];
char comment[160];
comment_of(w, comment, sizeof comment);
emit(" %s: %s\n", wards.w[w].name, comment);
}
}
bool flushed = out_finish(&out);
if (!ok) {
if (yes) place_unlock(lock_path);
return fail_rc;
}
if (!flushed) {
say(STDERR_FILENO, "suit: cannot write the plan: %s\n", strerror(errno));
rc = 1;
} else if (!yes) {
rc = 0;
if (nchanged > 0) say(STDOUT_FILENO, "nothing was changed; run again with --yes to make these changes\n");
} else {
rc = nchanged > 0 ? write_wardrobes(todo, order, nchanged) : 0;
if (rc == 0 && nchanged > 0)
say(STDOUT_FILENO, "nothing was applied to your folders: the next `suit run` places what the new config says\n");
}
if (yes) place_unlock(lock_path);
return rc;
}
int cmd_curate_apply(int argc, char **argv)
{
bool yes = false;
file_arg = nullptr;
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "--yes") == 0 && !yes) yes = true;
else if (file_arg == nullptr && argv[i][0] != '-') file_arg = argv[i];
else return usage_error();
}
if (file_arg == nullptr) return usage_error();
return apply(yes);
}