Skip to content
pi-c Artifact [bb1843ca26]
Login

Artifact [bb1843ca26]

Artifact bb1843ca2631541da3c1cdc93655ca181135c34761e8132c9df6f2fb8b18b182:


/* @file completion; see atfile.h. */
#include "tui/atfile.h"

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>

#include "ignore.h"
#include "tui/fuzzy.h"

typedef struct {
    char *path; /* relative to the walk's base */
    const char *name;
    int is_dir;
    int depth;
    int rank;
    double fuzzy;
} entry;

static int is_delim(char c)
{
    return c == ' ' || c == '\t' || c == '\n';
}

int atfile_token(const char *text, size_t cursor, size_t *start, char *query, size_t qcap, int *quoted)
{
    size_t ls = cursor, quotes = 0, qpos = 0, s;
    while (ls > 0 && text[ls - 1] != '\n')
        ls--;
    for (size_t i = ls; i < cursor; i++)
        if (text[i] == '"')
            quotes++, qpos = i;
    if (quotes % 2 == 1 && qpos > ls && text[qpos - 1] == '@' && (qpos - 1 == ls || is_delim(text[qpos - 2]))) {
        *start = qpos - 1, *quoted = 1;
        (void)snprintf(query, qcap, "%.*s", (int)(cursor - qpos - 1), text + qpos + 1);
        return 1;
    }
    s = cursor;
    while (s > ls && !is_delim(text[s - 1]))
        s--;
    while (s < cursor && strchr("([{<`'\"", text[s]))
        s++; /* opening wrappers before the path, as Pi strips them */
    if (s >= cursor || text[s] != '@')
        return 0;
    *start = s, *quoted = 0;
    (void)snprintf(query, qcap, "%.*s", (int)(cursor - s - 1), text + s + 1);
    return 1;
}

/* Names never listed, ignore files or not: version-control metadata. */
static int atfile_skip(const char *name)
{
    static const char *const skip[] = {".git",         "node_modules", ".fossil-settings", ".zit-settings",
                                       ".zit",         "_FOSSIL_",     ".fslckout"};
    for (size_t i = 0; i < sizeof skip / sizeof *skip; i++)
        if (strcmp(name, skip[i]) == 0)
            return 1;
    return 0;
}

static int add_entry(entry **v, size_t *n, size_t *cap, const char *rel, int is_dir, int depth)
{
    if (*n == *cap) {
        size_t nc = *cap ? *cap * 2 : 256;
        entry *p = realloc(*v, nc * sizeof **v);
        if (!p)
            return -1;
        *v = p, *cap = nc;
    }
    char *d = strdup(rel);
    if (!d)
        return -1;
    (*v)[*n] = (entry){.path = d, .is_dir = is_dir, .depth = depth};
    (*n)++;
    return 0;
}

/* Adds the entries of BASE/REL (REL "" for BASE itself), at DEPTH below it. */
static void scan(const char *base, const char *rel_dir, int depth, entry **v, size_t *n, size_t *cap,
                 pic_ignore *ig)
{
    char dir[4096];
    DIR *d;
    struct dirent *de;
    (void)snprintf(dir, sizeof dir, "%s%s%s", base, *rel_dir ? "/" : "", rel_dir);
    if (!(d = opendir(dir)))
        return;
    /* The folder's own ignore files join the rules; BFS scans a folder before
     * its children, and their paths are prefixed, so the rules never need to leave. */
    if (pic_ignore_load_dir(ig, dir, rel_dir, depth == 0) != 0) {
        closedir(d);
        return;
    }
    while ((de = readdir(d)) && *n < ATFILE_MAX_ENTRIES) {
        char full[8192], rel[4096];
        int is_dir;
        if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
            continue;
        (void)snprintf(rel, sizeof rel, "%s%s%s", rel_dir, *rel_dir ? "/" : "", de->d_name);
        (void)snprintf(full, sizeof full, "%s/%s", base, rel);
        is_dir = de->d_type == DT_DIR;
        if (de->d_type == DT_LNK || de->d_type == DT_UNKNOWN) {
            struct stat st;
            is_dir = stat(full, &st) == 0 && S_ISDIR(st.st_mode);
        } else if (de->d_type != DT_DIR && de->d_type != DT_REG) {
            continue;
        }
        if (atfile_skip(de->d_name) || pic_ignore_ignored(ig, rel, is_dir))
            continue;
        if (add_entry(v, n, cap, rel, is_dir, depth + 1) != 0)
            break;
    }
    closedir(d);
}

