Skip to content
suit Artifact [3c302895cd]
Login

Artifact [3c302895cd]

Artifact 3c302895cd3604c28c98b8943f8aec9d917780609da350295a6b4c0ebdc6a07d:


#include "exclude.h"

#include "platform.h"
#include "project.h"

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

static const char BEGIN[] = "# suit begin";
static const char END[] = "# suit end";

// ---- where the file is --------------------------------------------------------

static int no_exclude(const char *project, const char *why)
{
    say(STDERR_FILENO, "suit: cannot find the exclude file of %s: %s\n", project, why);
    return 1;
}

// The first line of PATH, without its end of line, into LINE. 0 read, 1 said why,
// -1 there is no such file and OPTIONAL says that is all right.
static int first_line(const char *project, const char *path, char *line, size_t cap, bool optional)
{
    size_t len;
    int err = 0;
    ReadResult r = project_read_file(path, line, cap - 1, &len, &err);
    if (r == READ_MISSING && optional) return -1;
    if (r == READ_MISSING) return no_exclude(project, "the .git file is gone");
    if (r == READ_BIG) return no_exclude(project, "a file there is too large to read");
    if (r == READ_FAILED) {
        char why[PROJECT_PATH_MAX + 64];
        snprintf(why, sizeof why, "cannot read %s: %s", path, strerror(err));
        return no_exclude(project, why);
    }
    line[strcspn(line, "\r\n")] = '\0';
    return 0;
}

// OUT = REL, or BASE/REL if REL is not absolute. False if it does not fit.
static bool resolve_path(const char *base, const char *rel, char *out, size_t cap)
{
    int n = rel[0] == '/' ? snprintf(out, cap, "%s", rel) : snprintf(out, cap, "%s/%s", base, rel);
    ensure(n > 0);  // only an encoding error gives less
    return (size_t)n < cap;
}

// PATH, which is absolute, with its "." and ".." parts and doubled slashes taken
// out, so that two ways of naming one folder give one string. A worktree's
// commondir says "../.." and the main repository is also named by its own path.
static void tidy(char *path)
{
    char *out = path;
    for (const char *s = path; *s != '\0';) {
        size_t len = strcspn(s + 1, "/") + 1;  // the "/" and the part after it
        bool dot = len == 2 && s[1] == '.';
        bool dotdot = len == 3 && s[1] == '.' && s[2] == '.';
        if (dotdot) {
            while (out > path && *--out != '/') {}
        } else if (len > 1 && !dot) {
            memmove(out, s, len);
            out += len;
        }
        s += len;
    }
    *out = '\0';  // the root is the empty string: "/info/exclude" follows
}

int exclude_path(const char *project, char *out, size_t cap)
{
    char git[PROJECT_PATH_MAX + 8];
    char common[PROJECT_PATH_MAX + 8];
    int n = snprintf(git, sizeof git, "%s/.git", project);
    ensure(n > 0 && (size_t)n < sizeof git);  // a project's path is shorter than PROJECT_PATH_MAX
    struct stat st;
    if (sys_lstat(git, &st) != 0) {
        char why[EXCLUDE_PATH_MAX + 64];
        snprintf(why, sizeof why, "cannot look at %s: %s", git, strerror(errno));
        return no_exclude(project, why);
    }
    memcpy(common, git, (size_t)n + 1);
    if (!S_ISDIR(st.st_mode)) {
        // A linked worktree: .git names the worktree's own folder, which names the main one.
        char line[EXCLUDE_PATH_MAX + 8];
        int rc = first_line(project, git, line, sizeof line, false);
        if (rc != 0) return rc;
        if (strncmp(line, "gitdir:", 7) != 0) return no_exclude(project, ".git is not a 'gitdir: PATH' file");
        const char *rel = line + 7 + strspn(line + 7, " ");
        char gitdir[EXCLUDE_PATH_MAX];
        if (!resolve_path(project, rel, gitdir, sizeof gitdir)) return no_exclude(project, "the path is too long");
        char file[EXCLUDE_PATH_MAX + 16];
        [[maybe_unused]] int flen = snprintf(file, sizeof file, "%s/commondir", gitdir);
        ensure(flen > 0 && (size_t)flen < sizeof file);  // gitdir fits in EXCLUDE_PATH_MAX
        rc = first_line(project, file, line, sizeof line, true);
        if (rc == -1) memcpy(common, gitdir, strlen(gitdir) + 1);
        else if (rc != 0) return rc;
        else if (!resolve_path(gitdir, line, common, sizeof common)) return no_exclude(project, "the path is too long");
    }
    tidy(common);
    n = snprintf(out, cap, "%s/info/exclude", common);
    ensure(n > 0);
    if ((size_t)n >= cap) return no_exclude(project, "the path is too long");
    return 0;
}

