Code

IO API: replace init_io_fd with io_open which calls fopen(3)
[tig.git] / tig.c
diff --git a/tig.c b/tig.c
index 6665d61145761253a6278403927a369e62bc07cb..12c385ad27c3bf5a5b9acf1f026e04734c454822 100644 (file)
--- a/tig.c
+++ b/tig.c
@@ -35,6 +35,7 @@
 #include <sys/stat.h>
 #include <unistd.h>
 #include <time.h>
+#include <fcntl.h>
 
 #include <regex.h>
 
@@ -64,7 +65,6 @@
 static void __NORETURN die(const char *err, ...);
 static void warn(const char *msg, ...);
 static void report(const char *msg, ...);
-static int read_properties(FILE *pipe, const char *separators, int (*read)(char *, size_t, char *, size_t));
 static void set_nonblocking_input(bool loading);
 static size_t utf8_length(const char *string, int *width, size_t max_width, int *trimmed, bool reserve);
 static bool prompt_yesno(const char *prompt);
@@ -119,34 +119,6 @@ static int load_refs(void);
 #define GIT_CONFIG "config"
 #endif
 
-#define TIG_LS_REMOTE \
-       "git ls-remote . 2>/dev/null"
-
-#define TIG_DIFF_CMD \
-       "git show --pretty=fuller --no-color --root --patch-with-stat --find-copies-harder -C %s 2>/dev/null"
-
-#define TIG_LOG_CMD    \
-       "git log --no-color --cc --stat -n100 %s 2>/dev/null"
-
-#define TIG_MAIN_BASE \
-       "git log --no-color --pretty=raw --parents --topo-order"
-
-#define TIG_MAIN_CMD \
-       TIG_MAIN_BASE " %s 2>/dev/null"
-
-#define TIG_TREE_CMD   \
-       "git ls-tree %s %s"
-
-#define TIG_BLOB_CMD   \
-       "git cat-file blob %s"
-
-/* XXX: Needs to be defined to the empty string. */
-#define TIG_HELP_CMD   ""
-#define TIG_PAGER_CMD  ""
-#define TIG_STATUS_CMD ""
-#define TIG_STAGE_CMD  ""
-#define TIG_BLAME_CMD  ""
-
 /* Some ascii-shorthands fitted into the ncurses namespace. */
 #define KEY_TAB                '\t'
 #define KEY_RETURN     '\r'
@@ -359,6 +331,18 @@ argv_from_string(const char *argv[SIZEOF_ARG], int *argc, char *cmd)
        return *argc < SIZEOF_ARG;
 }
 
+static void
+argv_from_env(const char **argv, const char *name)
+{
+       char *env = argv ? getenv(name) : NULL;
+       int argc = 0;
+
+       if (env && *env)
+               env = strdup(env);
+       if (env && !argv_from_string(argv, &argc, env))
+               die("Too many arguments in the `%s` environment variable", name);
+}
+
 
 /*
  * Executing external commands.
@@ -366,6 +350,7 @@ argv_from_string(const char *argv[SIZEOF_ARG], int *argc, char *cmd)
 
 enum io_type {
        IO_FD,                  /* File descriptor based IO. */
+       IO_BG,                  /* Execute command in the background. */
        IO_FG,                  /* Execute command with same std{in,out,err}. */
        IO_RD,                  /* Read only fork+exec IO. */
        IO_WR,                  /* Write only fork+exec IO. */
@@ -407,10 +392,10 @@ init_io_rd(struct io *io, const char *argv[], const char *dir,
 }
 
 static bool
-init_io_fd(struct io *io, FILE *pipe)
+io_open(struct io *io, const char *name)
 {
        init_io(io, NULL, IO_FD);
-       io->pipe = pipe;
+       io->pipe = *name ? fopen(name, "r") : stdin;
        return io->pipe != NULL;
 }
 
@@ -432,6 +417,9 @@ start_io(struct io *io)
        char buf[SIZEOF_STR * 2];
        size_t bufpos = 0;
 
+       if (io->type == IO_FD)
+               return TRUE;
+
        if (io->dir && *io->dir &&
            !string_format_from(buf, &bufpos, "cd %s;", io->dir))
                return FALSE;
@@ -439,7 +427,7 @@ start_io(struct io *io)
        if (!string_format_from(buf, &bufpos, "%s", io->sh))
                return FALSE;
 
-       if (io->type == IO_FG)
+       if (io->type == IO_FG || io->type == IO_BG)
                return system(buf) == 0;
 
        io->pipe = popen(io->sh, io->type == IO_RD ? "r" : "w");
@@ -447,10 +435,11 @@ start_io(struct io *io)
 }
 
 static bool
-run_io(struct io *io, enum io_type type, const char *cmd)
+run_io(struct io *io, const char **argv, const char *dir, enum io_type type)
 {
-       init_io(io, NULL, type);
-       string_ncopy(io->sh, cmd, strlen(cmd));
+       init_io(io, dir, type);
+       if (!format_command(io->sh, argv, FORMAT_NONE))
+               return FALSE;
        return start_io(io);
 }
 
@@ -460,6 +449,17 @@ run_io_do(struct io *io)
        return start_io(io) && done_io(io);
 }
 
+static int
+run_io_bg(const char **argv)
+{
+       struct io io = {};
+
+       init_io(&io, NULL, IO_BG);
+       if (!format_command(io.sh, argv, FORMAT_NONE))
+               return FALSE;
+       return run_io_do(&io);
+}
+
 static bool
 run_io_fg(const char **argv, const char *dir)
 {
@@ -472,18 +472,9 @@ run_io_fg(const char **argv, const char *dir)
 }
 
 static bool
