Skip to content
pi-c Documentation
Login

Documentation

/* pic command line: submit work, run it durably, inspect the journal. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "pic.h"

static int usage(void) {
    fputs("usage: pic --db PATH [--workspace DIR] submit KEY TEXT\n"
          "       pic --db PATH --workspace DIR [--exec-timeout SECONDS] run --script FILE\n"
          "       pic --db PATH dump | check\n",
          stderr);
    return 2;
}

int main(int argc, char **argv) {
    const char *db = NULL, *workspace = NULL, *script = NULL;
    int exec_seconds = 30;
    struct stat st;
    pic_store s;
    int i = 1, rc = 0;
    while (i + 1 < argc && strncmp(argv[i], "--", 2) == 0) {
        if (strcmp(argv[i], "--db") == 0) {
            db = argv[i + 1];
        } else if (strcmp(argv[i], "--workspace") == 0) {
            workspace = argv[i + 1];
        } else if (strcmp(argv[i], "--exec-timeout") == 0) {
            char *end = NULL;
            long v = strtol(argv[i + 1], &end, 10);
            if (!end || *end || v < 1 || v > 3600) {
                return usage();
            }
            exec_seconds = (int)v;
        } else {
            return usage();
        }
        i += 2;
    }
    if (!db || i >= argc) {
        return usage();
    }
    /* A missing workspace would otherwise be recorded as a permanent tool error. */
    if (workspace && (stat(workspace, &st) != 0 || !S_ISDIR(st.st_mode))) {
        fprintf(stderr, "pic: workspace is not a directory: %s\n", workspace);
        return 1;
    }
    if (pic_open(&s, db) != 0) {
        fprintf(stderr, "pic: %s\n", s.err);
        pic_close(&s);
        return 1;
    }
    if (strcmp(argv[i], "submit") == 0 && argc - i == 3) {
        int duplicate = 0;
        rc = pic_submit(&s, argv[i + 1], argv[i + 2], &duplicate);
        if (rc == 0) {
            puts(duplicate ? "duplicate: already admitted" : "admitted");
        }
    } else if (strcmp(argv[i], "run") == 0 && argc - i == 3 && strcmp(argv[i + 1], "--script") == 0 && workspace) {
        script = argv[i + 2];
        rc = pic_run(&s, workspace, script, exec_seconds);
    } else if (strcmp(argv[i], "dump") == 0 && argc - i == 1) {
        rc = pic_dump(&s);
    } else if (strcmp(argv[i], "check") == 0 && argc - i == 1) {
        rc = pic_check(&s);
        if (rc == 0) {
            puts("check: ok");
        }
    } else {
        pic_close(&s);
        return usage();
    }
    if (rc != 0) {
        fprintf(stderr, "pic: %s\n", s.err);
    }
    pic_close(&s);
    return rc == 0 ? 0 : 1;
}