bool exclude_line(const char *rel, char *out, size_t cap)
{
    size_t len = 0;
    if (cap < 2) return false;
    out[len++] = '/';
    for (; *rel != '\0'; rel++) {
        bool special = strchr("\\*?[", *rel) != nullptr;
        if (len + (special ? 2 : 1) + 1 > cap) return false;
        if (special) out[len++] = '\\';
        out[len++] = *rel;
    }
    out[len] = '\0';
    return true;
}

// ---- the block ----------------------------------------------------------------

static char old_text[EXCLUDE_FILE_MAX + 1];
static char new_text[EXCLUDE_FILE_MAX + 1];

typedef struct {
    size_t len;
    bool over;
} Text;

static void append(Text *o, const char *s, size_t n)
{
    if (o->over || o->len + n > EXCLUDE_FILE_MAX) {
        o->over = true;
        return;
    }
    memcpy(new_text + o->len, s, n);
    o->len += n;
}

static bool line_is(const char *p, size_t len, const char *text)
{
    return len == strlen(text) && memcmp(p, text, len) == 0;
}

// Where the block is in old_text (LEN bytes): its first byte, the byte after its
// end line, and whether that line has no newline. False, with *error set, if a
// "begin" has no "end".
typedef struct {
    bool found;
    bool open;
    size_t begin;
    size_t stop;
    bool no_eol;
} Where;

static Where find_block(size_t len)
{
    Where w = {};
    bool begun = false;
    for (size_t pos = 0; pos < len;) {
        const char *nl = memchr(old_text + pos, '\n', len - pos);
        size_t ll = nl != nullptr ? (size_t)(nl - (old_text + pos)) : len - pos;
        size_t next = nl != nullptr ? pos + ll + 1 : len;
        if (!begun && line_is(old_text + pos, ll, BEGIN)) {
            begun = true;
            w.begin = pos;
        } else if (begun && line_is(old_text + pos, ll, END)) {
            w.found = true;
            w.stop = next;
            w.no_eol = nl == nullptr;
            return w;
        }
        pos = next;
    }
    w.open = begun;
    return w;
}

static int edit_failed(const char *path, const char *what, int err)
{
    say(STDERR_FILENO, "suit: cannot %s %s: %s\n", what, path, strerror(err));
    return 1;
}

int exclude_edit(const char *path, const char *const *lines, uint32_t n, bool created, bool dry,
    bool *changed, bool *exists)
{
    size_t len = 0;
    int err = 0;
    ReadResult r = project_read_file(path, old_text, EXCLUDE_FILE_MAX, &len, &err);
    if (r == READ_FAILED) return edit_failed(path, "read", err);
    if (r == READ_BIG) {
        say(STDERR_FILENO, "suit: %s is over %zu bytes\n", path, EXCLUDE_FILE_MAX);
        return 1;
    }
    *exists = r == READ_OK;
    Where w = find_block(len);
    if (w.open) {
        say(STDERR_FILENO, "suit: %s has a '%s' line and no '%s' line after it\n", path, BEGIN, END);
        return 1;
    }
    // The bytes that were there before suit: what is before the block, less the
    // newline suit added to end a last line that had none, and what is after.
    bool added_eol = w.found ? (w.no_eol && w.begin > 0) : (len > 0 && old_text[len - 1] != '\n');
    size_t before = w.found ? w.begin - (added_eol ? 1 : 0) : len;
    Text o = {};
    append(&o, old_text, before);
    if (n > 0) {
        if (added_eol) append(&o, "\n", 1);
        append(&o, BEGIN, strlen(BEGIN));
        append(&o, "\n", 1);
        for (uint32_t i = 0; i < n; i++) {
            append(&o, lines[i], strlen(lines[i]));
            append(&o, "\n", 1);
        }
        append(&o, END, strlen(END));
        if (!added_eol) append(&o, "\n", 1);
    }
    if (w.found) append(&o, old_text + w.stop, len - w.stop);
    if (o.over) {
        say(STDERR_FILENO, "suit: %s would be over %zu bytes\n", path, EXCLUDE_FILE_MAX);
        return 1;
    }
    *changed = *exists ? (o.len != len || memcmp(new_text, old_text, len) != 0) : n > 0;
    if (dry || !*changed) return 0;
    if (n == 0 && o.len == 0 && created) {
        if (sys_unlink(path) != 0) return edit_failed(path, "remove", errno);
        return 0;
    }
    err = sys_write_atomic(path, new_text, o.len);
    return err == 0 ? 0 : edit_failed(path, "write", err);
}