Skip to content
suit Artifact [cecffc135d]
Login

Artifact [cecffc135d]

Artifact cecffc135d11bb66568a8d36f5aa4bf18bc492f09114cb7855e68447e3b95628:


#include "store.h"

#include "conf.h"
#include "platform.h"
#include "stamp.h"
#include "store_fs.h"

#include "libfossil.h"

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

constexpr size_t PATH_CAP = 4096;

// Every command is a list of steps run in order. A step is one libfossil call
// or one small decision of ours, and returns 0 to go on, STEP_DONE to stop
// with the exit code in Store.exit_code, STEP_ERR after reporting its own
// error, or a libfossil result code, which run() reports with libfossil's
// message and the step's name. The one place that decides what a failure
// looks like is run().
enum { STEP_DONE = -1, STEP_ERR = -2 };

typedef struct {
    fsl_cx *f;
    char name[CONF_NAME_MAX + 1];
    char repo[PATH_CAP];
    char dir[PATH_CAP];
    size_t home_len;
    bool have_ckout;   // the working copy has its checkout database
    const char *message;
    char user[256];
    int exit_code;
    unsigned count;    // lines a visitor printed
    fsl_id_t trunk;    // trunk's tip
    fsl_id_t before;   // the version the update started from
    fsl_id_t target;   // the version the update goes to
    fsl_undo_e undo;   // what fsl_undo can do
} Store;

typedef int (*StepFn)(Store *);

typedef struct {
    const char *what;
    StepFn fn;
} Step;

static void report(const Store *s, const char *what, int rc)
{
    char const *msg = "";
    fsl_size_t len = 0;
    (void)fsl_cx_err_get(s->f, &msg, &len);
    say(STDERR_FILENO, "suit: store %s: %s failed: %s: %.*s\n", s->name, what, fsl_rc_cstr(rc),
        (int)len, msg);
}

static int run(Store *s, const char *name, const char *message, const Step *steps, size_t n)
{
    memset(s, 0, sizeof *s);
    s->message = message;
    if (!conf_name_ok(name, strlen(name), false)) {
        say(STDERR_FILENO, "suit: '%.40s' is not a wardrobe name (letters, digits, . _ -)\n", name);
        return 2;
    }
    strcpy(s->name, name);
    int result = 0;
    for (size_t i = 0; i < n; i++) {
        int rc = steps[i].fn(s);
        if (rc == STEP_DONE) {
            result = s->exit_code;
            break;
        }
        if (rc != 0) {
            result = 1;
            if (rc != STEP_ERR) report(s, steps[i].what, rc);
            break;
        }
    }
    if (s->f != nullptr) fsl_cx_finalize(s->f);
    return result;
}

// ---- steps every command starts with --------------------------------------

