Skip to content
suit Artifact [0d2ca8d2bd]
Login

Artifact [0d2ca8d2bd]

Artifact 0d2ca8d2bdddf23443d511530de410dd80c8a60423cd4cc39590687d44435673:


#include "scan.h"

#include "platform.h"

#include "sqlite3.h"

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

// Room for a path of fewer than PROJECT_PATH_MAX bytes and a fixed suffix.
constexpr size_t BUF = PROJECT_PATH_MAX + 64;
constexpr size_t CONFIG_MAX = 131072;

static Projects *list;
static const Projects *hand;

static void note(const char *what, const char *why)
{
    say(STDERR_FILENO, "suit: note: %s: %s\n", what, why);
}

// A path of at most PROJECT_PATH_MAX - 1 bytes and a suffix of a few bytes.
static void join_fixed(char *out, const char *dir, const char *suffix)
{
    [[maybe_unused]] int n = snprintf(out, BUF, "%s%s", dir, suffix);
    ensure(n > 0 && (size_t)n < BUF);
}

// OUT = REL, or BASE/REL if REL is not absolute. False if it is too long.
static bool resolve(const char *base, const char *rel, char *out)
{
    int n = rel[0] == '/' ? snprintf(out, BUF, "%s", rel) : snprintf(out, BUF, "%s/%s", base, rel);
    ensure(n > 0);
    return (size_t)n < PROJECT_PATH_MAX;
}

// True if R is READ_OK. Otherwise says why, unless there was no such file.
static bool usable(const char *path, ReadResult r, int err)
{
    if (r == READ_FAILED) note(path, strerror(err));
    if (r == READ_BIG) note(path, "too large to read");
    return r == READ_OK;
}

// The first line of PATH, without its end of line, into LINE.
static ReadResult first_line(const char *path, char *line, size_t cap, int *err)
{
    size_t len;
    ReadResult r = project_read_file(path, line, cap - 1, &len, err);
    if (r == READ_OK) line[strcspn(line, "\r\n")] = '\0';
    return r;
}

static void set_key(const char *url, char *key)
{
    (void)project_key_from_url(url, key, PROJECT_KEY_MAX + 1);
}

// ---- git ------------------------------------------------------------------

// The folder holding the config of the repository the file DIR/.git points at:
// the one named by "gitdir:", or the one its "commondir" file names.
static bool linked_config_dir(const char *dir, char *cfgdir)
{
    char gitfile[BUF];
    join_fixed(gitfile, dir, "/.git");
    char line[PROJECT_PATH_MAX + 8];
    int err = 0;
    ReadResult r = first_line(gitfile, line, sizeof line, &err);
    if (!usable(gitfile, r, err)) return false;
    if (strncmp(line, "gitdir:", 7) != 0) {
        note(gitfile, "is not a 'gitdir: PATH' file");
        return false;
    }
    char *rel = line + 7;
    while (*rel == ' ') rel++;
    char gitdir[BUF];
    if (!resolve(dir, rel, gitdir)) {
        note(gitfile, "the path is too long");
        return false;
    }
    char common[BUF];
    join_fixed(common, gitdir, "/commondir");
    r = first_line(common, line, sizeof line, &err);
    if (r == READ_MISSING) {
        memcpy(cfgdir, gitdir, strlen(gitdir) + 1);
        return true;
    }
    if (!usable(common, r, err)) return false;
    if (!resolve(gitdir, line, cfgdir)) {
        note(common, "the path is too long");
        return false;
    }
    return true;
}

static void git_key(const char *dir, bool git_dir, char *key)
{
    char cfgdir[BUF];
    join_fixed(cfgdir, dir, "/.git");
    if (!git_dir && !linked_config_dir(dir, cfgdir)) return;
    char config[BUF];
    join_fixed(config, cfgdir, "/config");
    static char text[CONFIG_MAX + 1];
    size_t len;
    int err = 0;
    ReadResult r = project_read_file(config, text, CONFIG_MAX, &len, &err);
    if (!usable(config, r, err)) return;
    char url[PROJECT_URL_MAX];
    if (project_git_remote(text, len, url, sizeof url)) set_key(url, key);
}

// ---- fossil ---------------------------------------------------------------

typedef enum { Q_FOUND, Q_NONE, Q_ERROR } QueryResult;

// The one text value SQL selects from the database FILE, opened read-only. It
// selects at most CAP - 1 bytes.
static QueryResult query_text(const char *file, const char *sql, char *out, [[maybe_unused]] size_t cap)
{
    sqlite3 *db = nullptr;
    sqlite3_stmt *st = nullptr;
    int rc = sqlite3_open_v2(file, &db, SQLITE_OPEN_READONLY, nullptr);
    ensure(db != nullptr);
    if (rc == SQLITE_OK) rc = sqlite3_prepare_v2(db, sql, -1, &st, nullptr);
    if (rc == SQLITE_OK) rc = sqlite3_step(st);
    QueryResult r = Q_ERROR;
    if (rc == SQLITE_ROW) {
        const char *v = (const char *)sqlite3_column_text(st, 0);
        ensure(v != nullptr && strlen(v) < cap);
        memcpy(out, v, strlen(v) + 1);
        r = Q_FOUND;
    } else if (rc == SQLITE_DONE) {
        r = Q_NONE;
    } else {
        note(file, sqlite3_errmsg(db));
    }
    sqlite3_finalize(st);
    sqlite3_close(db);
    return r;
}

