git.con commit Merge branch 'js/diffstat' into next (07512ea)
   1#include <stdio.h>
   2#include <sys/types.h>
   3#include <sys/stat.h>
   4#include <dirent.h>
   5#include <unistd.h>
   6#include <stdlib.h>
   7#include <string.h>
   8#include <errno.h>
   9#include <limits.h>
  10#include <stdarg.h>
  11#include <sys/ioctl.h>
  12#include "git-compat-util.h"
  13#include "exec_cmd.h"
  14#include "common-cmds.h"
  15
  16#include "cache.h"
  17#include "commit.h"
  18#include "diff.h"
  19#include "revision.h"
  20#include "log-tree.h"
  21
  22#ifndef PATH_MAX
  23# define PATH_MAX 4096
  24#endif
  25
  26static const char git_usage[] =
  27        "Usage: git [--version] [--exec-path[=GIT_EXEC_PATH]] [--help] COMMAND [ ARGS ]";
  28
  29/* most gui terms set COLUMNS (although some don't export it) */
  30static int term_columns(void)
  31{
  32        char *col_string = getenv("COLUMNS");
  33        int n_cols = 0;
  34
  35        if (col_string && (n_cols = atoi(col_string)) > 0)
  36                return n_cols;
  37
  38#ifdef TIOCGWINSZ
  39        {
  40                struct winsize ws;
  41                if (!ioctl(1, TIOCGWINSZ, &ws)) {
  42                        if (ws.ws_col)
  43                                return ws.ws_col;
  44                }
  45        }
  46#endif
  47
  48        return 80;
  49}
  50
  51static void oom(void)
  52{
  53        fprintf(stderr, "git: out of memory\n");
  54        exit(1);
  55}
  56
  57static inline void mput_char(char c, unsigned int num)
  58{
  59        while(num--)
  60                putchar(c);
  61}
  62
  63static struct cmdname {
  64        size_t len;
  65        char name[1];
  66} **cmdname;
  67static int cmdname_alloc, cmdname_cnt;
  68
  69static void add_cmdname(const char *name, int len)
  70{
  71        struct cmdname *ent;
  72        if (cmdname_alloc <= cmdname_cnt) {
  73                cmdname_alloc = cmdname_alloc + 200;
  74                cmdname = realloc(cmdname, cmdname_alloc * sizeof(*cmdname));
  75                if (!cmdname)
  76                        oom();
  77        }
  78        ent = malloc(sizeof(*ent) + len);
  79        if (!ent)
  80                oom();
  81        ent->len = len;
  82        memcpy(ent->name, name, len);
  83        ent->name[len] = 0;
  84        cmdname[cmdname_cnt++] = ent;
  85}
  86
  87static int cmdname_compare(const void *a_, const void *b_)
  88{
  89        struct cmdname *a = *(struct cmdname **)a_;
  90        struct cmdname *b = *(struct cmdname **)b_;
  91        return strcmp(a->name, b->name);
  92}
  93
  94static void pretty_print_string_list(struct cmdname **cmdname, int longest)
  95{
  96        int cols = 1, rows;
  97        int space = longest + 1; /* min 1 SP between words */
  98        int max_cols = term_columns() - 1; /* don't print *on* the edge */
  99        int i, j;
 100
 101        if (space < max_cols)
 102                cols = max_cols / space;
 103        rows = (cmdname_cnt + cols - 1) / cols;
 104
 105        qsort(cmdname, cmdname_cnt, sizeof(*cmdname), cmdname_compare);
 106
 107        for (i = 0; i < rows; i++) {
 108                printf("  ");
 109
 110                for (j = 0; j < cols; j++) {
 111                        int n = j * rows + i;
 112                        int size = space;
 113                        if (n >= cmdname_cnt)
 114                                break;
 115                        if (j == cols-1 || n + rows >= cmdname_cnt)
 116                                size = 1;
 117                        printf("%-*s", size, cmdname[n]->name);
 118                }
 119                putchar('\n');
 120        }
 121}
 122
 123static void list_commands(const char *exec_path, const char *pattern)
 124{
 125        unsigned int longest = 0;
 126        char path[PATH_MAX];
 127        int dirlen;
 128        DIR *dir = opendir(exec_path);
 129        struct dirent *de;
 130
 131        if (!dir) {
 132                fprintf(stderr, "git: '%s': %s\n", exec_path, strerror(errno));
 133                exit(1);
 134        }
 135
 136        dirlen = strlen(exec_path);
 137        if (PATH_MAX - 20 < dirlen) {
 138                fprintf(stderr, "git: insanely long exec-path '%s'\n",
 139                        exec_path);
 140                exit(1);
 141        }
 142
 143        memcpy(path, exec_path, dirlen);
 144        path[dirlen++] = '/';
 145
 146        while ((de = readdir(dir)) != NULL) {
 147                struct stat st;
 148                int entlen;
 149
 150                if (strncmp(de->d_name, "git-", 4))
 151                        continue;
 152                strcpy(path+dirlen, de->d_name);
 153                if (stat(path, &st) || /* stat, not lstat */
 154                    !S_ISREG(st.st_mode) ||
 155                    !(st.st_mode & S_IXUSR))
 156                        continue;
 157
 158                entlen = strlen(de->d_name);
 159                if (4 < entlen && !strcmp(de->d_name + entlen - 4, ".exe"))
 160                        entlen -= 4;
 161
 162                if (longest < entlen)
 163                        longest = entlen;
 164
 165                add_cmdname(de->d_name + 4, entlen-4);
 166        }
 167        closedir(dir);
 168
 169        printf("git commands available in '%s'\n", exec_path);
 170        printf("----------------------------");
 171        mput_char('-', strlen(exec_path));
 172        putchar('\n');
 173        pretty_print_string_list(cmdname, longest - 4);
 174        putchar('\n');
 175}
 176
 177static void list_common_cmds_help(void)
 178{
 179        int i, longest = 0;
 180
 181        for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
 182                if (longest < strlen(common_cmds[i].name))
 183                        longest = strlen(common_cmds[i].name);
 184        }
 185
 186        puts("The most commonly used git commands are:");
 187        for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
 188                printf("    %s", common_cmds[i].name);
 189                mput_char(' ', longest - strlen(common_cmds[i].name) + 4);
 190                puts(common_cmds[i].help);
 191        }
 192        puts("(use 'git help -a' to get a list of all installed git commands)");
 193}
 194
 195#ifdef __GNUC__
 196static void cmd_usage(int show_all, const char *exec_path, const char *fmt, ...)
 197        __attribute__((__format__(__printf__, 3, 4), __noreturn__));
 198#endif
 199static void cmd_usage(int show_all, const char *exec_path, const char *fmt, ...)
 200{
 201        if (fmt) {
 202                va_list ap;
 203
 204                va_start(ap, fmt);
 205                printf("git: ");
 206                vprintf(fmt, ap);
 207                va_end(ap);
 208                putchar('\n');
 209        }
 210        else
 211                puts(git_usage);
 212
 213        if (exec_path) {
 214                putchar('\n');
 215                if (show_all)
 216                        list_commands(exec_path, "git-*");
 217                else
 218                        list_common_cmds_help();
 219        }
 220
 221        exit(1);
 222}
 223
 224static void prepend_to_path(const char *dir, int len)
 225{
 226        char *path, *old_path = getenv("PATH");
 227        int path_len = len;
 228
 229        if (!old_path)
 230                old_path = "/usr/local/bin:/usr/bin:/bin";
 231
 232        path_len = len + strlen(old_path) + 1;
 233
 234        path = malloc(path_len + 1);
 235
 236        memcpy(path, dir, len);
 237        path[len] = ':';
 238        memcpy(path + len + 1, old_path, path_len - len);
 239
 240        setenv("PATH", path, 1);
 241}
 242
 243static void show_man_page(const char *git_cmd)
 244{
 245        const char *page;
 246
 247        if (!strncmp(git_cmd, "git", 3))
 248                page = git_cmd;
 249        else {
 250                int page_len = strlen(git_cmd) + 4;
 251                char *p = malloc(page_len + 1);
 252                strcpy(p, "git-");
 253                strcpy(p + 4, git_cmd);
 254                p[page_len] = 0;
 255                page = p;
 256        }
 257
 258        execlp("man", "man", page, NULL);
 259}
 260
 261static int cmd_version(int argc, const char **argv, char **envp)
 262{
 263        printf("git version %s\n", GIT_VERSION);
 264        return 0;
 265}
 266
 267static int cmd_help(int argc, const char **argv, char **envp)
 268{
 269        const char *help_cmd = argv[1];
 270        if (!help_cmd)
 271                cmd_usage(0, git_exec_path(), NULL);
 272        else if (!strcmp(help_cmd, "--all") || !strcmp(help_cmd, "-a"))
 273                cmd_usage(1, git_exec_path(), NULL);
 274        else
 275                show_man_page(help_cmd);
 276        return 0;
 277}
 278
 279#define LOGSIZE (65536)
 280
 281static int cmd_log_wc(int argc, const char **argv, char **envp,
 282                      struct whatchanged_opt *wcopt)
 283{
 284        struct commit *commit;
 285        char *buf = xmalloc(LOGSIZE);
 286        const char *commit_prefix = "commit ";
 287        int shown = 0;
 288        struct rev_info *rev = &wcopt->revopt;
 289        struct log_tree_opt *opt = &wcopt->logopt;
 290
 291        opt->commit_format = CMIT_FMT_DEFAULT;
 292        wcopt->abbrev = DEFAULT_ABBREV;
 293        argc = parse_whatchanged_opt(argc, argv, wcopt);
 294
 295        if (opt->commit_format == CMIT_FMT_ONELINE)
 296                commit_prefix = "";
 297
 298        prepare_revision_walk(rev);
 299        setup_pager();
 300        while ((commit = get_revision(rev)) != NULL) {
 301                if (shown && wcopt->do_diff &&
 302                    opt->commit_format != CMIT_FMT_ONELINE)
 303                        putchar('\n');
 304                fputs(commit_prefix, stdout);
 305                if (wcopt->abbrev_commit && wcopt->abbrev)
 306                        fputs(find_unique_abbrev(commit->object.sha1, wcopt->abbrev),
 307                              stdout);
 308                else
 309                        fputs(sha1_to_hex(commit->object.sha1), stdout);
 310                if (rev->parents) {
 311                        struct commit_list *parents = commit->parents;
 312                        while (parents) {
 313                                struct object *o = &(parents->item->object);
 314                                parents = parents->next;
 315                                if (o->flags & TMP_MARK)
 316                                        continue;
 317                                printf(" %s", sha1_to_hex(o->sha1));
 318                                o->flags |= TMP_MARK;
 319                        }
 320                        /* TMP_MARK is a general purpose flag that can
 321                         * be used locally, but the user should clean
 322                         * things up after it is done with them.
 323                         */
 324                        for (parents = commit->parents;
 325                             parents;
 326                             parents = parents->next)
 327                                parents->item->object.flags &= ~TMP_MARK;
 328                }
 329                if (opt->commit_format == CMIT_FMT_ONELINE)
 330                        putchar(' ');
 331                else
 332                        putchar('\n');
 333                pretty_print_commit(opt->commit_format, commit, ~0, buf,
 334                                    LOGSIZE, wcopt->abbrev);
 335                printf("%s\n", buf);
 336                if (wcopt->do_diff) {
 337                        printf("---\n");
 338                        log_tree_commit(opt, commit);
 339                }
 340                shown = 1;
 341                free(commit->buffer);
 342                commit->buffer = NULL;
 343        }
 344        free(buf);
 345        return 0;
 346}
 347
 348static int cmd_log(int ac, const char **av, char **ep)
 349{
 350        struct whatchanged_opt wcopt;
 351
 352        memset(&wcopt, 0, sizeof(wcopt));
 353        init_log_tree_opt(&wcopt.logopt);
 354        return cmd_log_wc(ac, av, ep, &wcopt);
 355}
 356
 357static int cmd_whatchanged(int ac, const char **av, char **ep)
 358{
 359        struct whatchanged_opt wcopt;
 360
 361        memset(&wcopt, 0, sizeof(wcopt));
 362        wcopt.do_diff = 1;
 363        init_log_tree_opt(&wcopt.logopt);
 364        wcopt.logopt.diffopt.recursive = 1;
 365        return cmd_log_wc(ac, av, ep, &wcopt);
 366}
 367
 368static int cmd_show(int ac, const char **av, char **ep)
 369{
 370        struct whatchanged_opt wcopt;
 371
 372        memset(&wcopt, 0, sizeof(wcopt));
 373        wcopt.do_diff = 1;
 374        init_log_tree_opt(&wcopt.logopt);
 375        wcopt.logopt.ignore_merges = 0;
 376        wcopt.logopt.combine_merges = 1;
 377        wcopt.logopt.dense_combined_merges = 1;
 378        wcopt.logopt.diffopt.recursive = 1;
 379        return cmd_log_wc(ac, av, ep, &wcopt);
 380}
 381
 382static void handle_internal_command(int argc, const char **argv, char **envp)
 383{
 384        const char *cmd = argv[0];
 385        static struct cmd_struct {
 386                const char *cmd;
 387                int (*fn)(int, const char **, char **);
 388        } commands[] = {
 389                { "version", cmd_version },
 390                { "help", cmd_help },
 391                { "log", cmd_log },
 392                { "show", cmd_show },
 393                { "whatchanged", cmd_whatchanged },
 394        };
 395        int i;
 396
 397        /* Turn "git cmd --help" into "git help cmd" */
 398        if (argc > 1 && !strcmp(argv[1], "--help")) {
 399                argv[1] = argv[0];
 400                argv[0] = cmd = "help";
 401        }
 402
 403        for (i = 0; i < ARRAY_SIZE(commands); i++) {
 404                struct cmd_struct *p = commands+i;
 405                if (strcmp(p->cmd, cmd))
 406                        continue;
 407                exit(p->fn(argc, argv, envp));
 408        }
 409}
 410
 411int main(int argc, const char **argv, char **envp)
 412{
 413        const char *cmd = argv[0];
 414        char *slash = strrchr(cmd, '/');
 415        char git_command[PATH_MAX + 1];
 416        const char *exec_path = NULL;
 417
 418        /*
 419         * Take the basename of argv[0] as the command
 420         * name, and the dirname as the default exec_path
 421         * if it's an absolute path and we don't have
 422         * anything better.
 423         */
 424        if (slash) {
 425                *slash++ = 0;
 426                if (*cmd == '/')
 427                        exec_path = cmd;
 428                cmd = slash;
 429        }
 430
 431        /*
 432         * "git-xxxx" is the same as "git xxxx", but we obviously:
 433         *
 434         *  - cannot take flags in between the "git" and the "xxxx".
 435         *  - cannot execute it externally (since it would just do
 436         *    the same thing over again)
 437         *
 438         * So we just directly call the internal command handler, and
 439         * die if that one cannot handle it.
 440         */
 441        if (!strncmp(cmd, "git-", 4)) {
 442                cmd += 4;
 443                argv[0] = cmd;
 444                handle_internal_command(argc, argv, envp);
 445                die("cannot handle %s internally", cmd);
 446        }
 447
 448        /* Default command: "help" */
 449        cmd = "help";
 450
 451        /* Look for flags.. */
 452        while (argc > 1) {
 453                cmd = *++argv;
 454                argc--;
 455
 456                if (strncmp(cmd, "--", 2))
 457                        break;
 458
 459                cmd += 2;
 460
 461                /*
 462                 * For legacy reasons, the "version" and "help"
 463                 * commands can be written with "--" prepended
 464                 * to make them look like flags.
 465                 */
 466                if (!strcmp(cmd, "help"))
 467                        break;
 468                if (!strcmp(cmd, "version"))
 469                        break;
 470
 471                /*
 472                 * Check remaining flags (which by now must be
 473                 * "--exec-path", but maybe we will accept
 474                 * other arguments some day)
 475                 */
 476                if (!strncmp(cmd, "exec-path", 9)) {
 477                        cmd += 9;
 478                        if (*cmd == '=') {
 479                                git_set_exec_path(cmd + 1);
 480                                continue;
 481                        }
 482                        puts(git_exec_path());
 483                        exit(0);
 484                }
 485                cmd_usage(0, NULL, NULL);
 486        }
 487        argv[0] = cmd;
 488
 489        /*
 490         * We search for git commands in the following order:
 491         *  - git_exec_path()
 492         *  - the path of the "git" command if we could find it
 493         *    in $0
 494         *  - the regular PATH.
 495         */
 496        if (exec_path)
 497                prepend_to_path(exec_path, strlen(exec_path));
 498        exec_path = git_exec_path();
 499        prepend_to_path(exec_path, strlen(exec_path));
 500
 501        /* See if it's an internal command */
 502        handle_internal_command(argc, argv, envp);
 503
 504        /* .. then try the external ones */
 505        execv_git_cmd(argv);
 506
 507        if (errno == ENOENT)
 508                cmd_usage(0, exec_path, "'%s' is not a git-command", cmd);
 509
 510        fprintf(stderr, "Failed to run command '%s': %s\n",
 511                git_command, strerror(errno));
 512
 513        return 1;
 514}