-run_io_format(struct io *io, const char *cmd, ...)
+run_io_rd(struct io *io, const char **argv, enum format_flags flags)
 {
-       va_list args;
-
-       va_start(args, cmd);
-       init_io(io, NULL, IO_RD);
-
-       if (vsnprintf(io->sh, sizeof(io->sh), cmd, args) >= sizeof(io->sh))
-               io->sh[0] = 0;
-       va_end(args);
-
-       return io->sh[0] ? start_io(io) : FALSE;
+       return init_io_rd(io, argv, NULL, flags) && start_io(io);
 }
 
 static bool
@@ -504,6 +495,17 @@ io_strerror(struct io *io)
        return strerror(io->error);
 }
 
+static size_t
+io_read(struct io *io, void *buf, size_t bufsize)
+{
+       size_t readsize = fread(buf, 1, bufsize, io->pipe);
+
+       if (ferror(io->pipe))
+               io->error = errno;
+
+       return readsize;
+}
+
 static char *
 io_gets(struct io *io)
 {
@@ -523,6 +525,38 @@ io_gets(struct io *io)
        return io->buf;
 }
 
+static bool
+io_write(struct io *io, const void *buf, size_t bufsize)
+{
+       size_t written = 0;
+
+       while (!io_error(io) && written < bufsize) {
+               written += fwrite(buf + written, 1, bufsize - written, io->pipe);
+               if (ferror(io->pipe))
+                       io->error = errno;
+       }
+
+       return written == bufsize;
+}
+
+static bool
+run_io_buf(const char **argv, char buf[], size_t bufsize)
+{
+       struct io io = {};
+       bool error;
+
+       if (!run_io_rd(&io, argv, FORMAT_NONE))
+               return FALSE;
+
+       io.buf = buf;
+       io.bufalloc = bufsize;
+       error = !io_gets(&io) && io_error(&io);
+       io.buf = NULL;
+
+       return done_io(&io) || error;
+}
+
+static int read_properties(struct io *io, const char *separators, int (*read)(char *, size_t, char *, size_t));
 
 /*
  * User requests
@@ -666,14 +700,12 @@ static bool opt_show_refs         = TRUE;
 static int opt_num_interval            = NUMBER_INTERVAL;
 static int opt_tab_size                        = TAB_SIZE;
 static int opt_author_cols             = AUTHOR_COLS-1;
-static char opt_cmd[SIZEOF_STR]                = "";
 static char opt_path[SIZEOF_STR]       = "";
 static char opt_file[SIZEOF_STR]       = "";
 static char opt_ref[SIZEOF_REF]                = "";
 static char opt_head[SIZEOF_REF]       = "";
 static char opt_head_rev[SIZEOF_REV]   = "";
 static char opt_remote[SIZEOF_REF]     = "";
-static FILE *opt_pipe                  = NULL;
 static char opt_encoding[20]           = "UTF-8";
 static bool opt_utf8                   = TRUE;
 static char opt_codeset[20]            = "UTF-8";
@@ -689,18 +721,21 @@ static FILE *opt_tty                      = NULL;
 #define is_head_commit(rev)    (!strcmp((rev), "HEAD") || !strcmp(opt_head_rev, (rev)))
 
 static enum request
-parse_options(int argc, const char *argv[])
+parse_options(int argc, const char *argv[], const char ***run_argv)
 {
        enum request request = REQ_VIEW_MAIN;
-       size_t buf_size;
        const char *subcommand;
        bool seen_dashdash = FALSE;
-       int i;
+       /* XXX: This is vulnerable to the user overriding options
+        * required for the main view parser. */
+       const char *custom_argv[SIZEOF_ARG] = {
+               "git", "log", "--no-color", "--pretty=raw", "--parents",
+                       "--topo-order", NULL
+       };
+       int i, j = 6;
 
-       if (!isatty(STDIN_FILENO)) {
-               opt_pipe = stdin;
+       if (!isatty(STDIN_FILENO))
                return REQ_VIEW_PAGER;
-       }
 
        if (argc <= 1)
                return REQ_VIEW_MAIN;
@@ -737,14 +772,10 @@ parse_options(int argc, const char *argv[])
                subcommand = NULL;
        }
 
-       if (!subcommand)
-               /* XXX: This is vulnerable to the user overriding
-                * options required for the main view parser. */
-               string_copy(opt_cmd, TIG_MAIN_BASE);
-       else
-               string_format(opt_cmd, "git %s", subcommand);
-
-       buf_size = strlen(opt_cmd);
+       if (subcommand) {
+               custom_argv[1] = subcommand;
+               j = 2;
+       }
 
        for (i = 1 + !!subcommand; i < argc; i++) {
                const char *opt = argv[i];
@@ -761,13 +792,13 @@ parse_options(int argc, const char *argv[])
                        return REQ_NONE;
                }
 
-               opt_cmd[buf_size++] = ' ';
-               buf_size = sq_quote(opt_cmd, buf_size, opt);
-               if (buf_size >= sizeof(opt_cmd))
+               custom_argv[j++] = opt;
+               if (j >= ARRAY_SIZE(custom_argv))
                        die("command too long");
        }
 
-       opt_cmd[buf_size] = 0;
+       custom_argv[j] = NULL;
+       *run_argv = custom_argv;
 
        return request;
 }
