Skip to content
suit Documentation
Login

Documentation

#include "wardrobes.h"

#include "platform.h"

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

typedef struct {
    Wards *w;
    const char *dir;
    int rc;  // why the walk stopped
} Find;

static int add_wardrobe(void *state, const char *entry)
{
    Find *f = state;
    size_t len = strlen(entry);
    if (entry[0] == '.' || !conf_name_ok(entry, len, false)) return 0;
    char path[WARDROBE_PATH_MAX];
    int n = snprintf(path, sizeof path, "%s/%s/suit.conf", f->dir, entry);
    ensure(n > 0 && (size_t)n < sizeof path);  // the caller left room for a name of any length
    struct stat st;
    if (sys_stat(path, &st) != 0) {
        if (errno == ENOENT || errno == ENOTDIR) return 0;
        say(STDERR_FILENO, "suit: cannot look at %s: %s\n", path, strerror(errno));
        f->rc = 1;
        return 1;
    }
    if (!S_ISREG(st.st_mode)) return 0;
    if (f->w->n == WARDROBE_MAX) {
        say(STDERR_FILENO, "suit: more than %u wardrobes with a suit.conf in %s\n", WARDROBE_MAX, f->dir);
        f->rc = 2;
        return 1;
    }
    Ward *out = &f->w->w[f->w->n++];
    memcpy(out->name, entry, len + 1);
    memcpy(out->conf, path, (size_t)n + 1);
    snprintf(out->store, sizeof out->store, "%s/%s", f->dir, entry);
    return 0;
}

static int cmp_wardrobe(const void *pa, const void *pb)
{
    const Ward *a = pa;
    const Ward *b = pb;
    return strcmp(a->name, b->name);
}

int wardrobes_find(Wards *w, const char *suit_home)
{
    char dir[WARDROBE_PATH_MAX];
    [[maybe_unused]] int n = snprintf(dir, sizeof dir, "%s/store", suit_home);
    ensure(n > 0 && (size_t)n < sizeof dir);  // the caller checked the home folder's length
    w->n = 0;
    Find f = {w, dir, 0};
    int rc = sys_listdir(dir, add_wardrobe, &f);
    if (rc > 0) return f.rc;
    if (rc < 0 && errno != ENOENT) {
        say(STDERR_FILENO, "suit: cannot read %s: %s\n", dir, strerror(errno));
        return 1;
    }
    if (w->n == 0) {
        say(STDERR_FILENO, "%s:0: no wardrobe with a suit.conf\n", dir);
        return 2;
    }
    qsort(w->w, w->n, sizeof w->w[0], cmp_wardrobe);
    return 0;
}

static Conf part;

int wardrobes_load(const Wards *w, Conf *c)
{
    ConfError err;
    conf_merge_init(c);
    for (uint32_t i = 0; i < w->n; i++) {
        if (!conf_load_part(&part, w->w[i].conf, &err)) {
            say(STDERR_FILENO, "%s:%d: %s\n", w->w[i].conf, err.line, err.msg);
            return 1;
        }
        if (!conf_merge(c, &part, i, w, &err)) {
            say(STDERR_FILENO, "%s:%d: %s\n", w->w[err.ward].conf, err.line, err.msg);
            return 1;
        }
    }
    if (conf_check(c, &err)) return 0;
    say(STDERR_FILENO, "%s:%d: %s\n", w->w[err.ward].conf, err.line, err.msg);
    return 1;
}