static int step_paths(Store *s)
{
    char rel[CONF_NAME_MAX + 32];
    [[maybe_unused]] int n = snprintf(rel, sizeof rel, "wardrobes/%s.fossil", s->name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    s->home_len = suit_home_path(s->repo, sizeof s->repo, rel);
    if (s->home_len == 0) return STEP_ERR;
    n = snprintf(rel, sizeof rel, "store/%s", s->name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    // The store's path is shorter than the wardrobe's, so it fits if that did.
    [[maybe_unused]] size_t dir_home = suit_home_path(s->dir, sizeof s->dir, rel);
    ensure(dir_home != 0);
    return 0;
}

static int step_wardrobe_exists(Store *s)
{
    struct stat st;
    if (sys_stat(s->repo, &st) == 0) return 0;
    say(STDERR_FILENO, "suit: store %s: no wardrobe at %s: %s\n", s->name, s->repo,
        strerror(errno));
    return STEP_ERR;
}

static int step_init(Store *s)
{
    [[maybe_unused]] int rc = fsl_cx_init(&s->f, nullptr);
    ensure(rc == 0);  // it fails only when out of memory
    return 0;
}

static int step_fs(Store *s)
{
    return store_fs_install(s->f);
}

// Every question libfossil asks about overwriting a file is answered yes: the
// store is suit's, and an update has already been checked to be safe.
static int confirm_yes(fsl_confirm_detail const *detail, fsl_confirm_response *answer, void *state)
{
    (void)detail;
    (void)state;
    answer->response = FSL_CRESPONSE_YES;
    return 0;
}

static int step_confirmer(Store *s)
{
    fsl_confirmer c = fsl_confirmer_empty;
    c.callback = confirm_yes;
    fsl_cx_confirmer(s->f, &c, nullptr);
    return 0;
}

static int step_user(Store *s)
{
    const char *user = sys_getenv("USER");
    if (user == nullptr || user[0] == '\0') user = sys_getenv("LOGNAME");
    if (user == nullptr || user[0] == '\0') {
        say(STDERR_FILENO, "suit: store %s: cannot tell who you are; set USER\n", s->name);
        return STEP_ERR;
    }
    snprintf(s->user, sizeof s->user, "%s", user);
    return fsl_cx_user_set(s->f, s->user);
}

static int step_repo(Store *s)
{
    return s->have_ckout ? 0 : fsl_repo_open(s->f, s->repo);
}

static int step_ckout_existing(Store *s)
{
    return fsl_ckout_open_dir(s->f, s->dir, false);
}

#define PREPARE                                                                                    \
    {"find the wardrobe", step_paths}, {"find the wardrobe", step_wardrobe_exists},                \
        {"start libfossil", step_init}, {"install the file writer", step_fs},                      \
        {"install the confirmer", step_confirmer}, {"find the user", step_user}

// ---- open -----------------------------------------------------------------

static int make_dir(const char *path)
{
    if (sys_mkdir(path, 0755) != 0 && errno != EEXIST) {
        say(STDERR_FILENO, "suit: cannot create %s: %s\n", path, strerror(errno));
        return STEP_ERR;
    }
    return 0;
}

// Make $SUIT_HOME, $SUIT_HOME/store and the store's own folder.
static int step_dirs(Store *s)
{
    char path[PATH_CAP];
    memcpy(path, s->repo, s->home_len);
    path[s->home_len] = '\0';
    int rc = make_dir(path);
    snprintf(path + s->home_len, sizeof path - s->home_len, "/store");
    rc = rc != 0 ? rc : make_dir(path);
    return rc != 0 ? rc : make_dir(s->dir);
}

static int step_find_ckout(Store *s)
{
    char db[PATH_CAP + 16];
    [[maybe_unused]] int n = snprintf(db, sizeof db, "%s/.fslckout", s->dir);
    ensure(n > 0 && (size_t)n < sizeof db);
    struct stat st;
    s->have_ckout = sys_stat(db, &st) == 0;
    return 0;
}

// An existing working copy opens its own repository; a new one is made for the
// repository step_repo opened.
static int step_ckout(Store *s)
{
    if (s->have_ckout) return fsl_ckout_open_dir(s->f, s->dir, false);
    fsl_repo_open_ckout_opt o = fsl_repo_open_ckout_opt_empty;
    o.targetDir = s->dir;
    o.checkForOpenedCkout = false;
    return fsl_repo_open_ckout(s->f, &o);
}

static int step_trunk(Store *s)
{
    return fsl_sym_to_rid(s->f, "trunk", FSL_SATYPE_CHECKIN, &s->trunk);
}

// A working copy that was created but never filled (an earlier open stopped
// part way) is at no version yet.
static int step_extract(Store *s)
{
    fsl_id_t current = 0;
    fsl_ckout_version_info(s->f, &current, nullptr);
    if (current > 0) return 0;
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.checkinRid = s->trunk;
    return fsl_repo_ckout(s->f, &o);
}

int store_open(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"make the store folders", step_dirs},
        {"look for the working copy", step_find_ckout},
        {"open the wardrobe", step_repo},
        {"open the working copy", step_ckout},
        
        {"find trunk", step_trunk},
        {"extract the files", step_extract},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

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

// What status calls each kind of change. The special kinds sit together after
// FSL_CKOUT_CHANGE_ADDED; everything below them is an edit of some sort.
static const char *change_word(fsl_ckout_change_e change)
{
    static const char *const special[] = {"added", "deleted", "deleted", "edited"};
    static_assert(FSL_CKOUT_CHANGE_REMOVED == FSL_CKOUT_CHANGE_ADDED + 1);
    static_assert(FSL_CKOUT_CHANGE_MISSING == FSL_CKOUT_CHANGE_ADDED + 2);
    static_assert(FSL_CKOUT_CHANGE_RENAMED == FSL_CKOUT_CHANGE_ADDED + 3);
    unsigned i = (unsigned)change - (unsigned)FSL_CKOUT_CHANGE_ADDED;
    return i < sizeof special / sizeof special[0] ? special[i] : "edited";
}

static int print_change(void *state, fsl_ckout_change_e change, char const *filename,
    char const *origName)
{
    (void)origName;
    Store *s = state;
    say(STDOUT_FILENO, "%s %s\n", change_word(change), filename);
    s->count++;
    return 0;
}

static int step_txn_begin(Store *s)
{
    return fsl_cx_txn_begin(s->f);
}

static int step_manage_all(Store *s)
{
    fsl_ckout_manage_opt o = fsl_ckout_manage_opt_empty;
    o.filename = s->dir;
    o.relativeToCwd = false;
    o.checkIgnoreGlobs = false;
    return fsl_ckout_manage(s->f, &o);
}

// Check every file's content, not just its size and time: an edit made in the
// same second as the file was written, to the same length, must not be missed.
static int step_scan(Store *s)
{
    return fsl_vfile_changes_scan(s->f, -1, FSL_VFILE_CKSIG_HASH);
}

static int step_print_changes(Store *s)
{
    return fsl_ckout_changes_visit(s->f, -1, false, print_change, s);
}

// What status did to the checkout database was only to look; undo it.
static int step_txn_rollback(Store *s)
{
    return fsl_cx_txn_end_v2(s->f, false, false);
}

int store_status(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        
        {"begin", step_txn_begin},
        {"look for new files", step_manage_all},
        {"look for changes", step_scan},
        {"list the changes", step_print_changes},
        {"end", step_txn_rollback},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- commit ---------------------------------------------------------------

// A file gone from disk is a deletion: take it out of the next check-in's
// file list. Anything else that changed is counted.
static int unmanage_missing(void *state, fsl_ckout_change_e change, char const *filename,
    char const *origName)
{
    (void)origName;
    Store *s = state;
    s->count++;
    if (change != FSL_CKOUT_CHANGE_MISSING) return 0;
    fsl_ckout_unmanage_opt o = fsl_ckout_unmanage_opt_empty;
    o.filename = filename;
    o.relativeToCwd = false;
    o.scanForChanges = false;
    return fsl_ckout_unmanage(s->f, &o);
}

static int step_count_changes(Store *s)
{
    return fsl_ckout_changes_visit(s->f, -1, false, unmanage_missing, s);
}

// Nothing to check in is not an error.
static int step_anything(Store *s)
{
    s->exit_code = 0;
    return s->count == 0 ? STEP_DONE : 0;
}

static int step_checkin(Store *s)
{
    fsl_checkin_opt o = fsl_checkin_opt_empty;
    o.scanForChanges = false;
    o.message = s->message;
    o.user = s->user;
    fsl_uuid_str uuid = nullptr;
    int rc = fsl_checkin_commit(s->f, &o, nullptr, &uuid);
    if (rc == 0) say(STDOUT_FILENO, "checked in %.12s\n", uuid);
    fsl_free(uuid);
    return rc;
}

int store_commit(const char *name, const char *message)
{
    static const Step steps[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        
        {"look for new files", step_manage_all},
        {"look for changes", step_scan},
        {"find deletions", step_count_changes},
        {"look for anything to check in", step_anything},
        {"check in", step_checkin},
    };
    Store s;
    return run(&s, name, message, steps, sizeof steps / sizeof steps[0]);
}

// ---- update ---------------------------------------------------------------

static int step_list_changes(Store *s)
{
    return fsl_ckout_changes_visit(s->f, -1, false, print_change, s);
}

static int step_before(Store *s)
{
    fsl_ckout_version_info(s->f, &s->before, nullptr);
    return 0;
}

// The caller commits first.
static int step_refuse_local_changes(Store *s)
{
    s->exit_code = EXIT_LOCAL_CHANGES;
    return s->count > 0 ? STEP_DONE : 0;
}

// Trunk's tip, or where the checkout is if that is not known.
static int step_target(Store *s)
{
    fsl_id_t tip = 0;
    int rc = fsl_ckout_calc_update_version(s->f, &tip);
    // 0 means libfossil found no version; the store stays where it is. This is
    // arithmetic and not a branch because no repository we could build in a
    // test made libfossil answer 0.
    s->target = (fsl_id_t)(tip > 0) * tip + (fsl_id_t)(tip <= 0) * s->before;
    return rc;
}

// Updating to the version the store is at would replace what `suit back` can
// undo with an update that did nothing.
static int step_up_to_date(Store *s)
{
    s->exit_code = 0;
    if (s->target != s->before) return 0;
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "updated to %.12s\n", uuid);
    return STEP_DONE;
}

static int print_conflict(fsl_ckup_state const *state)
{
    static const unsigned conflicts =
        (1u << FSL_CKUP_FCHANGE_CONFLICT_MERGED) | (1u << FSL_CKUP_FCHANGE_CONFLICT_ADDED) |
        (1u << FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED) | (1u << FSL_CKUP_FCHANGE_CONFLICT_RM) |
        (1u << FSL_CKUP_FCHANGE_CONFLICT_SYMLINK) | (1u << FSL_CKUP_FCHANGE_CONFLICT_BINARY);
    Store *s = state->callbackState;
    ensure(state->fileChangeType >= 0 && state->fileChangeType < 32);
    if (((1u << state->fileChangeType) & conflicts) != 0) {
        say(STDOUT_FILENO, "conflict %s\n", state->extractState->fCard->name);
        s->count++;
    }
    return 0;
}

static int update_to(Store *s, fsl_id_t version, bool dry_run)
{
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.scanForChanges = false;
    o.checkinRid = version;
    o.dryRun = dry_run;
    o.callback = print_conflict;
    o.callbackState = s;
    return fsl_ckout_update(s->f, &o);
}

// A dry run still changes the checkout database; the caller rolls it back.
static int step_dry_run(Store *s)
{
    s->count = 0;
    return update_to(s, s->target, true);
}

// A conflict stops the update before it changes anything.
static int step_refuse_conflicts(Store *s)
{
    s->exit_code = EXIT_CONFLICT;
    return s->count > 0 ? STEP_DONE : 0;
}

// Put every file back to the checkout's version, writing over whatever the
// failed update left. Files are compared by content for this.
static int put_back(Store *s)
{
    fsl_cx_err_reset(s->f);
    (void)fsl_vfile_changes_scan(s->f, -1, FSL_VFILE_CKSIG_HASH);
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.scanForChanges = false;
    o.checkinRid = s->before;
    return fsl_repo_ckout(s->f, &o);
}

static int step_apply(Store *s)
{
    int rc = update_to(s, s->target, false);
    if (rc == 0) return 0;
    report(s, "update", rc);
    if (put_back(s) == 0)
        say(STDERR_FILENO, "suit: store %s: the files are back at the version they were at\n",
            s->name);
    else
        say(STDERR_FILENO, "suit: store %s: could not put the files back; the working copy is half updated\n",
            s->name);
    return STEP_ERR;
}

static int step_report_version(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "updated to %.12s\n", uuid);
    return 0;
}

// Two sessions, because libfossil's dry run leaves the checkout version it
// went to in memory after the database is rolled back: the trial finds out
// what would happen, and the update starts again from the database.
int store_update(const char *name)
{
    static const Step trial[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"look for changes", step_scan},
        {"list the changes", step_list_changes},
        {"check for local changes", step_refuse_local_changes},
        {"find the version", step_before},
        {"find the version to update to", step_target},
        {"begin the trial", step_txn_begin},
        {"try the update", step_dry_run},
        {"end the trial", step_txn_rollback},
        {"check for conflicts", step_refuse_conflicts},
    };
    static const Step apply[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"look for changes", step_scan},
        {"find the version", step_before},
        {"find the version to update to", step_target},
        {"see if there is anything to do", step_up_to_date},
        {"update", step_apply},
        {"report", step_report_version},
    };
    Store s;
    int rc = run(&s, name, nullptr, trial, sizeof trial / sizeof trial[0]);
    return rc != 0 ? rc : run(&s, name, nullptr, apply, sizeof apply / sizeof apply[0]);
}

// ---- back -----------------------------------------------------------------

static int step_undo_state(Store *s)
{
    return fsl_undo_state(s->f, &s->undo, nullptr);
}

static int step_anything_to_undo(Store *s)
{
    if (s->undo == FSL_UNDO_UNDO) return 0;
    say(STDERR_FILENO, "suit: store %s: nothing to go back to\n", s->name);
    s->exit_code = EXIT_NOTHING_TO_UNDO;
    return STEP_DONE;
}

static int step_undo(Store *s)
{
    int rc = fsl_undo(s->f, false, false);
    if (rc != FSL_RC_CONFLICT) return rc;
    say(STDERR_FILENO, "suit: store %s: cannot go back: the store has changed since the update\n",
        s->name);
    s->exit_code = EXIT_NOTHING_TO_UNDO;
    return STEP_DONE;
}

static int step_report_back(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "back at %.12s\n", uuid);
    return 0;
}

int store_back(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        
        {"see what can be undone", step_undo_state},
        {"see what can be undone", step_anything_to_undo},
        {"go back", step_undo},
        {"report", step_report_back},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}