/* Breadth-first (the entry list is the queue), so the cap keeps the shallow entries. */
static size_t walk(const char *base, entry **out)
{
    entry *v = NULL;
    size_t n = 0, cap = 0;
    pic_ignore ig = {0};
    scan(base, "", 0, &v, &n, &cap, &ig);
    for (size_t qi = 0; qi < n; qi++) {
        if (v[qi].is_dir && v[qi].depth < ATFILE_MAX_DEPTH) {
            char rel[4096];
            (void)snprintf(rel, sizeof rel, "%s", v[qi].path);
            scan(base, rel, v[qi].depth, &v, &n, &cap, &ig);
        }
    }
    pic_ignore_free(&ig);
    for (size_t i = 0; i < n; i++) {
        const char *sl = strrchr(v[i].path, '/');
        v[i].name = sl ? sl + 1 : v[i].path;
    }
    *out = v;
    return n;
}

static int cmp(const void *pa, const void *pb)
{
    const entry *a = pa, *b = pb;
    if (a->rank != b->rank)
        return b->rank - a->rank;
    if (a->fuzzy != b->fuzzy)
        return a->fuzzy < b->fuzzy ? -1 : 1;
    if (a->depth != b->depth)
        return a->depth - b->depth;
    if (strlen(a->path) != strlen(b->path))
        return strlen(a->path) < strlen(b->path) ? -1 : 1;
    return strcmp(a->path, b->path);
}

/* Pi's scoreEntry on the name; the extra 20 is a fuzzy-only match. */
static int rank_of(const char *name, const char *q, int is_dir)
{
    int s;
    if (!*q)
        return 1;
    if (strcasecmp(name, q) == 0)
        s = 100;
    else if (strncasecmp(name, q, strlen(q)) == 0)
        s = 80;
    else if (strcasestr(name, q))
        s = 50;
    else
        s = 20;
    return is_dir ? s + 10 : s;
}

size_t atfile_candidates(const char *root, const char *query, int quoted, atfile_item *out, size_t cap)
{
    char base[4096], display[4096] = "", q[512];
    const char *slash = strrchr(query, '/');
    entry *v = NULL;
    size_t n, m = 0, k = 0;
    struct stat st;
    if (slash) {
        (void)snprintf(display, sizeof display, "%.*s", (int)(slash - query + 1), query);
        (void)snprintf(q, sizeof q, "%s", slash + 1);
        if (display[0] == '/')
            (void)snprintf(base, sizeof base, "%s", display);
        else if (display[0] == '~' && display[1] == '/' && getenv("HOME"))
            (void)snprintf(base, sizeof base, "%s/%s", getenv("HOME"), display + 2);
        else
            (void)snprintf(base, sizeof base, "%s/%s", root, display);
        if (stat(base, &st) != 0 || !S_ISDIR(st.st_mode))
            return 0;
        for (size_t l = strlen(base); l > 1 && base[l - 1] == '/'; l--)
            base[l - 1] = 0;
    } else {
        (void)snprintf(base, sizeof base, "%s", root);
        (void)snprintf(q, sizeof q, "%s", query);
    }
    n = walk(base, &v);
    for (size_t i = 0; i < n; i++) {
        double sc = 0;
        if (*q && !tui_fuzzy_match(q, v[i].name, &sc)) {
            free(v[i].path);
            continue;
        }
        v[i].rank = rank_of(v[i].name, q, v[i].is_dir);
        v[i].fuzzy = sc;
        v[m++] = v[i];
    }
    qsort(v, m, sizeof *v, cmp);
    for (size_t i = 0; i < m; i++) {
        if (k < cap) {
            char path[4096];
            (void)snprintf(path, sizeof path, "%s%s%s", display, v[i].path, v[i].is_dir ? "/" : "");
            atfile_item *it = &out[k++];
            it->is_dir = v[i].is_dir;
            if (quoted || strpbrk(path, " \t"))
                (void)snprintf(it->value, sizeof it->value, "@\"%s\"", path);
            else
                (void)snprintf(it->value, sizeof it->value, "@%s", path);
            (void)snprintf(it->label, sizeof it->label, "%s%s", v[i].name, v[i].is_dir ? "/" : "");
            if (strcmp(path, it->label) != 0)
                (void)snprintf(it->label + strlen(it->label), sizeof it->label - strlen(it->label), "  %s", path);
        }
        free(v[i].path);
    }
    free(v);
    return k;
}