static void fossil_key(const char *dir, char *key)
{
    char ckout[BUF];
    join_fixed(ckout, dir, "/.fslckout");
    char rel[PROJECT_PATH_MAX];
    if (query_text(ckout,
            "SELECT value FROM vvar WHERE name='repository' AND length(CAST(value AS BLOB))<4096",
            rel, sizeof rel) != Q_FOUND)
        return;
    char repo[BUF];
    if (!resolve(dir, rel, repo)) {
        note(ckout, "the repository path is too long");
        return;
    }
    char url[PROJECT_URL_MAX];
    if (query_text(repo,
            "SELECT value FROM config WHERE name='last-sync-url' AND length(CAST(value AS BLOB))<2048",
            url, sizeof url) == Q_FOUND)
        set_key(url, key);
}

// ---- recording ------------------------------------------------------------

// Add a project folder. 1 if the list is full. A hand-set key wins.
static int record(const char *dir, const char *key, ProjectKind kind)
{
    if (!project_path_ok(dir)) {
        note(dir, "not recorded: the path has a control character");
        return 0;
    }
    const ProjectEntry *h = projects_find(hand, dir);
    AddResult a = projects_add(list, h != nullptr ? h->key : key, dir, kind);
    if (a != ADD_FULL) return 0;  // a duplicate was recorded already, as a worktree
    say(STDERR_FILENO, "suit: too many projects (limit %u, or %zu bytes of text)\n", PROJECT_ENTRY_MAX,
        sizeof list->buf);
    return 1;
}

typedef struct {
    const char *key;
    const char *dir;  // the main repository's .git/worktrees
} Worktrees;

// One entry of .git/worktrees: the file "gitdir" names that worktree's .git file.
static int worktree(void *state, const char *name)
{
    const Worktrees *w = state;
    char gitdir[BUF];
    [[maybe_unused]] int n = snprintf(gitdir, sizeof gitdir, "%s/%s/gitdir", w->dir, name);
    ensure(n > 0 && (size_t)n < sizeof gitdir);
    char line[PROJECT_PATH_MAX + 8];
    int err = 0;
    ReadResult r = first_line(gitdir, line, sizeof line, &err);
    if (!usable(gitdir, r, err)) return 0;
    size_t len = strlen(line);
    bool named = len > 5 && strcmp(line + len - 5, "/.git") == 0;
    if (named) line[len - 5] = '\0';
    if (!named || !project_path_ok(line)) {
        note(gitdir, "does not name the .git file of a worktree");
        return 0;
    }
    struct stat st;
    if (sys_stat(line, &st) != 0) return 0;  // a worktree that was removed
    return record(line, w->key, KIND_GIT);
}

static int record_project(const char *dir, ProjectKind kind, bool git_dir)
{
    char key[PROJECT_KEY_MAX + 1] = "";
    if (kind == KIND_GIT) git_key(dir, git_dir, key);
    if (kind == KIND_FOSSIL) fossil_key(dir, key);
    int rc = record(dir, key, kind);
    if (rc != 0 || kind != KIND_GIT || !git_dir) return rc;

    char dirs[BUF];
    join_fixed(dirs, dir, "/.git/worktrees");
    const ProjectEntry *main = projects_find(list, dir);
    if (main == nullptr) return 0;  // not recorded: its path has a control character
    Worktrees w = {main->key, dirs};
    rc = sys_listdir(dirs, worktree, &w);
    if (rc < 0 && errno != ENOENT) note(dirs, strerror(errno));
    return rc > 0 ? rc : 0;
}

// ---- walking --------------------------------------------------------------

static ProjectKind find_marker(const char *dir, bool *git_dir)
{
    static const struct {
        const char *name;
        ProjectKind kind;
    } markers[] = {{"/.git", KIND_GIT}, {"/.fslckout", KIND_FOSSIL}, {"/.zit-checkout", KIND_ZIT}};
    for (size_t i = 0; i < sizeof markers / sizeof markers[0]; i++) {
        char path[BUF];
        join_fixed(path, dir, markers[i].name);
        struct stat st;
        if (sys_stat(path, &st) != 0) continue;
        *git_dir = S_ISDIR(st.st_mode);
        return markers[i].kind;
    }
    return KIND_NONE;
}

static int visit(const char *dir, int depth);

typedef struct {
    const char *dir;
    int depth;
} Walk;

static int child(void *state, const char *name)
{
    const Walk *w = state;
    char path[BUF];
    [[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", w->dir, name);
    ensure(n > 0 && (size_t)n < sizeof path);  // a root is short enough for four levels below it
    struct stat st;
    if (sys_lstat(path, &st) != 0) {
        note(path, strerror(errno));
        return 0;
    }
    return S_ISDIR(st.st_mode) ? visit(path, w->depth + 1) : 0;
}

static int visit(const char *dir, int depth)
{
    bool git_dir = false;
    ProjectKind kind = find_marker(dir, &git_dir);
    if (kind != KIND_NONE) return record_project(dir, kind, git_dir);
    if (depth == SCAN_DEPTH) return 0;
    Walk w = {dir, depth};
    int rc = sys_listdir(dir, child, &w);
    if (rc < 0) note(dir, strerror(errno));
    return rc > 0 ? rc : 0;
}

int scan_projects(const Roots *roots, const Projects *set, Projects *out)
{
    list = out;
    hand = set;
    out->n = 0;
    out->used = 0;
    for (uint32_t i = 0; i < roots->n; i++)
        if (visit(roots->path[i], 0) != 0) return 1;
    return 0;
}