@@ -1525,17 +1556,16 @@ read_option(char *opt, size_t optlen, char *value, size_t valuelen)
 static void
 load_option_file(const char *path)
 {
-       FILE *file;
+       struct io io = {};
 
        /* It's ok that the file doesn't exist. */
-       file = fopen(path, "r");
-       if (!file)
+       if (!io_open(&io, path))
                return;
 
        config_lineno = 0;
        config_errors = FALSE;
 
-       if (read_properties(file, " \t", read_option) == ERR ||
+       if (read_properties(&io, " \t", read_option) == ERR ||
            config_errors == TRUE)
                fprintf(stderr, "Errors while loading %s.\n", path);
 }
@@ -1594,7 +1624,6 @@ static char ref_head[SIZEOF_REF]  = "HEAD";
 
 struct view {
        const char *name;       /* View name */
-       const char *cmd_fmt;    /* Default command line format */
        const char *cmd_env;    /* Command line set via environment */
        const char *id;         /* Points to either of ref_{head,commit,blob} */
 
@@ -1643,6 +1672,8 @@ struct view {
 struct view_ops {
        /* What type of content being displayed. Used in the title bar. */
        const char *type;
+       /* Default command arguments. */
+       const char **argv;
        /* Open and reads in all view content. */
        bool (*open)(struct view *view);
        /* Read one line; updates view->line. */
@@ -1659,6 +1690,7 @@ struct view_ops {
 
 static struct view_ops blame_ops;
 static struct view_ops blob_ops;
+static struct view_ops diff_ops;
 static struct view_ops help_ops;
 static struct view_ops log_ops;
 static struct view_ops main_ops;
@@ -1667,16 +1699,16 @@ static struct view_ops stage_ops;
 static struct view_ops status_ops;
 static struct view_ops tree_ops;
 
-#define VIEW_STR(name, cmd, env, ref, ops, map, git) \
-       { name, cmd, #env, ref, ops, map, git }
+#define VIEW_STR(name, env, ref, ops, map, git) \
+       { name, #env, ref, ops, map, git }
 
 #define VIEW_(id, name, ops, git, ref) \
-       VIEW_STR(name, TIG_##id##_CMD,  TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
+       VIEW_STR(name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
 
 
 static struct view views[] = {
        VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
-       VIEW_(DIFF,   "diff",   &pager_ops,  TRUE,  ref_commit),
+       VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
        VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
        VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
        VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
@@ -2532,38 +2564,25 @@ prepare_update(struct view *view, const char *argv[], const char *dir,
 }
 
 static bool
-begin_update(struct view *view, bool refresh)
+prepare_update_file(struct view *view, const char *name)
 {
-       if (init_io_fd(&view->io, opt_pipe)) {
-               opt_pipe = NULL;
-
-       } else if (opt_cmd[0]) {
-               if (!run_io(&view->io, IO_RD, opt_cmd))
-                       return FALSE;
-               view->ref[0] = 0;
-               opt_cmd[0] = 0;
+       if (view->pipe)
+               end_update(view, TRUE);
+       return io_open(&view->io, name);
+}
 
-       } else if (refresh) {
+static bool
+begin_update(struct view *view, bool refresh)
+{
+       if (refresh) {
                if (!start_io(&view->io))
                        return FALSE;
 
-       } else if (view == VIEW(REQ_VIEW_TREE)) {
-               const char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
-               char path[SIZEOF_STR];
-
-               if (strcmp(view->vid, view->id))
-                       opt_path[0] = path[0] = 0;
-               else if (sq_quote(path, 0, opt_path) >= sizeof(path))
-                       return FALSE;
-
-               if (!run_io_format(&view->io, format, view->id, path))
-                       return FALSE;
-
        } else {
-               const char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
-               const char *id = view->id;
+               if (view == VIEW(REQ_VIEW_TREE) && strcmp(view->vid, view->id))
+                       opt_path[0] = 0;
 
-               if (!run_io_format(&view->io, format, id, id, id, id, id))
+               if (!run_io_rd(&view->io, view->ops->argv, FORMAT_ALL))
                        return FALSE;
 
                /* Put the current ref_* value to the view title ref
@@ -2968,7 +2987,7 @@ view_driver(struct view *view, enum request request)
                break;
 
        case REQ_VIEW_PAGER:
-               if (!opt_pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
+               if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
                        report("No pager content, press %s to run command from prompt",
                               get_key(REQ_PROMPT));
                        break;
@@ -3164,20 +3183,12 @@ pager_draw(struct view *view, struct line *line, unsigned int lineno)
 static bool
 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
 {
+       const char *describe_argv[] = { "git", "describe", commit_id, NULL };
        char refbuf[SIZEOF_STR];
        char *ref = NULL;
-       FILE *pipe;
-
-       if (!string_format(refbuf, "git describe %s 2>/dev/null", commit_id))
-               return TRUE;
-
-       pipe = popen(refbuf, "r");
-       if (!pipe)
-               return TRUE;
 
-       if ((ref = fgets(refbuf, sizeof(refbuf), pipe)))
-               ref = chomp_string(ref);
-       pclose(pipe);
+       if (run_io_buf(describe_argv, refbuf, sizeof(refbuf)))
+               ref = chomp_string(refbuf);
 
        if (!ref || !*ref)
                return TRUE;
@@ -3315,6 +3326,7 @@ pager_select(struct view *view, struct line *line)
 static struct view_ops pager_ops = {
        "line",
        NULL,
+       NULL,
        pager_read,
        pager_draw,
        pager_request,
@@ -3322,6 +3334,10 @@ static struct view_ops pager_ops = {
        pager_select,
 };
 
+static const char *log_argv[SIZEOF_ARG] = {
+       "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
+};
+
 static enum request
 log_request(struct view *view, enum request request, struct line *line)
 {
@@ -3337,6 +3353,7 @@ log_request(struct view *view, enum request request, struct line *line)
 
 static struct view_ops log_ops = {
        "line",
+       log_argv,
        NULL,
        pager_read,
        pager_draw,
@@ -3345,6 +3362,21 @@ static struct view_ops log_ops = {
        pager_select,
 };
 
+static const char *diff_argv[SIZEOF_ARG] = {
+       "git", "show", "--pretty=fuller", "--no-color", "--root",
+               "--patch-with-stat", "--find-copies-harder", "-C", "%(commit)", NULL
+};
+
+static struct view_ops diff_ops = {
+       "line",
+       diff_argv,
+       NULL,
+       pager_read,
+       pager_draw,
+       pager_request,
+       pager_grep,
+       pager_select,
+};
 
 /*
  * Help backend
@@ -3430,6 +3462,7 @@ help_open(struct view *view)
 
 static struct view_ops help_ops = {
        "line",
+       NULL,
        help_open,
        NULL,
        pager_draw,
@@ -3698,8 +3731,13 @@ tree_select(struct view *view, struct line *line)
        string_copy_rev(view->ref, text);
 }
 
+static const char *tree_argv[SIZEOF_ARG] = {
+       "git", "ls-tree", "%(commit)", "%(directory)", NULL
+};
+
 static struct view_ops tree_ops = {
        "file",
+       tree_argv,
        NULL,
        tree_read,
        pager_draw,
@@ -3716,8 +3754,13 @@ blob_read(struct view *view, char *line)
        return add_line_text(view, line, LINE_DEFAULT) != NULL;
 }
 
+static const char *blob_argv[SIZEOF_ARG] = {
+       "git", "cat-file", "blob", "%(blob)", NULL
+};
+
 static struct view_ops blob_ops = {
        "line",
+       blob_argv,
        NULL,
        blob_read,
        pager_draw,
@@ -3737,6 +3780,18 @@ static struct view_ops blob_ops = {
  *     reading output from git-blame.
  */
 
+static const char *blame_head_argv[] = {
+       "git", "blame", "--incremental", "--", "%(file)", NULL
+};
+
+static const char *blame_ref_argv[] = {
+       "git", "blame", "--incremental", "%(ref)", "--", "%(file)", NULL
+};
+
+static const char *blame_cat_file_argv[] = {
+       "git", "cat-file", "blob", "%(ref):%(file)", NULL
+};
+
 struct blame_commit {
        char id[SIZEOF_REV];            /* SHA1 ID. */
        char title[128];                /* First line of the commit message. */
@@ -3750,25 +3805,11 @@ struct blame {
        char text[1];
 };
 
-#define BLAME_CAT_FILE_CMD "git cat-file blob %s:%s"
-#define BLAME_INCREMENTAL_CMD "git blame --incremental %s -- %s"
-
 static bool
 blame_open(struct view *view)
 {
-       char path[SIZEOF_STR];
-       char ref[SIZEOF_STR] = "";
-
-       if (sq_quote(path, 0, opt_file) >= sizeof(path))
-               return FALSE;
-
-       if (*opt_ref && sq_quote(ref, 0, opt_ref) >= sizeof(ref))
-               return FALSE;
-
-       if (*opt_ref || !init_io_fd(&view->io, fopen(opt_file, "r"))) {
-               const char *id = *opt_ref ? ref : "HEAD";
-
-               if (!run_io_format(&view->io, BLAME_CAT_FILE_CMD, id, path))
+       if (*opt_ref || !io_open(&view->io, opt_file)) {
+               if (!run_io_rd(&view->io, blame_cat_file_argv, FORMAT_ALL))
                        return FALSE;
        }
 
@@ -3855,17 +3896,13 @@ static bool
 blame_read_file(struct view *view, const char *line, bool *read_file)
 {
        if (!line) {
-               char ref[SIZEOF_STR] = "";
-               char path[SIZEOF_STR];
+               const char **argv = *opt_ref ? blame_ref_argv : blame_head_argv;
                struct io io = {};
 
                if (view->lines == 0 && !view->parent)
                        die("No blame exist for %s", view->vid);
 
-               if (view->lines == 0 ||
-                   sq_quote(path, 0, opt_file) >= sizeof(path) ||
-                   (*opt_ref && sq_quote(ref, 0, opt_ref) >= sizeof(ref)) ||
-                   !run_io_format(&io, BLAME_INCREMENTAL_CMD, ref, path)) {
+               if (view->lines == 0 || !run_io_rd(&io, argv, FORMAT_ALL)) {
                        report("Failed to load blame data");
                        return TRUE;
                }
@@ -4015,11 +4052,18 @@ blame_request(struct view *view, enum request request, struct line *line)
                        break;
 
                if (!strcmp(blame->commit->id, NULL_ID)) {
-                       char path[SIZEOF_STR];
-
-                       if (sq_quote(path, 0, view->vid) >= sizeof(path))
+                       struct view *diff = VIEW(REQ_VIEW_DIFF);
+                       const char *diff_index_argv[] = {
+                               "git", "diff-index", "--root", "--cached",
+                                       "--patch-with-stat", "-C", "-M",
+                                       "HEAD", "--", view->vid, NULL
+                       };
+
+                       if (!prepare_update(diff, diff_index_argv, NULL, FORMAT_DASH)) {
+                               report("Failed to allocate diff command");
                                break;
-                       string_format(opt_cmd, "git diff-index --root --patch-with-stat -C -M --cached HEAD -- %s 2>/dev/null", path);
+                       }
+                       flags |= OPEN_PREPARED;
                }
 
                open_view(view, REQ_VIEW_DIFF, flags);
@@ -4077,6 +4121,7 @@ blame_select(struct view *view, struct line *line)
 
 static struct view_ops blame_ops = {
        "line",
+       NULL,
        blame_open,
        blame_read,
        blame_draw,
@@ -4150,26 +4195,25 @@ status_get_diff(struct status *file, const char *buf, size_t bufsize)
 }
 
 static bool
-status_run(struct view *view, const char cmd[], char status, enum line_type type)
+status_run(struct view *view, const char *argv[], char status, enum line_type type)
 {
        struct status *file = NULL;
        struct status *unmerged = NULL;
        char buf[SIZEOF_STR * 4];
        size_t bufsize = 0;
-       FILE *pipe;
+       struct io io = {};
 
-       pipe = popen(cmd, "r");
-       if (!pipe)
+       if (!run_io(&io, argv, NULL, IO_RD))
                return FALSE;
 
        add_line_data(view, NULL, type);
 
-       while (!feof(pipe) && !ferror(pipe)) {
+       while (!io_eof(&io)) {
                char *sep;
                size_t readsize;
 
-               readsize = fread(buf + bufsize, 1, sizeof(buf) - bufsize, pipe);
-               if (!readsize)
+               readsize = io_read(&io, buf + bufsize, sizeof(buf) - bufsize);
+               if (io_error(&io))
                        break;
                bufsize += readsize;
 
@@ -4250,35 +4294,40 @@ status_run(struct view *view, const char cmd[], char status, enum line_type type
                }
        }
 
-       if (ferror(pipe)) {
+       if (io_error(&io)) {
 error_out:
-               pclose(pipe);
+               done_io(&io);
                return FALSE;
        }
 
        if (!view->line[view->lines - 1].data)
                add_line_data(view, NULL, LINE_STAT_NONE);
 
-       pclose(pipe);
+       done_io(&io);
        return TRUE;
 }
 
 /* Don't show unmerged entries in the staged section. */
-#define STATUS_DIFF_INDEX_CMD "git diff-index -z --diff-filter=ACDMRTXB --cached -M HEAD"
-#define STATUS_DIFF_FILES_CMD "git diff-files -z"
-#define STATUS_LIST_OTHER_CMD \
-       "git ls-files -z --others --exclude-standard"
-#define STATUS_LIST_NO_HEAD_CMD \
-       "git ls-files -z --cached --exclude-standard"
+static const char *status_diff_index_argv[] = {
+       "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
+                            "--cached", "-M", "HEAD", NULL
+};
+
+static const char *status_diff_files_argv[] = {
+       "git", "diff-files", "-z", NULL
+};
 
-#define STATUS_DIFF_INDEX_SHOW_CMD \
-       "git diff-index --root --patch-with-stat -C -M --cached HEAD -- %s %s 2>/dev/null"
+static const char *status_list_other_argv[] = {
+       "git", "ls-files", "-z", "--others", "--exclude-standard", NULL
+};
 
-#define STATUS_DIFF_FILES_SHOW_CMD \
-       "git diff-files --root --patch-with-stat -C -M -- %s %s 2>/dev/null"
+static const char *status_list_no_head_argv[] = {
+       "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
+};
 
-#define STATUS_DIFF_NO_HEAD_SHOW_CMD \
-       "git diff --no-color --patch-with-stat /dev/null %s 2>/dev/null"
+static const char *update_index_argv[] = {
+       "git", "update-index", "-q", "--unmerged", "--refresh", NULL
+};
 
 /* First parse staged info using git-diff-index(1), then parse unstaged
  * info using git-diff-files(1), and finally untracked files using
@@ -4301,17 +4350,17 @@ status_open(struct view *view)
        else if (!string_format(status_onbranch, "On branch %s", opt_head))
                return FALSE;
 
-       system("git update-index -q --refresh >/dev/null 2>/dev/null");
+       run_io_bg(update_index_argv);
 
        if (is_initial_commit()) {
-               if (!status_run(view, STATUS_LIST_NO_HEAD_CMD, 'A', LINE_STAT_STAGED))
+               if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
                        return FALSE;
-       } else if (!status_run(view, STATUS_DIFF_INDEX_CMD, 0, LINE_STAT_STAGED)) {
+       } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
                return FALSE;
        }
 
-       if (!status_run(view, STATUS_DIFF_FILES_CMD, 0, LINE_STAT_UNSTAGED) ||
-           !status_run(view, STATUS_LIST_OTHER_CMD, '?', LINE_STAT_UNTRACKED))
+       if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
+           !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
                return FALSE;
 
        /* If all went well restore the previous line number to stay in
@@ -4393,11 +4442,13 @@ static enum request
 status_enter(struct view *view, struct line *line)
 {
        struct status *status = line->data;
-       char oldpath[SIZEOF_STR] = "";
-       char newpath[SIZEOF_STR] = "";
+       const char *oldpath = status ? status->old.name : NULL;
+       /* Diffs for unmerged entries are empty when passing the new
+        * path, so leave it empty. */
+       const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
        const char *info;
-       size_t cmdsize = 0;
        enum open_flags split;
+       struct view *stage = VIEW(REQ_VIEW_STAGE);
 
        if (line->type == LINE_STAT_NONE ||
            (!status && line[1].type == LINE_STAT_NONE)) {
@@ -4405,32 +4456,24 @@ status_enter(struct view *view, struct line *line)
                return REQ_NONE;
        }
 
-       if (status) {
-               if (sq_quote(oldpath, 0, status->old.name) >= sizeof(oldpath))
-                       return REQ_QUIT;
-               /* Diffs for unmerged entries are empty when pasing the
-                * new path, so leave it empty. */
-               if (status->status != 'U' &&
-                   sq_quote(newpath, 0, status->new.name) >= sizeof(newpath))
-                       return REQ_QUIT;
-       }
-
-       if (opt_cdup[0] &&
-           line->type != LINE_STAT_UNTRACKED &&
-           !string_format_from(opt_cmd, &cmdsize, "cd %s;", opt_cdup))
-               return REQ_QUIT;
-
        switch (line->type) {
        case LINE_STAT_STAGED:
                if (is_initial_commit()) {
-                       if (!string_format_from(opt_cmd, &cmdsize,
-                                               STATUS_DIFF_NO_HEAD_SHOW_CMD,
-                                               newpath))
+                       const char *no_head_diff_argv[] = {
+                               "git", "diff", "--no-color", "--patch-with-stat",
+                                       "--", "/dev/null", newpath, NULL
+                       };
+
+                       if (!prepare_update(stage, no_head_diff_argv, opt_cdup, FORMAT_DASH))
                                return REQ_QUIT;
                } else {
-                       if (!string_format_from(opt_cmd, &cmdsize,
-                                               STATUS_DIFF_INDEX_SHOW_CMD,
-                                               oldpath, newpath))
+                       const char *index_show_argv[] = {
+                               "git", "diff-index", "--root", "--patch-with-stat",
+                                       "-C", "-M", "--cached", "HEAD", "--",
+                                       oldpath, newpath, NULL
+                       };
+
+                       if (!prepare_update(stage, index_show_argv, opt_cdup, FORMAT_DASH))
                                return REQ_QUIT;
                }
 
@@ -4441,20 +4484,22 @@ status_enter(struct view *view, struct line *line)
                break;
 
        case LINE_STAT_UNSTAGED:
-               if (!string_format_from(opt_cmd, &cmdsize,
-                                       STATUS_DIFF_FILES_SHOW_CMD, oldpath, newpath))
+       {
+               const char *files_show_argv[] = {
+                       "git", "diff-files", "--root", "--patch-with-stat",
+                               "-C", "-M", "--", oldpath, newpath, NULL
+               };
+
+               if (!prepare_update(stage, files_show_argv, opt_cdup, FORMAT_DASH))
                        return REQ_QUIT;
                if (status)
                        info = "Unstaged changes to %s";
                else
                        info = "Unstaged changes";
                break;
-
+       }
        case LINE_STAT_UNTRACKED:
-               if (opt_pipe)
-                       return REQ_QUIT;
-
-               if (!status) {
+               if (!newpath) {
                        report("No file to show");
                        return REQ_NONE;
                }
@@ -4464,7 +4509,8 @@ status_enter(struct view *view, struct line *line)
                        return REQ_NONE;
                }
 
-               opt_pipe = fopen(status->new.name, "r");
+               if (!prepare_update_file(stage, newpath))
+                       return REQ_QUIT;
                info = "Untracked file %s";
                break;
 
@@ -4476,7 +4522,7 @@ status_enter(struct view *view, struct line *line)
        }
 
        split = view_is_displayed(view) ? OPEN_SPLIT : 0;
-       open_view(view, REQ_VIEW_STAGE, OPEN_RELOAD | split);
+       open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH | split);
        if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
                if (status) {
                        stage_status = *status;
@@ -4510,40 +4556,37 @@ status_exists(struct status *status, enum line_type type)
 }
 
 
-static FILE *
-status_update_prepare(enum line_type type)
+static bool
+status_update_prepare(struct io *io, enum line_type type)
 {
-       char cmd[SIZEOF_STR];
-       size_t cmdsize = 0;
-
-       if (opt_cdup[0] &&
-           type != LINE_STAT_UNTRACKED &&
-           !string_format_from(cmd, &cmdsize, "cd %s;", opt_cdup))
-               return NULL;
+       const char *staged_argv[] = {
+               "git", "update-index", "-z", "--index-info", NULL
+       };
+       const char *others_argv[] = {
+               "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
+       };
 
        switch (type) {
        case LINE_STAT_STAGED:
-               string_add(cmd, cmdsize, "git update-index -z --index-info");
-               break;
+               return run_io(io, staged_argv, opt_cdup, IO_WR);
 
        case LINE_STAT_UNSTAGED:
+               return run_io(io, others_argv, opt_cdup, IO_WR);
+
        case LINE_STAT_UNTRACKED:
-               string_add(cmd, cmdsize, "git update-index -z --add --remove --stdin");
-               break;
+               return run_io(io, others_argv, NULL, IO_WR);
 
        default:
                die("line type %d not handled in switch", type);
+               return FALSE;
        }
-
-       return popen(cmd, "w");
 }
 
 static bool
-status_update_write(FILE *pipe, struct status *status, enum line_type type)
+status_update_write(struct io *io, struct status *status, enum line_type type)
 {
        char buf[SIZEOF_STR];
        size_t bufsize = 0;
-       size_t written = 0;
 
        switch (type) {
        case LINE_STAT_STAGED:
@@ -4564,37 +4607,33 @@ status_update_write(FILE *pipe, struct status *status, enum line_type type)
                die("line type %d not handled in switch", type);
        }
 
-       while (!ferror(pipe) && written < bufsize) {
-               written += fwrite(buf + written, 1, bufsize - written, pipe);
-       }
-
-       return written == bufsize;
+       return io_write(io, buf, bufsize);
 }
 
 static bool
 status_update_file(struct status *status, enum line_type type)
 {
-       FILE *pipe = status_update_prepare(type);
+       struct io io = {};
        bool result;
 
-       if (!pipe)
+       if (!status_update_prepare(&io, type))
                return FALSE;
 
-       result = status_update_write(pipe, status, type);
-       pclose(pipe);
+       result = status_update_write(&io, status, type);
+       done_io(&io);
        return result;
 }
 
 static bool
 status_update_files(struct view *view, struct line *line)
 {
-       FILE *pipe = status_update_prepare(line->type);
+       struct io io = {};
        bool result = TRUE;
        struct line *pos = view->line + view->lines;
        int files = 0;
        int file, done;
 
-       if (!pipe)
+       if (!status_update_prepare(&io, line->type))
                return FALSE;
 
        for (pos = line; pos < view->line + view->lines && pos->data; pos++)
@@ -4609,10 +4648,10 @@ status_update_files(struct view *view, struct line *line)
                                      file, files, done);
                        update_view_title(view);
                }
-               result = status_update_write(pipe, line->data, line->type);
+               result = status_update_write(&io, line->data, line->type);
        }
 
-       pclose(pipe);
+       done_io(&io);
        return result;
 }
 
@@ -4812,6 +4851,7 @@ status_grep(struct view *view, struct line *line)
 
 static struct view_ops status_ops = {
        "file",
+       NULL,
        status_open,
        NULL,
        status_draw,
@@ -4822,27 +4862,13 @@ static struct view_ops status_ops = {
 
 
 static bool
-stage_diff_line(FILE *pipe, struct line *line)
-{
-       const char *buf = line->data;
-       size_t bufsize = strlen(buf);
-       size_t written = 0;
-
-       while (!ferror(pipe) && written < bufsize) {
-               written += fwrite(buf + written, 1, bufsize - written, pipe);
-       }
-
-       fputc('\n', pipe);
-
-       return written == bufsize;
-}
-
-static bool
-stage_diff_write(FILE *pipe, struct line *line, struct line *end)
+stage_diff_write(struct io *io, struct line *line, struct line *end)
 {
        while (line < end) {
-               if (!stage_diff_line(pipe, line++))
+               if (!io_write(io, line->data, strlen(line->data)) ||
+                   !io_write(io, "\n", 1))
                        return FALSE;
+               line++;
                if (line->type == LINE_DIFF_CHUNK ||
                    line->type == LINE_DIFF_HEADER)
                        break;
@@ -4864,35 +4890,32 @@ stage_diff_find(struct view *view, struct line *line, enum line_type type)
 static bool
 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
 {
-       char cmd[SIZEOF_STR];
-       size_t cmdsize = 0;
+       const char *apply_argv[SIZEOF_ARG] = {
+               "git", "apply", "--whitespace=nowarn", NULL
+       };
        struct line *diff_hdr;
-       FILE *pipe;
+       struct io io = {};
+       int argc = 3;
 
        diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
        if (!diff_hdr)
                return FALSE;
 
-       if (opt_cdup[0] &&
-           !string_format_from(cmd, &cmdsize, "cd %s;", opt_cdup))
-               return FALSE;
-
-       if (!string_format_from(cmd, &cmdsize,
-                               "git apply --whitespace=nowarn %s %s - && "
-                               "git update-index -q --unmerged --refresh 2>/dev/null",
-                               revert ? "" : "--cached",
-                               revert || stage_line_type == LINE_STAT_STAGED ? "-R" : ""))
-               return FALSE;
-
-       pipe = popen(cmd, "w");
-       if (!pipe)
+       if (!revert)
+               apply_argv[argc++] = "--cached";
+       if (revert || stage_line_type == LINE_STAT_STAGED)
+               apply_argv[argc++] = "-R";
+       apply_argv[argc++] = "-";
+       apply_argv[argc++] = NULL;
+       if (!run_io(&io, apply_argv, opt_cdup, IO_WR))
                return FALSE;
 
-       if (!stage_diff_write(pipe, diff_hdr, chunk) ||
-           !stage_diff_write(pipe, chunk, view->line + view->lines))
+       if (!stage_diff_write(&io, diff_hdr, chunk) ||
+           !stage_diff_write(&io, chunk, view->line + view->lines))
                chunk = NULL;
 
-       pclose(pipe);
+       done_io(&io);
+       run_io_bg(update_index_argv);
 
        return chunk ? TRUE : FALSE;
 }
@@ -5057,7 +5080,10 @@ stage_request(struct view *view, enum request request, struct line *line)
                        return REQ_NONE;
                }
 
-               opt_pipe = fopen(stage_status.new.name, "r");
+               if (!prepare_update_file(view, stage_status.new.name)) {
+                       report("Failed to open file: %s", strerror(errno));
+                       return REQ_NONE;
+               }
        }
        open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
 
@@ -5067,6 +5093,7 @@ stage_request(struct view *view, enum request request, struct line *line)
 static struct view_ops stage_ops = {
        "line",
        NULL,
+       NULL,
        pager_read,
        pager_draw,
        stage_request,
@@ -5295,6 +5322,11 @@ update_rev_graph(struct rev_graph *graph)
  * Main view backend
  */
 
+static const char *main_argv[SIZEOF_ARG] = {
+       "git", "log", "--no-color", "--pretty=raw", "--parents",
+                     "--topo-order", "%(head)", NULL
+};
+
 static bool
 main_draw(struct view *view, struct line *line, unsigned int lineno)
 {
@@ -5575,6 +5607,7 @@ main_select(struct view *view, struct line *line)
 
 static struct view_ops main_ops = {
        "commit",
+       main_argv,
        NULL,
        main_read,
        main_draw,
@@ -5969,9 +6002,20 @@ read_prompt(const char *prompt)
 }
 
 /*
- * Repository references
+ * Repository properties
  */
 
+static int
+git_properties(const char **argv, const char *separators,
+              int (*read_property)(char *, size_t, char *, size_t))
+{
+       struct io io = {};
+
+       if (init_io_rd(&io, argv, NULL, FORMAT_NONE))
+               return read_properties(&io, separators, read_property);
+       return ERR;
+}
+
 static struct ref *refs = NULL;
 static size_t refs_alloc = 0;
 static size_t refs_size = 0;
@@ -6128,8 +6172,15 @@ read_ref(char *id, size_t idlen, char *name, size_t namelen)
 static int
 load_refs(void)
 {
-       const char *cmd_env = getenv("TIG_LS_REMOTE");
-       const char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
+       static const char *ls_remote_argv[SIZEOF_ARG] = {
+               "git", "ls-remote", ".", NULL
+       };
+       static bool init = FALSE;
+
+       if (!init) {
+               argv_from_env(ls_remote_argv, "TIG_LS_REMOTE");
+               init = TRUE;
+       }
 
        if (!*opt_git_dir)
                return OK;
@@ -6139,7 +6190,7 @@ load_refs(void)
        while (id_refs_size > 0)
                free(id_refs[--id_refs_size]);
 
-       return read_properties(popen(cmd, "r"), "\t", read_ref);
+       return git_properties(ls_remote_argv, "\t", read_ref);
 }
 
 static int
@@ -6179,8 +6230,9 @@ read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen
 static int
 load_git_config(void)
 {
-       return read_properties(popen("git " GIT_CONFIG " --list", "r"),
-                              "=", read_repo_config_option);
+       const char *config_list_argv[] = { "git", GIT_CONFIG, "--list", NULL };
+
+       return git_properties(config_list_argv, "=", read_repo_config_option);
 }
 
 static int
@@ -6196,15 +6248,8 @@ read_repo_info(char *name, size_t namelen, char *value, size_t valuelen)
                 * the option else either "true" or "false" is printed.
                 * Default to true for the unknown case. */
                opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
-
-       } else if (opt_cdup[0] == ' ') {
-               string_ncopy(opt_cdup, name, namelen);
        } else {
-               if (!prefixcmp(name, "refs/heads/")) {
-                       namelen -= STRING_SIZE("refs/heads/");
-                       name    += STRING_SIZE("refs/heads/");
-                       string_ncopy(opt_head, name, namelen);
-               }
+               string_ncopy(opt_cdup, name, namelen);
        }
 
        return OK;
@@ -6213,34 +6258,37 @@ read_repo_info(char *name, size_t namelen, char *value, size_t valuelen)
 static int
 load_repo_info(void)
 {
-       int result;
-       FILE *pipe = popen("(git rev-parse --git-dir --is-inside-work-tree "
-                          " --show-cdup; git symbolic-ref HEAD) 2>/dev/null", "r");
+       const char *head_argv[] = {
+               "git", "symbolic-ref", "HEAD", NULL
+       };
+       const char *rev_parse_argv[] = {
+               "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
+                       "--show-cdup", NULL
+       };
 
-       /* XXX: The line outputted by "--show-cdup" can be empty so
-        * initialize it to something invalid to make it possible to
-        * detect whether it has been set or not. */
-       opt_cdup[0] = ' ';
+       if (run_io_buf(head_argv, opt_head, sizeof(opt_head))) {
+               chomp_string(opt_head);
+               if (!prefixcmp(opt_head, "refs/heads/")) {
+                       char *offset = opt_head + STRING_SIZE("refs/heads/");
 
-       result = read_properties(pipe, "=", read_repo_info);
-       if (opt_cdup[0] == ' ')
-               opt_cdup[0] = 0;
+                       memmove(opt_head, offset, strlen(offset) + 1);
+               }
+       }
 
-       return result;
+       return git_properties(rev_parse_argv, "=", read_repo_info);
 }
 
 static int
-read_properties(FILE *pipe, const char *separators,
+read_properties(struct io *io, const char *separators,
                int (*read_property)(char *, size_t, char *, size_t))
 {
-       char buffer[BUFSIZ];
        char *name;
        int state = OK;
 
-       if (!pipe)
+       if (!start_io(io))
                return ERR;
 
-       while (state == OK && (name = fgets(buffer, sizeof(buffer), pipe))) {
+       while (state == OK && (name = io_gets(io))) {
                char *value;
                size_t namelen;
                size_t valuelen;
@@ -6261,10 +6309,9 @@ read_properties(FILE *pipe, const char *separators,
                state = read_property(name, namelen, value, valuelen);
        }
 
-       if (state != ERR && ferror(pipe))
+       if (state != ERR && io_error(io))
                state = ERR;
-
-       pclose(pipe);
+       done_io(io);
 
        return state;
 }
@@ -6314,6 +6361,7 @@ warn(const char *msg, ...)
 int
 main(int argc, const char *argv[])
 {
+       const char **run_argv = NULL;
        struct view *view;
        enum request request;
        size_t i;
@@ -6335,7 +6383,7 @@ main(int argc, const char *argv[])
        if (load_git_config() == ERR)
                die("Failed to load repo config.");
 
-       request = parse_options(argc, argv);
+       request = parse_options(argc, argv, &run_argv);
        if (request == REQ_NONE)
                return 0;
 
@@ -6356,10 +6404,19 @@ main(int argc, const char *argv[])
                die("Failed to load refs.");
 
        foreach_view (view, i)
-               view->cmd_env = getenv(view->cmd_env);
+               argv_from_env(view->ops->argv, view->cmd_env);
 
        init_display();
 
+       if (request == REQ_VIEW_PAGER || run_argv) {
+               if (request == REQ_VIEW_PAGER)
+                       io_open(&VIEW(request)->io, "");
+               else if (!prepare_update(VIEW(request), run_argv, NULL, FORMAT_NONE))
+                       die("Failed to format arguments");
+               open_view(NULL, request, OPEN_PREPARED);
+               request = REQ_NONE;
+       }
+
        while (view_driver(display[current_view], request)) {
                int key;
                int i;