From f35f5603f4f07c939754743b2a6cf61bb3a4694e Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Thu, 3 Apr 2008 02:12:06 -0700 Subject: [PATCH 01/95] revision traversal: --children option This adds a new --children option to the revision machinery. In addition to the list of parents, child commits of each commit are computed and stored as a decoration to each commit. Signed-off-by: Junio C Hamano --- revision.c | 40 +++++++++++++++++++++++++++++++++++++--- revision.h | 1 + 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/revision.c b/revision.c index ffbed3fbf2..979241eb0d 100644 --- a/revision.c +++ b/revision.c @@ -9,6 +9,7 @@ #include "grep.h" #include "reflog-walk.h" #include "patch-ids.h" +#include "decorate.h" volatile show_early_output_fn_t show_early_output; @@ -1310,6 +1311,11 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch revs->no_walk = 0; continue; } + if (!strcmp(arg, "--children")) { + revs->children.name = "children"; + revs->limited = 1; + continue; + } opts = diff_opt_parse(&revs->diffopt, argv+i, argc-i); if (opts > 0) { @@ -1395,10 +1401,31 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch if (revs->reverse && revs->reflog_info) die("cannot combine --reverse with --walk-reflogs"); - + if (revs->parents && revs->children.name) + die("cannot combine --parents and --children"); return left; } +static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child) +{ + struct commit_list *l = xcalloc(1, sizeof(*l)); + + l->item = child; + l->next = add_decoration(&revs->children, &parent->object, l); +} + +static void set_children(struct rev_info *revs) +{ + struct commit_list *l; + for (l = revs->commits; l; l = l->next) { + struct commit *commit = l->item; + struct commit_list *p; + + for (p = commit->parents; p; p = p->next) + add_child(revs, p->item, commit); + } +} + int prepare_revision_walk(struct rev_info *revs) { int nr = revs->pending.nr; @@ -1427,6 +1454,8 @@ int prepare_revision_walk(struct rev_info *revs) return -1; if (revs->topo_order) sort_in_topological_order(&revs->commits, revs->lifo); + if (revs->children.name) + set_children(revs); return 0; } @@ -1504,6 +1533,11 @@ static int commit_match(struct commit *commit, struct rev_info *opt) commit->buffer, strlen(commit->buffer)); } +static inline int want_ancestry(struct rev_info *revs) +{ + return (revs->parents || revs->children.name); +} + enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit) { if (commit->object.flags & SHOWN) @@ -1524,13 +1558,13 @@ enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit) /* Commit without changes? */ if (commit->object.flags & TREESAME) { /* drop merges unless we want parenthood */ - if (!revs->parents) + if (!want_ancestry(revs)) return commit_ignore; /* non-merge - always ignore it */ if (!commit->parents || !commit->parents->next) return commit_ignore; } - if (revs->parents && rewrite_parents(revs, commit) < 0) + if (want_ancestry(revs) && rewrite_parents(revs, commit) < 0) return commit_error; } return commit_show; diff --git a/revision.h b/revision.h index c8b3b948ec..966116cd5b 100644 --- a/revision.h +++ b/revision.h @@ -98,6 +98,7 @@ struct rev_info { struct diff_options pruning; struct reflog_walk_info *reflog_info; + struct decoration children; }; #define REV_TREE_SAME 0 From 72276a3ecbe6353b83ab37e0ce96cc21c94cf6ee Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Thu, 3 Apr 2008 23:01:47 -0700 Subject: [PATCH 02/95] rev-list --children Just like --parents option shows the parents of commits, this shows the children of commits. Signed-off-by: Junio C Hamano --- Documentation/rev-list-options.txt | 4 ++++ builtin-rev-list.c | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/Documentation/rev-list-options.txt b/Documentation/rev-list-options.txt index 2648a55085..e5823950e2 100644 --- a/Documentation/rev-list-options.txt +++ b/Documentation/rev-list-options.txt @@ -42,6 +42,10 @@ format, often found in E-mail messages. Print the parents of the commit. +--children:: + + Print the children of the commit. + --timestamp:: Print the raw commit timestamp. diff --git a/builtin-rev-list.c b/builtin-rev-list.c index edc0bd35bb..9da2f76375 100644 --- a/builtin-rev-list.c +++ b/builtin-rev-list.c @@ -36,6 +36,7 @@ static const char rev_list_usage[] = " --reverse\n" " formatting output:\n" " --parents\n" +" --children\n" " --objects | --objects-edge\n" " --unpacked\n" " --header | --pretty\n" @@ -84,6 +85,15 @@ static void show_commit(struct commit *commit) parents = parents->next; } } + if (revs.children.name) { + struct commit_list *children; + + children = lookup_decoration(&revs.children, &commit->object); + while (children) { + printf(" %s", sha1_to_hex(children->item->object.sha1)); + children = children->next; + } + } show_decorations(commit); if (revs.commit_format == CMIT_FMT_ONELINE) putchar(' '); From f6c07d7d475ffaa67b817beb2635fd73a5e0e962 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 2 Apr 2008 22:17:53 -0700 Subject: [PATCH 03/95] builtin-blame.c: move prepare_final() into a separate function. After parsing the command line, we have a long loop to compute the commit object to start annotating from. Move the logic to a separate function, so that later patches become easier to read. It also makes fill_origin_blob() return void; the check is always done on !file->ptr, and nobody looks at the return value from the function. Signed-off-by: Junio C Hamano --- builtin-blame.c | 56 +++++++++++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/builtin-blame.c b/builtin-blame.c index bfd562d7d2..996f535767 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -91,7 +91,7 @@ struct origin { * Given an origin, prepare mmfile_t structure to be used by the * diff machinery */ -static char *fill_origin_blob(struct origin *o, mmfile_t *file) +static void fill_origin_blob(struct origin *o, mmfile_t *file) { if (!o->file.ptr) { enum object_type type; @@ -106,7 +106,6 @@ static char *fill_origin_blob(struct origin *o, mmfile_t *file) } else *file = o->file; - return file->ptr; } /* @@ -2006,6 +2005,10 @@ static int git_blame_config(const char *var, const char *value) return git_default_config(var, value); } +/* + * Prepare a dummy commit that represents the work tree (or staged) item. + * Note that annotating work tree item never works in the reverse. + */ static struct commit *fake_working_tree_commit(const char *path, const char *contents_from) { struct commit *commit; @@ -2122,6 +2125,33 @@ static struct commit *fake_working_tree_commit(const char *path, const char *con return commit; } +static const char *prepare_final(struct scoreboard *sb, struct rev_info *revs) +{ + int i; + const char *final_commit_name = NULL; + + /* + * There must be one and only one positive commit in the + * revs->pending array. + */ + for (i = 0; i < revs->pending.nr; i++) { + struct object *obj = revs->pending.objects[i].item; + if (obj->flags & UNINTERESTING) + continue; + while (obj->type == OBJ_TAG) + obj = deref_tag(obj, NULL, 0); + if (obj->type != OBJ_COMMIT) + die("Non commit %s?", revs->pending.objects[i].name); + if (sb->final) + die("More than one commit to dig from %s and %s?", + revs->pending.objects[i].name, + final_commit_name); + sb->final = (struct commit *) obj; + final_commit_name = revs->pending.objects[i].name; + } + return final_commit_name; +} + int cmd_blame(int argc, const char **argv, const char *prefix) { struct rev_info revs; @@ -2327,27 +2357,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) setup_revisions(unk, argv, &revs, NULL); memset(&sb, 0, sizeof(sb)); - /* - * There must be one and only one positive commit in the - * revs->pending array. - */ - for (i = 0; i < revs.pending.nr; i++) { - struct object *obj = revs.pending.objects[i].item; - if (obj->flags & UNINTERESTING) - continue; - while (obj->type == OBJ_TAG) - obj = deref_tag(obj, NULL, 0); - if (obj->type != OBJ_COMMIT) - die("Non commit %s?", - revs.pending.objects[i].name); - if (sb.final) - die("More than one commit to dig from %s and %s?", - revs.pending.objects[i].name, - final_commit_name); - sb.final = (struct commit *) obj; - final_commit_name = revs.pending.objects[i].name; - } - + final_commit_name = prepare_final(&sb, &revs); if (!sb.final) { /* * "--not A B -- path" without anything positive; From 69264f46a193ae9dec5761984b4bae32f4810916 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Thu, 3 Apr 2008 00:56:23 -0700 Subject: [PATCH 04/95] builtin-blame.c: allow more than 16 parents This removes the hardcoded 16 parents limit from git-blame by allowing the parent array to be allocated dynamically. As the ultimate objective is not about allowing dodecapus, but about annotating the history upside down, it also renames "parent" in the code to "scapegoat"; the name of the game used to be "pass blame to your parents", but now it is "find a scapegoat to pass blame on". Signed-off-by: Junio C Hamano --- builtin-blame.c | 91 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 60 insertions(+), 31 deletions(-) diff --git a/builtin-blame.c b/builtin-blame.c index 996f535767..fbc441fb9f 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -1191,18 +1191,45 @@ static void pass_whole_blame(struct scoreboard *sb, } } -#define MAXPARENT 16 +/* + * We pass blame from the current commit to its parents. We keep saying + * "parent" (and "porigin"), but what we mean is to find scapegoat to + * exonerate ourselves. + */ +static struct commit_list *first_scapegoat(struct commit *commit) +{ + return commit->parents; +} + +static int num_scapegoats(struct commit *commit) +{ + int cnt; + struct commit_list *l = first_scapegoat(commit); + for (cnt = 0; l; l = l->next) + cnt++; + return cnt; +} + +#define MAXSG 16 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) { - int i, pass; + int i, pass, num_sg; struct commit *commit = origin->commit; - struct commit_list *parent; - struct origin *parent_origin[MAXPARENT], *porigin; + struct commit_list *sg; + struct origin *sg_buf[MAXSG]; + struct origin *porigin, **sg_origin = sg_buf; - memset(parent_origin, 0, sizeof(parent_origin)); + num_sg = num_scapegoats(commit); + if (!num_sg) + goto finish; + else if (num_sg < ARRAY_SIZE(sg_buf)) + memset(sg_buf, 0, sizeof(sg_buf)); + else + sg_origin = xcalloc(num_sg, sizeof(*sg_origin)); - /* The first pass looks for unrenamed path to optimize for + /* + * The first pass looks for unrenamed path to optimize for * common cases, then we look for renames in the second pass. */ for (pass = 0; pass < 2; pass++) { @@ -1210,13 +1237,13 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) struct commit *, struct origin *); find = pass ? find_rename : find_origin; - for (i = 0, parent = commit->parents; - i < MAXPARENT && parent; - parent = parent->next, i++) { - struct commit *p = parent->item; + for (i = 0, sg = first_scapegoat(commit); + i < num_sg && sg; + sg = sg->next, i++) { + struct commit *p = sg->item; int j, same; - if (parent_origin[i]) + if (sg_origin[i]) continue; if (parse_commit(p)) continue; @@ -1229,24 +1256,24 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) goto finish; } for (j = same = 0; j < i; j++) - if (parent_origin[j] && - !hashcmp(parent_origin[j]->blob_sha1, + if (sg_origin[j] && + !hashcmp(sg_origin[j]->blob_sha1, porigin->blob_sha1)) { same = 1; break; } if (!same) - parent_origin[i] = porigin; + sg_origin[i] = porigin; else origin_decref(porigin); } } num_commits++; - for (i = 0, parent = commit->parents; - i < MAXPARENT && parent; - parent = parent->next, i++) { - struct origin *porigin = parent_origin[i]; + for (i = 0, sg = first_scapegoat(commit); + i < num_sg && sg; + sg = sg->next, i++) { + struct origin *porigin = sg_origin[i]; if (!porigin) continue; if (pass_blame_to_parent(sb, origin, porigin)) @@ -1257,10 +1284,10 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) * Optionally find moves in parents' files. */ if (opt & PICKAXE_BLAME_MOVE) - for (i = 0, parent = commit->parents; - i < MAXPARENT && parent; - parent = parent->next, i++) { - struct origin *porigin = parent_origin[i]; + for (i = 0, sg = first_scapegoat(commit); + i < num_sg && sg; + sg = sg->next, i++) { + struct origin *porigin = sg_origin[i]; if (!porigin) continue; if (find_move_in_parent(sb, origin, porigin)) @@ -1271,23 +1298,25 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) * Optionally find copies from parents' files. */ if (opt & PICKAXE_BLAME_COPY) - for (i = 0, parent = commit->parents; - i < MAXPARENT && parent; - parent = parent->next, i++) { - struct origin *porigin = parent_origin[i]; - if (find_copy_in_parent(sb, origin, parent->item, + for (i = 0, sg = first_scapegoat(commit); + i < num_sg && sg; + sg = sg->next, i++) { + struct origin *porigin = sg_origin[i]; + if (find_copy_in_parent(sb, origin, sg->item, porigin, opt)) goto finish; } finish: - for (i = 0; i < MAXPARENT; i++) { - if (parent_origin[i]) { - drop_origin_blob(parent_origin[i]); - origin_decref(parent_origin[i]); + for (i = 0; i < num_sg; i++) { + if (sg_origin[i]) { + drop_origin_blob(sg_origin[i]); + origin_decref(sg_origin[i]); } } drop_origin_blob(origin); + if (sg_buf != sg_origin) + free(sg_origin); } /* From 85af7929ee125385c2771fa4eaccfa2f29dc63c9 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 2 Apr 2008 22:17:53 -0700 Subject: [PATCH 05/95] git-blame --reverse This new option allows "git blame" to read an old version of the file, and up to which commit each line survived (i.e. their children rewrote the line out of the contents). The previous revision machinery update to decorate each commit with its children was leading to this change. When the --reverse option is given, we read the old version and pass blame to the children of the current suspect, instead of the usual order of starting from the latest and passing blame to parents. The standard yardstick of "blame" in git.git history is "rev-list.c" which was refactored heavily in its existence. For example: git blame -C -C -w --reverse 9de48752..master -- rev-list.c begins like this: 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 1) #include "cache... 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 2) #include "commi... 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 3) #include "tree.... 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 4) #include "blob.... 213523f4 rev-list.c (JC Hamano 2006-03-01 5) #include "epoch... 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 6) ab57c8dd rev-list.c (JC Hamano 2006-02-24 7) #define SEEN ab57c8dd rev-list.c (JC Hamano 2006-02-24 8) #define INTERES... 213523f4 rev-list.c (JC Hamano 2006-03-01 9) #define COUNTED... 7e21c29b rev-list.c (LTorvalds 2005-07-06 10) #define SHOWN ... 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 11) 6c41b801 builtin-rev-list.c (JC Hamano 2008-04-02 12) static const ch... b1349229 rev-list.c (LTorvalds 2005-07-26 13) "usage: git-... This reveals that the original first four lines survived until now in builtin-rev-list.c , inclusion of "epoch.h" was removed after 213523f4 while the contents was still in rev-list.c. This mode probably needs more tweaking so that the commit that removed the line (i.e. the children of the commits listed in the above sample output) is shown instead to be useful, but then there is a little matter of which child of a fork point to show. For now, you can find the diff that rewrote the fifth line above by doing: $ git log --children 213523f4^.. to find its child, which is 1025fe5 (Merge branch 'lt/rev-list' into next, 2006-03-01), and then look at that child with: $ git show 1025fe5 Signed-off-by: Junio C Hamano --- builtin-blame.c | 81 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 65 insertions(+), 16 deletions(-) diff --git a/builtin-blame.c b/builtin-blame.c index fbc441fb9f..5c7546db25 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -43,6 +43,7 @@ static int max_orig_digits; static int max_digits; static int max_score_digits; static int show_root; +static int reverse; static int blank_boundary; static int incremental; static int cmd_is_annotate; @@ -177,7 +178,7 @@ struct blame_entry { struct scoreboard { /* the final commit (i.e. where we started digging from) */ struct commit *final; - + struct rev_info *revs; const char *path; /* @@ -1196,15 +1197,17 @@ static void pass_whole_blame(struct scoreboard *sb, * "parent" (and "porigin"), but what we mean is to find scapegoat to * exonerate ourselves. */ -static struct commit_list *first_scapegoat(struct commit *commit) +static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit) { - return commit->parents; + if (!reverse) + return commit->parents; + return lookup_decoration(&revs->children, &commit->object); } -static int num_scapegoats(struct commit *commit) +static int num_scapegoats(struct rev_info *revs, struct commit *commit) { int cnt; - struct commit_list *l = first_scapegoat(commit); + struct commit_list *l = first_scapegoat(revs, commit); for (cnt = 0; l; l = l->next) cnt++; return cnt; @@ -1214,13 +1217,14 @@ static int num_scapegoats(struct commit *commit) static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) { + struct rev_info *revs = sb->revs; int i, pass, num_sg; struct commit *commit = origin->commit; struct commit_list *sg; struct origin *sg_buf[MAXSG]; struct origin *porigin, **sg_origin = sg_buf; - num_sg = num_scapegoats(commit); + num_sg = num_scapegoats(revs, commit); if (!num_sg) goto finish; else if (num_sg < ARRAY_SIZE(sg_buf)) @@ -1237,7 +1241,7 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) struct commit *, struct origin *); find = pass ? find_rename : find_origin; - for (i = 0, sg = first_scapegoat(commit); + for (i = 0, sg = first_scapegoat(revs, commit); i < num_sg && sg; sg = sg->next, i++) { struct commit *p = sg->item; @@ -1270,7 +1274,7 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) } num_commits++; - for (i = 0, sg = first_scapegoat(commit); + for (i = 0, sg = first_scapegoat(revs, commit); i < num_sg && sg; sg = sg->next, i++) { struct origin *porigin = sg_origin[i]; @@ -1284,7 +1288,7 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) * Optionally find moves in parents' files. */ if (opt & PICKAXE_BLAME_MOVE) - for (i = 0, sg = first_scapegoat(commit); + for (i = 0, sg = first_scapegoat(revs, commit); i < num_sg && sg; sg = sg->next, i++) { struct origin *porigin = sg_origin[i]; @@ -1298,7 +1302,7 @@ static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt) * Optionally find copies from parents' files. */ if (opt & PICKAXE_BLAME_COPY) - for (i = 0, sg = first_scapegoat(commit); + for (i = 0, sg = first_scapegoat(revs, commit); i < num_sg && sg; sg = sg->next, i++) { struct origin *porigin = sg_origin[i]; @@ -1515,8 +1519,10 @@ static void found_guilty_entry(struct blame_entry *ent) * is still unknown, pick one blame_entry, and allow its current * suspect to pass blames to its parents. */ -static void assign_blame(struct scoreboard *sb, struct rev_info *revs, int opt) +static void assign_blame(struct scoreboard *sb, int opt) { + struct rev_info *revs = sb->revs; + while (1) { struct blame_entry *ent; struct commit *commit; @@ -1537,8 +1543,9 @@ static void assign_blame(struct scoreboard *sb, struct rev_info *revs, int opt) commit = suspect->commit; if (!commit->object.parsed) parse_commit(commit); - if (!(commit->object.flags & UNINTERESTING) && - !(revs->max_age != -1 && commit->date < revs->max_age)) + if (reverse || + (!(commit->object.flags & UNINTERESTING) && + !(revs->max_age != -1 && commit->date < revs->max_age))) pass_blame(sb, suspect, opt); else { commit->object.flags |= UNINTERESTING; @@ -2154,10 +2161,11 @@ static struct commit *fake_working_tree_commit(const char *path, const char *con return commit; } -static const char *prepare_final(struct scoreboard *sb, struct rev_info *revs) +static const char *prepare_final(struct scoreboard *sb) { int i; const char *final_commit_name = NULL; + struct rev_info *revs = sb->revs; /* * There must be one and only one positive commit in the @@ -2181,6 +2189,36 @@ static const char *prepare_final(struct scoreboard *sb, struct rev_info *revs) return final_commit_name; } +static const char *prepare_initial(struct scoreboard *sb) +{ + int i; + const char *final_commit_name = NULL; + struct rev_info *revs = sb->revs; + + /* + * There must be one and only one negative commit, and it must be + * the boundary. + */ + for (i = 0; i < revs->pending.nr; i++) { + struct object *obj = revs->pending.objects[i].item; + if (!(obj->flags & UNINTERESTING)) + continue; + while (obj->type == OBJ_TAG) + obj = deref_tag(obj, NULL, 0); + if (obj->type != OBJ_COMMIT) + die("Non commit %s?", revs->pending.objects[i].name); + if (sb->final) + die("More than one commit to dig down to %s and %s?", + revs->pending.objects[i].name, + final_commit_name); + sb->final = (struct commit *) obj; + final_commit_name = revs->pending.objects[i].name; + } + if (!final_commit_name) + die("No commit to dig down to?"); + return final_commit_name; +} + int cmd_blame(int argc, const char **argv, const char *prefix) { struct rev_info revs; @@ -2213,6 +2251,10 @@ int cmd_blame(int argc, const char **argv, const char *prefix) blank_boundary = 1; else if (!strcmp("--root", arg)) show_root = 1; + else if (!strcmp("--reverse", arg)) { + argv[unk++] = "--children"; + reverse = 1; + } else if (!strcmp(arg, "--show-stats")) show_stats = 1; else if (!strcmp("-c", arg)) @@ -2386,7 +2428,14 @@ int cmd_blame(int argc, const char **argv, const char *prefix) setup_revisions(unk, argv, &revs, NULL); memset(&sb, 0, sizeof(sb)); - final_commit_name = prepare_final(&sb, &revs); + sb.revs = &revs; + if (!reverse) + final_commit_name = prepare_final(&sb); + else if (contents_from) + die("--contents and --children do not blend well."); + else + final_commit_name = prepare_initial(&sb); + if (!sb.final) { /* * "--not A B -- path" without anything positive; @@ -2464,7 +2513,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) if (!incremental) setup_pager(); - assign_blame(&sb, &revs, opt); + assign_blame(&sb, opt); if (incremental) return 0; From 7e7bbcb4b35cbb4bbb5e65cf057c84b16dbd3d39 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Mon, 23 Jun 2008 21:59:37 +0200 Subject: [PATCH 06/95] parse-opt: have parse_options_{start,end}. Make the struct optparse_t public under the better name parse_opt_ctx_t. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 69 ++++++++++++++++++++++++++++--------------------- parse-options.h | 16 ++++++++++++ 2 files changed, 55 insertions(+), 30 deletions(-) diff --git a/parse-options.c b/parse-options.c index b8bde2b04a..9964877edf 100644 --- a/parse-options.c +++ b/parse-options.c @@ -4,14 +4,7 @@ #define OPT_SHORT 1 #define OPT_UNSET 2 -struct optparse_t { - const char **argv; - const char **out; - int argc, cpidx; - const char *opt; -}; - -static inline const char *get_arg(struct optparse_t *p) +static inline const char *get_arg(struct parse_opt_ctx_t *p) { if (p->opt) { const char *res = p->opt; @@ -37,7 +30,7 @@ static int opterror(const struct option *opt, const char *reason, int flags) return error("option `%s' %s", opt->long_name, reason); } -static int get_value(struct optparse_t *p, +static int get_value(struct parse_opt_ctx_t *p, const struct option *opt, int flags) { const char *s, *arg; @@ -131,7 +124,7 @@ static int get_value(struct optparse_t *p, } } -static int parse_short_opt(struct optparse_t *p, const struct option *options) +static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *options) { for (; options->type != OPTION_END; options++) { if (options->short_name == *p->opt) { @@ -142,7 +135,7 @@ static int parse_short_opt(struct optparse_t *p, const struct option *options) return error("unknown switch `%c'", *p->opt); } -static int parse_long_opt(struct optparse_t *p, const char *arg, +static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg, const struct option *options) { const char *arg_end = strchr(arg, '='); @@ -247,45 +240,63 @@ void check_typos(const char *arg, const struct option *options) } } +void parse_options_start(struct parse_opt_ctx_t *ctx, + int argc, const char **argv, int flags) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->argc = argc - 1; + ctx->argv = argv + 1; + ctx->out = argv; + ctx->flags = flags; +} + +int parse_options_end(struct parse_opt_ctx_t *ctx) +{ + memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out)); + ctx->out[ctx->cpidx + ctx->argc] = NULL; + return ctx->cpidx + ctx->argc; +} + static NORETURN void usage_with_options_internal(const char * const *, const struct option *, int); int parse_options(int argc, const char **argv, const struct option *options, const char * const usagestr[], int flags) { - struct optparse_t args = { argv + 1, argv, argc - 1, 0, NULL }; + struct parse_opt_ctx_t ctx; - for (; args.argc; args.argc--, args.argv++) { - const char *arg = args.argv[0]; + parse_options_start(&ctx, argc, argv, flags); + for (; ctx.argc; ctx.argc--, ctx.argv++) { + const char *arg = ctx.argv[0]; if (*arg != '-' || !arg[1]) { - if (flags & PARSE_OPT_STOP_AT_NON_OPTION) + if (ctx.flags & PARSE_OPT_STOP_AT_NON_OPTION) break; - args.out[args.cpidx++] = args.argv[0]; + ctx.out[ctx.cpidx++] = ctx.argv[0]; continue; } if (arg[1] != '-') { - args.opt = arg + 1; - if (*args.opt == 'h') + ctx.opt = arg + 1; + if (*ctx.opt == 'h') usage_with_options(usagestr, options); - if (parse_short_opt(&args, options) < 0) + if (parse_short_opt(&ctx, options) < 0) usage_with_options(usagestr, options); - if (args.opt) + if (ctx.opt) check_typos(arg + 1, options); - while (args.opt) { - if (*args.opt == 'h') + while (ctx.opt) { + if (*ctx.opt == 'h') usage_with_options(usagestr, options); - if (parse_short_opt(&args, options) < 0) + if (parse_short_opt(&ctx, options) < 0) usage_with_options(usagestr, options); } continue; } if (!arg[2]) { /* "--" */ - if (!(flags & PARSE_OPT_KEEP_DASHDASH)) { - args.argc--; - args.argv++; + if (!(ctx.flags & PARSE_OPT_KEEP_DASHDASH)) { + ctx.argc--; + ctx.argv++; } break; } @@ -294,13 +305,11 @@ int parse_options(int argc, const char **argv, const struct option *options, usage_with_options_internal(usagestr, options, 1); if (!strcmp(arg + 2, "help")) usage_with_options(usagestr, options); - if (parse_long_opt(&args, arg + 2, options)) + if (parse_long_opt(&ctx, arg + 2, options)) usage_with_options(usagestr, options); } - memmove(args.out + args.cpidx, args.argv, args.argc * sizeof(*args.out)); - args.out[args.cpidx + args.argc] = NULL; - return args.cpidx + args.argc; + return parse_options_end(&ctx); } #define USAGE_OPTS_WIDTH 24 diff --git a/parse-options.h b/parse-options.h index 4ee443dafe..72027f3c66 100644 --- a/parse-options.h +++ b/parse-options.h @@ -111,6 +111,22 @@ extern int parse_options(int argc, const char **argv, extern NORETURN void usage_with_options(const char * const *usagestr, const struct option *options); +/*----- incremantal advanced APIs -----*/ + +struct parse_opt_ctx_t { + const char **argv; + const char **out; + int argc, cpidx; + const char *opt; + int flags; +}; + +extern void parse_options_start(struct parse_opt_ctx_t *ctx, + int argc, const char **argv, int flags); + +extern int parse_options_end(struct parse_opt_ctx_t *ctx); + + /*----- some often used options -----*/ extern int parse_opt_abbrev_cb(const struct option *, const char *, int); extern int parse_opt_approxidate_cb(const struct option *, const char *, int); From ee68b87a62a245fca46374fe5132aec58d802baa Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Mon, 23 Jun 2008 22:28:04 +0200 Subject: [PATCH 07/95] parse-opt: Export a non NORETURN usage dumper. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 24 +++++++++++++++++------- parse-options.h | 9 +++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/parse-options.c b/parse-options.c index 9964877edf..007b78eb24 100644 --- a/parse-options.c +++ b/parse-options.c @@ -257,8 +257,8 @@ int parse_options_end(struct parse_opt_ctx_t *ctx) return ctx->cpidx + ctx->argc; } -static NORETURN void usage_with_options_internal(const char * const *, - const struct option *, int); +static int usage_with_options_internal(const char * const *, + const struct option *, int, int); int parse_options(int argc, const char **argv, const struct option *options, const char * const usagestr[], int flags) @@ -302,7 +302,7 @@ int parse_options(int argc, const char **argv, const struct option *options, } if (!strcmp(arg + 2, "help-all")) - usage_with_options_internal(usagestr, options, 1); + usage_with_options_internal(usagestr, options, 1, 1); if (!strcmp(arg + 2, "help")) usage_with_options(usagestr, options); if (parse_long_opt(&ctx, arg + 2, options)) @@ -315,8 +315,8 @@ int parse_options(int argc, const char **argv, const struct option *options, #define USAGE_OPTS_WIDTH 24 #define USAGE_GAP 2 -void usage_with_options_internal(const char * const *usagestr, - const struct option *opts, int full) +int usage_with_options_internal(const char * const *usagestr, + const struct option *opts, int full, int do_exit) { fprintf(stderr, "usage: %s\n", *usagestr++); while (*usagestr && **usagestr) @@ -401,15 +401,25 @@ void usage_with_options_internal(const char * const *usagestr, } fputc('\n', stderr); - exit(129); + if (do_exit) + exit(129); + return PARSE_OPT_HELP; } void usage_with_options(const char * const *usagestr, const struct option *opts) { - usage_with_options_internal(usagestr, opts, 0); + usage_with_options_internal(usagestr, opts, 0, 1); + exit(129); /* make gcc happy */ } +int parse_options_usage(const char * const *usagestr, + const struct option *opts) +{ + return usage_with_options_internal(usagestr, opts, 0, 0); +} + + /*----- some often used options -----*/ #include "cache.h" diff --git a/parse-options.h b/parse-options.h index 72027f3c66..f66ca352dc 100644 --- a/parse-options.h +++ b/parse-options.h @@ -113,6 +113,12 @@ extern NORETURN void usage_with_options(const char * const *usagestr, /*----- incremantal advanced APIs -----*/ +enum { + PARSE_OPT_HELP = -1, + PARSE_OPT_DONE, + PARSE_OPT_UNKNOWN, +}; + struct parse_opt_ctx_t { const char **argv; const char **out; @@ -121,6 +127,9 @@ struct parse_opt_ctx_t { int flags; }; +extern int parse_options_usage(const char * const *usagestr, + const struct option *opts); + extern void parse_options_start(struct parse_opt_ctx_t *ctx, int argc, const char **argv, int flags); From ff43ec3e2d2f71482fe17ba9ba5f4e8074cc54ee Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Mon, 23 Jun 2008 22:38:58 +0200 Subject: [PATCH 08/95] parse-opt: create parse_options_step. For now it's unable to stop at unknown options, this commit merely reorganize some code around. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 117 +++++++++++++++++++++++++++--------------------- parse-options.h | 4 ++ 2 files changed, 69 insertions(+), 52 deletions(-) diff --git a/parse-options.c b/parse-options.c index 007b78eb24..04adf219ca 100644 --- a/parse-options.c +++ b/parse-options.c @@ -250,6 +250,58 @@ void parse_options_start(struct parse_opt_ctx_t *ctx, ctx->flags = flags; } +static int usage_with_options_internal(const char * const *, + const struct option *, int); + +int parse_options_step(struct parse_opt_ctx_t *ctx, + const struct option *options, + const char * const usagestr[]) +{ + for (; ctx->argc; ctx->argc--, ctx->argv++) { + const char *arg = ctx->argv[0]; + + if (*arg != '-' || !arg[1]) { + if (ctx->flags & PARSE_OPT_STOP_AT_NON_OPTION) + break; + ctx->out[ctx->cpidx++] = ctx->argv[0]; + continue; + } + + if (arg[1] != '-') { + ctx->opt = arg + 1; + if (*ctx->opt == 'h') + return parse_options_usage(usagestr, options); + if (parse_short_opt(ctx, options) < 0) + usage_with_options(usagestr, options); + if (ctx->opt) + check_typos(arg + 1, options); + while (ctx->opt) { + if (*ctx->opt == 'h') + return parse_options_usage(usagestr, options); + if (parse_short_opt(ctx, options) < 0) + usage_with_options(usagestr, options); + } + continue; + } + + if (!arg[2]) { /* "--" */ + if (!(ctx->flags & PARSE_OPT_KEEP_DASHDASH)) { + ctx->argc--; + ctx->argv++; + } + break; + } + + if (!strcmp(arg + 2, "help-all")) + return usage_with_options_internal(usagestr, options, 1); + if (!strcmp(arg + 2, "help")) + return parse_options_usage(usagestr, options); + if (parse_long_opt(ctx, arg + 2, options)) + usage_with_options(usagestr, options); + } + return PARSE_OPT_DONE; +} + int parse_options_end(struct parse_opt_ctx_t *ctx) { memmove(ctx->out + ctx->cpidx, ctx->argv, ctx->argc * sizeof(*ctx->out)); @@ -257,56 +309,19 @@ int parse_options_end(struct parse_opt_ctx_t *ctx) return ctx->cpidx + ctx->argc; } -static int usage_with_options_internal(const char * const *, - const struct option *, int, int); - int parse_options(int argc, const char **argv, const struct option *options, - const char * const usagestr[], int flags) + const char * const usagestr[], int flags) { struct parse_opt_ctx_t ctx; parse_options_start(&ctx, argc, argv, flags); - for (; ctx.argc; ctx.argc--, ctx.argv++) { - const char *arg = ctx.argv[0]; - - if (*arg != '-' || !arg[1]) { - if (ctx.flags & PARSE_OPT_STOP_AT_NON_OPTION) - break; - ctx.out[ctx.cpidx++] = ctx.argv[0]; - continue; - } - - if (arg[1] != '-') { - ctx.opt = arg + 1; - if (*ctx.opt == 'h') - usage_with_options(usagestr, options); - if (parse_short_opt(&ctx, options) < 0) - usage_with_options(usagestr, options); - if (ctx.opt) - check_typos(arg + 1, options); - while (ctx.opt) { - if (*ctx.opt == 'h') - usage_with_options(usagestr, options); - if (parse_short_opt(&ctx, options) < 0) - usage_with_options(usagestr, options); - } - continue; - } - - if (!arg[2]) { /* "--" */ - if (!(ctx.flags & PARSE_OPT_KEEP_DASHDASH)) { - ctx.argc--; - ctx.argv++; - } - break; - } - - if (!strcmp(arg + 2, "help-all")) - usage_with_options_internal(usagestr, options, 1, 1); - if (!strcmp(arg + 2, "help")) - usage_with_options(usagestr, options); - if (parse_long_opt(&ctx, arg + 2, options)) - usage_with_options(usagestr, options); + switch (parse_options_step(&ctx, options, usagestr)) { + case PARSE_OPT_HELP: + exit(129); + case PARSE_OPT_DONE: + break; + default: /* PARSE_OPT_UNKNOWN */ + abort(); /* unreached yet */ } return parse_options_end(&ctx); @@ -316,7 +331,7 @@ int parse_options(int argc, const char **argv, const struct option *options, #define USAGE_GAP 2 int usage_with_options_internal(const char * const *usagestr, - const struct option *opts, int full, int do_exit) + const struct option *opts, int full) { fprintf(stderr, "usage: %s\n", *usagestr++); while (*usagestr && **usagestr) @@ -401,22 +416,20 @@ int usage_with_options_internal(const char * const *usagestr, } fputc('\n', stderr); - if (do_exit) - exit(129); return PARSE_OPT_HELP; } void usage_with_options(const char * const *usagestr, - const struct option *opts) + const struct option *opts) { - usage_with_options_internal(usagestr, opts, 0, 1); - exit(129); /* make gcc happy */ + usage_with_options_internal(usagestr, opts, 0); + exit(129); } int parse_options_usage(const char * const *usagestr, const struct option *opts) { - return usage_with_options_internal(usagestr, opts, 0, 0); + return usage_with_options_internal(usagestr, opts, 0); } diff --git a/parse-options.h b/parse-options.h index f66ca352dc..33c683cb54 100644 --- a/parse-options.h +++ b/parse-options.h @@ -133,6 +133,10 @@ extern int parse_options_usage(const char * const *usagestr, extern void parse_options_start(struct parse_opt_ctx_t *ctx, int argc, const char **argv, int flags); +extern int parse_options_step(struct parse_opt_ctx_t *ctx, + const struct option *options, + const char * const usagestr[]); + extern int parse_options_end(struct parse_opt_ctx_t *ctx); From 07fe54db3cdf42500ac2e893b670fd74841afdc4 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Mon, 23 Jun 2008 22:46:36 +0200 Subject: [PATCH 09/95] parse-opt: do not print errors on unknown options, return -2 intead. This way we can catch "unknown" options more easily. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 43 ++++++++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/parse-options.c b/parse-options.c index 04adf219ca..19fc849f4b 100644 --- a/parse-options.c +++ b/parse-options.c @@ -94,14 +94,14 @@ static int get_value(struct parse_opt_ctx_t *p, case OPTION_CALLBACK: if (unset) - return (*opt->callback)(opt, NULL, 1); + return (*opt->callback)(opt, NULL, 1) ? (-1) : 0; if (opt->flags & PARSE_OPT_NOARG) - return (*opt->callback)(opt, NULL, 0); + return (*opt->callback)(opt, NULL, 0) ? (-1) : 0; if (opt->flags & PARSE_OPT_OPTARG && !p->opt) - return (*opt->callback)(opt, NULL, 0); + return (*opt->callback)(opt, NULL, 0) ? (-1) : 0; if (!arg) return opterror(opt, "requires a value", flags); - return (*opt->callback)(opt, get_arg(p), 0); + return (*opt->callback)(opt, get_arg(p), 0) ? (-1) : 0; case OPTION_INTEGER: if (unset) { @@ -132,7 +132,7 @@ static int parse_short_opt(struct parse_opt_ctx_t *p, const struct option *optio return get_value(p, options, OPT_SHORT); } } - return error("unknown switch `%c'", *p->opt); + return -2; } static int parse_long_opt(struct parse_opt_ctx_t *p, const char *arg, @@ -217,7 +217,7 @@ is_abbreviated: abbrev_option->long_name); if (abbrev_option) return get_value(p, abbrev_option, abbrev_flags); - return error("unknown option `%s'", arg); + return -2; } void check_typos(const char *arg, const struct option *options) @@ -271,15 +271,23 @@ int parse_options_step(struct parse_opt_ctx_t *ctx, ctx->opt = arg + 1; if (*ctx->opt == 'h') return parse_options_usage(usagestr, options); - if (parse_short_opt(ctx, options) < 0) - usage_with_options(usagestr, options); + switch (parse_short_opt(ctx, options)) { + case -1: + return parse_options_usage(usagestr, options); + case -2: + return PARSE_OPT_UNKNOWN; + } if (ctx->opt) check_typos(arg + 1, options); while (ctx->opt) { if (*ctx->opt == 'h') return parse_options_usage(usagestr, options); - if (parse_short_opt(ctx, options) < 0) - usage_with_options(usagestr, options); + switch (parse_short_opt(ctx, options)) { + case -1: + return parse_options_usage(usagestr, options); + case -2: + return PARSE_OPT_UNKNOWN; + } } continue; } @@ -296,8 +304,12 @@ int parse_options_step(struct parse_opt_ctx_t *ctx, return usage_with_options_internal(usagestr, options, 1); if (!strcmp(arg + 2, "help")) return parse_options_usage(usagestr, options); - if (parse_long_opt(ctx, arg + 2, options)) - usage_with_options(usagestr, options); + switch (parse_long_opt(ctx, arg + 2, options)) { + case -1: + return parse_options_usage(usagestr, options); + case -2: + return PARSE_OPT_UNKNOWN; + } } return PARSE_OPT_DONE; } @@ -321,7 +333,12 @@ int parse_options(int argc, const char **argv, const struct option *options, case PARSE_OPT_DONE: break; default: /* PARSE_OPT_UNKNOWN */ - abort(); /* unreached yet */ + if (ctx.argv[0][1] == '-') { + error("unknown option `%s'", ctx.argv[0] + 2); + } else { + error("unknown switch `%c'", *ctx.opt); + } + usage_with_options(usagestr, options); } return parse_options_end(&ctx); From 26141b5b60eea36f1d771312f6cae9e56dbbf760 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Mon, 23 Jun 2008 22:55:11 +0200 Subject: [PATCH 10/95] parse-opt: fake short strings for callers to believe in. If we begin to parse -abc and that the parser knew about -a and -b, it will fake a -c switch for the caller to deal with. Of course in the case of -acb (supposing -c is not taking an argument) the caller will have to be especially clever to do the same thing. We could think about exposing an API to do so if it's really needed, but oh well... Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 11 +++++++++++ parse-options.h | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/parse-options.c b/parse-options.c index 19fc849f4b..0d3818ab48 100644 --- a/parse-options.c +++ b/parse-options.c @@ -1,5 +1,6 @@ #include "git-compat-util.h" #include "parse-options.h" +#include "cache.h" #define OPT_SHORT 1 #define OPT_UNSET 2 @@ -257,6 +258,9 @@ int parse_options_step(struct parse_opt_ctx_t *ctx, const struct option *options, const char * const usagestr[]) { + /* we must reset ->opt, unknown short option leave it dangling */ + ctx->opt = NULL; + for (; ctx->argc; ctx->argc--, ctx->argv++) { const char *arg = ctx->argv[0]; @@ -286,6 +290,13 @@ int parse_options_step(struct parse_opt_ctx_t *ctx, case -1: return parse_options_usage(usagestr, options); case -2: + /* fake a short option thing to hide the fact that we may have + * started to parse aggregated stuff + * + * This is leaky, too bad. + */ + ctx->argv[0] = xstrdup(ctx->opt - 1); + *(char *)ctx->argv[0] = '-'; return PARSE_OPT_UNKNOWN; } } diff --git a/parse-options.h b/parse-options.h index 33c683cb54..aeed627e97 100644 --- a/parse-options.h +++ b/parse-options.h @@ -119,6 +119,11 @@ enum { PARSE_OPT_UNKNOWN, }; +/* + * It's okay for the caller to consume argv/argc in the usual way. + * Other fields of that structure are private to parse-options and should not + * be modified in any way. + */ struct parse_opt_ctx_t { const char **argv; const char **out; From a32a4eaa36527ab1c9a999357f9edd5e04591a4a Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Tue, 24 Jun 2008 00:31:31 +0200 Subject: [PATCH 11/95] parse-opt: add PARSE_OPT_KEEP_ARGV0 parser option. This way, argv[0] isn't clobbered when parse-options filters argv[]. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 1 + parse-options.h | 1 + 2 files changed, 2 insertions(+) diff --git a/parse-options.c b/parse-options.c index 0d3818ab48..469831d21b 100644 --- a/parse-options.c +++ b/parse-options.c @@ -248,6 +248,7 @@ void parse_options_start(struct parse_opt_ctx_t *ctx, ctx->argc = argc - 1; ctx->argv = argv + 1; ctx->out = argv; + ctx->cpidx = ((flags & PARSE_OPT_KEEP_ARGV0) != 0); ctx->flags = flags; } diff --git a/parse-options.h b/parse-options.h index aeed627e97..c5f0b4b4da 100644 --- a/parse-options.h +++ b/parse-options.h @@ -20,6 +20,7 @@ enum parse_opt_type { enum parse_opt_flags { PARSE_OPT_KEEP_DASHDASH = 1, PARSE_OPT_STOP_AT_NON_OPTION = 2, + PARSE_OPT_KEEP_ARGV0 = 4, }; enum parse_opt_option_flags { From 0989fe9623dc8d98033f6acdcc0c84ec28571b19 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:21:54 +0200 Subject: [PATCH 12/95] Move split_cmdline() to alias.c split_cmdline() is currently used for aliases only, but later it can be useful for other builtins as well. Move it to alias.c for now, indicating that originally it's for aliases, but we'll have it in libgit this way. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- alias.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ cache.h | 1 + git.c | 53 ----------------------------------------------------- 3 files changed, 55 insertions(+), 53 deletions(-) diff --git a/alias.c b/alias.c index 995f3e6a0a..ccb1108c94 100644 --- a/alias.c +++ b/alias.c @@ -21,3 +21,57 @@ char *alias_lookup(const char *alias) git_config(alias_lookup_cb, NULL); return alias_val; } + +int split_cmdline(char *cmdline, const char ***argv) +{ + int src, dst, count = 0, size = 16; + char quoted = 0; + + *argv = xmalloc(sizeof(char*) * size); + + /* split alias_string */ + (*argv)[count++] = cmdline; + for (src = dst = 0; cmdline[src];) { + char c = cmdline[src]; + if (!quoted && isspace(c)) { + cmdline[dst++] = 0; + while (cmdline[++src] + && isspace(cmdline[src])) + ; /* skip */ + if (count >= size) { + size += 16; + *argv = xrealloc(*argv, sizeof(char*) * size); + } + (*argv)[count++] = cmdline + dst; + } else if (!quoted && (c == '\'' || c == '"')) { + quoted = c; + src++; + } else if (c == quoted) { + quoted = 0; + src++; + } else { + if (c == '\\' && quoted != '\'') { + src++; + c = cmdline[src]; + if (!c) { + free(*argv); + *argv = NULL; + return error("cmdline ends with \\"); + } + } + cmdline[dst++] = c; + src++; + } + } + + cmdline[dst] = 0; + + if (quoted) { + free(*argv); + *argv = NULL; + return error("unclosed quote"); + } + + return count; +} + diff --git a/cache.h b/cache.h index 64ef86e129..6913573d1a 100644 --- a/cache.h +++ b/cache.h @@ -831,5 +831,6 @@ int report_path_error(const char *ps_matched, const char **pathspec, int prefix_ void overlay_tree_on_cache(const char *tree_name, const char *prefix); char *alias_lookup(const char *alias); +int split_cmdline(char *cmdline, const char ***argv); #endif /* CACHE_H */ diff --git a/git.c b/git.c index 59f0fcc1f2..2fbe96b9ba 100644 --- a/git.c +++ b/git.c @@ -90,59 +90,6 @@ static int handle_options(const char*** argv, int* argc, int* envchanged) return handled; } -static int split_cmdline(char *cmdline, const char ***argv) -{ - int src, dst, count = 0, size = 16; - char quoted = 0; - - *argv = xmalloc(sizeof(char*) * size); - - /* split alias_string */ - (*argv)[count++] = cmdline; - for (src = dst = 0; cmdline[src];) { - char c = cmdline[src]; - if (!quoted && isspace(c)) { - cmdline[dst++] = 0; - while (cmdline[++src] - && isspace(cmdline[src])) - ; /* skip */ - if (count >= size) { - size += 16; - *argv = xrealloc(*argv, sizeof(char*) * size); - } - (*argv)[count++] = cmdline + dst; - } else if(!quoted && (c == '\'' || c == '"')) { - quoted = c; - src++; - } else if (c == quoted) { - quoted = 0; - src++; - } else { - if (c == '\\' && quoted != '\'') { - src++; - c = cmdline[src]; - if (!c) { - free(*argv); - *argv = NULL; - return error("cmdline ends with \\"); - } - } - cmdline[dst++] = c; - src++; - } - } - - cmdline[dst] = 0; - - if (quoted) { - free(*argv); - *argv = NULL; - return error("unclosed quote"); - } - - return count; -} - static int handle_alias(int *argcp, const char ***argv) { int envchanged = 0, ret = 0, saved_errno = errno; From 653194758ee338b7c87d011007c532ed5cf68d45 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:21:55 +0200 Subject: [PATCH 13/95] Move commit_list_count() to commit.c This function is useful outside builtin-merge-recursive, for example in builtin-merge. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- builtin-merge-recursive.c | 8 -------- commit.c | 8 ++++++++ commit.h | 1 + 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/builtin-merge-recursive.c b/builtin-merge-recursive.c index 43bf6aa45e..3731853f83 100644 --- a/builtin-merge-recursive.c +++ b/builtin-merge-recursive.c @@ -42,14 +42,6 @@ static struct tree *shift_tree_object(struct tree *one, struct tree *two) * - *(int *)commit->object.sha1 set to the virtual id. */ -static unsigned commit_list_count(const struct commit_list *l) -{ - unsigned c = 0; - for (; l; l = l->next ) - c++; - return c; -} - static struct commit *make_virtual_commit(struct tree *tree, const char *comment) { struct commit *commit = xcalloc(1, sizeof(struct commit)); diff --git a/commit.c b/commit.c index e2d8624d9c..bbf9c75416 100644 --- a/commit.c +++ b/commit.c @@ -325,6 +325,14 @@ struct commit_list *commit_list_insert(struct commit *item, struct commit_list * return new_list; } +unsigned commit_list_count(const struct commit_list *l) +{ + unsigned c = 0; + for (; l; l = l->next ) + c++; + return c; +} + void free_commit_list(struct commit_list *list) { while (list) { diff --git a/commit.h b/commit.h index 2d94d4148e..7f8c5ee0fc 100644 --- a/commit.h +++ b/commit.h @@ -41,6 +41,7 @@ int parse_commit_buffer(struct commit *item, void *buffer, unsigned long size); int parse_commit(struct commit *item); struct commit_list * commit_list_insert(struct commit *item, struct commit_list **list_p); +unsigned commit_list_count(const struct commit_list *l); struct commit_list * insert_by_date(struct commit *item, struct commit_list **list); void free_commit_list(struct commit_list *list); From fbca58373291afa07c5b30ab562d36ce0f6174e0 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:21:56 +0200 Subject: [PATCH 14/95] Move parse-options's skip_prefix() to git-compat-util.h builtin-remote.c and parse-options.c both have a skip_prefix() function, for the same purpose. Move parse-options's one to git-compat-util.h and let builtin-remote use it as well. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- builtin-remote.c | 39 ++++++++++++++++++++++++++------------- git-compat-util.h | 6 ++++++ parse-options.c | 6 ------ 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/builtin-remote.c b/builtin-remote.c index 145dd8568c..1491354a9d 100644 --- a/builtin-remote.c +++ b/builtin-remote.c @@ -29,12 +29,6 @@ static inline int postfixcmp(const char *string, const char *postfix) return strcmp(string + len1 - len2, postfix); } -static inline const char *skip_prefix(const char *name, const char *prefix) -{ - return !name ? "" : - prefixcmp(name, prefix) ? name : name + strlen(prefix); -} - static int opt_parse_track(const struct option *opt, const char *arg, int not) { struct path_list *list = opt->value; @@ -182,12 +176,18 @@ static int config_read_branches(const char *key, const char *value, void *cb) info->remote = xstrdup(value); } else { char *space = strchr(value, ' '); - value = skip_prefix(value, "refs/heads/"); + const char *ptr = skip_prefix(value, "refs/heads/"); + if (ptr) + value = ptr; while (space) { char *merge; merge = xstrndup(value, space - value); path_list_append(merge, &info->merge); - value = skip_prefix(space + 1, "refs/heads/"); + ptr = skip_prefix(space + 1, "refs/heads/"); + if (ptr) + value = ptr; + else + value = space + 1; space = strchr(value, ' '); } path_list_append(xstrdup(value), &info->merge); @@ -219,7 +219,12 @@ static int handle_one_branch(const char *refname, refspec.dst = (char *)refname; if (!remote_find_tracking(states->remote, &refspec)) { struct path_list_item *item; - const char *name = skip_prefix(refspec.src, "refs/heads/"); + const char *name, *ptr; + ptr = skip_prefix(refspec.src, "refs/heads/"); + if (ptr) + name = ptr; + else + name = refspec.src; /* symbolic refs pointing nowhere were handled already */ if ((flags & REF_ISSYMREF) || unsorted_path_list_has_path(&states->tracked, @@ -248,6 +253,7 @@ static int get_ref_states(const struct ref *ref, struct ref_states *states) struct path_list *target = &states->tracked; unsigned char sha1[20]; void *util = NULL; + const char *ptr; if (!ref->peer_ref || read_ref(ref->peer_ref->name, sha1)) target = &states->new; @@ -256,8 +262,10 @@ static int get_ref_states(const struct ref *ref, struct ref_states *states) if (hashcmp(sha1, ref->new_sha1)) util = &states; } - path_list_append(skip_prefix(ref->name, "refs/heads/"), - target)->util = util; + ptr = skip_prefix(ref->name, "refs/heads/"); + if (!ptr) + ptr = ref->name; + path_list_append(ptr, target)->util = util; } free_refs(fetch_map); @@ -522,10 +530,15 @@ static int show(int argc, const char **argv) "es" : ""); for (i = 0; i < states.remote->push_refspec_nr; i++) { struct refspec *spec = states.remote->push + i; + const char *p = "", *q = ""; + if (spec->src) + p = skip_prefix(spec->src, "refs/heads/"); + if (spec->dst) + q = skip_prefix(spec->dst, "refs/heads/"); printf(" %s%s%s%s", spec->force ? "+" : "", - skip_prefix(spec->src, "refs/heads/"), + p ? p : spec->src, spec->dst ? ":" : "", - skip_prefix(spec->dst, "refs/heads/")); + q ? q : spec->dst); } printf("\n"); } diff --git a/git-compat-util.h b/git-compat-util.h index 6f94a8197f..31edc98f30 100644 --- a/git-compat-util.h +++ b/git-compat-util.h @@ -127,6 +127,12 @@ extern void set_warn_routine(void (*routine)(const char *warn, va_list params)); extern int prefixcmp(const char *str, const char *prefix); +static inline const char *skip_prefix(const char *str, const char *prefix) +{ + size_t len = strlen(prefix); + return strncmp(str, prefix, len) ? NULL : str + len; +} + #ifdef NO_MMAP #ifndef PROT_READ diff --git a/parse-options.c b/parse-options.c index b8bde2b04a..bbc3ca4a9f 100644 --- a/parse-options.c +++ b/parse-options.c @@ -22,12 +22,6 @@ static inline const char *get_arg(struct optparse_t *p) return *++p->argv; } -static inline const char *skip_prefix(const char *str, const char *prefix) -{ - size_t len = strlen(prefix); - return strncmp(str, prefix, len) ? NULL : str + len; -} - static int opterror(const struct option *opt, const char *reason, int flags) { if (flags & OPT_SHORT) From b2eabcc2539c021ea6cb2d1d2d28c8213986a186 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Sun, 29 Jun 2008 16:51:38 +0200 Subject: [PATCH 15/95] Add new test to ensure git-merge handles pull.twohead and pull.octopus Test if the given strategies are used and test the case when multiple strategies are configured using a space separated list. Also test if the best strategy is picked if none is specified. This is done by adding a simple test case where recursive detects a rename, but resolve does not, and verify that finally merge will pick up the previous. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t7601-merge-pull-config.sh | 129 +++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100755 t/t7601-merge-pull-config.sh diff --git a/t/t7601-merge-pull-config.sh b/t/t7601-merge-pull-config.sh new file mode 100755 index 0000000000..32585f8e0d --- /dev/null +++ b/t/t7601-merge-pull-config.sh @@ -0,0 +1,129 @@ +#!/bin/sh + +test_description='git-merge + +Testing pull.* configuration parsing.' + +. ./test-lib.sh + +test_expect_success 'setup' ' + echo c0 >c0.c && + git add c0.c && + git commit -m c0 && + git tag c0 && + echo c1 >c1.c && + git add c1.c && + git commit -m c1 && + git tag c1 && + git reset --hard c0 && + echo c2 >c2.c && + git add c2.c && + git commit -m c2 && + git tag c2 && + git reset --hard c0 && + echo c3 >c3.c && + git add c3.c && + git commit -m c3 && + git tag c3 +' + +test_expect_success 'merge c1 with c2' ' + git reset --hard c1 && + test -f c0.c && + test -f c1.c && + test ! -f c2.c && + test ! -f c3.c && + git merge c2 && + test -f c1.c && + test -f c2.c +' + +test_expect_success 'merge c1 with c2 (ours in pull.twohead)' ' + git reset --hard c1 && + git config pull.twohead ours && + git merge c2 && + test -f c1.c && + ! test -f c2.c +' + +test_expect_success 'merge c1 with c2 and c3 (recursive in pull.octopus)' ' + git reset --hard c1 && + git config pull.octopus "recursive" && + test_must_fail git merge c2 c3 && + test "$(git rev-parse c1)" = "$(git rev-parse HEAD)" +' + +test_expect_success 'merge c1 with c2 and c3 (recursive and octopus in pull.octopus)' ' + git reset --hard c1 && + git config pull.octopus "recursive octopus" && + git merge c2 c3 && + test "$(git rev-parse c1)" != "$(git rev-parse HEAD)" && + test "$(git rev-parse c1)" = "$(git rev-parse HEAD^1)" && + test "$(git rev-parse c2)" = "$(git rev-parse HEAD^2)" && + test "$(git rev-parse c3)" = "$(git rev-parse HEAD^3)" && + git diff --exit-code && + test -f c0.c && + test -f c1.c && + test -f c2.c && + test -f c3.c +' + +conflict_count() +{ + eval $1=`{ + git diff-files --name-only + git ls-files --unmerged + } | wc -l` +} + +# c4 - c5 +# \ c6 +# +# There are two conflicts here: +# +# 1) Because foo.c is renamed to bar.c, recursive will handle this, +# resolve won't. +# +# 2) One in conflict.c and that will always fail. + +test_expect_success 'setup conflicted merge' ' + git reset --hard c0 && + echo A >conflict.c && + git add conflict.c && + echo contents >foo.c && + git add foo.c && + git commit -m c4 && + git tag c4 && + echo B >conflict.c && + git add conflict.c && + git mv foo.c bar.c && + git commit -m c5 && + git tag c5 && + git reset --hard c4 && + echo C >conflict.c && + git add conflict.c && + echo secondline >> foo.c && + git add foo.c && + git commit -m c6 && + git tag c6 +' + +# First do the merge with resolve and recursive then verify that +# recusive is choosen. + +test_expect_success 'merge picks up the best result' ' + git config pull.twohead "recursive resolve" && + git reset --hard c5 && + git merge -s resolve c6 + conflict_count resolve_count && + git reset --hard c5 && + git merge -s recursive c6 + conflict_count recursive_count && + git reset --hard c5 && + git merge c6 + conflict_count auto_count && + test "$auto_count" = "$recursive_count" && + test "$auto_count" != "$resolve_count" +' + +test_done From e46bbcf6e89e4b1d3d8de1d20d836538ab0f0c85 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:21:58 +0200 Subject: [PATCH 16/95] Move read_cache_unmerged() to read-cache.c builtin-read-tree has a read_cache_unmerged() which is useful for other builtins, for example builtin-merge uses it as well. Move it to read-cache.c to avoid code duplication. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- builtin-read-tree.c | 24 ------------------------ cache.h | 2 ++ read-cache.c | 31 +++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 24 deletions(-) diff --git a/builtin-read-tree.c b/builtin-read-tree.c index 5a09e17f1a..72a6de302f 100644 --- a/builtin-read-tree.c +++ b/builtin-read-tree.c @@ -29,30 +29,6 @@ static int list_tree(unsigned char *sha1) return 0; } -static int read_cache_unmerged(void) -{ - int i; - struct cache_entry **dst; - struct cache_entry *last = NULL; - - read_cache(); - dst = active_cache; - for (i = 0; i < active_nr; i++) { - struct cache_entry *ce = active_cache[i]; - if (ce_stage(ce)) { - remove_name_hash(ce); - if (last && !strcmp(ce->name, last->name)) - continue; - cache_tree_invalidate_path(active_cache_tree, ce->name); - last = ce; - continue; - } - *dst++ = ce; - } - active_nr = dst - active_cache; - return !!last; -} - static void prime_cache_tree_rec(struct cache_tree *it, struct tree *tree) { struct tree_desc desc; diff --git a/cache.h b/cache.h index 6913573d1a..d0d74a3ff8 100644 --- a/cache.h +++ b/cache.h @@ -254,6 +254,7 @@ static inline void remove_name_hash(struct cache_entry *ce) #define read_cache() read_index(&the_index) #define read_cache_from(path) read_index_from(&the_index, (path)) +#define read_cache_unmerged() read_index_unmerged(&the_index) #define write_cache(newfd, cache, entries) write_index(&the_index, (newfd)) #define discard_cache() discard_index(&the_index) #define unmerged_cache() unmerged_index(&the_index) @@ -356,6 +357,7 @@ extern int init_db(const char *template_dir, unsigned int flags); /* Initialize and use the cache information */ extern int read_index(struct index_state *); extern int read_index_from(struct index_state *, const char *path); +extern int read_index_unmerged(struct index_state *); extern int write_index(const struct index_state *, int newfd); extern int discard_index(struct index_state *); extern int unmerged_index(const struct index_state *); diff --git a/read-cache.c b/read-cache.c index f83de8c415..d801f9d1cf 100644 --- a/read-cache.c +++ b/read-cache.c @@ -1410,3 +1410,34 @@ int write_index(const struct index_state *istate, int newfd) } return ce_flush(&c, newfd); } + +/* + * Read the index file that is potentially unmerged into given + * index_state, dropping any unmerged entries. Returns true is + * the index is unmerged. Callers who want to refuse to work + * from an unmerged state can call this and check its return value, + * instead of calling read_cache(). + */ +int read_index_unmerged(struct index_state *istate) +{ + int i; + struct cache_entry **dst; + struct cache_entry *last = NULL; + + read_index(istate); + dst = istate->cache; + for (i = 0; i < istate->cache_nr; i++) { + struct cache_entry *ce = istate->cache[i]; + if (ce_stage(ce)) { + remove_name_hash(ce); + if (last && !strcmp(ce->name, last->name)) + continue; + cache_tree_invalidate_path(istate->cache_tree, ce->name); + last = ce; + continue; + } + *dst++ = ce; + } + istate->cache_nr = dst - istate->cache; + return !!last; +} From 0b9a969e0fbb0a09e9de931cfe27005cbfd6cb7d Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:21:59 +0200 Subject: [PATCH 17/95] git-fmt-merge-msg: make it usable from other builtins Move all functionality (except config and option parsing) from cmd_fmt_merge_msg() to fmt_merge_msg(), so that other builtins can use it without a child process. All functions have been changed to use strbufs, and now only cmd_fmt_merge_msg() reads directly from a file / writes anything to stdout. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- builtin-fmt-merge-msg.c | 205 ++++++++++++++++++++++------------------ builtin.h | 3 + 2 files changed, 117 insertions(+), 91 deletions(-) diff --git a/builtin-fmt-merge-msg.c b/builtin-fmt-merge-msg.c index b892621ab5..dbd7d2ddae 100644 --- a/builtin-fmt-merge-msg.c +++ b/builtin-fmt-merge-msg.c @@ -159,23 +159,24 @@ static int handle_line(char *line) } static void print_joined(const char *singular, const char *plural, - struct list *list) + struct list *list, struct strbuf *out) { if (list->nr == 0) return; if (list->nr == 1) { - printf("%s%s", singular, list->list[0]); + strbuf_addf(out, "%s%s", singular, list->list[0]); } else { int i; - printf("%s", plural); + strbuf_addstr(out, plural); for (i = 0; i < list->nr - 1; i++) - printf("%s%s", i > 0 ? ", " : "", list->list[i]); - printf(" and %s", list->list[list->nr - 1]); + strbuf_addf(out, "%s%s", i > 0 ? ", " : "", list->list[i]); + strbuf_addf(out, " and %s", list->list[list->nr - 1]); } } static void shortlog(const char *name, unsigned char *sha1, - struct commit *head, struct rev_info *rev, int limit) + struct commit *head, struct rev_info *rev, int limit, + struct strbuf *out) { int i, count = 0; struct commit *commit; @@ -232,15 +233,15 @@ static void shortlog(const char *name, unsigned char *sha1, } if (count > limit) - printf("\n* %s: (%d commits)\n", name, count); + strbuf_addf(out, "\n* %s: (%d commits)\n", name, count); else - printf("\n* %s:\n", name); + strbuf_addf(out, "\n* %s:\n", name); for (i = 0; i < subjects.nr; i++) if (i >= limit) - printf(" ...\n"); + strbuf_addf(out, " ...\n"); else - printf(" %s\n", subjects.list[i]); + strbuf_addf(out, " %s\n", subjects.list[i]); clear_commit_marks((struct commit *)branch, flags); clear_commit_marks(head, flags); @@ -251,15 +252,105 @@ static void shortlog(const char *name, unsigned char *sha1, free_list(&subjects); } -int cmd_fmt_merge_msg(int argc, const char **argv, const char *prefix) -{ - int limit = 20, i = 0; +int fmt_merge_msg(int merge_summary, struct strbuf *in, struct strbuf *out) { + int limit = 20, i = 0, pos = 0; char line[1024]; - FILE *in = stdin; - const char *sep = ""; + char *p = line, *sep = ""; unsigned char head_sha1[20]; const char *current_branch; + /* get current branch */ + current_branch = resolve_ref("HEAD", head_sha1, 1, NULL); + if (!current_branch) + die("No current branch"); + if (!prefixcmp(current_branch, "refs/heads/")) + current_branch += 11; + + /* get a line */ + while (pos < in->len) { + int len; + char *newline; + + p = in->buf + pos; + newline = strchr(p, '\n'); + len = newline ? newline - p : strlen(p); + pos += len + !!newline; + i++; + p[len] = 0; + if (handle_line(p)) + die ("Error in line %d: %.*s", i, len, p); + } + + strbuf_addstr(out, "Merge "); + for (i = 0; i < srcs.nr; i++) { + struct src_data *src_data = srcs.payload[i]; + const char *subsep = ""; + + strbuf_addstr(out, sep); + sep = "; "; + + if (src_data->head_status == 1) { + strbuf_addstr(out, srcs.list[i]); + continue; + } + if (src_data->head_status == 3) { + subsep = ", "; + strbuf_addstr(out, "HEAD"); + } + if (src_data->branch.nr) { + strbuf_addstr(out, subsep); + subsep = ", "; + print_joined("branch ", "branches ", &src_data->branch, + out); + } + if (src_data->r_branch.nr) { + strbuf_addstr(out, subsep); + subsep = ", "; + print_joined("remote branch ", "remote branches ", + &src_data->r_branch, out); + } + if (src_data->tag.nr) { + strbuf_addstr(out, subsep); + subsep = ", "; + print_joined("tag ", "tags ", &src_data->tag, out); + } + if (src_data->generic.nr) { + strbuf_addstr(out, subsep); + print_joined("commit ", "commits ", &src_data->generic, + out); + } + if (strcmp(".", srcs.list[i])) + strbuf_addf(out, " of %s", srcs.list[i]); + } + + if (!strcmp("master", current_branch)) + strbuf_addch(out, '\n'); + else + strbuf_addf(out, " into %s\n", current_branch); + + if (merge_summary) { + struct commit *head; + struct rev_info rev; + + head = lookup_commit(head_sha1); + init_revisions(&rev, NULL); + rev.commit_format = CMIT_FMT_ONELINE; + rev.ignore_merges = 1; + rev.limited = 1; + + for (i = 0; i < origins.nr; i++) + shortlog(origins.list[i], origins.payload[i], + head, &rev, limit, out); + } + return 0; +} + +int cmd_fmt_merge_msg(int argc, const char **argv, const char *prefix) +{ + FILE *in = stdin; + struct strbuf input, output; + int ret; + git_config(fmt_merge_msg_config, NULL); while (argc > 1) { @@ -288,82 +379,14 @@ int cmd_fmt_merge_msg(int argc, const char **argv, const char *prefix) if (argc > 1) usage(fmt_merge_msg_usage); - /* get current branch */ - current_branch = resolve_ref("HEAD", head_sha1, 1, NULL); - if (!current_branch) - die("No current branch"); - if (!prefixcmp(current_branch, "refs/heads/")) - current_branch += 11; - - while (fgets(line, sizeof(line), in)) { - i++; - if (line[0] == 0) - continue; - if (handle_line(line)) - die ("Error in line %d: %s", i, line); - } - - printf("Merge "); - for (i = 0; i < srcs.nr; i++) { - struct src_data *src_data = srcs.payload[i]; - const char *subsep = ""; - - printf(sep); - sep = "; "; - - if (src_data->head_status == 1) { - printf(srcs.list[i]); - continue; - } - if (src_data->head_status == 3) { - subsep = ", "; - printf("HEAD"); - } - if (src_data->branch.nr) { - printf(subsep); - subsep = ", "; - print_joined("branch ", "branches ", &src_data->branch); - } - if (src_data->r_branch.nr) { - printf(subsep); - subsep = ", "; - print_joined("remote branch ", "remote branches ", - &src_data->r_branch); - } - if (src_data->tag.nr) { - printf(subsep); - subsep = ", "; - print_joined("tag ", "tags ", &src_data->tag); - } - if (src_data->generic.nr) { - printf(subsep); - print_joined("commit ", "commits ", &src_data->generic); - } - if (strcmp(".", srcs.list[i])) - printf(" of %s", srcs.list[i]); - } - - if (!strcmp("master", current_branch)) - putchar('\n'); - else - printf(" into %s\n", current_branch); - - if (merge_summary) { - struct commit *head; - struct rev_info rev; - - head = lookup_commit(head_sha1); - init_revisions(&rev, prefix); - rev.commit_format = CMIT_FMT_ONELINE; - rev.ignore_merges = 1; - rev.limited = 1; - - for (i = 0; i < origins.nr; i++) - shortlog(origins.list[i], origins.payload[i], - head, &rev, limit); - } - - /* No cleanup yet; is standalone anyway */ + strbuf_init(&input, 0); + if (strbuf_read(&input, fileno(in), 0) < 0) + die("could not read input file %s", strerror(errno)); + strbuf_init(&output, 0); + ret = fmt_merge_msg(merge_summary, &input, &output); + if (ret) + return ret; + printf("%s", output.buf); return 0; } diff --git a/builtin.h b/builtin.h index b460b2da6f..2b01feabcb 100644 --- a/builtin.h +++ b/builtin.h @@ -2,6 +2,7 @@ #define BUILTIN_H #include "git-compat-util.h" +#include "strbuf.h" extern const char git_version_string[]; extern const char git_usage_string[]; @@ -11,6 +12,8 @@ extern void list_common_cmds_help(void); extern void help_unknown_cmd(const char *cmd); extern void prune_packed_objects(int); extern int read_line_with_nul(char *buf, int size, FILE *file); +extern int fmt_merge_msg(int merge_summary, struct strbuf *in, + struct strbuf *out); extern int cmd_add(int argc, const char **argv, const char *prefix); extern int cmd_annotate(int argc, const char **argv, const char *prefix); From 5240c9d75d8e1b747da427ba6320432d3201168a Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:22:00 +0200 Subject: [PATCH 18/95] Introduce get_octopus_merge_bases() in commit.c This is like get_merge_bases() but it works for multiple heads, like show-branch --merge-base. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- commit.c | 27 +++++++++++++++++++++++++++ commit.h | 1 + 2 files changed, 28 insertions(+) diff --git a/commit.c b/commit.c index bbf9c75416..6052ca34c8 100644 --- a/commit.c +++ b/commit.c @@ -600,6 +600,33 @@ static struct commit_list *merge_bases(struct commit *one, struct commit *two) return result; } +struct commit_list *get_octopus_merge_bases(struct commit_list *in) +{ + struct commit_list *i, *j, *k, *ret = NULL; + struct commit_list **pptr = &ret; + + for (i = in; i; i = i->next) { + if (!ret) + pptr = &commit_list_insert(i->item, pptr)->next; + else { + struct commit_list *new = NULL, *end = NULL; + + for (j = ret; j; j = j->next) { + struct commit_list *bases; + bases = get_merge_bases(i->item, j->item, 1); + if (!new) + new = bases; + else + end->next = bases; + for (k = bases; k; k = k->next) + end = k; + } + ret = new; + } + } + return ret; +} + struct commit_list *get_merge_bases(struct commit *one, struct commit *two, int cleanup) { diff --git a/commit.h b/commit.h index 7f8c5ee0fc..dcec7fb9a2 100644 --- a/commit.h +++ b/commit.h @@ -121,6 +121,7 @@ int read_graft_file(const char *graft_file); struct commit_graft *lookup_commit_graft(const unsigned char *sha1); extern struct commit_list *get_merge_bases(struct commit *rev1, struct commit *rev2, int cleanup); +extern struct commit_list *get_octopus_merge_bases(struct commit_list *in); extern int register_shallow(const unsigned char *sha1); extern int unregister_shallow(const unsigned char *sha1); From 5948e2ae27d936f7737f4d7433ca6c0b879fe4c8 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 19:06:26 +0200 Subject: [PATCH 19/95] Add new test to ensure git-merge handles more than 25 refs. The old shell version handled only 25 refs but we no longer have this limitation. Add a test to make sure this limitation will not be introduced again in the future. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t7602-merge-octopus-many.sh | 52 +++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 t/t7602-merge-octopus-many.sh diff --git a/t/t7602-merge-octopus-many.sh b/t/t7602-merge-octopus-many.sh new file mode 100755 index 0000000000..f3a4bb2ea2 --- /dev/null +++ b/t/t7602-merge-octopus-many.sh @@ -0,0 +1,52 @@ +#!/bin/sh + +test_description='git-merge + +Testing octopus merge with more than 25 refs.' + +. ./test-lib.sh + +test_expect_success 'setup' ' + echo c0 > c0.c && + git add c0.c && + git commit -m c0 && + git tag c0 && + i=1 && + while test $i -le 30 + do + git reset --hard c0 && + echo c$i > c$i.c && + git add c$i.c && + git commit -m c$i && + git tag c$i && + i=`expr $i + 1` || return 1 + done +' + +test_expect_failure 'merge c1 with c2, c3, c4, ... c29' ' + git reset --hard c1 && + i=2 && + refs="" && + while test $i -le 30 + do + refs="$refs c$i" + i=`expr $i + 1` + done + git merge $refs && + test "$(git rev-parse c1)" != "$(git rev-parse HEAD)" && + i=1 && + while test $i -le 30 + do + test "$(git rev-parse c$i)" = "$(git rev-parse HEAD^$i)" && + i=`expr $i + 1` || return 1 + done && + git diff --exit-code && + i=1 && + while test $i -le 30 + do + test -f c$i.c && + i=`expr $i + 1` || return 1 + done +' + +test_done From 6a938648e1454842157b84408acbb6471ec6745f Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Fri, 27 Jun 2008 18:22:02 +0200 Subject: [PATCH 20/95] Introduce get_merge_bases_many() This introduces a new function get_merge_bases_many() which is a natural extension of two commit merge base computation. It is given one commit (one) and a set of other commits (twos), and computes the merge base of one and a merge across other commits. This is mostly useful to figure out the common ancestor when iterating over heads during an octopus merge. When making an octopus between commits A, B, C and D, we first merge tree of A and B, and then try to merge C with it. If we were making pairwise merge, we would be recording the tree resulting from the merge between A and B as a commit, say M, and then the next round we will be computing the merge base between M and C. o---C...* / . o---B...M / . o---o---A But during an octopus merge, we actually do not create a commit M. In order to figure out that the common ancestor to use for this merge, instead of computing the merge base between C and M, we can call merge_bases_many() with one set to C and twos containing A and B. Signed-off-by: Junio C Hamano --- commit.c | 56 ++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/commit.c b/commit.c index 6052ca34c8..cafed26928 100644 --- a/commit.c +++ b/commit.c @@ -533,26 +533,34 @@ static struct commit *interesting(struct commit_list *list) return NULL; } -static struct commit_list *merge_bases(struct commit *one, struct commit *two) +static struct commit_list *merge_bases_many(struct commit *one, int n, struct commit **twos) { struct commit_list *list = NULL; struct commit_list *result = NULL; + int i; - if (one == two) - /* We do not mark this even with RESULT so we do not - * have to clean it up. - */ - return commit_list_insert(one, &result); + for (i = 0; i < n; i++) { + if (one == twos[i]) + /* + * We do not mark this even with RESULT so we do not + * have to clean it up. + */ + return commit_list_insert(one, &result); + } if (parse_commit(one)) return NULL; - if (parse_commit(two)) - return NULL; + for (i = 0; i < n; i++) { + if (parse_commit(twos[i])) + return NULL; + } one->object.flags |= PARENT1; - two->object.flags |= PARENT2; insert_by_date(one, &list); - insert_by_date(two, &list); + for (i = 0; i < n; i++) { + twos[i]->object.flags |= PARENT2; + insert_by_date(twos[i], &list); + } while (interesting(list)) { struct commit *commit; @@ -627,21 +635,26 @@ struct commit_list *get_octopus_merge_bases(struct commit_list *in) return ret; } -struct commit_list *get_merge_bases(struct commit *one, - struct commit *two, int cleanup) +struct commit_list *get_merge_bases_many(struct commit *one, + int n, + struct commit **twos, + int cleanup) { struct commit_list *list; struct commit **rslt; struct commit_list *result; int cnt, i, j; - result = merge_bases(one, two); - if (one == two) - return result; + result = merge_bases_many(one, n, twos); + for (i = 0; i < n; i++) { + if (one == twos[i]) + return result; + } if (!result || !result->next) { if (cleanup) { clear_commit_marks(one, all_flags); - clear_commit_marks(two, all_flags); + for (i = 0; i < n; i++) + clear_commit_marks(twos[i], all_flags); } return result; } @@ -659,12 +672,13 @@ struct commit_list *get_merge_bases(struct commit *one, free_commit_list(result); clear_commit_marks(one, all_flags); - clear_commit_marks(two, all_flags); + for (i = 0; i < n; i++) + clear_commit_marks(twos[i], all_flags); for (i = 0; i < cnt - 1; i++) { for (j = i+1; j < cnt; j++) { if (!rslt[i] || !rslt[j]) continue; - result = merge_bases(rslt[i], rslt[j]); + result = merge_bases_many(rslt[i], 1, &rslt[j]); clear_commit_marks(rslt[i], all_flags); clear_commit_marks(rslt[j], all_flags); for (list = result; list; list = list->next) { @@ -686,6 +700,12 @@ struct commit_list *get_merge_bases(struct commit *one, return result; } +struct commit_list *get_merge_bases(struct commit *one, struct commit *two, + int cleanup) +{ + return get_merge_bases_many(one, 1, &two, cleanup); +} + int in_merge_bases(struct commit *commit, struct commit **reference, int num) { struct commit_list *bases, *b; From 98cf9c3bd7504d36e6049939bf9cc624f2cf5b9f Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Fri, 27 Jun 2008 18:22:03 +0200 Subject: [PATCH 21/95] Introduce reduce_heads() The new function reduce_heads() is given a list of commits, and removes ones that can be reached from other commits in the list. It is useful for reducing the commits randomly thrown at the git-merge command and remove redundant commits that the user shouldn't have given to it. The implementation uses the get_merge_bases_many() introduced in the previous commit. If the merge base between one commit taken from the list and the remaining commits is the commit itself, that means the commit is reachable from some of the other commits. Signed-off-by: Junio C Hamano --- commit.c | 45 +++++++++++++++++++++++++++++++++++++++++++++ commit.h | 2 ++ 2 files changed, 47 insertions(+) diff --git a/commit.c b/commit.c index cafed26928..d20b14ee3e 100644 --- a/commit.c +++ b/commit.c @@ -725,3 +725,48 @@ int in_merge_bases(struct commit *commit, struct commit **reference, int num) free_commit_list(bases); return ret; } + +struct commit_list *reduce_heads(struct commit_list *heads) +{ + struct commit_list *p; + struct commit_list *result = NULL, **tail = &result; + struct commit **other; + size_t num_head, num_other; + + if (!heads) + return NULL; + + /* Avoid unnecessary reallocations */ + for (p = heads, num_head = 0; p; p = p->next) + num_head++; + other = xcalloc(sizeof(*other), num_head); + + /* For each commit, see if it can be reached by others */ + for (p = heads; p; p = p->next) { + struct commit_list *q, *base; + + num_other = 0; + for (q = heads; q; q = q->next) { + if (p == q) + continue; + other[num_other++] = q->item; + } + if (num_other) { + base = get_merge_bases_many(p->item, num_other, other, 1); + } else + base = NULL; + /* + * If p->item does not have anything common with other + * commits, there won't be any merge base. If it is + * reachable from some of the others, p->item will be + * the merge base. If its history is connected with + * others, but p->item is not reachable by others, we + * will get something other than p->item back. + */ + if (!base || (base->item != p->item)) + tail = &(commit_list_insert(p->item, tail)->next); + free_commit_list(base); + } + free(other); + return result; +} diff --git a/commit.h b/commit.h index dcec7fb9a2..2acfc79d34 100644 --- a/commit.h +++ b/commit.h @@ -140,4 +140,6 @@ static inline int single_parent(struct commit *commit) return commit->parents && !commit->parents->next; } +struct commit_list *reduce_heads(struct commit_list *heads); + #endif /* COMMIT_H */ From f4022fa33f1b0a63029d1bc3748f01f720151218 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:22:06 +0200 Subject: [PATCH 22/95] Add new test case to ensure git-merge reduces octopus parents when possible The old shell version used show-branch --independent to filter for the ones that cannot be reached from any other reference. The new C version uses reduce_heads() from commit.c for this, so add test to ensure it works as expected. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t7603-merge-reduce-heads.sh | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100755 t/t7603-merge-reduce-heads.sh diff --git a/t/t7603-merge-reduce-heads.sh b/t/t7603-merge-reduce-heads.sh new file mode 100755 index 0000000000..17b19dc11f --- /dev/null +++ b/t/t7603-merge-reduce-heads.sh @@ -0,0 +1,63 @@ +#!/bin/sh + +test_description='git-merge + +Testing octopus merge when reducing parents to independent branches.' + +. ./test-lib.sh + +# 0 - 1 +# \ 2 +# \ 3 +# \ 4 - 5 +# +# So 1, 2, 3 and 5 should be kept, 4 should be avoided. + +test_expect_success 'setup' ' + echo c0 > c0.c && + git add c0.c && + git commit -m c0 && + git tag c0 && + echo c1 > c1.c && + git add c1.c && + git commit -m c1 && + git tag c1 && + git reset --hard c0 && + echo c2 > c2.c && + git add c2.c && + git commit -m c2 && + git tag c2 && + git reset --hard c0 && + echo c3 > c3.c && + git add c3.c && + git commit -m c3 && + git tag c3 && + git reset --hard c0 && + echo c4 > c4.c && + git add c4.c && + git commit -m c4 && + git tag c4 && + echo c5 > c5.c && + git add c5.c && + git commit -m c5 && + git tag c5 +' + +test_expect_success 'merge c1 with c2, c3, c4, c5' ' + git reset --hard c1 && + git merge c2 c3 c4 c5 && + test "$(git rev-parse c1)" != "$(git rev-parse HEAD)" && + test "$(git rev-parse c1)" = "$(git rev-parse HEAD^1)" && + test "$(git rev-parse c2)" = "$(git rev-parse HEAD^2)" && + test "$(git rev-parse c3)" = "$(git rev-parse HEAD^3)" && + test "$(git rev-parse c5)" = "$(git rev-parse HEAD^4)" && + git diff --exit-code && + test -f c0.c && + test -f c1.c && + test -f c2.c && + test -f c3.c && + test -f c4.c && + test -f c5.c +' + +test_done From 8cbd4310821ea2957d32a36c34fa314cf99ca9f3 Mon Sep 17 00:00:00 2001 From: Thomas Rast Date: Wed, 2 Jul 2008 23:59:16 +0200 Subject: [PATCH 23/95] git-add--interactive: replace hunk recounting with apply --recount We recounted the postimage offsets to compensate for hunks that were not selected. Now apply --recount can do the job for us. Signed-off-by: Thomas Rast Signed-off-by: Junio C Hamano --- git-add--interactive.perl | 30 +++--------------------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/git-add--interactive.perl b/git-add--interactive.perl index 903953e68e..e1964a588e 100755 --- a/git-add--interactive.perl +++ b/git-add--interactive.perl @@ -970,39 +970,15 @@ sub patch_update_file { push @result, @{$mode->{TEXT}}; } for (@hunk) { - my $text = $_->{TEXT}; - my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = - parse_hunk_header($text->[0]); - - if (!$_->{USE}) { - # We would have added ($n_cnt - $o_cnt) lines - # to the postimage if we were to use this hunk, - # but we didn't. So the line number that the next - # hunk starts at would be shifted by that much. - $n_lofs -= ($n_cnt - $o_cnt); - next; - } - else { - if ($n_lofs) { - $n_ofs += $n_lofs; - $text->[0] = ("@@ -$o_ofs" . - (($o_cnt != 1) - ? ",$o_cnt" : '') . - " +$n_ofs" . - (($n_cnt != 1) - ? ",$n_cnt" : '') . - " @@\n"); - } - for (@$text) { - push @result, $_; - } + if ($_->{USE}) { + push @result, @{$_->{TEXT}}; } } if (@result) { my $fh; - open $fh, '| git apply --cached'; + open $fh, '| git apply --cached --recount'; for (@{$head->{TEXT}}, @result) { print $fh $_; } From 0beee4c6dec15292415e3d56075c16a76a22af54 Mon Sep 17 00:00:00 2001 From: Thomas Rast Date: Wed, 2 Jul 2008 23:59:44 +0200 Subject: [PATCH 24/95] git-add--interactive: remove hunk coalescing Current git-apply has no trouble at all applying chunks that have overlapping context, as produced by the splitting feature. So we can drop the manual coalescing. Signed-off-by: Thomas Rast Signed-off-by: Junio C Hamano --- git-add--interactive.perl | 89 --------------------------------------- 1 file changed, 89 deletions(-) diff --git a/git-add--interactive.perl b/git-add--interactive.perl index e1964a588e..a4234d39e9 100755 --- a/git-add--interactive.perl +++ b/git-add--interactive.perl @@ -682,93 +682,6 @@ sub split_hunk { return @split; } -sub find_last_o_ctx { - my ($it) = @_; - my $text = $it->{TEXT}; - my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]); - my $i = @{$text}; - my $last_o_ctx = $o_ofs + $o_cnt; - while (0 < --$i) { - my $line = $text->[$i]; - if ($line =~ /^ /) { - $last_o_ctx--; - next; - } - last; - } - return $last_o_ctx; -} - -sub merge_hunk { - my ($prev, $this) = @_; - my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) = - parse_hunk_header($prev->{TEXT}[0]); - my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) = - parse_hunk_header($this->{TEXT}[0]); - - my (@line, $i, $ofs, $o_cnt, $n_cnt); - $ofs = $o0_ofs; - $o_cnt = $n_cnt = 0; - for ($i = 1; $i < @{$prev->{TEXT}}; $i++) { - my $line = $prev->{TEXT}[$i]; - if ($line =~ /^\+/) { - $n_cnt++; - push @line, $line; - next; - } - - last if ($o1_ofs <= $ofs); - - $o_cnt++; - $ofs++; - if ($line =~ /^ /) { - $n_cnt++; - } - push @line, $line; - } - - for ($i = 1; $i < @{$this->{TEXT}}; $i++) { - my $line = $this->{TEXT}[$i]; - if ($line =~ /^\+/) { - $n_cnt++; - push @line, $line; - next; - } - $ofs++; - $o_cnt++; - if ($line =~ /^ /) { - $n_cnt++; - } - push @line, $line; - } - my $head = ("@@ -$o0_ofs" . - (($o_cnt != 1) ? ",$o_cnt" : '') . - " +$n0_ofs" . - (($n_cnt != 1) ? ",$n_cnt" : '') . - " @@\n"); - @{$prev->{TEXT}} = ($head, @line); -} - -sub coalesce_overlapping_hunks { - my (@in) = @_; - my @out = (); - - my ($last_o_ctx); - - for (grep { $_->{USE} } @in) { - my $text = $_->{TEXT}; - my ($o_ofs) = parse_hunk_header($text->[0]); - if (defined $last_o_ctx && - $o_ofs <= $last_o_ctx) { - merge_hunk($out[-1], $_); - } - else { - push @out, $_; - } - $last_o_ctx = find_last_o_ctx($out[-1]); - } - return @out; -} sub help_patch_cmd { print colored $help_color, <<\EOF ; @@ -962,8 +875,6 @@ sub patch_update_file { } } - @hunk = coalesce_overlapping_hunks(@hunk); - my $n_lofs = 0; my @result = (); if ($mode->{USE}) { From ac083c47ea226b470afab39d975e718a475a3c78 Mon Sep 17 00:00:00 2001 From: Thomas Rast Date: Thu, 3 Jul 2008 00:00:00 +0200 Subject: [PATCH 25/95] git-add--interactive: manual hunk editing mode Adds a new option 'e' to the 'add -p' command loop that lets you edit the current hunk in your favourite editor. If the resulting patch applies cleanly, the edited hunk will immediately be marked for staging. If it does not apply cleanly, you will be given an opportunity to edit again. If all lines of the hunk are removed, then the edit is aborted and the hunk is left unchanged. Applying the changed hunk(s) relies on Johannes Schindelin's new --recount option for git-apply. Note that the "real patch" test intentionally uses (echo e; echo n; echo d) | git add -p even though the 'n' and 'd' are superfluous at first sight. They serve to get out of the interaction loop if git add -p wrongly concludes the patch does not apply. Many thanks to Jeff King for lots of help and suggestions. Signed-off-by: Thomas Rast Signed-off-by: Junio C Hamano --- Documentation/git-add.txt | 1 + git-add--interactive.perl | 119 +++++++++++++++++++++++++++++++++++++ t/t3701-add-interactive.sh | 67 +++++++++++++++++++++ 3 files changed, 187 insertions(+) diff --git a/Documentation/git-add.txt b/Documentation/git-add.txt index 011a743652..46dd56c12a 100644 --- a/Documentation/git-add.txt +++ b/Documentation/git-add.txt @@ -236,6 +236,7 @@ patch:: k - leave this hunk undecided, see previous undecided hunk K - leave this hunk undecided, see previous hunk s - split the current hunk into smaller hunks + e - manually edit the current hunk ? - print help + After deciding the fate for all hunks, if there is any hunk diff --git a/git-add--interactive.perl b/git-add--interactive.perl index a4234d39e9..801d7c0251 100755 --- a/git-add--interactive.perl +++ b/git-add--interactive.perl @@ -18,6 +18,18 @@ my ($fraginfo_color) = $diff_use_color ? ( $repo->get_color('color.diff.frag', 'cyan'), ) : (); +my ($diff_plain_color) = + $diff_use_color ? ( + $repo->get_color('color.diff.plain', ''), + ) : (); +my ($diff_old_color) = + $diff_use_color ? ( + $repo->get_color('color.diff.old', 'red'), + ) : (); +my ($diff_new_color) = + $diff_use_color ? ( + $repo->get_color('color.diff.new', 'green'), + ) : (); my $normal_color = $repo->get_color("", "reset"); @@ -683,6 +695,105 @@ sub split_hunk { } +sub color_diff { + return map { + colored((/^@/ ? $fraginfo_color : + /^\+/ ? $diff_new_color : + /^-/ ? $diff_old_color : + $diff_plain_color), + $_); + } @_; +} + +sub edit_hunk_manually { + my ($oldtext) = @_; + + my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff"; + my $fh; + open $fh, '>', $hunkfile + or die "failed to open hunk edit file for writing: " . $!; + print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n"; + print $fh @$oldtext; + print $fh <config("core.editor") + || $ENV{VISUAL} || $ENV{EDITOR} || "vi"; + system('sh', '-c', $editor.' "$@"', $editor, $hunkfile); + + open $fh, '<', $hunkfile + or die "failed to open hunk edit file for reading: " . $!; + my @newtext = grep { !/^#/ } <$fh>; + close $fh; + unlink $hunkfile; + + # Abort if nothing remains + if (!grep { /\S/ } @newtext) { + return undef; + } + + # Reinsert the first hunk header if the user accidentally deleted it + if ($newtext[0] !~ /^@/) { + unshift @newtext, $oldtext->[0]; + } + return \@newtext; +} + +sub diff_applies { + my $fh; + open $fh, '| git apply --recount --cached --check'; + for my $h (@_) { + print $fh @{$h->{TEXT}}; + } + return close $fh; +} + +sub prompt_yesno { + my ($prompt) = @_; + while (1) { + print colored $prompt_color, $prompt; + my $line = ; + return 0 if $line =~ /^n/i; + return 1 if $line =~ /^y/i; + } +} + +sub edit_hunk_loop { + my ($head, $hunk, $ix) = @_; + my $text = $hunk->[$ix]->{TEXT}; + + while (1) { + $text = edit_hunk_manually($text); + if (!defined $text) { + return undef; + } + my $newhunk = { TEXT => $text, USE => 1 }; + if (diff_applies($head, + @{$hunk}[0..$ix-1], + $newhunk, + @{$hunk}[$ix+1..$#{$hunk}])) { + $newhunk->{DISPLAY} = [color_diff(@{$text})]; + return $newhunk; + } + else { + prompt_yesno( + 'Your edited hunk does not apply. Edit again ' + . '(saying "no" discards!) [y/n]? ' + ) or return undef; + } + } +} + sub help_patch_cmd { print colored $help_color, <<\EOF ; y - stage this hunk @@ -694,6 +805,7 @@ J - leave this hunk undecided, see next hunk k - leave this hunk undecided, see previous undecided hunk K - leave this hunk undecided, see previous hunk s - split the current hunk into smaller hunks +e - manually edit the current hunk ? - print help EOF } @@ -798,6 +910,7 @@ sub patch_update_file { if (hunk_splittable($hunk[$ix]{TEXT})) { $other .= '/s'; } + $other .= '/e'; for (@{$hunk[$ix]{DISPLAY}}) { print; } @@ -862,6 +975,12 @@ sub patch_update_file { $num = scalar @hunk; next; } + elsif ($line =~ /^e/) { + my $newhunk = edit_hunk_loop($head, \@hunk, $ix); + if (defined $newhunk) { + splice @hunk, $ix, 1, $newhunk; + } + } else { help_patch_cmd($other); next; diff --git a/t/t3701-add-interactive.sh b/t/t3701-add-interactive.sh index fae64eae9f..e95663d8e6 100755 --- a/t/t3701-add-interactive.sh +++ b/t/t3701-add-interactive.sh @@ -66,6 +66,73 @@ test_expect_success 'revert works (commit)' ' grep "unchanged *+3/-0 file" output ' +cat >expected <fake_editor.sh < diff && + test_cmp expected diff +' + +cat >patch <fake_editor.sh +cat >>fake_editor.sh <<\EOF +mv -f "$1" oldpatch && +mv -f patch "$1" +EOF +chmod a+x fake_editor.sh +test_set_editor "$(pwd)/fake_editor.sh" +test_expect_success 'bad edit rejected' ' + git reset && + (echo e; echo n; echo d) | git add -p >output && + grep "hunk does not apply" output +' + +cat >patch <output && + grep "hunk does not apply" output +' + +cat >patch <expected <output && + test_cmp expected output +' + if test "$(git config --bool core.filemode)" = false then say 'skipping filemode tests (filesystem does not properly support modes)' From 6d21bf96b59cbcc818fdc83b654d7fc83dd2c9cd Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 2 Jul 2008 00:51:18 -0700 Subject: [PATCH 26/95] Refactor "tracking statistics" code used by "git checkout" People seem to like "Your branch is ahead by N commit" report made by "git checkout", but the interface into the statistics function was a bit clunky. This splits the function into three parts: * The core "commit counting" function that takes "struct branch" and returns number of commits to show if we are ahead, behind or forked; * Convenience "stat formating" function that takes "struct branch" and formats the report into a given strbuf, using the above function; * "checkout" specific function that takes "branch_info" (type that is internal to checkout implementation), calls the above function and print the formatted result. in the hope that the former two can be more easily reusable. Signed-off-by: Junio C Hamano --- builtin-checkout.c | 94 +++---------------------------------- remote.c | 113 +++++++++++++++++++++++++++++++++++++++++++++ remote.h | 4 ++ 3 files changed, 123 insertions(+), 88 deletions(-) diff --git a/builtin-checkout.c b/builtin-checkout.c index 93ea69bfaa..d6641c2c56 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -305,97 +305,15 @@ static int merge_working_tree(struct checkout_opts *opts, return 0; } -static void report_tracking(struct branch_info *new, struct checkout_opts *opts) +static void report_tracking(struct branch_info *new) { - /* - * We have switched to a new branch; is it building on - * top of another branch, and if so does that other branch - * have changes we do not have yet? - */ - char *base; - unsigned char sha1[20]; - struct commit *ours, *theirs; - char symmetric[84]; - struct rev_info revs; - const char *rev_argv[10]; - int rev_argc; - int num_ours, num_theirs; - const char *remote_msg; + struct strbuf sb = STRBUF_INIT; struct branch *branch = branch_get(new->name); - /* - * Nothing to report unless we are marked to build on top of - * somebody else. - */ - if (!branch || !branch->merge || !branch->merge[0] || !branch->merge[0]->dst) + if (!format_tracking_info(branch, &sb)) return; - - /* - * If what we used to build on no longer exists, there is - * nothing to report. - */ - base = branch->merge[0]->dst; - if (!resolve_ref(base, sha1, 1, NULL)) - return; - - theirs = lookup_commit(sha1); - ours = new->commit; - if (!hashcmp(sha1, ours->object.sha1)) - return; /* we are the same */ - - /* Run "rev-list --left-right ours...theirs" internally... */ - rev_argc = 0; - rev_argv[rev_argc++] = NULL; - rev_argv[rev_argc++] = "--left-right"; - rev_argv[rev_argc++] = symmetric; - rev_argv[rev_argc++] = "--"; - rev_argv[rev_argc] = NULL; - - strcpy(symmetric, sha1_to_hex(ours->object.sha1)); - strcpy(symmetric + 40, "..."); - strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1)); - - init_revisions(&revs, NULL); - setup_revisions(rev_argc, rev_argv, &revs, NULL); - prepare_revision_walk(&revs); - - /* ... and count the commits on each side. */ - num_ours = 0; - num_theirs = 0; - while (1) { - struct commit *c = get_revision(&revs); - if (!c) - break; - if (c->object.flags & SYMMETRIC_LEFT) - num_ours++; - else - num_theirs++; - } - - if (!prefixcmp(base, "refs/remotes/")) { - remote_msg = " remote"; - base += strlen("refs/remotes/"); - } else { - remote_msg = ""; - } - - if (!num_theirs) - printf("Your branch is ahead of the tracked%s branch '%s' " - "by %d commit%s.\n", - remote_msg, base, - num_ours, (num_ours == 1) ? "" : "s"); - else if (!num_ours) - printf("Your branch is behind the tracked%s branch '%s' " - "by %d commit%s,\n" - "and can be fast-forwarded.\n", - remote_msg, base, - num_theirs, (num_theirs == 1) ? "" : "s"); - else - printf("Your branch and the tracked%s branch '%s' " - "have diverged,\nand respectively " - "have %d and %d different commit(s) each.\n", - remote_msg, base, - num_ours, num_theirs); + fputs(sb.buf, stdout); + strbuf_release(&sb); } static void update_refs_for_switch(struct checkout_opts *opts, @@ -441,7 +359,7 @@ static void update_refs_for_switch(struct checkout_opts *opts, remove_branch_state(); strbuf_release(&msg); if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD"))) - report_tracking(new, opts); + report_tracking(new); } static int switch_branches(struct checkout_opts *opts, struct branch_info *new) diff --git a/remote.c b/remote.c index ff2c802167..bd5c3be3ec 100644 --- a/remote.c +++ b/remote.c @@ -1,6 +1,9 @@ #include "cache.h" #include "remote.h" #include "refs.h" +#include "commit.h" +#include "diff.h" +#include "revision.h" static struct refspec s_tag_refspec = { 0, @@ -1222,3 +1225,113 @@ int resolve_remote_symref(struct ref *ref, struct ref *list) } return 1; } + +/* + * Return true if there is anything to report, otherwise false. + */ +int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs) +{ + unsigned char sha1[20]; + struct commit *ours, *theirs; + char symmetric[84]; + struct rev_info revs; + const char *rev_argv[10], *base; + int rev_argc; + + /* + * Nothing to report unless we are marked to build on top of + * somebody else. + */ + if (!branch || + !branch->merge || !branch->merge[0] || !branch->merge[0]->dst) + return 0; + + /* + * If what we used to build on no longer exists, there is + * nothing to report. + */ + base = branch->merge[0]->dst; + if (!resolve_ref(base, sha1, 1, NULL)) + return 0; + theirs = lookup_commit(sha1); + if (!theirs) + return 0; + + if (!resolve_ref(branch->refname, sha1, 1, NULL)) + return 0; + ours = lookup_commit(sha1); + if (!ours) + return 0; + + /* are we the same? */ + if (theirs == ours) + return 0; + + /* Run "rev-list --left-right ours...theirs" internally... */ + rev_argc = 0; + rev_argv[rev_argc++] = NULL; + rev_argv[rev_argc++] = "--left-right"; + rev_argv[rev_argc++] = symmetric; + rev_argv[rev_argc++] = "--"; + rev_argv[rev_argc] = NULL; + + strcpy(symmetric, sha1_to_hex(ours->object.sha1)); + strcpy(symmetric + 40, "..."); + strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1)); + + init_revisions(&revs, NULL); + setup_revisions(rev_argc, rev_argv, &revs, NULL); + prepare_revision_walk(&revs); + + /* ... and count the commits on each side. */ + *num_ours = 0; + *num_theirs = 0; + while (1) { + struct commit *c = get_revision(&revs); + if (!c) + break; + if (c->object.flags & SYMMETRIC_LEFT) + (*num_ours)++; + else + (*num_theirs)++; + } + return 1; +} + +/* + * Return true when there is anything to report, otherwise false. + */ +int format_tracking_info(struct branch *branch, struct strbuf *sb) +{ + int num_ours, num_theirs; + const char *base, *remote_msg; + + if (!stat_tracking_info(branch, &num_ours, &num_theirs)) + return 0; + + base = branch->merge[0]->dst; + if (!prefixcmp(base, "refs/remotes/")) { + remote_msg = " remote"; + base += strlen("refs/remotes/"); + } else { + remote_msg = ""; + } + if (!num_theirs) + strbuf_addf(sb, "Your branch is ahead of the tracked%s branch '%s' " + "by %d commit%s.\n", + remote_msg, base, + num_ours, (num_ours == 1) ? "" : "s"); + else if (!num_ours) + strbuf_addf(sb, "Your branch is behind the tracked%s branch '%s' " + "by %d commit%s,\n" + "and can be fast-forwarded.\n", + remote_msg, base, + num_theirs, (num_theirs == 1) ? "" : "s"); + else + strbuf_addf(sb, "Your branch and the tracked%s branch '%s' " + "have diverged,\nand respectively " + "have %d and %d different commit(s) each.\n", + remote_msg, base, + num_ours, num_theirs); + return 1; +} diff --git a/remote.h b/remote.h index 8eed87ba5a..091b1d041f 100644 --- a/remote.h +++ b/remote.h @@ -129,4 +129,8 @@ enum match_refs_flags { MATCH_REFS_MIRROR = (1 << 1), }; +/* Reporting of tracking info */ +int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs); +int format_tracking_info(struct branch *branch, struct strbuf *sb); + #endif From b6975ab59b07e5416b3f9b6f077d3cb50ef5ac7e Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 2 Jul 2008 00:52:16 -0700 Subject: [PATCH 27/95] git-status: show the remote tracking statistics This teaches "git status" to show the same remote tracking statistics "git checkout" gives at the beginning of the output. Now the necessary low-level machinery is properly factored out, we can do this quite cleanly. Signed-off-by: Junio C Hamano --- wt-status.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/wt-status.c b/wt-status.c index 28c9e637e3..eeb106e13e 100644 --- a/wt-status.c +++ b/wt-status.c @@ -9,6 +9,7 @@ #include "diffcore.h" #include "quote.h" #include "run-command.h" +#include "remote.h" int wt_status_relative_paths = 1; int wt_status_use_color = -1; @@ -315,6 +316,25 @@ static void wt_status_print_verbose(struct wt_status *s) run_diff_index(&rev, 1); } +static void wt_status_print_tracking(struct wt_status *s) +{ + struct strbuf sb = STRBUF_INIT; + const char *cp, *ep; + struct branch *branch; + + assert(s->branch && !s->is_initial); + if (prefixcmp(s->branch, "refs/heads/")) + return; + branch = branch_get(s->branch + 11); + if (!format_tracking_info(branch, &sb)) + return; + + for (cp = sb.buf; (ep = strchr(cp, '\n')) != NULL; cp = ep + 1) + color_fprintf_ln(s->fp, color(WT_STATUS_HEADER), + "# %.*s", (int)(ep - cp), cp); + color_fprintf_ln(s->fp, color(WT_STATUS_HEADER), "#"); +} + void wt_status_print(struct wt_status *s) { unsigned char sha1[20]; @@ -333,6 +353,8 @@ void wt_status_print(struct wt_status *s) } color_fprintf(s->fp, color(WT_STATUS_HEADER), "# "); color_fprintf_ln(s->fp, branch_color, "%s%s", on_what, branch_name); + if (!s->is_initial) + wt_status_print_tracking(s); } if (s->is_initial) { From 94fcb730ff665d356689f3d30e20e0fd75c6f62f Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 2 Jul 2008 00:52:41 -0700 Subject: [PATCH 28/95] git-branch -v: show the remote tracking statistics This teaches "git branch -v" to insert the remote tracking statistics in brackets, just before the one-liner commit log message for the branch. Signed-off-by: Junio C Hamano --- builtin-branch.c | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/builtin-branch.c b/builtin-branch.c index d279702ba9..e9423d1e4c 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -282,6 +282,23 @@ static int ref_cmp(const void *r1, const void *r2) return strcmp(c1->name, c2->name); } +static void fill_tracking_info(char *stat, const char *branch_name) +{ + int ours, theirs; + struct branch *branch = branch_get(branch_name); + + if (!stat_tracking_info(branch, &ours, &theirs) || (!ours && !theirs)) { + stat[0] = '\0'; + return; + } + if (!ours) + sprintf(stat, "[behind %d] ", theirs); + else if (!theirs) + sprintf(stat, "[ahead %d] ", ours); + else + sprintf(stat, "[ahead %d, behind %d] ", ours, theirs); +} + static void print_ref_item(struct ref_item *item, int maxwidth, int verbose, int abbrev, int current) { @@ -310,6 +327,7 @@ static void print_ref_item(struct ref_item *item, int maxwidth, int verbose, if (verbose) { struct strbuf subject; const char *sub = " **** invalid ref ****"; + char stat[128]; strbuf_init(&subject, 0); @@ -319,10 +337,15 @@ static void print_ref_item(struct ref_item *item, int maxwidth, int verbose, &subject, 0, NULL, NULL, 0, 0); sub = subject.buf; } - printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color), + + if (item->kind == REF_LOCAL_BRANCH) + fill_tracking_info(stat, item->name); + + printf("%c %s%-*s%s %s %s%s\n", c, branch_get_color(color), maxwidth, item->name, branch_get_color(COLOR_BRANCH_RESET), - find_unique_abbrev(item->sha1, abbrev), sub); + find_unique_abbrev(item->sha1, abbrev), + stat, sub); strbuf_release(&subject); } else { printf("%c %s%s%s\n", c, branch_get_color(color), item->name, From c0234b2ef6a8eaa27d9d93c4c96b36d9e82ebf9c Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Thu, 3 Jul 2008 12:09:48 -0700 Subject: [PATCH 29/95] stat_tracking_info(): clear object flags used during counting When left-right traversal counts the commits in a diverged history, it leaves the flags in the commits smudged, and we need to clear them before we return. Otherwise the caller cannot inspect other branches with this function again. Signed-off-by: Junio C Hamano --- remote.c | 4 +++ revision.h | 1 + t/t6040-tracking-info.sh | 70 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100755 t/t6040-tracking-info.sh diff --git a/remote.c b/remote.c index bd5c3be3ec..df8bd72ba9 100644 --- a/remote.c +++ b/remote.c @@ -1295,6 +1295,10 @@ int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs) else (*num_theirs)++; } + + /* clear object flags smudged by the above traversal */ + clear_commit_marks(ours, ALL_REV_FLAGS); + clear_commit_marks(theirs, ALL_REV_FLAGS); return 1; } diff --git a/revision.h b/revision.h index abce5001f1..e8bac6d141 100644 --- a/revision.h +++ b/revision.h @@ -11,6 +11,7 @@ #define ADDED (1u<<7) /* Parents already parsed and added? */ #define SYMMETRIC_LEFT (1u<<8) #define TOPOSORT (1u<<9) /* In the active toposort list.. */ +#define ALL_REV_FLAGS ((1u<<10)-1) struct rev_info; struct log_info; diff --git a/t/t6040-tracking-info.sh b/t/t6040-tracking-info.sh new file mode 100755 index 0000000000..aac212e936 --- /dev/null +++ b/t/t6040-tracking-info.sh @@ -0,0 +1,70 @@ +#!/bin/sh + +test_description='remote tracking stats' + +. ./test-lib.sh + +advance () { + echo "$1" >"$1" && + git add "$1" && + test_tick && + git commit -m "$1" +} + +test_expect_success setup ' + for i in a b c; + do + advance $i || break + done && + git clone . test && + ( + cd test && + git checkout -b b1 origin && + git reset --hard HEAD^ && + advance d && + git checkout -b b2 origin && + git reset --hard b1 && + git checkout -b b3 origin && + git reset --hard HEAD^ && + git checkout -b b4 origin && + advance e && + advance f + ) +' + +script='s/^..\(b.\)[ 0-9a-f]*\[\([^]]*\)\].*/\1 \2/p' +cat >expect <<\EOF +b1 ahead 1, behind 1 +b2 ahead 1, behind 1 +b3 behind 1 +b4 ahead 2 +EOF + +test_expect_success 'branch -v' ' + ( + cd test && + git branch -v + ) | + sed -n -e "$script" >actual && + test_cmp expect actual +' + +test_expect_success 'checkout' ' + ( + cd test && git checkout b1 + ) >actual && + grep -e "have 1 and 1 different" actual +' + +test_expect_success 'status' ' + ( + cd test && + git checkout b1 >/dev/null && + # reports nothing to commit + test_must_fail git status + ) >actual && + grep -e "have 1 and 1 different" actual +' + + +test_done From 656b50345239293929ad8c639c5f1941c6b867ad Mon Sep 17 00:00:00 2001 From: Abhijit Menon-Sen Date: Thu, 3 Jul 2008 11:46:05 +0530 Subject: [PATCH 30/95] Implement "git stash branch " Restores the stashed state on a new branch rooted at the commit on which the stash was originally created, so that conflicts caused by subsequent changes on the original branch can be dealt with. (Thanks to Junio for this nice idea.) Signed-off-by: Abhijit Menon-Sen Signed-off-by: Junio C Hamano --- Documentation/git-stash.txt | 19 ++++++++++++++++++- git-stash.sh | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Documentation/git-stash.txt b/Documentation/git-stash.txt index 23ac331295..a4cbd0ce60 100644 --- a/Documentation/git-stash.txt +++ b/Documentation/git-stash.txt @@ -8,8 +8,11 @@ git-stash - Stash the changes in a dirty working directory away SYNOPSIS -------- [verse] -'git stash' (list | show [] | apply [] | clear | drop [] | pop []) +'git stash' list +'git stash' (show | apply | drop | pop ) [] +'git stash' branch [] 'git stash' [save []] +'git stash' clear DESCRIPTION ----------- @@ -81,6 +84,20 @@ tree's changes, but also the index's ones. However, this can fail, when you have conflicts (which are stored in the index, where you therefore can no longer apply the changes as they were originally). +branch []:: + + Creates and checks out a new branch named `` starting from + the commit at which the `` was originally created, applies the + changes recorded in `` to the new working tree and index, then + drops the `` if that completes successfully. When no `` + is given, applies the latest one. ++ +This is useful if the branch on which you ran `git stash save` has +changed enough that `git stash apply` fails due to conflicts. Since +the stash is applied on top of the commit that was HEAD at the time +`git stash` was run, it restores the originally stashed state with +no conflicts. + clear:: Remove all the stashed states. Note that those states will then be subject to pruning, and may be difficult or impossible to recover. diff --git a/git-stash.sh b/git-stash.sh index 4938ade589..889445c4fc 100755 --- a/git-stash.sh +++ b/git-stash.sh @@ -218,6 +218,23 @@ drop_stash () { git rev-parse --verify "$ref_stash@{0}" > /dev/null 2>&1 || clear_stash } +apply_to_branch () { + have_stash || die 'Nothing to apply' + + test -n "$1" || die 'No branch name specified' + branch=$1 + + if test -z "$2" + then + set x "$ref_stash@{0}" + fi + stash=$2 + + git-checkout -b $branch $stash^ && + apply_stash --index $stash && + drop_stash $stash +} + # Main command set case "$1" in list) @@ -264,6 +281,10 @@ pop) drop_stash "$@" fi ;; +branch) + shift + apply_to_branch "$@" + ;; *) if test $# -eq 0 then From 7bedebcaad351108a8f6eab6a031f2be2c06b613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?SZEDER=20G=C3=A1bor?= Date: Fri, 27 Jun 2008 16:37:15 +0200 Subject: [PATCH 31/95] stash: introduce 'stash save --keep-index' option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 'git stash save' saves local modifications to a new stash, and runs 'git reset --hard' to revert them to a clean index and work tree. When the '--keep-index' option is specified, after that 'git reset --hard' the previous contents of the index is restored and the work tree is updated to match the index. This option is useful if the user wants to commit only parts of his local modifications, but wants to test those parts before committing. Also add support for the completion of the new option, and add an example use case to the documentation. Signed-off-by: SZEDER Gábor Signed-off-by: Junio C Hamano --- Documentation/git-stash.txt | 22 +++++++++++++++++++++- contrib/completion/git-completion.bash | 13 ++++++++++++- git-stash.sh | 22 ++++++++++++++++++---- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/Documentation/git-stash.txt b/Documentation/git-stash.txt index 23ac331295..8f331ee7d4 100644 --- a/Documentation/git-stash.txt +++ b/Documentation/git-stash.txt @@ -36,12 +36,15 @@ is also possible). OPTIONS ------- -save []:: +save [--keep-index] []:: Save your local modifications to a new 'stash', and run `git reset --hard` to revert them. This is the default action when no subcommand is given. The part is optional and gives the description along with the stashed state. ++ +If the `--keep-index` option is used, all changes already added to the +index are left intact. list []:: @@ -169,6 +172,23 @@ $ git stash apply ... continue hacking ... ---------------------------------------------------------------- +Testing partial commits:: + +You can use `git stash save --keep-index` when you want to make two or +more commits out of the changes in the work tree, and you want to test +each change before committing: ++ +---------------------------------------------------------------- +... hack hack hack ... +$ git add --patch foo +$ git stash save --keep-index +$ build && run tests +$ git commit -m 'First part' +$ git stash apply +$ build && run tests +$ git commit -a -m 'Second part' +---------------------------------------------------------------- + SEE ALSO -------- linkgit:git-checkout[1], diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash index 3f46149853..595de80ea4 100755 --- a/contrib/completion/git-completion.bash +++ b/contrib/completion/git-completion.bash @@ -1137,8 +1137,19 @@ _git_show () _git_stash () { local subcommands='save list show apply clear drop pop create' - if [ -z "$(__git_find_subcommand "$subcommands")" ]; then + local subcommand="$(__git_find_subcommand "$subcommands")" + if [ -z "$subcommand" ]; then __gitcomp "$subcommands" + else + local cur="${COMP_WORDS[COMP_CWORD]}" + case "$subcommand,$cur" in + save,--*) + __gitcomp "--keep-index" + ;; + *) + COMPREPLY=() + ;; + esac fi } diff --git a/git-stash.sh b/git-stash.sh index 4938ade589..92531a2951 100755 --- a/git-stash.sh +++ b/git-stash.sh @@ -86,6 +86,13 @@ create_stash () { } save_stash () { + keep_index= + case "$1" in + --keep-index) + keep_index=t + shift + esac + stash_msg="$1" if no_changes @@ -104,6 +111,13 @@ save_stash () { git update-ref -m "$stash_msg" $ref_stash $w_commit || die "Cannot save the current status" printf 'Saved working directory and index state "%s"\n' "$stash_msg" + + git reset --hard + + if test -n "$keep_index" && test -n $i_tree + then + git read-tree --reset -u $i_tree + fi } have_stash () { @@ -153,7 +167,8 @@ apply_stash () { die "$*: no valid stashed state found" unstashed_index_tree= - if test -n "$unstash_index" && test "$b_tree" != "$i_tree" + if test -n "$unstash_index" && test "$b_tree" != "$i_tree" && + test "$c_tree" != "$i_tree" then git diff-tree --binary $s^2^..$s^2 | git apply --cached test $? -ne 0 && @@ -235,7 +250,7 @@ show) ;; save) shift - save_stash "$*" && git-reset --hard + save_stash "$*" ;; apply) shift @@ -268,8 +283,7 @@ pop) if test $# -eq 0 then save_stash && - echo '(To restore them type "git stash apply")' && - git-reset --hard + echo '(To restore them type "git stash apply")' else usage fi From 926ab840cdc867b54fa93b8e1ece2790315c2456 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sun, 6 Jul 2008 02:54:56 -0700 Subject: [PATCH 32/95] branch -r -v: do not spit out garbage The codepath to emit relationship between the branch and what it tracks forgot to initialize a string buffer stat[] to empty when showing a tracking branch. This moves the emptying so that the buffer starts as empty and stays so when no information is added to fix this issue. Signed-off-by: Junio C Hamano --- builtin-branch.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/builtin-branch.c b/builtin-branch.c index e9423d1e4c..ff71f3d8a6 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -287,10 +287,8 @@ static void fill_tracking_info(char *stat, const char *branch_name) int ours, theirs; struct branch *branch = branch_get(branch_name); - if (!stat_tracking_info(branch, &ours, &theirs) || (!ours && !theirs)) { - stat[0] = '\0'; + if (!stat_tracking_info(branch, &ours, &theirs) || (!ours && !theirs)) return; - } if (!ours) sprintf(stat, "[behind %d] ", theirs); else if (!theirs) @@ -330,6 +328,7 @@ static void print_ref_item(struct ref_item *item, int maxwidth, int verbose, char stat[128]; strbuf_init(&subject, 0); + stat[0] = '\0'; commit = lookup_commit(item->sha1); if (commit && !parse_commit(commit)) { From c1fb35b98aa36ce789c60520028d95e5f9fee43c Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Fri, 27 Jun 2008 18:22:07 +0200 Subject: [PATCH 33/95] Add new test case to ensure git-merge prepends the custom merge message There was no test for this before, so the testsuite passed, even in case the merge summary was missing from the merge commit message. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t7604-merge-custom-message.sh | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100755 t/t7604-merge-custom-message.sh diff --git a/t/t7604-merge-custom-message.sh b/t/t7604-merge-custom-message.sh new file mode 100755 index 0000000000..6081677d23 --- /dev/null +++ b/t/t7604-merge-custom-message.sh @@ -0,0 +1,37 @@ +#!/bin/sh + +test_description='git-merge + +Testing merge when using a custom message for the merge commit.' + +. ./test-lib.sh + +test_expect_success 'setup' ' + echo c0 > c0.c && + git add c0.c && + git commit -m c0 && + git tag c0 && + echo c1 > c1.c && + git add c1.c && + git commit -m c1 && + git tag c1 && + git reset --hard c0 && + echo c2 > c2.c && + git add c2.c && + git commit -m c2 && + git tag c2 +' + +cat >expected <<\EOF +custom message + +Merge commit 'c2' +EOF +test_expect_success 'merge c2 with a custom message' ' + git reset --hard c1 && + git merge -m "custom message" c2 && + git cat-file commit HEAD | sed -e "1,/^$/d" > actual && + test_cmp expected actual +' + +test_done From 7b9c0a69a5f64fffb5de8b49a96f41ac35b4a84f Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Tue, 1 Jul 2008 04:37:49 +0200 Subject: [PATCH 34/95] git-commit-tree: make it usable from other builtins Move all functionality (except option parsing) from cmd_commit_tree() to commit_tree(), so that other builtins can use it without a child process. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- builtin-commit-tree.c | 71 +++++++++++++++++++++++++------------------ builtin.h | 4 +++ 2 files changed, 45 insertions(+), 30 deletions(-) diff --git a/builtin-commit-tree.c b/builtin-commit-tree.c index 3881f6c2f5..7a9a309be0 100644 --- a/builtin-commit-tree.c +++ b/builtin-commit-tree.c @@ -45,41 +45,19 @@ static const char commit_utf8_warn[] = "You may want to amend it after fixing the message, or set the config\n" "variable i18n.commitencoding to the encoding your project uses.\n"; -int cmd_commit_tree(int argc, const char **argv, const char *prefix) +int commit_tree(const char *msg, unsigned char *tree, + struct commit_list *parents, unsigned char *ret) { - int i; - struct commit_list *parents = NULL; - unsigned char tree_sha1[20]; - unsigned char commit_sha1[20]; - struct strbuf buffer; int encoding_is_utf8; + struct strbuf buffer; - git_config(git_default_config, NULL); - - if (argc < 2) - usage(commit_tree_usage); - if (get_sha1(argv[1], tree_sha1)) - die("Not a valid object name %s", argv[1]); - - check_valid(tree_sha1, OBJ_TREE); - for (i = 2; i < argc; i += 2) { - unsigned char sha1[20]; - const char *a, *b; - a = argv[i]; b = argv[i+1]; - if (!b || strcmp(a, "-p")) - usage(commit_tree_usage); - - if (get_sha1(b, sha1)) - die("Not a valid object name %s", b); - check_valid(sha1, OBJ_COMMIT); - new_parent(lookup_commit(sha1), &parents); - } + check_valid(tree, OBJ_TREE); /* Not having i18n.commitencoding is the same as having utf-8 */ encoding_is_utf8 = is_encoding_utf8(git_commit_encoding); strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */ - strbuf_addf(&buffer, "tree %s\n", sha1_to_hex(tree_sha1)); + strbuf_addf(&buffer, "tree %s\n", sha1_to_hex(tree)); /* * NOTE! This ordering means that the same exact tree merged with a @@ -102,14 +80,47 @@ int cmd_commit_tree(int argc, const char **argv, const char *prefix) strbuf_addch(&buffer, '\n'); /* And add the comment */ - if (strbuf_read(&buffer, 0, 0) < 0) - die("git-commit-tree: read returned %s", strerror(errno)); + strbuf_addstr(&buffer, msg); /* And check the encoding */ if (encoding_is_utf8 && !is_utf8(buffer.buf)) fprintf(stderr, commit_utf8_warn); - if (!write_sha1_file(buffer.buf, buffer.len, commit_type, commit_sha1)) { + return write_sha1_file(buffer.buf, buffer.len, commit_type, ret); +} + +int cmd_commit_tree(int argc, const char **argv, const char *prefix) +{ + int i; + struct commit_list *parents = NULL; + unsigned char tree_sha1[20]; + unsigned char commit_sha1[20]; + struct strbuf buffer = STRBUF_INIT; + + git_config(git_default_config, NULL); + + if (argc < 2) + usage(commit_tree_usage); + if (get_sha1(argv[1], tree_sha1)) + die("Not a valid object name %s", argv[1]); + + for (i = 2; i < argc; i += 2) { + unsigned char sha1[20]; + const char *a, *b; + a = argv[i]; b = argv[i+1]; + if (!b || strcmp(a, "-p")) + usage(commit_tree_usage); + + if (get_sha1(b, sha1)) + die("Not a valid object name %s", b); + check_valid(sha1, OBJ_COMMIT); + new_parent(lookup_commit(sha1), &parents); + } + + if (strbuf_read(&buffer, 0, 0) < 0) + die("git-commit-tree: read returned %s", strerror(errno)); + + if (!commit_tree(buffer.buf, tree_sha1, parents, commit_sha1)) { printf("%s\n", sha1_to_hex(commit_sha1)); return 0; } diff --git a/builtin.h b/builtin.h index 2b01feabcb..05ee56f21b 100644 --- a/builtin.h +++ b/builtin.h @@ -3,6 +3,8 @@ #include "git-compat-util.h" #include "strbuf.h" +#include "cache.h" +#include "commit.h" extern const char git_version_string[]; extern const char git_usage_string[]; @@ -14,6 +16,8 @@ extern void prune_packed_objects(int); extern int read_line_with_nul(char *buf, int size, FILE *file); extern int fmt_merge_msg(int merge_summary, struct strbuf *in, struct strbuf *out); +extern int commit_tree(const char *msg, unsigned char *tree, + struct commit_list *parents, unsigned char *ret); extern int cmd_add(int argc, const char **argv, const char *prefix); extern int cmd_annotate(int argc, const char **argv, const char *prefix); From 1c6669351a47c834cceb75d6044a1aae259fc69f Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Sat, 5 Jul 2008 16:23:58 +0200 Subject: [PATCH 35/95] Fix t7601-merge-pull-config.sh on AIX The test failed on AIX (and likely other OS, such as apparently OSX) where wc -l outputs whitespace. Also, avoid unnecessary eval in conflict_count(). Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t7601-merge-pull-config.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/t/t7601-merge-pull-config.sh b/t/t7601-merge-pull-config.sh index 32585f8e0d..95b4d71c51 100755 --- a/t/t7601-merge-pull-config.sh +++ b/t/t7601-merge-pull-config.sh @@ -70,10 +70,10 @@ test_expect_success 'merge c1 with c2 and c3 (recursive and octopus in pull.octo conflict_count() { - eval $1=`{ + { git diff-files --name-only git ls-files --unmerged - } | wc -l` + } | wc -l } # c4 - c5 @@ -115,15 +115,15 @@ test_expect_success 'merge picks up the best result' ' git config pull.twohead "recursive resolve" && git reset --hard c5 && git merge -s resolve c6 - conflict_count resolve_count && + resolve_count=$(conflict_count) && git reset --hard c5 && git merge -s recursive c6 - conflict_count recursive_count && + recursive_count=$(conflict_count) && git reset --hard c5 && git merge c6 - conflict_count auto_count && - test "$auto_count" = "$recursive_count" && - test "$auto_count" != "$resolve_count" + auto_count=$(conflict_count) && + test $auto_count = $recursive_count && + test $auto_count != $resolve_count ' test_done From 4a588075c54cd5902e5f4d43b9d6b0c31d0f9769 Mon Sep 17 00:00:00 2001 From: Abhijit Menon-Sen Date: Mon, 7 Jul 2008 02:50:10 +0530 Subject: [PATCH 36/95] Add a test for "git stash branch" Make sure that applying the stash to a new branch after a conflicting change doesn't result in an error when you try to commit. Signed-off-by: Abhijit Menon-Sen Signed-off-by: Junio C Hamano --- t/t3903-stash.sh | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/t/t3903-stash.sh b/t/t3903-stash.sh index 54d99ed0c3..8d4804b658 100755 --- a/t/t3903-stash.sh +++ b/t/t3903-stash.sh @@ -117,4 +117,64 @@ test_expect_success 'stash pop' ' test 0 = $(git stash list | wc -l) ' +cat > expect << EOF +diff --git a/file2 b/file2 +new file mode 100644 +index 0000000..1fe912c +--- /dev/null ++++ b/file2 +@@ -0,0 +1 @@ ++bar2 +EOF + +cat > expect1 << EOF +diff --git a/file b/file +index 257cc56..5716ca5 100644 +--- a/file ++++ b/file +@@ -1 +1 @@ +-foo ++bar +EOF + +cat > expect2 << EOF +diff --git a/file b/file +index 7601807..5716ca5 100644 +--- a/file ++++ b/file +@@ -1 +1 @@ +-baz ++bar +diff --git a/file2 b/file2 +new file mode 100644 +index 0000000..1fe912c +--- /dev/null ++++ b/file2 +@@ -0,0 +1 @@ ++bar2 +EOF + +test_expect_success 'stash branch' ' + echo foo > file && + git commit file -m first + echo bar > file && + echo bar2 > file2 && + git add file2 && + git stash && + echo baz > file && + git commit file -m second && + git stash branch stashbranch && + test refs/heads/stashbranch = $(git symbolic-ref HEAD) && + test $(git rev-parse HEAD) = $(git rev-parse master^) && + git diff --cached > output && + test_cmp output expect && + git diff > output && + test_cmp output expect1 && + git add file && + git commit -m alternate\ second && + git diff master..stashbranch > output && + test_cmp output expect2 && + test 0 = $(git stash list | wc -l) +' + test_done From 22568f0a336ac37ae7329c917857b455839d1d09 Mon Sep 17 00:00:00 2001 From: Adam Brewster Date: Sat, 5 Jul 2008 17:26:40 -0400 Subject: [PATCH 37/95] Teach git-bundle to read revision arguments from stdin like git-rev-list. This patch allows the caller to feed the revision parameters to git-bundle from its standard input. This way, a script do not have to worry about limitation of the length of command line. Documentation/git-bundle.txt says that git-bundle takes arguments acceptable to git-rev-list. Obviously some arguments that git-rev-list handles don't make sense for git-bundle (e.g. --bisect) but --stdin is pretty reasonable. Signed-off-by: Adam Brewster Signed-off-by: Junio C Hamano --- bundle.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/bundle.c b/bundle.c index 0ba5df17e1..00b2aabefc 100644 --- a/bundle.c +++ b/bundle.c @@ -178,6 +178,7 @@ int create_bundle(struct bundle_header *header, const char *path, int i, ref_count = 0; char buffer[1024]; struct rev_info revs; + int read_from_stdin = 0; struct child_process rls; FILE *rls_fout; @@ -227,8 +228,16 @@ int create_bundle(struct bundle_header *header, const char *path, /* write references */ argc = setup_revisions(argc, argv, &revs, NULL); - if (argc > 1) - return error("unrecognized argument: %s'", argv[1]); + + for (i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--stdin")) { + if (read_from_stdin++) + die("--stdin given twice?"); + read_revisions_from_stdin(&revs); + continue; + } + return error("unrecognized argument: %s'", argv[i]); + } for (i = 0; i < revs.pending.nr; i++) { struct object_array_entry *e = revs.pending.objects + i; From 22e407951ef2572c1e68a39364fd3c4b649a3495 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Mon, 7 Jul 2008 00:16:38 -0700 Subject: [PATCH 38/95] Teach "am" and "rebase" to mark the original position with ORIG_HEAD "merge" and "reset" leave the original point in history in ORIG_HEAD, which makes it easy to go back to where you were before you inflict a major damage to your history and realize that you do not like the result at all. These days with reflog, we technically do not need to use ORIG_HEAD, but it is a handy way nevertheless. This teaches "am" and "rebase" (all forms --- the vanilla one that uses "am" as its backend, "-m" variant that cherry-picks, and "--interactive") to do the same. The original idea and a partial implementation to do this only for "rebase -m" was by Brian Gernhardt; this extends on his idea. Signed-off-by: Junio C Hamano --- git-am.sh | 1 + git-rebase--interactive.sh | 1 + git-rebase.sh | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/git-am.sh b/git-am.sh index 2c517ede59..fe53608c94 100755 --- a/git-am.sh +++ b/git-am.sh @@ -241,6 +241,7 @@ else : >"$dotest/rebasing" else : >"$dotest/applying" + git update-ref ORIG_HEAD HEAD fi fi diff --git a/git-rebase--interactive.sh b/git-rebase--interactive.sh index a64d9d57ab..02d7e3c7b0 100755 --- a/git-rebase--interactive.sh +++ b/git-rebase--interactive.sh @@ -549,6 +549,7 @@ EOF has_action "$TODO" || die_abort "Nothing to do" + git update-ref ORIG_HEAD $HEAD output git checkout $ONTO && do_rest ;; esac diff --git a/git-rebase.sh b/git-rebase.sh index e2d85eeeab..2597d777d6 100755 --- a/git-rebase.sh +++ b/git-rebase.sh @@ -378,7 +378,7 @@ fi echo "First, rewinding head to replay your work on top of it..." git checkout "$onto^0" >/dev/null 2>&1 || die "could not detach HEAD" -# git reset --hard "$onto^0" +git update-ref ORIG_HEAD $branch # If the $onto is a proper descendant of the tip of the branch, then # we just fast forwarded. From f95ebf74296077d5fdccaa2668edc527841db521 Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Fri, 4 Jul 2008 16:19:52 +0100 Subject: [PATCH 39/95] Allow cherry-picking root commits A root commit couldn't be cherry-picked. But its semantics can be defined as simply merging two trees by overlaying disjoint parts and merging overlapping files without any common ancestor. You should be able to rebase originally independent branches on top of another branch by using this. Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano --- builtin-revert.c | 26 ++++++++++++++++---------- t/t3503-cherry-pick-root.sh | 30 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) create mode 100755 t/t3503-cherry-pick-root.sh diff --git a/builtin-revert.c b/builtin-revert.c index 0270f9b85a..f3d452418c 100644 --- a/builtin-revert.c +++ b/builtin-revert.c @@ -206,6 +206,7 @@ static int merge_recursive(const char *base_sha1, { char buffer[256]; const char *argv[6]; + int i = 0; sprintf(buffer, "GITHEAD_%s", head_sha1); setenv(buffer, head_name, 1); @@ -218,12 +219,13 @@ static int merge_recursive(const char *base_sha1, * and $prev on top of us (when reverting), or the change between * $prev and $commit on top of us (when cherry-picking or replaying). */ - argv[0] = "merge-recursive"; - argv[1] = base_sha1; - argv[2] = "--"; - argv[3] = head_sha1; - argv[4] = next_sha1; - argv[5] = NULL; + argv[i++] = "merge-recursive"; + if (base_sha1) + argv[i++] = base_sha1; + argv[i++] = "--"; + argv[i++] = head_sha1; + argv[i++] = next_sha1; + argv[i++] = NULL; return run_command_v_opt(argv, RUN_COMMAND_NO_STDIN | RUN_GIT_CMD); } @@ -297,9 +299,12 @@ static int revert_or_cherry_pick(int argc, const char **argv) discard_cache(); } - if (!commit->parents) - die ("Cannot %s a root commit", me); - if (commit->parents->next) { + if (!commit->parents) { + if (action == REVERT) + die ("Cannot revert a root commit"); + parent = NULL; + } + else if (commit->parents->next) { /* Reverting or cherry-picking a merge commit */ int cnt; struct commit_list *p; @@ -368,7 +373,8 @@ static int revert_or_cherry_pick(int argc, const char **argv) } } - if (merge_recursive(sha1_to_hex(base->object.sha1), + if (merge_recursive(base == NULL ? + NULL : sha1_to_hex(base->object.sha1), sha1_to_hex(head), "HEAD", sha1_to_hex(next->object.sha1), oneline) || write_cache_as_tree(head, 0, NULL)) { diff --git a/t/t3503-cherry-pick-root.sh b/t/t3503-cherry-pick-root.sh new file mode 100755 index 0000000000..b0faa29918 --- /dev/null +++ b/t/t3503-cherry-pick-root.sh @@ -0,0 +1,30 @@ +#!/bin/sh + +test_description='test cherry-picking a root commit' + +. ./test-lib.sh + +test_expect_success setup ' + + echo first > file1 && + git add file1 && + test_tick && + git commit -m "first" && + + git symbolic-ref HEAD refs/heads/second && + rm .git/index file1 && + echo second > file2 && + git add file2 && + test_tick && + git commit -m "second" + +' + +test_expect_success 'cherry-pick a root commit' ' + + git cherry-pick master && + test first = $(cat file1) + +' + +test_done From 1c7b76be7d620bbaf2e6b8417f04012326bbb9df Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Mon, 7 Jul 2008 19:24:20 +0200 Subject: [PATCH 40/95] Build in merge Mentored-by: Johannes Schindelin Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- Makefile | 2 +- builtin-merge.c | 1153 +++++++++++++++++ builtin.h | 1 + git-merge.sh => contrib/examples/git-merge.sh | 0 git.c | 1 + t/t7602-merge-octopus-many.sh | 2 +- 6 files changed, 1157 insertions(+), 2 deletions(-) create mode 100644 builtin-merge.c rename git-merge.sh => contrib/examples/git-merge.sh (100%) diff --git a/Makefile b/Makefile index bf77292f1c..fbc53e9cb3 100644 --- a/Makefile +++ b/Makefile @@ -240,7 +240,6 @@ SCRIPT_SH += git-lost-found.sh SCRIPT_SH += git-merge-octopus.sh SCRIPT_SH += git-merge-one-file.sh SCRIPT_SH += git-merge-resolve.sh -SCRIPT_SH += git-merge.sh SCRIPT_SH += git-merge-stupid.sh SCRIPT_SH += git-mergetool.sh SCRIPT_SH += git-parse-remote.sh @@ -515,6 +514,7 @@ BUILTIN_OBJS += builtin-ls-remote.o BUILTIN_OBJS += builtin-ls-tree.o BUILTIN_OBJS += builtin-mailinfo.o BUILTIN_OBJS += builtin-mailsplit.o +BUILTIN_OBJS += builtin-merge.o BUILTIN_OBJS += builtin-merge-base.o BUILTIN_OBJS += builtin-merge-file.o BUILTIN_OBJS += builtin-merge-ours.o diff --git a/builtin-merge.c b/builtin-merge.c new file mode 100644 index 0000000000..b2e702a11f --- /dev/null +++ b/builtin-merge.c @@ -0,0 +1,1153 @@ +/* + * Builtin "git merge" + * + * Copyright (c) 2008 Miklos Vajna + * + * Based on git-merge.sh by Junio C Hamano. + */ + +#include "cache.h" +#include "parse-options.h" +#include "builtin.h" +#include "run-command.h" +#include "diff.h" +#include "refs.h" +#include "commit.h" +#include "diffcore.h" +#include "revision.h" +#include "unpack-trees.h" +#include "cache-tree.h" +#include "dir.h" +#include "utf8.h" +#include "log-tree.h" +#include "color.h" + +#define DEFAULT_TWOHEAD (1<<0) +#define DEFAULT_OCTOPUS (1<<1) +#define NO_FAST_FORWARD (1<<2) +#define NO_TRIVIAL (1<<3) + +struct strategy { + const char *name; + unsigned attr; +}; + +static const char * const builtin_merge_usage[] = { + "git-merge [options] ...", + "git-merge [options] HEAD ", + NULL +}; + +static int show_diffstat = 1, option_log, squash; +static int option_commit = 1, allow_fast_forward = 1; +static int allow_trivial = 1, have_message; +static struct strbuf merge_msg; +static struct commit_list *remoteheads; +static unsigned char head[20], stash[20]; +static struct strategy **use_strategies; +static size_t use_strategies_nr, use_strategies_alloc; +static const char *branch; + +static struct strategy all_strategy[] = { + { "recur", NO_TRIVIAL }, + { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL }, + { "octopus", DEFAULT_OCTOPUS }, + { "resolve", 0 }, + { "stupid", 0 }, + { "ours", NO_FAST_FORWARD | NO_TRIVIAL }, + { "subtree", NO_FAST_FORWARD | NO_TRIVIAL }, +}; + +static const char *pull_twohead, *pull_octopus; + +static int option_parse_message(const struct option *opt, + const char *arg, int unset) +{ + struct strbuf *buf = opt->value; + + if (unset) + strbuf_setlen(buf, 0); + else { + strbuf_addf(buf, "%s\n\n", arg); + have_message = 1; + } + return 0; +} + +static struct strategy *get_strategy(const char *name) +{ + int i; + + if (!name) + return NULL; + + for (i = 0; i < ARRAY_SIZE(all_strategy); i++) + if (!strcmp(name, all_strategy[i].name)) + return &all_strategy[i]; + return NULL; +} + +static void append_strategy(struct strategy *s) +{ + ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc); + use_strategies[use_strategies_nr++] = s; +} + +static int option_parse_strategy(const struct option *opt, + const char *name, int unset) +{ + int i; + struct strategy *s; + + if (unset) + return 0; + + s = get_strategy(name); + + if (s) + append_strategy(s); + else { + struct strbuf err; + strbuf_init(&err, 0); + for (i = 0; i < ARRAY_SIZE(all_strategy); i++) + strbuf_addf(&err, " %s", all_strategy[i].name); + fprintf(stderr, "Could not find merge strategy '%s'.\n", name); + fprintf(stderr, "Available strategies are:%s.\n", err.buf); + exit(1); + } + return 0; +} + +static int option_parse_n(const struct option *opt, + const char *arg, int unset) +{ + show_diffstat = unset; + return 0; +} + +static struct option builtin_merge_options[] = { + { OPTION_CALLBACK, 'n', NULL, NULL, NULL, + "do not show a diffstat at the end of the merge", + PARSE_OPT_NOARG, option_parse_n }, + OPT_BOOLEAN(0, "stat", &show_diffstat, + "show a diffstat at the end of the merge"), + OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"), + OPT_BOOLEAN(0, "log", &option_log, + "add list of one-line log to merge commit message"), + OPT_BOOLEAN(0, "squash", &squash, + "create a single commit instead of doing a merge"), + OPT_BOOLEAN(0, "commit", &option_commit, + "perform a commit if the merge succeeds (default)"), + OPT_BOOLEAN(0, "ff", &allow_fast_forward, + "allow fast forward (default)"), + OPT_CALLBACK('s', "strategy", &use_strategies, "strategy", + "merge strategy to use", option_parse_strategy), + OPT_CALLBACK('m', "message", &merge_msg, "message", + "message to be used for the merge commit (if any)", + option_parse_message), + OPT_END() +}; + +/* Cleans up metadata that is uninteresting after a succeeded merge. */ +static void drop_save(void) +{ + unlink(git_path("MERGE_HEAD")); + unlink(git_path("MERGE_MSG")); +} + +static void save_state(void) +{ + int len; + struct child_process cp; + struct strbuf buffer = STRBUF_INIT; + const char *argv[] = {"stash", "create", NULL}; + + memset(&cp, 0, sizeof(cp)); + cp.argv = argv; + cp.out = -1; + cp.git_cmd = 1; + + if (start_command(&cp)) + die("could not run stash."); + len = strbuf_read(&buffer, cp.out, 1024); + close(cp.out); + + if (finish_command(&cp) || len < 0) + die("stash failed"); + else if (!len) + return; + strbuf_setlen(&buffer, buffer.len-1); + if (get_sha1(buffer.buf, stash)) + die("not a valid object: %s", buffer.buf); +} + +static void reset_hard(unsigned const char *sha1, int verbose) +{ + int i = 0; + const char *args[6]; + + args[i++] = "read-tree"; + if (verbose) + args[i++] = "-v"; + args[i++] = "--reset"; + args[i++] = "-u"; + args[i++] = sha1_to_hex(sha1); + args[i] = NULL; + + if (run_command_v_opt(args, RUN_GIT_CMD)) + die("read-tree failed"); +} + +static void restore_state(void) +{ + struct strbuf sb; + const char *args[] = { "stash", "apply", NULL, NULL }; + + if (is_null_sha1(stash)) + return; + + reset_hard(head, 1); + + strbuf_init(&sb, 0); + args[2] = sha1_to_hex(stash); + + /* + * It is OK to ignore error here, for example when there was + * nothing to restore. + */ + run_command_v_opt(args, RUN_GIT_CMD); + + strbuf_release(&sb); + refresh_cache(REFRESH_QUIET); +} + +/* This is called when no merge was necessary. */ +static void finish_up_to_date(const char *msg) +{ + printf("%s%s\n", squash ? " (nothing to squash)" : "", msg); + drop_save(); +} + +static void squash_message(void) +{ + struct rev_info rev; + struct commit *commit; + struct strbuf out; + struct commit_list *j; + int fd; + + printf("Squash commit -- not updating HEAD\n"); + fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666); + if (fd < 0) + die("Could not write to %s", git_path("SQUASH_MSG")); + + init_revisions(&rev, NULL); + rev.ignore_merges = 1; + rev.commit_format = CMIT_FMT_MEDIUM; + + commit = lookup_commit(head); + commit->object.flags |= UNINTERESTING; + add_pending_object(&rev, &commit->object, NULL); + + for (j = remoteheads; j; j = j->next) + add_pending_object(&rev, &j->item->object, NULL); + + setup_revisions(0, NULL, &rev, NULL); + if (prepare_revision_walk(&rev)) + die("revision walk setup failed"); + + strbuf_init(&out, 0); + strbuf_addstr(&out, "Squashed commit of the following:\n"); + while ((commit = get_revision(&rev)) != NULL) { + strbuf_addch(&out, '\n'); + strbuf_addf(&out, "commit %s\n", + sha1_to_hex(commit->object.sha1)); + pretty_print_commit(rev.commit_format, commit, &out, rev.abbrev, + NULL, NULL, rev.date_mode, 0); + } + write(fd, out.buf, out.len); + close(fd); + strbuf_release(&out); +} + +static int run_hook(const char *name) +{ + struct child_process hook; + const char *argv[3], *env[2]; + char index[PATH_MAX]; + + argv[0] = git_path("hooks/%s", name); + if (access(argv[0], X_OK) < 0) + return 0; + + snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", get_index_file()); + env[0] = index; + env[1] = NULL; + + if (squash) + argv[1] = "1"; + else + argv[1] = "0"; + argv[2] = NULL; + + memset(&hook, 0, sizeof(hook)); + hook.argv = argv; + hook.no_stdin = 1; + hook.stdout_to_stderr = 1; + hook.env = env; + + return run_command(&hook); +} + +static void finish(const unsigned char *new_head, const char *msg) +{ + struct strbuf reflog_message; + + strbuf_init(&reflog_message, 0); + if (!msg) + strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION")); + else { + printf("%s\n", msg); + strbuf_addf(&reflog_message, "%s: %s", + getenv("GIT_REFLOG_ACTION"), msg); + } + if (squash) { + squash_message(); + } else { + if (!merge_msg.len) + printf("No merge message -- not updating HEAD\n"); + else { + const char *argv_gc_auto[] = { "gc", "--auto", NULL }; + update_ref(reflog_message.buf, "HEAD", + new_head, head, 0, + DIE_ON_ERR); + /* + * We ignore errors in 'gc --auto', since the + * user should see them. + */ + run_command_v_opt(argv_gc_auto, RUN_GIT_CMD); + } + } + if (new_head && show_diffstat) { + struct diff_options opts; + diff_setup(&opts); + opts.output_format |= + DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT; + opts.detect_rename = DIFF_DETECT_RENAME; + if (diff_use_color_default > 0) + DIFF_OPT_SET(&opts, COLOR_DIFF); + if (diff_setup_done(&opts) < 0) + die("diff_setup_done failed"); + diff_tree_sha1(head, new_head, "", &opts); + diffcore_std(&opts); + diff_flush(&opts); + } + + /* Run a post-merge hook */ + run_hook("post-merge"); + + strbuf_release(&reflog_message); +} + +/* Get the name for the merge commit's message. */ +static void merge_name(const char *remote, struct strbuf *msg) +{ + struct object *remote_head; + unsigned char branch_head[20], buf_sha[20]; + struct strbuf buf; + const char *ptr; + int len, early; + + memset(branch_head, 0, sizeof(branch_head)); + remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT); + if (!remote_head) + die("'%s' does not point to a commit", remote); + + strbuf_init(&buf, 0); + strbuf_addstr(&buf, "refs/heads/"); + strbuf_addstr(&buf, remote); + resolve_ref(buf.buf, branch_head, 0, 0); + + if (!hashcmp(remote_head->sha1, branch_head)) { + strbuf_addf(msg, "%s\t\tbranch '%s' of .\n", + sha1_to_hex(branch_head), remote); + return; + } + + /* See if remote matches ^^^.. or ~ */ + for (len = 0, ptr = remote + strlen(remote); + remote < ptr && ptr[-1] == '^'; + ptr--) + len++; + if (len) + early = 1; + else { + early = 0; + ptr = strrchr(remote, '~'); + if (ptr) { + int seen_nonzero = 0; + + len++; /* count ~ */ + while (*++ptr && isdigit(*ptr)) { + seen_nonzero |= (*ptr != '0'); + len++; + } + if (*ptr) + len = 0; /* not ...~ */ + else if (seen_nonzero) + early = 1; + else if (len == 1) + early = 1; /* "name~" is "name~1"! */ + } + } + if (len) { + struct strbuf truname = STRBUF_INIT; + strbuf_addstr(&truname, "refs/heads/"); + strbuf_addstr(&truname, remote); + strbuf_setlen(&truname, len+11); + if (resolve_ref(truname.buf, buf_sha, 0, 0)) { + strbuf_addf(msg, + "%s\t\tbranch '%s'%s of .\n", + sha1_to_hex(remote_head->sha1), + truname.buf, + (early ? " (early part)" : "")); + return; + } + } + + if (!strcmp(remote, "FETCH_HEAD") && + !access(git_path("FETCH_HEAD"), R_OK)) { + FILE *fp; + struct strbuf line; + char *ptr; + + strbuf_init(&line, 0); + fp = fopen(git_path("FETCH_HEAD"), "r"); + if (!fp) + die("could not open %s for reading: %s", + git_path("FETCH_HEAD"), strerror(errno)); + strbuf_getline(&line, fp, '\n'); + fclose(fp); + ptr = strstr(line.buf, "\tnot-for-merge\t"); + if (ptr) + strbuf_remove(&line, ptr-line.buf+1, 13); + strbuf_addbuf(msg, &line); + strbuf_release(&line); + return; + } + strbuf_addf(msg, "%s\t\tcommit '%s'\n", + sha1_to_hex(remote_head->sha1), remote); +} + +int git_merge_config(const char *k, const char *v, void *cb) +{ + if (branch && !prefixcmp(k, "branch.") && + !prefixcmp(k + 7, branch) && + !strcmp(k + 7 + strlen(branch), ".mergeoptions")) { + const char **argv; + int argc; + char *buf; + + buf = xstrdup(v); + argc = split_cmdline(buf, &argv); + argv = xrealloc(argv, sizeof(*argv) * (argc + 2)); + memmove(argv + 1, argv, sizeof(*argv) * (argc + 1)); + argc++; + parse_options(argc, argv, builtin_merge_options, + builtin_merge_usage, 0); + free(buf); + } + + if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat")) + show_diffstat = git_config_bool(k, v); + else if (!strcmp(k, "pull.twohead")) + return git_config_string(&pull_twohead, k, v); + else if (!strcmp(k, "pull.octopus")) + return git_config_string(&pull_octopus, k, v); + return git_diff_ui_config(k, v, cb); +} + +static int read_tree_trivial(unsigned char *common, unsigned char *head, + unsigned char *one) +{ + int i, nr_trees = 0; + struct tree *trees[MAX_UNPACK_TREES]; + struct tree_desc t[MAX_UNPACK_TREES]; + struct unpack_trees_options opts; + + memset(&opts, 0, sizeof(opts)); + opts.head_idx = 2; + opts.src_index = &the_index; + opts.dst_index = &the_index; + opts.update = 1; + opts.verbose_update = 1; + opts.trivial_merges_only = 1; + opts.merge = 1; + trees[nr_trees] = parse_tree_indirect(common); + if (!trees[nr_trees++]) + return -1; + trees[nr_trees] = parse_tree_indirect(head); + if (!trees[nr_trees++]) + return -1; + trees[nr_trees] = parse_tree_indirect(one); + if (!trees[nr_trees++]) + return -1; + opts.fn = threeway_merge; + cache_tree_free(&active_cache_tree); + for (i = 0; i < nr_trees; i++) { + parse_tree(trees[i]); + init_tree_desc(t+i, trees[i]->buffer, trees[i]->size); + } + if (unpack_trees(nr_trees, t, &opts)) + return -1; + return 0; +} + +static void write_tree_trivial(unsigned char *sha1) +{ + if (write_cache_as_tree(sha1, 0, NULL)) + die("git write-tree failed to write a tree"); +} + +static int try_merge_strategy(const char *strategy, struct commit_list *common, + const char *head_arg) +{ + const char **args; + int i = 0, ret; + struct commit_list *j; + struct strbuf buf; + + args = xmalloc((4 + commit_list_count(common) + + commit_list_count(remoteheads)) * sizeof(char *)); + strbuf_init(&buf, 0); + strbuf_addf(&buf, "merge-%s", strategy); + args[i++] = buf.buf; + for (j = common; j; j = j->next) + args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1)); + args[i++] = "--"; + args[i++] = head_arg; + for (j = remoteheads; j; j = j->next) + args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1)); + args[i] = NULL; + ret = run_command_v_opt(args, RUN_GIT_CMD); + strbuf_release(&buf); + i = 1; + for (j = common; j; j = j->next) + free((void *)args[i++]); + i += 2; + for (j = remoteheads; j; j = j->next) + free((void *)args[i++]); + free(args); + return -ret; +} + +static void count_diff_files(struct diff_queue_struct *q, + struct diff_options *opt, void *data) +{ + int *count = data; + + (*count) += q->nr; +} + +static int count_unmerged_entries(void) +{ + const struct index_state *state = &the_index; + int i, ret = 0; + + for (i = 0; i < state->cache_nr; i++) + if (ce_stage(state->cache[i])) + ret++; + + return ret; +} + +static int checkout_fast_forward(unsigned char *head, unsigned char *remote) +{ + struct tree *trees[MAX_UNPACK_TREES]; + struct unpack_trees_options opts; + struct tree_desc t[MAX_UNPACK_TREES]; + int i, fd, nr_trees = 0; + struct dir_struct dir; + struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file)); + + if (read_cache_unmerged()) + die("you need to resolve your current index first"); + + fd = hold_locked_index(lock_file, 1); + + memset(&trees, 0, sizeof(trees)); + memset(&opts, 0, sizeof(opts)); + memset(&t, 0, sizeof(t)); + dir.show_ignored = 1; + dir.exclude_per_dir = ".gitignore"; + opts.dir = &dir; + + opts.head_idx = 1; + opts.src_index = &the_index; + opts.dst_index = &the_index; + opts.update = 1; + opts.verbose_update = 1; + opts.merge = 1; + opts.fn = twoway_merge; + + trees[nr_trees] = parse_tree_indirect(head); + if (!trees[nr_trees++]) + return -1; + trees[nr_trees] = parse_tree_indirect(remote); + if (!trees[nr_trees++]) + return -1; + for (i = 0; i < nr_trees; i++) { + parse_tree(trees[i]); + init_tree_desc(t+i, trees[i]->buffer, trees[i]->size); + } + if (unpack_trees(nr_trees, t, &opts)) + return -1; + if (write_cache(fd, active_cache, active_nr) || + commit_locked_index(lock_file)) + die("unable to write new index file"); + return 0; +} + +static void split_merge_strategies(const char *string, struct strategy **list, + int *nr, int *alloc) +{ + char *p, *q, *buf; + + if (!string) + return; + + buf = xstrdup(string); + q = buf; + for (;;) { + p = strchr(q, ' '); + if (!p) { + ALLOC_GROW(*list, *nr + 1, *alloc); + (*list)[(*nr)++].name = xstrdup(q); + free(buf); + return; + } else { + *p = '\0'; + ALLOC_GROW(*list, *nr + 1, *alloc); + (*list)[(*nr)++].name = xstrdup(q); + q = ++p; + } + } +} + +static void add_strategies(const char *string, unsigned attr) +{ + struct strategy *list = NULL; + int list_alloc = 0, list_nr = 0, i; + + memset(&list, 0, sizeof(list)); + split_merge_strategies(string, &list, &list_nr, &list_alloc); + if (list != NULL) { + for (i = 0; i < list_nr; i++) { + struct strategy *s; + + s = get_strategy(list[i].name); + if (s) + append_strategy(s); + } + return; + } + for (i = 0; i < ARRAY_SIZE(all_strategy); i++) + if (all_strategy[i].attr & attr) + append_strategy(&all_strategy[i]); + +} + +static int merge_trivial(void) +{ + unsigned char result_tree[20], result_commit[20]; + struct commit_list parent; + + write_tree_trivial(result_tree); + printf("Wonderful.\n"); + parent.item = remoteheads->item; + parent.next = NULL; + commit_tree(merge_msg.buf, result_tree, &parent, result_commit); + finish(result_commit, "In-index merge"); + drop_save(); + return 0; +} + +static int finish_automerge(struct commit_list *common, + unsigned char *result_tree, + const char *wt_strategy) +{ + struct commit_list *parents = NULL, *j; + struct strbuf buf = STRBUF_INIT; + unsigned char result_commit[20]; + + free_commit_list(common); + if (allow_fast_forward) { + parents = remoteheads; + commit_list_insert(lookup_commit(head), &parents); + parents = reduce_heads(parents); + } else { + struct commit_list **pptr = &parents; + + pptr = &commit_list_insert(lookup_commit(head), + pptr)->next; + for (j = remoteheads; j; j = j->next) + pptr = &commit_list_insert(j->item, pptr)->next; + } + free_commit_list(remoteheads); + strbuf_addch(&merge_msg, '\n'); + commit_tree(merge_msg.buf, result_tree, parents, result_commit); + strbuf_addf(&buf, "Merge made by %s.", wt_strategy); + finish(result_commit, buf.buf); + strbuf_release(&buf); + drop_save(); + return 0; +} + +static int suggest_conflicts(void) +{ + FILE *fp; + int pos; + + fp = fopen(git_path("MERGE_MSG"), "a"); + if (!fp) + die("Could open %s for writing", git_path("MERGE_MSG")); + fprintf(fp, "\nConflicts:\n"); + for (pos = 0; pos < active_nr; pos++) { + struct cache_entry *ce = active_cache[pos]; + + if (ce_stage(ce)) { + fprintf(fp, "\t%s\n", ce->name); + while (pos + 1 < active_nr && + !strcmp(ce->name, + active_cache[pos + 1]->name)) + pos++; + } + } + fclose(fp); + rerere(); + printf("Automatic merge failed; " + "fix conflicts and then commit the result.\n"); + return 1; +} + +static struct commit *is_old_style_invocation(int argc, const char **argv) +{ + struct commit *second_token = NULL; + if (argc > 1) { + unsigned char second_sha1[20]; + + if (get_sha1(argv[1], second_sha1)) + return NULL; + second_token = lookup_commit_reference_gently(second_sha1, 0); + if (!second_token) + die("'%s' is not a commit", argv[1]); + if (hashcmp(second_token->object.sha1, head)) + return NULL; + } + return second_token; +} + +static int evaluate_result(void) +{ + int cnt = 0; + struct rev_info rev; + + if (read_cache() < 0) + die("failed to read the cache"); + + /* Check how many files differ. */ + init_revisions(&rev, ""); + setup_revisions(0, NULL, &rev, NULL); + rev.diffopt.output_format |= + DIFF_FORMAT_CALLBACK; + rev.diffopt.format_callback = count_diff_files; + rev.diffopt.format_callback_data = &cnt; + run_diff_files(&rev, 0); + + /* + * Check how many unmerged entries are + * there. + */ + cnt += count_unmerged_entries(); + + return cnt; +} + +int cmd_merge(int argc, const char **argv, const char *prefix) +{ + unsigned char result_tree[20]; + struct strbuf buf; + const char *head_arg; + int flag, head_invalid = 0, i; + int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0; + struct commit_list *common = NULL; + const char *best_strategy = NULL, *wt_strategy = NULL; + struct commit_list **remotes = &remoteheads; + + setup_work_tree(); + if (unmerged_cache()) + die("You are in the middle of a conflicted merge."); + + /* + * Check if we are _not_ on a detached HEAD, i.e. if there is a + * current branch. + */ + branch = resolve_ref("HEAD", head, 0, &flag); + if (branch && !prefixcmp(branch, "refs/heads/")) + branch += 11; + if (is_null_sha1(head)) + head_invalid = 1; + + git_config(git_merge_config, NULL); + + /* for color.ui */ + if (diff_use_color_default == -1) + diff_use_color_default = git_use_color_default; + + argc = parse_options(argc, argv, builtin_merge_options, + builtin_merge_usage, 0); + + if (squash) { + if (!allow_fast_forward) + die("You cannot combine --squash with --no-ff."); + option_commit = 0; + } + + if (!argc) + usage_with_options(builtin_merge_usage, + builtin_merge_options); + + /* + * This could be traditional "merge HEAD ..." and + * the way we can tell it is to see if the second token is HEAD, + * but some people might have misused the interface and used a + * committish that is the same as HEAD there instead. + * Traditional format never would have "-m" so it is an + * additional safety measure to check for it. + */ + strbuf_init(&buf, 0); + + if (!have_message && is_old_style_invocation(argc, argv)) { + strbuf_addstr(&merge_msg, argv[0]); + head_arg = argv[1]; + argv += 2; + argc -= 2; + } else if (head_invalid) { + struct object *remote_head; + /* + * If the merged head is a valid one there is no reason + * to forbid "git merge" into a branch yet to be born. + * We do the same for "git pull". + */ + if (argc != 1) + die("Can merge only exactly one commit into " + "empty head"); + remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT); + if (!remote_head) + die("%s - not something we can merge", argv[0]); + update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0, + DIE_ON_ERR); + reset_hard(remote_head->sha1, 0); + return 0; + } else { + struct strbuf msg; + + /* We are invoked directly as the first-class UI. */ + head_arg = "HEAD"; + + /* + * All the rest are the commits being merged; + * prepare the standard merge summary message to + * be appended to the given message. If remote + * is invalid we will die later in the common + * codepath so we discard the error in this + * loop. + */ + strbuf_init(&msg, 0); + for (i = 0; i < argc; i++) + merge_name(argv[i], &msg); + fmt_merge_msg(option_log, &msg, &merge_msg); + if (merge_msg.len) + strbuf_setlen(&merge_msg, merge_msg.len-1); + } + + if (head_invalid || !argc) + usage_with_options(builtin_merge_usage, + builtin_merge_options); + + strbuf_addstr(&buf, "merge"); + for (i = 0; i < argc; i++) + strbuf_addf(&buf, " %s", argv[i]); + setenv("GIT_REFLOG_ACTION", buf.buf, 0); + strbuf_reset(&buf); + + for (i = 0; i < argc; i++) { + struct object *o; + + o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT); + if (!o) + die("%s - not something we can merge", argv[i]); + remotes = &commit_list_insert(lookup_commit(o->sha1), + remotes)->next; + + strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1)); + setenv(buf.buf, argv[i], 1); + strbuf_reset(&buf); + } + + if (!use_strategies) { + if (!remoteheads->next) + add_strategies(pull_twohead, DEFAULT_TWOHEAD); + else + add_strategies(pull_octopus, DEFAULT_OCTOPUS); + } + + for (i = 0; i < use_strategies_nr; i++) { + if (use_strategies[i]->attr & NO_FAST_FORWARD) + allow_fast_forward = 0; + if (use_strategies[i]->attr & NO_TRIVIAL) + allow_trivial = 0; + } + + if (!remoteheads->next) + common = get_merge_bases(lookup_commit(head), + remoteheads->item, 1); + else { + struct commit_list *list = remoteheads; + commit_list_insert(lookup_commit(head), &list); + common = get_octopus_merge_bases(list); + free(list); + } + + update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0, + DIE_ON_ERR); + + if (!common) + ; /* No common ancestors found. We need a real merge. */ + else if (!remoteheads->next && !common->next && + common->item == remoteheads->item) { + /* + * If head can reach all the merge then we are up to date. + * but first the most common case of merging one remote. + */ + finish_up_to_date("Already up-to-date."); + return 0; + } else if (allow_fast_forward && !remoteheads->next && + !common->next && + !hashcmp(common->item->object.sha1, head)) { + /* Again the most common case of merging one remote. */ + struct strbuf msg; + struct object *o; + char hex[41]; + + strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV)); + + printf("Updating %s..%s\n", + hex, + find_unique_abbrev(remoteheads->item->object.sha1, + DEFAULT_ABBREV)); + refresh_cache(REFRESH_QUIET); + strbuf_init(&msg, 0); + strbuf_addstr(&msg, "Fast forward"); + if (have_message) + strbuf_addstr(&msg, + " (no commit created; -m option ignored)"); + o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1), + 0, NULL, OBJ_COMMIT); + if (!o) + return 1; + + if (checkout_fast_forward(head, remoteheads->item->object.sha1)) + return 1; + + finish(o->sha1, msg.buf); + drop_save(); + return 0; + } else if (!remoteheads->next && common->next) + ; + /* + * We are not doing octopus and not fast forward. Need + * a real merge. + */ + else if (!remoteheads->next && !common->next && option_commit) { + /* + * We are not doing octopus, not fast forward, and have + * only one common. + */ + refresh_cache(REFRESH_QUIET); + if (allow_trivial) { + /* See if it is really trivial. */ + git_committer_info(IDENT_ERROR_ON_NO_NAME); + printf("Trying really trivial in-index merge...\n"); + if (!read_tree_trivial(common->item->object.sha1, + head, remoteheads->item->object.sha1)) + return merge_trivial(); + printf("Nope.\n"); + } + } else { + /* + * An octopus. If we can reach all the remote we are up + * to date. + */ + int up_to_date = 1; + struct commit_list *j; + + for (j = remoteheads; j; j = j->next) { + struct commit_list *common_one; + + /* + * Here we *have* to calculate the individual + * merge_bases again, otherwise "git merge HEAD^ + * HEAD^^" would be missed. + */ + common_one = get_merge_bases(lookup_commit(head), + j->item, 1); + if (hashcmp(common_one->item->object.sha1, + j->item->object.sha1)) { + up_to_date = 0; + break; + } + } + if (up_to_date) { + finish_up_to_date("Already up-to-date. Yeeah!"); + return 0; + } + } + + /* We are going to make a new commit. */ + git_committer_info(IDENT_ERROR_ON_NO_NAME); + + /* + * At this point, we need a real merge. No matter what strategy + * we use, it would operate on the index, possibly affecting the + * working tree, and when resolved cleanly, have the desired + * tree in the index -- this means that the index must be in + * sync with the head commit. The strategies are responsible + * to ensure this. + */ + if (use_strategies_nr != 1) { + /* + * Stash away the local changes so that we can try more + * than one. + */ + save_state(); + } else { + memcpy(stash, null_sha1, 20); + } + + for (i = 0; i < use_strategies_nr; i++) { + int ret; + if (i) { + printf("Rewinding the tree to pristine...\n"); + restore_state(); + } + if (use_strategies_nr != 1) + printf("Trying merge strategy %s...\n", + use_strategies[i]->name); + /* + * Remember which strategy left the state in the working + * tree. + */ + wt_strategy = use_strategies[i]->name; + + ret = try_merge_strategy(use_strategies[i]->name, + common, head_arg); + if (!option_commit && !ret) { + merge_was_ok = 1; + /* + * This is necessary here just to avoid writing + * the tree, but later we will *not* exit with + * status code 1 because merge_was_ok is set. + */ + ret = 1; + } + + if (ret) { + /* + * The backend exits with 1 when conflicts are + * left to be resolved, with 2 when it does not + * handle the given merge at all. + */ + if (ret == 1) { + int cnt = evaluate_result(); + + if (best_cnt <= 0 || cnt <= best_cnt) { + best_strategy = use_strategies[i]->name; + best_cnt = cnt; + } + } + if (merge_was_ok) + break; + else + continue; + } + + /* Automerge succeeded. */ + write_tree_trivial(result_tree); + automerge_was_ok = 1; + break; + } + + /* + * If we have a resulting tree, that means the strategy module + * auto resolved the merge cleanly. + */ + if (automerge_was_ok) + return finish_automerge(common, result_tree, wt_strategy); + + /* + * Pick the result from the best strategy and have the user fix + * it up. + */ + if (!best_strategy) { + restore_state(); + if (use_strategies_nr > 1) + fprintf(stderr, + "No merge strategy handled the merge.\n"); + else + fprintf(stderr, "Merge with strategy %s failed.\n", + use_strategies[0]->name); + return 2; + } else if (best_strategy == wt_strategy) + ; /* We already have its result in the working tree. */ + else { + printf("Rewinding the tree to pristine...\n"); + restore_state(); + printf("Using the %s to prepare resolving by hand.\n", + best_strategy); + try_merge_strategy(best_strategy, common, head_arg); + } + + if (squash) + finish(NULL, NULL); + else { + int fd; + struct commit_list *j; + + for (j = remoteheads; j; j = j->next) + strbuf_addf(&buf, "%s\n", + sha1_to_hex(j->item->object.sha1)); + fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666); + if (fd < 0) + die("Could open %s for writing", + git_path("MERGE_HEAD")); + if (write_in_full(fd, buf.buf, buf.len) != buf.len) + die("Could not write to %s", git_path("MERGE_HEAD")); + close(fd); + strbuf_addch(&merge_msg, '\n'); + fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666); + if (fd < 0) + die("Could open %s for writing", git_path("MERGE_MSG")); + if (write_in_full(fd, merge_msg.buf, merge_msg.len) != + merge_msg.len) + die("Could not write to %s", git_path("MERGE_MSG")); + close(fd); + } + + if (merge_was_ok) { + fprintf(stderr, "Automatic merge went well; " + "stopped before committing as requested\n"); + return 0; + } else + return suggest_conflicts(); +} diff --git a/builtin.h b/builtin.h index 05ee56f21b..0e605d4f4a 100644 --- a/builtin.h +++ b/builtin.h @@ -64,6 +64,7 @@ extern int cmd_ls_tree(int argc, const char **argv, const char *prefix); extern int cmd_ls_remote(int argc, const char **argv, const char *prefix); extern int cmd_mailinfo(int argc, const char **argv, const char *prefix); extern int cmd_mailsplit(int argc, const char **argv, const char *prefix); +extern int cmd_merge(int argc, const char **argv, const char *prefix); extern int cmd_merge_base(int argc, const char **argv, const char *prefix); extern int cmd_merge_ours(int argc, const char **argv, const char *prefix); extern int cmd_merge_file(int argc, const char **argv, const char *prefix); diff --git a/git-merge.sh b/contrib/examples/git-merge.sh similarity index 100% rename from git-merge.sh rename to contrib/examples/git-merge.sh diff --git a/git.c b/git.c index 2fbe96b9ba..770aadd0a4 100644 --- a/git.c +++ b/git.c @@ -271,6 +271,7 @@ static void handle_internal_command(int argc, const char **argv) { "ls-remote", cmd_ls_remote }, { "mailinfo", cmd_mailinfo }, { "mailsplit", cmd_mailsplit }, + { "merge", cmd_merge, RUN_SETUP | NEED_WORK_TREE }, { "merge-base", cmd_merge_base, RUN_SETUP }, { "merge-file", cmd_merge_file }, { "merge-ours", cmd_merge_ours, RUN_SETUP }, diff --git a/t/t7602-merge-octopus-many.sh b/t/t7602-merge-octopus-many.sh index f3a4bb2ea2..fcb8285746 100755 --- a/t/t7602-merge-octopus-many.sh +++ b/t/t7602-merge-octopus-many.sh @@ -23,7 +23,7 @@ test_expect_success 'setup' ' done ' -test_expect_failure 'merge c1 with c2, c3, c4, ... c29' ' +test_expect_success 'merge c1 with c2, c3, c4, ... c29' ' git reset --hard c1 && i=2 && refs="" && From af894943cb9dbad1d6892dc983dc6ac0fa6ca8e8 Mon Sep 17 00:00:00 2001 From: Soeren Finster Date: Mon, 7 Jul 2008 18:50:13 +0200 Subject: [PATCH 41/95] git-gui: Exit shortcut in MacOSX repaired Now, as in all OSX apps, there is only one quit menu entry. It's automatically in the wish menu and calls ::tk::mac::Quit when used. Signed-off-by: Soeren Finster Signed-off-by: Shawn O. Pearce --- git-gui.sh | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/git-gui.sh b/git-gui.sh index d89f156fd5..940677cbd8 100755 --- a/git-gui.sh +++ b/git-gui.sh @@ -1995,9 +1995,13 @@ if {[is_enabled multicommit]} { } } -.mbar.repository add command -label [mc Quit] \ - -command do_quit \ - -accelerator $M1T-Q +if {[is_MacOSX]} { + proc ::tk::mac::Quit {args} { do_quit } +} else { + .mbar.repository add command -label [mc Quit] \ + -command do_quit \ + -accelerator $M1T-Q +} # -- Edit Menu # From 9869099bee332e4c351c3aaa15a74786d85909c7 Mon Sep 17 00:00:00 2001 From: Brian Gernhardt Date: Tue, 8 Jul 2008 00:12:22 -0400 Subject: [PATCH 42/95] Documentation: mention ORIG_HEAD in am, merge, and rebase Merge has always set ORIG_HEAD but never mentioned it, while we recently added it to am and rebase. These facts should be reflected in the documentation. git-reset also sets ORIG_HEAD, but that fact is already mentioned in the very first example so no changes were needed there. Signed-off-by: Brian Gernhardt Signed-off-by: Junio C Hamano --- Documentation/git-am.txt | 6 ++++++ Documentation/git-merge.txt | 4 +++- Documentation/git-rebase.txt | 3 ++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Documentation/git-am.txt b/Documentation/git-am.txt index 3863eebcef..88ca5f1183 100644 --- a/Documentation/git-am.txt +++ b/Documentation/git-am.txt @@ -145,6 +145,12 @@ directory exists, so if you decide to start over from scratch, run `rm -f -r .dotest` before running the command with mailbox names. +Before any patches are applied, ORIG_HEAD is set to the tip of the +current branch. This is useful if you have problems with multiple +commits, like running 'git am' on the wrong branch or an error in the +commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines). + SEE ALSO -------- diff --git a/Documentation/git-merge.txt b/Documentation/git-merge.txt index 62f99b5f3b..019e4ca8f5 100644 --- a/Documentation/git-merge.txt +++ b/Documentation/git-merge.txt @@ -81,7 +81,9 @@ Otherwise, merge will refuse to do any harm to your repository (that is, it may fetch the objects from remote, and it may even update the local branch used to keep track of the remote branch with `git pull remote rbranch:lbranch`, but your working tree, -`.git/HEAD` pointer and index file are left intact). +`.git/HEAD` pointer and index file are left intact). In addition, +merge always sets `.git/ORIG_HEAD` to the original state of HEAD so +a problematic merge can be removed by using `git reset ORIG_HEAD`. You may have local modifications in the working tree files. In other words, 'git-diff' is allowed to report changes. diff --git a/Documentation/git-rebase.txt b/Documentation/git-rebase.txt index f3459c7de7..e30f6a6982 100644 --- a/Documentation/git-rebase.txt +++ b/Documentation/git-rebase.txt @@ -26,7 +26,8 @@ of commits that would be shown by `git log ..HEAD`. The current branch is reset to , or if the --onto option was supplied. This has the exact same effect as -`git reset --hard ` (or ). +`git reset --hard ` (or ). ORIG_HEAD is set +to point at the tip of the branch before the reset. The commits that were previously saved into the temporary area are then reapplied to the current branch, one by one, in order. Note that From caf1899699b2255111a3db335553e31f3718c1c9 Mon Sep 17 00:00:00 2001 From: Eric Raible Date: Tue, 8 Jul 2008 00:40:56 -0700 Subject: [PATCH 43/95] Documentation: tweak use case in "git stash save --keep-index" The documentation suggests using "git stash apply" in the --keep-index workflow even though doing so will lead to clutter in the stash. And given that the changes are about to be committed anyway "git stash pop" is more sensible. Additionally the text preceeding the example claims that it works for "two or more commits", but the example itself is really tailored for just two. Expanding it just a little makes it clear how the procedure generalizes to N commits. Finally the example is annotated with some commentary to explain things on a line-by-line basis. --- Documentation/git-stash.txt | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Documentation/git-stash.txt b/Documentation/git-stash.txt index 8f331ee7d4..e2c8722376 100644 --- a/Documentation/git-stash.txt +++ b/Documentation/git-stash.txt @@ -180,13 +180,14 @@ each change before committing: + ---------------------------------------------------------------- ... hack hack hack ... -$ git add --patch foo -$ git stash save --keep-index -$ build && run tests -$ git commit -m 'First part' -$ git stash apply -$ build && run tests -$ git commit -a -m 'Second part' +$ git add --patch foo # add just first part to the index +$ git stash save --keep-index # save all other changes to the stash +$ edit/build/test first part +$ git commit foo -m 'First part' # commit fully tested change +$ git stash pop # prepare to work on all other changes +... repeat above five steps until one commit remains ... +$ edit/build/test remaining parts +$ git commit foo -m 'Remaining parts' ---------------------------------------------------------------- SEE ALSO From 02e542206f26cf06817ec2e9ffecf4f416e8e332 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Tue, 8 Jul 2008 15:19:33 +0200 Subject: [PATCH 44/95] revisions: split handle_revision_opt() from setup_revisions() Add two fields to struct rev_info: - .def to store --default argument; and - .show_merge 1-bit field. handle_revision_opt() is able to deal with any revision option, and consumes them, and leaves revision arguments or pseudo arguments (like --all, --not, ...) in place. For now setup_revisions() does a pass of handle_revision_opt() again so that code not using it in a parse-opt parser still work the same. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- revision.c | 548 ++++++++++++++++++++++------------------------------- revision.h | 4 + 2 files changed, 226 insertions(+), 326 deletions(-) diff --git a/revision.c b/revision.c index 5a1a948a41..4b6925be08 100644 --- a/revision.c +++ b/revision.c @@ -957,6 +957,212 @@ static void add_ignore_packed(struct rev_info *revs, const char *name) revs->ignore_packed[num] = NULL; } +int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, + int *unkc, const char **unkv) +{ + const char *arg = argv[0]; + + /* pseudo revision arguments */ + if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") || + !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") || + !strcmp(arg, "--reflog") || !strcmp(arg, "--not") || + !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk")) + { + unkv[(*unkc)++] = arg; + return 0; + } + + if (!prefixcmp(arg, "--max-count=")) { + revs->max_count = atoi(arg + 12); + } else if (!prefixcmp(arg, "--skip=")) { + revs->skip_count = atoi(arg + 7); + } else if ((*arg == '-') && isdigit(arg[1])) { + /* accept -, like traditional "head" */ + revs->max_count = atoi(arg + 1); + } else if (!strcmp(arg, "-n")) { + if (argc <= 1) + return error("-n requires an argument"); + revs->max_count = atoi(argv[1]); + return 2; + } else if (!prefixcmp(arg, "-n")) { + revs->max_count = atoi(arg + 2); + } else if (!prefixcmp(arg, "--max-age=")) { + revs->max_age = atoi(arg + 10); + } else if (!prefixcmp(arg, "--since=")) { + revs->max_age = approxidate(arg + 8); + } else if (!prefixcmp(arg, "--after=")) { + revs->max_age = approxidate(arg + 8); + } else if (!prefixcmp(arg, "--min-age=")) { + revs->min_age = atoi(arg + 10); + } else if (!prefixcmp(arg, "--before=")) { + revs->min_age = approxidate(arg + 9); + } else if (!prefixcmp(arg, "--until=")) { + revs->min_age = approxidate(arg + 8); + } else if (!strcmp(arg, "--first-parent")) { + revs->first_parent_only = 1; + } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) { + init_reflog_walk(&revs->reflog_info); + } else if (!strcmp(arg, "--default")) { + if (argc <= 1) + return error("bad --default argument"); + revs->def = argv[1]; + return 2; + } else if (!strcmp(arg, "--merge")) { + revs->show_merge = 1; + } else if (!strcmp(arg, "--topo-order")) { + revs->lifo = 1; + revs->topo_order = 1; + } else if (!strcmp(arg, "--date-order")) { + revs->lifo = 0; + revs->topo_order = 1; + } else if (!prefixcmp(arg, "--early-output")) { + int count = 100; + switch (arg[14]) { + case '=': + count = atoi(arg+15); + /* Fallthrough */ + case 0: + revs->topo_order = 1; + revs->early_output = count; + } + } else if (!strcmp(arg, "--parents")) { + revs->rewrite_parents = 1; + revs->print_parents = 1; + } else if (!strcmp(arg, "--dense")) { + revs->dense = 1; + } else if (!strcmp(arg, "--sparse")) { + revs->dense = 0; + } else if (!strcmp(arg, "--show-all")) { + revs->show_all = 1; + } else if (!strcmp(arg, "--remove-empty")) { + revs->remove_empty_trees = 1; + } else if (!strcmp(arg, "--no-merges")) { + revs->no_merges = 1; + } else if (!strcmp(arg, "--boundary")) { + revs->boundary = 1; + } else if (!strcmp(arg, "--left-right")) { + revs->left_right = 1; + } else if (!strcmp(arg, "--cherry-pick")) { + revs->cherry_pick = 1; + revs->limited = 1; + } else if (!strcmp(arg, "--objects")) { + revs->tag_objects = 1; + revs->tree_objects = 1; + revs->blob_objects = 1; + } else if (!strcmp(arg, "--objects-edge")) { + revs->tag_objects = 1; + revs->tree_objects = 1; + revs->blob_objects = 1; + revs->edge_hint = 1; + } else if (!strcmp(arg, "--unpacked")) { + revs->unpacked = 1; + free(revs->ignore_packed); + revs->ignore_packed = NULL; + revs->num_ignore_packed = 0; + } else if (!prefixcmp(arg, "--unpacked=")) { + revs->unpacked = 1; + add_ignore_packed(revs, arg+11); + } else if (!strcmp(arg, "-r")) { + revs->diff = 1; + DIFF_OPT_SET(&revs->diffopt, RECURSIVE); + } else if (!strcmp(arg, "-t")) { + revs->diff = 1; + DIFF_OPT_SET(&revs->diffopt, RECURSIVE); + DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE); + } else if (!strcmp(arg, "-m")) { + revs->ignore_merges = 0; + } else if (!strcmp(arg, "-c")) { + revs->diff = 1; + revs->dense_combined_merges = 0; + revs->combine_merges = 1; + } else if (!strcmp(arg, "--cc")) { + revs->diff = 1; + revs->dense_combined_merges = 1; + revs->combine_merges = 1; + } else if (!strcmp(arg, "-v")) { + revs->verbose_header = 1; + } else if (!strcmp(arg, "--pretty")) { + revs->verbose_header = 1; + get_commit_format(arg+8, revs); + } else if (!prefixcmp(arg, "--pretty=")) { + revs->verbose_header = 1; + get_commit_format(arg+9, revs); + } else if (!strcmp(arg, "--graph")) { + revs->topo_order = 1; + revs->rewrite_parents = 1; + revs->graph = graph_init(revs); + } else if (!strcmp(arg, "--root")) { + revs->show_root_diff = 1; + } else if (!strcmp(arg, "--no-commit-id")) { + revs->no_commit_id = 1; + } else if (!strcmp(arg, "--always")) { + revs->always_show_header = 1; + } else if (!strcmp(arg, "--no-abbrev")) { + revs->abbrev = 0; + } else if (!strcmp(arg, "--abbrev")) { + revs->abbrev = DEFAULT_ABBREV; + } else if (!prefixcmp(arg, "--abbrev=")) { + revs->abbrev = strtoul(arg + 9, NULL, 10); + if (revs->abbrev < MINIMUM_ABBREV) + revs->abbrev = MINIMUM_ABBREV; + else if (revs->abbrev > 40) + revs->abbrev = 40; + } else if (!strcmp(arg, "--abbrev-commit")) { + revs->abbrev_commit = 1; + } else if (!strcmp(arg, "--full-diff")) { + revs->diff = 1; + revs->full_diff = 1; + } else if (!strcmp(arg, "--full-history")) { + revs->simplify_history = 0; + } else if (!strcmp(arg, "--relative-date")) { + revs->date_mode = DATE_RELATIVE; + } else if (!strncmp(arg, "--date=", 7)) { + revs->date_mode = parse_date_format(arg + 7); + } else if (!strcmp(arg, "--log-size")) { + revs->show_log_size = 1; + } + /* + * Grepping the commit log + */ + else if (!prefixcmp(arg, "--author=")) { + add_header_grep(revs, "author", arg+9); + } else if (!prefixcmp(arg, "--committer=")) { + add_header_grep(revs, "committer", arg+12); + } else if (!prefixcmp(arg, "--grep=")) { + add_message_grep(revs, arg+7); + } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) { + if (revs->grep_filter) + revs->grep_filter->regflags |= REG_EXTENDED; + } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) { + if (revs->grep_filter) + revs->grep_filter->regflags |= REG_ICASE; + } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) { + if (revs->grep_filter) + revs->grep_filter->fixed = 1; + } else if (!strcmp(arg, "--all-match")) { + if (revs->grep_filter) + revs->grep_filter->all_match = 1; + } else if (!prefixcmp(arg, "--encoding=")) { + arg += 11; + if (strcmp(arg, "none")) + git_log_output_encoding = xstrdup(arg); + else + git_log_output_encoding = ""; + } else if (!strcmp(arg, "--reverse")) { + revs->reverse ^= 1; + } else if (!strcmp(arg, "--children")) { + revs->children.name = "children"; + revs->limited = 1; + } else { + int opts = diff_opt_parse(&revs->diffopt, argv, argc); + if (!opts) + unkv[(*unkc)++] = arg; + return opts; + } + + return 1; +} + /* * Parse revision information, filling in the "rev_info" structure, * and removing the used arguments from the argument list. @@ -966,12 +1172,7 @@ static void add_ignore_packed(struct rev_info *revs, const char *name) */ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const char *def) { - int i, flags, seen_dashdash, show_merge; - const char **unrecognized = argv + 1; - int left = 1; - int all_match = 0; - int regflags = 0; - int fixed = 0; + int i, flags, left, seen_dashdash; /* First, search for "--" */ seen_dashdash = 0; @@ -987,58 +1188,13 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch break; } - flags = show_merge = 0; - for (i = 1; i < argc; i++) { + /* Second, deal with arguments and options */ + flags = 0; + for (left = i = 1; i < argc; i++) { const char *arg = argv[i]; if (*arg == '-') { int opts; - if (!prefixcmp(arg, "--max-count=")) { - revs->max_count = atoi(arg + 12); - continue; - } - if (!prefixcmp(arg, "--skip=")) { - revs->skip_count = atoi(arg + 7); - continue; - } - /* accept -, like traditional "head" */ - if ((*arg == '-') && isdigit(arg[1])) { - revs->max_count = atoi(arg + 1); - continue; - } - if (!strcmp(arg, "-n")) { - if (argc <= i + 1) - die("-n requires an argument"); - revs->max_count = atoi(argv[++i]); - continue; - } - if (!prefixcmp(arg, "-n")) { - revs->max_count = atoi(arg + 2); - continue; - } - if (!prefixcmp(arg, "--max-age=")) { - revs->max_age = atoi(arg + 10); - continue; - } - if (!prefixcmp(arg, "--since=")) { - revs->max_age = approxidate(arg + 8); - continue; - } - if (!prefixcmp(arg, "--after=")) { - revs->max_age = approxidate(arg + 8); - continue; - } - if (!prefixcmp(arg, "--min-age=")) { - revs->min_age = atoi(arg + 10); - continue; - } - if (!prefixcmp(arg, "--before=")) { - revs->min_age = approxidate(arg + 9); - continue; - } - if (!prefixcmp(arg, "--until=")) { - revs->min_age = approxidate(arg + 8); - continue; - } + if (!strcmp(arg, "--all")) { handle_refs(revs, flags, for_each_ref); continue; @@ -1055,265 +1211,14 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch handle_refs(revs, flags, for_each_remote_ref); continue; } - if (!strcmp(arg, "--first-parent")) { - revs->first_parent_only = 1; - continue; - } if (!strcmp(arg, "--reflog")) { handle_reflog(revs, flags); continue; } - if (!strcmp(arg, "-g") || - !strcmp(arg, "--walk-reflogs")) { - init_reflog_walk(&revs->reflog_info); - continue; - } if (!strcmp(arg, "--not")) { flags ^= UNINTERESTING; continue; } - if (!strcmp(arg, "--default")) { - if (++i >= argc) - die("bad --default argument"); - def = argv[i]; - continue; - } - if (!strcmp(arg, "--merge")) { - show_merge = 1; - continue; - } - if (!strcmp(arg, "--topo-order")) { - revs->lifo = 1; - revs->topo_order = 1; - continue; - } - if (!strcmp(arg, "--date-order")) { - revs->lifo = 0; - revs->topo_order = 1; - continue; - } - if (!prefixcmp(arg, "--early-output")) { - int count = 100; - switch (arg[14]) { - case '=': - count = atoi(arg+15); - /* Fallthrough */ - case 0: - revs->topo_order = 1; - revs->early_output = count; - continue; - } - } - if (!strcmp(arg, "--parents")) { - revs->rewrite_parents = 1; - revs->print_parents = 1; - continue; - } - if (!strcmp(arg, "--dense")) { - revs->dense = 1; - continue; - } - if (!strcmp(arg, "--sparse")) { - revs->dense = 0; - continue; - } - if (!strcmp(arg, "--show-all")) { - revs->show_all = 1; - continue; - } - if (!strcmp(arg, "--remove-empty")) { - revs->remove_empty_trees = 1; - continue; - } - if (!strcmp(arg, "--no-merges")) { - revs->no_merges = 1; - continue; - } - if (!strcmp(arg, "--boundary")) { - revs->boundary = 1; - continue; - } - if (!strcmp(arg, "--left-right")) { - revs->left_right = 1; - continue; - } - if (!strcmp(arg, "--cherry-pick")) { - revs->cherry_pick = 1; - revs->limited = 1; - continue; - } - if (!strcmp(arg, "--objects")) { - revs->tag_objects = 1; - revs->tree_objects = 1; - revs->blob_objects = 1; - continue; - } - if (!strcmp(arg, "--objects-edge")) { - revs->tag_objects = 1; - revs->tree_objects = 1; - revs->blob_objects = 1; - revs->edge_hint = 1; - continue; - } - if (!strcmp(arg, "--unpacked")) { - revs->unpacked = 1; - free(revs->ignore_packed); - revs->ignore_packed = NULL; - revs->num_ignore_packed = 0; - continue; - } - if (!prefixcmp(arg, "--unpacked=")) { - revs->unpacked = 1; - add_ignore_packed(revs, arg+11); - continue; - } - if (!strcmp(arg, "-r")) { - revs->diff = 1; - DIFF_OPT_SET(&revs->diffopt, RECURSIVE); - continue; - } - if (!strcmp(arg, "-t")) { - revs->diff = 1; - DIFF_OPT_SET(&revs->diffopt, RECURSIVE); - DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE); - continue; - } - if (!strcmp(arg, "-m")) { - revs->ignore_merges = 0; - continue; - } - if (!strcmp(arg, "-c")) { - revs->diff = 1; - revs->dense_combined_merges = 0; - revs->combine_merges = 1; - continue; - } - if (!strcmp(arg, "--cc")) { - revs->diff = 1; - revs->dense_combined_merges = 1; - revs->combine_merges = 1; - continue; - } - if (!strcmp(arg, "-v")) { - revs->verbose_header = 1; - continue; - } - if (!strcmp(arg, "--pretty")) { - revs->verbose_header = 1; - get_commit_format(arg+8, revs); - continue; - } - if (!prefixcmp(arg, "--pretty=")) { - revs->verbose_header = 1; - get_commit_format(arg+9, revs); - continue; - } - if (!strcmp(arg, "--graph")) { - revs->topo_order = 1; - revs->rewrite_parents = 1; - revs->graph = graph_init(revs); - continue; - } - if (!strcmp(arg, "--root")) { - revs->show_root_diff = 1; - continue; - } - if (!strcmp(arg, "--no-commit-id")) { - revs->no_commit_id = 1; - continue; - } - if (!strcmp(arg, "--always")) { - revs->always_show_header = 1; - continue; - } - if (!strcmp(arg, "--no-abbrev")) { - revs->abbrev = 0; - continue; - } - if (!strcmp(arg, "--abbrev")) { - revs->abbrev = DEFAULT_ABBREV; - continue; - } - if (!prefixcmp(arg, "--abbrev=")) { - revs->abbrev = strtoul(arg + 9, NULL, 10); - if (revs->abbrev < MINIMUM_ABBREV) - revs->abbrev = MINIMUM_ABBREV; - else if (revs->abbrev > 40) - revs->abbrev = 40; - continue; - } - if (!strcmp(arg, "--abbrev-commit")) { - revs->abbrev_commit = 1; - continue; - } - if (!strcmp(arg, "--full-diff")) { - revs->diff = 1; - revs->full_diff = 1; - continue; - } - if (!strcmp(arg, "--full-history")) { - revs->simplify_history = 0; - continue; - } - if (!strcmp(arg, "--relative-date")) { - revs->date_mode = DATE_RELATIVE; - continue; - } - if (!strncmp(arg, "--date=", 7)) { - revs->date_mode = parse_date_format(arg + 7); - continue; - } - if (!strcmp(arg, "--log-size")) { - revs->show_log_size = 1; - continue; - } - - /* - * Grepping the commit log - */ - if (!prefixcmp(arg, "--author=")) { - add_header_grep(revs, "author", arg+9); - continue; - } - if (!prefixcmp(arg, "--committer=")) { - add_header_grep(revs, "committer", arg+12); - continue; - } - if (!prefixcmp(arg, "--grep=")) { - add_message_grep(revs, arg+7); - continue; - } - if (!strcmp(arg, "--extended-regexp") || - !strcmp(arg, "-E")) { - regflags |= REG_EXTENDED; - continue; - } - if (!strcmp(arg, "--regexp-ignore-case") || - !strcmp(arg, "-i")) { - regflags |= REG_ICASE; - continue; - } - if (!strcmp(arg, "--fixed-strings") || - !strcmp(arg, "-F")) { - fixed = 1; - continue; - } - if (!strcmp(arg, "--all-match")) { - all_match = 1; - continue; - } - if (!prefixcmp(arg, "--encoding=")) { - arg += 11; - if (strcmp(arg, "none")) - git_log_output_encoding = xstrdup(arg); - else - git_log_output_encoding = ""; - continue; - } - if (!strcmp(arg, "--reverse")) { - revs->reverse ^= 1; - continue; - } if (!strcmp(arg, "--no-walk")) { revs->no_walk = 1; continue; @@ -1322,19 +1227,14 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch revs->no_walk = 0; continue; } - if (!strcmp(arg, "--children")) { - revs->children.name = "children"; - revs->limited = 1; - continue; - } - opts = diff_opt_parse(&revs->diffopt, argv+i, argc-i); + opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv); if (opts > 0) { i += opts - 1; continue; } - *unrecognized++ = arg; - left++; + if (opts < 0) + exit(128); continue; } @@ -1358,21 +1258,18 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch } } - if (revs->grep_filter) { - revs->grep_filter->regflags |= regflags; - revs->grep_filter->fixed = fixed; - } - - if (show_merge) + if (revs->def == NULL) + revs->def = def; + if (revs->show_merge) prepare_show_merge(revs); - if (def && !revs->pending.nr) { + if (revs->def && !revs->pending.nr) { unsigned char sha1[20]; struct object *object; unsigned mode; - if (get_sha1_with_mode(def, sha1, &mode)) - die("bad default revision '%s'", def); - object = get_reference(revs, def, sha1, 0); - add_pending_object_with_mode(revs, object, def, mode); + if (get_sha1_with_mode(revs->def, sha1, &mode)) + die("bad default revision '%s'", revs->def); + object = get_reference(revs, revs->def, sha1, 0); + add_pending_object_with_mode(revs, object, revs->def, mode); } /* Did the user ask for any diff output? Run the diff! */ @@ -1406,7 +1303,6 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch die("diff_setup_done failed"); if (revs->grep_filter) { - revs->grep_filter->all_match = all_match; compile_grep_patterns(revs->grep_filter); } diff --git a/revision.h b/revision.h index dcf08e089a..c44498e3b3 100644 --- a/revision.h +++ b/revision.h @@ -25,6 +25,7 @@ struct rev_info { /* Basic information */ const char *prefix; + const char *def; void *prune_data; unsigned int early_output; @@ -65,6 +66,7 @@ struct rev_info { /* Format info */ unsigned int shown_one:1, + show_merge:1, abbrev_commit:1, use_terminator:1, missing_newline:1; @@ -117,6 +119,8 @@ volatile show_early_output_fn_t show_early_output; extern void init_revisions(struct rev_info *revs, const char *prefix); extern int setup_revisions(int argc, const char **argv, struct rev_info *revs, const char *def); +extern int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, + int *unkc, const char **unkv); extern int handle_revision_arg(const char *arg, struct rev_info *revs,int flags,int cant_be_filename); extern int prepare_revision_walk(struct rev_info *revs); From 5817da01434a24e693ea4d5ba6680d488f5f543f Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Tue, 8 Jul 2008 15:19:34 +0200 Subject: [PATCH 45/95] git-blame: migrate to incremental parse-option [1/2] This step merely moves the parser to an incremental version, still using parse_revisions. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- builtin-blame.c | 220 ++++++++++++++++++++++++++---------------------- 1 file changed, 118 insertions(+), 102 deletions(-) diff --git a/builtin-blame.c b/builtin-blame.c index cf41511c79..5e82cd3d54 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -18,24 +18,16 @@ #include "cache-tree.h" #include "path-list.h" #include "mailmap.h" +#include "parse-options.h" -static char blame_usage[] = -"git-blame [-c] [-b] [-l] [--root] [-t] [-f] [-n] [-s] [-p] [-w] [-L n,m] [-S ] [-M] [-C] [-C] [--contents ] [--incremental] [commit] [--] file\n" -" -c Use the same output mode as git-annotate (Default: off)\n" -" -b Show blank SHA-1 for boundary commits (Default: off)\n" -" -l Show long commit SHA1 (Default: off)\n" -" --root Do not treat root commits as boundaries (Default: off)\n" -" -t Show raw timestamp (Default: off)\n" -" -f, --show-name Show original filename (Default: auto)\n" -" -n, --show-number Show original linenumber (Default: off)\n" -" -s Suppress author name and timestamp (Default: off)\n" -" -p, --porcelain Show in a format designed for machine consumption\n" -" -w Ignore whitespace differences\n" -" -L n,m Process only line range n,m, counting from 1\n" -" -M, -C Find line movements within and across files\n" -" --incremental Show blame entries as we find them, incrementally\n" -" --contents file Use 's contents as the final image\n" -" -S revs-file Use revisions from revs-file instead of calling git-rev-list\n"; +static char blame_usage[] = "git-blame [options] [rev-opts] [rev] [--] file"; + +static const char *blame_opt_usage[] = { + blame_usage, + "", + "[rev-opts] are documented in git-rev-parse(1)", + NULL +}; static int longest_file; static int longest_author; @@ -2219,6 +2211,50 @@ static const char *prepare_initial(struct scoreboard *sb) return final_commit_name; } +static int blame_copy_callback(const struct option *option, const char *arg, int unset) +{ + int *opt = option->value; + + /* + * -C enables copy from removed files; + * -C -C enables copy from existing files, but only + * when blaming a new file; + * -C -C -C enables copy from existing files for + * everybody + */ + if (*opt & PICKAXE_BLAME_COPY_HARDER) + *opt |= PICKAXE_BLAME_COPY_HARDEST; + if (*opt & PICKAXE_BLAME_COPY) + *opt |= PICKAXE_BLAME_COPY_HARDER; + *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE; + + if (arg) + blame_copy_score = parse_score(arg); + return 0; +} + +static int blame_move_callback(const struct option *option, const char *arg, int unset) +{ + int *opt = option->value; + + *opt |= PICKAXE_BLAME_MOVE; + + if (arg) + blame_move_score = parse_score(arg); + return 0; +} + +static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset) +{ + const char **bottomtop = option->value; + if (!arg) + return -1; + if (*bottomtop) + die("More than one '-L n,m' option given"); + *bottomtop = arg; + return 0; +} + int cmd_blame(int argc, const char **argv, const char *prefix) { struct rev_info revs; @@ -2226,98 +2262,79 @@ int cmd_blame(int argc, const char **argv, const char *prefix) struct scoreboard sb; struct origin *o; struct blame_entry *ent; - int i, seen_dashdash, unk, opt; + int i, seen_dashdash, unk; long bottom, top, lno; - int output_option = 0; - int show_stats = 0; - const char *revs_file = NULL; const char *final_commit_name = NULL; enum object_type type; - const char *bottomtop = NULL; - const char *contents_from = NULL; + + static const char *bottomtop = NULL; + static int output_option = 0, opt = 0; + static int show_stats = 0; + static const char *revs_file = NULL; + static const char *contents_from = NULL; + static const struct option options[] = { + OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"), + OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"), + OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"), + OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"), + OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE), + OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME), + OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER), + OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN), + OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT), + OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP), + OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME), + OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR), + OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE), + OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from instead of calling git-rev-list"), + OPT_STRING(0, "contents", &contents_from, "file", "Use 's contents as the final image"), + { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback }, + { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback }, + OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback), + OPT_END() + }; + + struct parse_opt_ctx_t ctx; cmd_is_annotate = !strcmp(argv[0], "annotate"); git_config(git_blame_config, NULL); + init_revisions(&revs, NULL); save_commit_buffer = 0; - opt = 0; + parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH | + PARSE_OPT_KEEP_ARGV0); + for (;;) { + int n; + + switch (parse_options_step(&ctx, options, blame_opt_usage)) { + case PARSE_OPT_HELP: + exit(129); + case PARSE_OPT_DONE: + goto parse_done; + } + + if (!strcmp(ctx.argv[0], "--reverse")) { + ctx.argv[0] = "--children"; + reverse = 1; + } + n = handle_revision_opt(&revs, ctx.argc, ctx.argv, + &ctx.cpidx, ctx.out); + if (n <= 0) { + error("unknown option `%s'", ctx.argv[0]); + usage_with_options(blame_opt_usage, options); + } + ctx.argv += n; + ctx.argc -= n; + } +parse_done: + argc = parse_options_end(&ctx); + seen_dashdash = 0; for (unk = i = 1; i < argc; i++) { const char *arg = argv[i]; if (*arg != '-') break; - else if (!strcmp("-b", arg)) - blank_boundary = 1; - else if (!strcmp("--root", arg)) - show_root = 1; - else if (!strcmp("--reverse", arg)) { - argv[unk++] = "--children"; - reverse = 1; - } - else if (!strcmp(arg, "--show-stats")) - show_stats = 1; - else if (!strcmp("-c", arg)) - output_option |= OUTPUT_ANNOTATE_COMPAT; - else if (!strcmp("-t", arg)) - output_option |= OUTPUT_RAW_TIMESTAMP; - else if (!strcmp("-l", arg)) - output_option |= OUTPUT_LONG_OBJECT_NAME; - else if (!strcmp("-s", arg)) - output_option |= OUTPUT_NO_AUTHOR; - else if (!strcmp("-w", arg)) - xdl_opts |= XDF_IGNORE_WHITESPACE; - else if (!strcmp("-S", arg) && ++i < argc) - revs_file = argv[i]; - else if (!prefixcmp(arg, "-M")) { - opt |= PICKAXE_BLAME_MOVE; - blame_move_score = parse_score(arg+2); - } - else if (!prefixcmp(arg, "-C")) { - /* - * -C enables copy from removed files; - * -C -C enables copy from existing files, but only - * when blaming a new file; - * -C -C -C enables copy from existing files for - * everybody - */ - if (opt & PICKAXE_BLAME_COPY_HARDER) - opt |= PICKAXE_BLAME_COPY_HARDEST; - if (opt & PICKAXE_BLAME_COPY) - opt |= PICKAXE_BLAME_COPY_HARDER; - opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE; - blame_copy_score = parse_score(arg+2); - } - else if (!prefixcmp(arg, "-L")) { - if (!arg[2]) { - if (++i >= argc) - usage(blame_usage); - arg = argv[i]; - } - else - arg += 2; - if (bottomtop) - die("More than one '-L n,m' option given"); - bottomtop = arg; - } - else if (!strcmp("--contents", arg)) { - if (++i >= argc) - usage(blame_usage); - contents_from = argv[i]; - } - else if (!strcmp("--incremental", arg)) - incremental = 1; - else if (!strcmp("--score-debug", arg)) - output_option |= OUTPUT_SHOW_SCORE; - else if (!strcmp("-f", arg) || - !strcmp("--show-name", arg)) - output_option |= OUTPUT_SHOW_NAME; - else if (!strcmp("-n", arg) || - !strcmp("--show-number", arg)) - output_option |= OUTPUT_SHOW_NUMBER; - else if (!strcmp("-p", arg) || - !strcmp("--porcelain", arg)) - output_option |= OUTPUT_PORCELAIN; else if (!strcmp("--", arg)) { seen_dashdash = 1; i++; @@ -2364,16 +2381,16 @@ int cmd_blame(int argc, const char **argv, const char *prefix) if (seen_dashdash) { /* (1) */ if (argc <= i) - usage(blame_usage); + usage_with_options(blame_opt_usage, options); path = add_prefix(prefix, argv[i]); if (i + 1 == argc - 1) { if (unk != 1) - usage(blame_usage); + usage_with_options(blame_opt_usage, options); argv[unk++] = argv[i + 1]; } else if (i + 1 != argc) /* garbage at end */ - usage(blame_usage); + usage_with_options(blame_opt_usage, options); } else { int j; @@ -2383,7 +2400,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) if (seen_dashdash) { /* (2) */ if (seen_dashdash + 1 != argc - 1) - usage(blame_usage); + usage_with_options(blame_opt_usage, options); path = add_prefix(prefix, argv[seen_dashdash + 1]); for (j = i; j < seen_dashdash; j++) argv[unk++] = argv[j]; @@ -2391,7 +2408,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) else { /* (3) */ if (argc <= i) - usage(blame_usage); + usage_with_options(blame_opt_usage, options); path = add_prefix(prefix, argv[i]); if (i + 1 == argc - 1) { final_commit_name = argv[i + 1]; @@ -2405,7 +2422,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) } } else if (i != argc - 1) - usage(blame_usage); /* garbage at end */ + usage_with_options(blame_opt_usage, options); setup_work_tree(); if (!has_path_in_work_tree(path)) @@ -2424,7 +2441,6 @@ int cmd_blame(int argc, const char **argv, const char *prefix) argv[unk++] = "--"; /* terminate the rev name */ argv[unk] = NULL; - init_revisions(&revs, NULL); setup_revisions(unk, argv, &revs, NULL); memset(&sb, 0, sizeof(sb)); From 3f8d5204896a85d9268c579fc3e31b22b33fb803 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Tue, 8 Jul 2008 15:19:35 +0200 Subject: [PATCH 46/95] git-blame: migrate to incremental parse-option [2/2] Now use handle_revision_args instead of parse_revisions, and simplify the handling of old-style arguments a lot thanks to the filtering. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- builtin-blame.c | 130 ++++++++++++++---------------------------------- 1 file changed, 38 insertions(+), 92 deletions(-) diff --git a/builtin-blame.c b/builtin-blame.c index 5e82cd3d54..99f5140013 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -2262,8 +2262,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) struct scoreboard sb; struct origin *o; struct blame_entry *ent; - int i, seen_dashdash, unk; - long bottom, top, lno; + long dashdash_pos, bottom, top, lno; const char *final_commit_name = NULL; enum object_type type; @@ -2301,6 +2300,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) git_config(git_blame_config, NULL); init_revisions(&revs, NULL); save_commit_buffer = 0; + dashdash_pos = 0; parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0); @@ -2311,6 +2311,8 @@ int cmd_blame(int argc, const char **argv, const char *prefix) case PARSE_OPT_HELP: exit(129); case PARSE_OPT_DONE: + if (ctx.argv[0]) + dashdash_pos = ctx.cpidx; goto parse_done; } @@ -2330,20 +2332,6 @@ int cmd_blame(int argc, const char **argv, const char *prefix) parse_done: argc = parse_options_end(&ctx); - seen_dashdash = 0; - for (unk = i = 1; i < argc; i++) { - const char *arg = argv[i]; - if (*arg != '-') - break; - else if (!strcmp("--", arg)) { - seen_dashdash = 1; - i++; - break; - } - else - argv[unk++] = arg; - } - if (!blame_move_score) blame_move_score = BLAME_DEFAULT_MOVE_SCORE; if (!blame_copy_score) @@ -2356,92 +2344,50 @@ parse_done: * * The remaining are: * - * (1) if seen_dashdash, its either - * "-options -- " or - * "-options -- ". - * but the latter is allowed only if there is no - * options that we passed to revision machinery. + * (1) if dashdash_pos != 0, its either + * "blame [revisions] -- " or + * "blame -- " * - * (2) otherwise, we may have "--" somewhere later and - * might be looking at the first one of multiple 'rev' - * parameters (e.g. " master ^next ^maint -- path"). - * See if there is a dashdash first, and give the - * arguments before that to revision machinery. - * After that there must be one 'path'. + * (2) otherwise, its one of the two: + * "blame [revisions] " + * "blame " * - * (3) otherwise, its one of the three: - * "-options " - * "-options " - * "-options " - * but again the first one is allowed only if - * there is no options that we passed to revision - * machinery. + * Note that we must strip out from the arguments: we do not + * want the path pruning but we may want "bottom" processing. */ - - if (seen_dashdash) { - /* (1) */ - if (argc <= i) + if (dashdash_pos) { + switch (argc - dashdash_pos - 1) { + case 2: /* (1b) */ + if (argc != 4) + usage_with_options(blame_opt_usage, options); + /* reorder for the new way: -- */ + argv[1] = argv[3]; + argv[3] = argv[2]; + argv[2] = "--"; + /* FALLTHROUGH */ + case 1: /* (1a) */ + path = add_prefix(prefix, argv[--argc]); + argv[argc] = NULL; + break; + default: usage_with_options(blame_opt_usage, options); - path = add_prefix(prefix, argv[i]); - if (i + 1 == argc - 1) { - if (unk != 1) - usage_with_options(blame_opt_usage, options); - argv[unk++] = argv[i + 1]; } - else if (i + 1 != argc) - /* garbage at end */ + } else { + if (argc < 2) usage_with_options(blame_opt_usage, options); - } - else { - int j; - for (j = i; !seen_dashdash && j < argc; j++) - if (!strcmp(argv[j], "--")) - seen_dashdash = j; - if (seen_dashdash) { - /* (2) */ - if (seen_dashdash + 1 != argc - 1) - usage_with_options(blame_opt_usage, options); - path = add_prefix(prefix, argv[seen_dashdash + 1]); - for (j = i; j < seen_dashdash; j++) - argv[unk++] = argv[j]; + path = add_prefix(prefix, argv[argc - 1]); + if (argc == 3 && !has_path_in_work_tree(path)) { /* (2b) */ + path = add_prefix(prefix, argv[1]); + argv[1] = argv[2]; } - else { - /* (3) */ - if (argc <= i) - usage_with_options(blame_opt_usage, options); - path = add_prefix(prefix, argv[i]); - if (i + 1 == argc - 1) { - final_commit_name = argv[i + 1]; + argv[argc - 1] = "--"; - /* if (unk == 1) we could be getting - * old-style - */ - if (unk == 1 && !has_path_in_work_tree(path)) { - path = add_prefix(prefix, argv[i + 1]); - final_commit_name = argv[i]; - } - } - else if (i != argc - 1) - usage_with_options(blame_opt_usage, options); - - setup_work_tree(); - if (!has_path_in_work_tree(path)) - die("cannot stat path %s: %s", - path, strerror(errno)); - } + setup_work_tree(); + if (!has_path_in_work_tree(path)) + die("cannot stat path %s: %s", path, strerror(errno)); } - if (final_commit_name) - argv[unk++] = final_commit_name; - - /* - * Now we got rev and path. We do not want the path pruning - * but we may want "bottom" processing. - */ - argv[unk++] = "--"; /* terminate the rev name */ - argv[unk] = NULL; - - setup_revisions(unk, argv, &revs, NULL); + setup_revisions(argc, argv, &revs, NULL); memset(&sb, 0, sizeof(sb)); sb.revs = &revs; From 1cc6985ca7dd3aaab0617ec0fd00d4eb0b424465 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Tue, 8 Jul 2008 12:34:08 +0200 Subject: [PATCH 47/95] parse-options: add PARSE_OPT_LASTARG_DEFAULT flag If you set this for a given option, and the optoin appears without an argument on the command line, then the `defval' is used as its argument. Note that this flag is meaningless in presence of OPTARG or NOARG flags. (in the current implementation it will be ignored, but don't rely on it). Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- parse-options.c | 55 ++++++++++++++++++++++++------------------------- parse-options.h | 1 + 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/parse-options.c b/parse-options.c index 469831d21b..ae88885d4d 100644 --- a/parse-options.c +++ b/parse-options.c @@ -5,17 +5,6 @@ #define OPT_SHORT 1 #define OPT_UNSET 2 -static inline const char *get_arg(struct parse_opt_ctx_t *p) -{ - if (p->opt) { - const char *res = p->opt; - p->opt = NULL; - return res; - } - p->argc--; - return *++p->argv; -} - static inline const char *skip_prefix(const char *str, const char *prefix) { size_t len = strlen(prefix); @@ -31,8 +20,24 @@ static int opterror(const struct option *opt, const char *reason, int flags) return error("option `%s' %s", opt->long_name, reason); } +static int get_arg(struct parse_opt_ctx_t *p, const struct option *opt, + int flags, const char **arg) +{ + if (p->opt) { + *arg = p->opt; + p->opt = NULL; + } else if (p->argc == 1 && (opt->flags & PARSE_OPT_LASTARG_DEFAULT)) { + *arg = (const char *)opt->defval; + } else if (p->argc) { + p->argc--; + *arg = *++p->argv; + } else + return opterror(opt, "requires a value", flags); + return 0; +} + static int get_value(struct parse_opt_ctx_t *p, - const struct option *opt, int flags) + const struct option *opt, int flags) { const char *s, *arg; const int unset = flags & OPT_UNSET; @@ -58,7 +63,6 @@ static int get_value(struct parse_opt_ctx_t *p, } } - arg = p->opt ? p->opt : (p->argc > 1 ? p->argv[1] : NULL); switch (opt->type) { case OPTION_BIT: if (unset) @@ -80,17 +84,12 @@ static int get_value(struct parse_opt_ctx_t *p, return 0; case OPTION_STRING: - if (unset) { + if (unset) *(const char **)opt->value = NULL; - return 0; - } - if (opt->flags & PARSE_OPT_OPTARG && !p->opt) { + else if (opt->flags & PARSE_OPT_OPTARG && !p->opt) *(const char **)opt->value = (const char *)opt->defval; - return 0; - } - if (!arg) - return opterror(opt, "requires a value", flags); - *(const char **)opt->value = get_arg(p); + else + return get_arg(p, opt, flags, (const char **)opt->value); return 0; case OPTION_CALLBACK: @@ -100,9 +99,9 @@ static int get_value(struct parse_opt_ctx_t *p, return (*opt->callback)(opt, NULL, 0) ? (-1) : 0; if (opt->flags & PARSE_OPT_OPTARG && !p->opt) return (*opt->callback)(opt, NULL, 0) ? (-1) : 0; - if (!arg) - return opterror(opt, "requires a value", flags); - return (*opt->callback)(opt, get_arg(p), 0) ? (-1) : 0; + if (get_arg(p, opt, flags, &arg)) + return -1; + return (*opt->callback)(opt, arg, 0) ? (-1) : 0; case OPTION_INTEGER: if (unset) { @@ -113,9 +112,9 @@ static int get_value(struct parse_opt_ctx_t *p, *(int *)opt->value = opt->defval; return 0; } - if (!arg) - return opterror(opt, "requires a value", flags); - *(int *)opt->value = strtol(get_arg(p), (char **)&s, 10); + if (get_arg(p, opt, flags, &arg)) + return -1; + *(int *)opt->value = strtol(arg, (char **)&s, 10); if (*s) return opterror(opt, "expects a numerical value", flags); return 0; diff --git a/parse-options.h b/parse-options.h index c5f0b4b4da..bc317e7512 100644 --- a/parse-options.h +++ b/parse-options.h @@ -28,6 +28,7 @@ enum parse_opt_option_flags { PARSE_OPT_NOARG = 2, PARSE_OPT_NONEG = 4, PARSE_OPT_HIDDEN = 8, + PARSE_OPT_LASTARG_DEFAULT = 16, }; struct option; From e84fb2ff75f861a708ea5a914883e178a845f4ef Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 8 Jul 2008 17:31:51 -0700 Subject: [PATCH 48/95] branch --contains: default to HEAD We used to require the name of the commit to limit the branches shown to the --contains option, but more recent --merged/--no-meregd defaults to HEAD (and they do not allow arbitrary commit, which is a separate issue). This teaches --contains to default to HEAD when no parameter is given. Signed-off-by: Junio C Hamano --- builtin-branch.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/builtin-branch.c b/builtin-branch.c index d279702ba9..50cbc9c81a 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -438,13 +438,17 @@ int cmd_branch(int argc, const char **argv, const char *prefix) OPT_BOOLEAN( 0 , "color", &branch_use_color, "use colored output"), OPT_SET_INT('r', NULL, &kinds, "act on remote-tracking branches", REF_REMOTE_BRANCH), - OPT_CALLBACK(0, "contains", &with_commit, "commit", - "print only branches that contain the commit", - opt_parse_with_commit), + { + OPTION_CALLBACK, 0, "contains", &with_commit, "commit", + "print only branches that contain the commit", + PARSE_OPT_LASTARG_DEFAULT, + opt_parse_with_commit, (intptr_t)"HEAD", + }, { OPTION_CALLBACK, 0, "with", &with_commit, "commit", "print only branches that contain the commit", - PARSE_OPT_HIDDEN, opt_parse_with_commit, + PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT, + opt_parse_with_commit, (intptr_t) "HEAD", }, OPT__ABBREV(&abbrev), From 049716b370f2cebdbdeb278eb2a8c4eff8ed0acd Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 8 Jul 2008 17:55:47 -0700 Subject: [PATCH 49/95] branch --merged/--no-merged: allow specifying arbitrary commit "git-branch --merged" is a handy way to list all the branches that have already been merged to the current branch, but it did not allow checking against anything but the current branch. Having to switch branches only to list the branches that are merged with another branch made the feature practically useless. This updates the option parser so that "git branch --merged next" is accepted when you are on 'master' branch. Signed-off-by: Junio C Hamano --- Documentation/git-branch.txt | 27 ++++++++++--------- builtin-branch.c | 50 ++++++++++++++++++++++++++++++------ 2 files changed, 57 insertions(+), 20 deletions(-) diff --git a/Documentation/git-branch.txt b/Documentation/git-branch.txt index 0fd58083eb..450f90368f 100644 --- a/Documentation/git-branch.txt +++ b/Documentation/git-branch.txt @@ -8,24 +8,27 @@ git-branch - List, create, or delete branches SYNOPSIS -------- [verse] -'git-branch' [--color | --no-color] [-r | -a] [--merged | --no-merged] - [-v [--abbrev= | --no-abbrev]] - [--contains ] +'git-branch' [--color | --no-color] [-r | -a] + [-v [--abbrev= | --no-abbrev]] + [(--merged | --no-merged | --contains) []] 'git-branch' [--track | --no-track] [-l] [-f] [] 'git-branch' (-m | -M) [] 'git-branch' (-d | -D) [-r] ... DESCRIPTION ----------- -With no arguments given a list of existing branches -will be shown, the current branch will be highlighted with an asterisk. -Option `-r` causes the remote-tracking branches to be listed, -and option `-a` shows both. -With `--contains `, shows only the branches that -contains the named commit (in other words, the branches whose -tip commits are descendant of the named commit). -With `--merged`, only branches merged into HEAD will be listed, and -with `--no-merged` only branches not merged into HEAD will be listed. + +With no arguments, existing branches are listed, the current branch will +be highlighted with an asterisk. Option `-r` causes the remote-tracking +branches to be listed, and option `-a` shows both. + +With `--contains`, shows only the branches that contains the named commit +(in other words, the branches whose tip commits are descendant of the +named commit). With `--merged`, only branches merged into the named +commit (i.e. the branches whose tip commits are reachable from the named +commit) will be listed. With `--no-merged` only branches not merged into +the named commit will be listed. Missing argument defaults to +'HEAD' (i.e. the tip of the current branch). In its second form, a new branch named will be created. It will start out with a head equal to the one given as . diff --git a/builtin-branch.c b/builtin-branch.c index 50cbc9c81a..1926c47581 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -46,7 +46,12 @@ enum color_branch { COLOR_BRANCH_CURRENT = 4, }; -static int mergefilter = -1; +static enum merge_filter { + NO_FILTER = 0, + SHOW_NOT_MERGED, + SHOW_MERGED, +} merge_filter; +static unsigned char merge_filter_ref[20]; static int parse_branch_color_slot(const char *var, int ofs) { @@ -234,13 +239,15 @@ static int append_ref(const char *refname, const unsigned char *sha1, int flags, if ((kind & ref_list->kinds) == 0) return 0; - if (mergefilter > -1) { + if (merge_filter != NO_FILTER) { branch.item = lookup_commit_reference_gently(sha1, 1); if (!branch.item) die("Unable to lookup tip of branch %s", refname); - if (mergefilter == 0 && has_commit(head_sha1, &branch)) + if (merge_filter == SHOW_NOT_MERGED && + has_commit(merge_filter_ref, &branch)) return 0; - if (mergefilter == 1 && !has_commit(head_sha1, &branch)) + if (merge_filter == SHOW_MERGED && + !has_commit(merge_filter_ref, &branch)) return 0; } @@ -421,6 +428,20 @@ static int opt_parse_with_commit(const struct option *opt, const char *arg, int return 0; } +static int opt_parse_merge_filter(const struct option *opt, const char *arg, int unset) +{ + merge_filter = ((opt->long_name[0] == 'n') + ? SHOW_NOT_MERGED + : SHOW_MERGED); + if (unset) + merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */ + if (!arg) + arg = "HEAD"; + if (get_sha1(arg, merge_filter_ref)) + die("malformed object name %s", arg); + return 0; +} + int cmd_branch(int argc, const char **argv, const char *prefix) { int delete = 0, rename = 0, force_create = 0; @@ -461,7 +482,18 @@ int cmd_branch(int argc, const char **argv, const char *prefix) OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2), OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"), OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"), - OPT_SET_INT(0, "merged", &mergefilter, "list only merged branches", 1), + { + OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref, + "commit", "print only not merged branches", + PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG, + opt_parse_merge_filter, (intptr_t) "HEAD", + }, + { + OPTION_CALLBACK, 0, "merged", &merge_filter_ref, + "commit", "print only merged branches", + PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG, + opt_parse_merge_filter, (intptr_t) "HEAD", + }, OPT_END(), }; @@ -471,9 +503,6 @@ int cmd_branch(int argc, const char **argv, const char *prefix) branch_use_color = git_use_color_default; track = git_branch_track; - argc = parse_options(argc, argv, options, builtin_branch_usage, 0); - if (!!delete + !!rename + !!force_create > 1) - usage_with_options(builtin_branch_usage, options); head = resolve_ref("HEAD", head_sha1, 0, NULL); if (!head) @@ -486,6 +515,11 @@ int cmd_branch(int argc, const char **argv, const char *prefix) die("HEAD not found below refs/heads!"); head += 11; } + hashcpy(merge_filter_ref, head_sha1); + + argc = parse_options(argc, argv, options, builtin_branch_usage, 0); + if (!!delete + !!rename + !!force_create > 1) + usage_with_options(builtin_branch_usage, options); if (delete) return delete_branches(argc, argv, delete > 1, kinds); From 76447d235ce2f4ccee7905971a33d3baef252701 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Wed, 9 Jul 2008 22:47:38 +0200 Subject: [PATCH 50/95] git-blame: fix lapsus Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- builtin-blame.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/builtin-blame.c b/builtin-blame.c index 99f5140013..73d26c6e90 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -25,7 +25,7 @@ static char blame_usage[] = "git-blame [options] [rev-opts] [rev] [--] file"; static const char *blame_opt_usage[] = { blame_usage, "", - "[rev-opts] are documented in git-rev-parse(1)", + "[rev-opts] are documented in git-rev-list(1)", NULL }; From 14ec9cbdae1991a14aa1cce251e44ea5cfee5ade Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Wed, 9 Jul 2008 23:38:33 +0200 Subject: [PATCH 51/95] git-shortlog: migrate to parse-options partially. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- builtin-shortlog.c | 133 ++++++++++++++++++++++++++------------------- 1 file changed, 76 insertions(+), 57 deletions(-) diff --git a/builtin-shortlog.c b/builtin-shortlog.c index e6a2865019..9107bffb9b 100644 --- a/builtin-shortlog.c +++ b/builtin-shortlog.c @@ -7,9 +7,14 @@ #include "utf8.h" #include "mailmap.h" #include "shortlog.h" +#include "parse-options.h" -static const char shortlog_usage[] = -"git-shortlog [-n] [-s] [-e] [-w] [... ]"; +static char const * const shortlog_usage[] = { + "git-shortlog [-n] [-s] [-e] [-w] [rev-opts] [--] [... ]", + "", + "[rev-opts] are documented in git-rev-list(1)", + NULL +}; static int compare_by_number(const void *a1, const void *a2) { @@ -164,21 +169,19 @@ static void get_from_rev(struct rev_info *rev, struct shortlog *log) shortlog_add_commit(log, commit); } -static int parse_uint(char const **arg, int comma) +static int parse_uint(char const **arg, int comma, int defval) { unsigned long ul; int ret; char *endp; ul = strtoul(*arg, &endp, 10); - if (endp != *arg && *endp && *endp != comma) + if (*endp && *endp != comma) return -1; - ret = (int) ul; - if (ret != ul) + if (ul > INT_MAX) return -1; - *arg = endp; - if (**arg) - (*arg)++; + ret = *arg == endp ? defval : (int)ul; + *arg = *endp ? endp + 1 : endp; return ret; } @@ -187,30 +190,30 @@ static const char wrap_arg_usage[] = "-w[[,[,]]]"; #define DEFAULT_INDENT1 6 #define DEFAULT_INDENT2 9 -static void parse_wrap_args(const char *arg, int *in1, int *in2, int *wrap) +static int parse_wrap_args(const struct option *opt, const char *arg, int unset) { - arg += 2; /* skip -w */ + struct shortlog *log = opt->value; - *wrap = parse_uint(&arg, ','); - if (*wrap < 0) - die(wrap_arg_usage); - *in1 = parse_uint(&arg, ','); - if (*in1 < 0) - die(wrap_arg_usage); - *in2 = parse_uint(&arg, '\0'); - if (*in2 < 0) - die(wrap_arg_usage); + log->wrap_lines = !unset; + if (unset) + return 0; + if (!arg) { + log->wrap = DEFAULT_WRAPLEN; + log->in1 = DEFAULT_INDENT1; + log->in2 = DEFAULT_INDENT2; + return 0; + } - if (!*wrap) - *wrap = DEFAULT_WRAPLEN; - if (!*in1) - *in1 = DEFAULT_INDENT1; - if (!*in2) - *in2 = DEFAULT_INDENT2; - if (*wrap && - ((*in1 && *wrap <= *in1) || - (*in2 && *wrap <= *in2))) - die(wrap_arg_usage); + log->wrap = parse_uint(&arg, ',', DEFAULT_WRAPLEN); + log->in1 = parse_uint(&arg, ',', DEFAULT_INDENT1); + log->in2 = parse_uint(&arg, '\0', DEFAULT_INDENT2); + if (log->wrap < 0 || log->in1 < 0 || log->in2 < 0) + return error(wrap_arg_usage); + if (log->wrap && + ((log->in1 && log->wrap <= log->in1) || + (log->in2 && log->wrap <= log->in2))) + return error(wrap_arg_usage); + return 0; } void shortlog_init(struct shortlog *log) @@ -227,38 +230,54 @@ void shortlog_init(struct shortlog *log) int cmd_shortlog(int argc, const char **argv, const char *prefix) { - struct shortlog log; - struct rev_info rev; + static struct shortlog log; + static struct rev_info rev; int nongit; + static const struct option options[] = { + OPT_BOOLEAN('n', "numbered", &log.sort_by_number, + "sort output according to the number of commits per author"), + OPT_BOOLEAN('s', "summary", &log.summary, + "Suppress commit descriptions, only provides commit count"), + OPT_BOOLEAN('e', "email", &log.email, + "Show the email address of each author"), + { OPTION_CALLBACK, 'w', NULL, &log, "w[,i1[,i2]]", + "Linewrap output", PARSE_OPT_OPTARG, &parse_wrap_args }, + OPT_END(), + }; + + struct parse_opt_ctx_t ctx; + prefix = setup_git_directory_gently(&nongit); shortlog_init(&log); - - /* since -n is a shadowed rev argument, parse our args first */ - while (argc > 1) { - if (!strcmp(argv[1], "-n") || !strcmp(argv[1], "--numbered")) - log.sort_by_number = 1; - else if (!strcmp(argv[1], "-s") || - !strcmp(argv[1], "--summary")) - log.summary = 1; - else if (!strcmp(argv[1], "-e") || - !strcmp(argv[1], "--email")) - log.email = 1; - else if (!prefixcmp(argv[1], "-w")) { - log.wrap_lines = 1; - parse_wrap_args(argv[1], &log.in1, &log.in2, &log.wrap); - } - else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) - usage(shortlog_usage); - else - break; - argv++; - argc--; - } init_revisions(&rev, prefix); - argc = setup_revisions(argc, argv, &rev, NULL); - if (argc > 1) - die ("unrecognized argument: %s", argv[1]); + parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH | + PARSE_OPT_KEEP_ARGV0); + + for (;;) { + int n; + switch (parse_options_step(&ctx, options, shortlog_usage)) { + case PARSE_OPT_HELP: + exit(129); + case PARSE_OPT_DONE: + goto parse_done; + } + n = handle_revision_opt(&rev, ctx.argc, ctx.argv, + &ctx.cpidx, ctx.out); + if (n <= 0) { + error("unknown option `%s'", ctx.argv[0]); + usage_with_options(shortlog_usage, options); + } + ctx.argv += n; + ctx.argc -= n; + } +parse_done: + argc = parse_options_end(&ctx); + + if (setup_revisions(argc, argv, &rev, NULL) != 1) { + error("unrecognized argument: %s", argv[1]); + usage_with_options(shortlog_usage, options); + } /* assume HEAD if from a tty */ if (!nongit && !rev.pending.nr && isatty(0)) From 6b61ec0564993d2e60f7eb56c0f0fd9c313d5e2c Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Wed, 9 Jul 2008 23:38:34 +0200 Subject: [PATCH 52/95] revisions: refactor handle_revision_opt into parse_revision_opt. It seems we're using handle_revision_opt the same way each time, have a wrapper around it that does the 9-liner we copy each time instead. handle_revision_opt can be static in the module for now, it's always possible to make it public again if needed. Signed-off-by: Pierre Habouzit Signed-off-by: Junio C Hamano --- builtin-blame.c | 11 +---------- builtin-shortlog.c | 10 +--------- revision.c | 18 ++++++++++++++++-- revision.h | 7 +++++-- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/builtin-blame.c b/builtin-blame.c index 73d26c6e90..06c7de4297 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -2305,8 +2305,6 @@ int cmd_blame(int argc, const char **argv, const char *prefix) parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0); for (;;) { - int n; - switch (parse_options_step(&ctx, options, blame_opt_usage)) { case PARSE_OPT_HELP: exit(129); @@ -2320,14 +2318,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix) ctx.argv[0] = "--children"; reverse = 1; } - n = handle_revision_opt(&revs, ctx.argc, ctx.argv, - &ctx.cpidx, ctx.out); - if (n <= 0) { - error("unknown option `%s'", ctx.argv[0]); - usage_with_options(blame_opt_usage, options); - } - ctx.argv += n; - ctx.argc -= n; + parse_revision_opt(&revs, &ctx, options, blame_opt_usage); } parse_done: argc = parse_options_end(&ctx); diff --git a/builtin-shortlog.c b/builtin-shortlog.c index 9107bffb9b..01362022c0 100644 --- a/builtin-shortlog.c +++ b/builtin-shortlog.c @@ -255,21 +255,13 @@ int cmd_shortlog(int argc, const char **argv, const char *prefix) PARSE_OPT_KEEP_ARGV0); for (;;) { - int n; switch (parse_options_step(&ctx, options, shortlog_usage)) { case PARSE_OPT_HELP: exit(129); case PARSE_OPT_DONE: goto parse_done; } - n = handle_revision_opt(&rev, ctx.argc, ctx.argv, - &ctx.cpidx, ctx.out); - if (n <= 0) { - error("unknown option `%s'", ctx.argv[0]); - usage_with_options(shortlog_usage, options); - } - ctx.argv += n; - ctx.argc -= n; + parse_revision_opt(&rev, &ctx, options, shortlog_usage); } parse_done: argc = parse_options_end(&ctx); diff --git a/revision.c b/revision.c index 4b6925be08..93918da666 100644 --- a/revision.c +++ b/revision.c @@ -957,8 +957,8 @@ static void add_ignore_packed(struct rev_info *revs, const char *name) revs->ignore_packed[num] = NULL; } -int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, - int *unkc, const char **unkv) +static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, + int *unkc, const char **unkv) { const char *arg = argv[0]; @@ -1163,6 +1163,20 @@ int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, return 1; } +void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx, + const struct option *options, + const char * const usagestr[]) +{ + int n = handle_revision_opt(revs, ctx->argc, ctx->argv, + &ctx->cpidx, ctx->out); + if (n <= 0) { + error("unknown option `%s'", ctx->argv[0]); + usage_with_options(usagestr, options); + } + ctx->argv += n; + ctx->argc -= n; +} + /* * Parse revision information, filling in the "rev_info" structure, * and removing the used arguments from the argument list. diff --git a/revision.h b/revision.h index c44498e3b3..15dc14925f 100644 --- a/revision.h +++ b/revision.h @@ -1,6 +1,8 @@ #ifndef REVISION_H #define REVISION_H +#include "parse-options.h" + #define SEEN (1u<<0) #define UNINTERESTING (1u<<1) #define TREESAME (1u<<2) @@ -119,8 +121,9 @@ volatile show_early_output_fn_t show_early_output; extern void init_revisions(struct rev_info *revs, const char *prefix); extern int setup_revisions(int argc, const char **argv, struct rev_info *revs, const char *def); -extern int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, - int *unkc, const char **unkv); +extern void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx, + const struct option *options, + const char * const usagestr[]); extern int handle_revision_arg(const char *arg, struct rev_info *revs,int flags,int cant_be_filename); extern int prepare_revision_walk(struct rev_info *revs); From 99d698f1e703754422f1dd780487ddbff3726dc3 Mon Sep 17 00:00:00 2001 From: Olivier Marin Date: Mon, 7 Jul 2008 14:42:48 +0200 Subject: [PATCH 53/95] builtin-rerere: more carefully find conflict markers When a conflicting file contains a line that begin with "=======", rerere failed to parse conflict markers. This result to a wrong preimage file and an unexpected error for the user. The boundary between ours and theirs not just begin with 7 equals, but is followed by either a SP or a LF. This patch enforces parsing rules so that markers match in the right order, and when ambiguous, the command does not autoresolve the conflicted file. Especially because we are introducing rerere.autoupdate configuration (which is off by default for safety) that automatically stages the resolution made by rerere, it is necessary to make sure that we do not autoresolve when there is any ambiguity. Signed-off-by: Olivier Marin Signed-off-by: Junio C Hamano --- builtin-rerere.c | 16 +++++++++++++--- t/t4200-rerere.sh | 26 ++++++++++++++++++++------ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/builtin-rerere.c b/builtin-rerere.c index 839b26e8e0..69c3a52d5e 100644 --- a/builtin-rerere.c +++ b/builtin-rerere.c @@ -112,11 +112,17 @@ static int handle_file(const char *path, strbuf_init(&one, 0); strbuf_init(&two, 0); while (fgets(buf, sizeof(buf), f)) { - if (!prefixcmp(buf, "<<<<<<< ")) + if (!prefixcmp(buf, "<<<<<<< ")) { + if (hunk) + goto bad; hunk = 1; - else if (!prefixcmp(buf, "=======")) + } else if (!prefixcmp(buf, "=======") && isspace(buf[7])) { + if (hunk != 1) + goto bad; hunk = 2; - else if (!prefixcmp(buf, ">>>>>>> ")) { + } else if (!prefixcmp(buf, ">>>>>>> ")) { + if (hunk != 2) + goto bad; if (strbuf_cmp(&one, &two) > 0) strbuf_swap(&one, &two); hunk_no++; @@ -142,6 +148,10 @@ static int handle_file(const char *path, strbuf_addstr(&two, buf); else if (out) fputs(buf, out); + continue; + bad: + hunk = 99; /* force error exit */ + break; } strbuf_release(&one); strbuf_release(&two); diff --git a/t/t4200-rerere.sh b/t/t4200-rerere.sh index a64727d5ad..cf10557dd2 100755 --- a/t/t4200-rerere.sh +++ b/t/t4200-rerere.sh @@ -9,6 +9,8 @@ test_description='git rerere . ./test-lib.sh cat > a1 << EOF +Some title +========== Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, @@ -24,6 +26,8 @@ git commit -q -a -m initial git checkout -b first cat >> a1 << EOF +Some title +========== To die, to sleep; To sleep: perchance to dream: ay, there's the rub; For in that sleep of death what dreams may come @@ -35,7 +39,7 @@ git commit -q -a -m first git checkout -b second master git show first:a1 | -sed -e 's/To die, t/To die! T/' > a1 +sed -e 's/To die, t/To die! T/' -e 's/Some title/Some Title/' > a1 echo "* END *" >>a1 git commit -q -a -m second @@ -55,14 +59,14 @@ test_expect_success 'conflicting merge' ' sha1=$(sed -e 's/ .*//' .git/rr-cache/MERGE_RR) rr=.git/rr-cache/$sha1 -test_expect_success 'recorded preimage' "grep ======= $rr/preimage" +test_expect_success 'recorded preimage' "grep ^=======$ $rr/preimage" test_expect_success 'rerere.enabled works, too' ' rm -rf .git/rr-cache && git config rerere.enabled true && git reset --hard && ! git merge first && - grep ======= $rr/preimage + grep ^=======$ $rr/preimage ' test_expect_success 'no postimage or thisimage yet' \ @@ -71,7 +75,7 @@ test_expect_success 'no postimage or thisimage yet' \ test_expect_success 'preimage has right number of lines' ' cnt=$(sed -ne "/^<<<<<<>>>>>>/p" $rr/preimage | wc -l) && - test $cnt = 9 + test $cnt = 13 ' @@ -80,13 +84,23 @@ git show first:a1 > a1 cat > expect << EOF --- a/a1 +++ b/a1 -@@ -6,17 +6,9 @@ +@@ -1,4 +1,4 @@ +-Some Title ++Some title + ========== + Whether 'tis nobler in the mind to suffer + The slings and arrows of outrageous fortune, +@@ -8,21 +8,11 @@ The heart-ache and the thousand natural shocks That flesh is heir to, 'tis a consummation Devoutly to be wish'd. -<<<<<<< +-Some Title +-========== -To die! To sleep; -======= + Some title + ========== To die, to sleep; ->>>>>>> To sleep: perchance to dream: ay, there's the rub; @@ -124,7 +138,7 @@ test_expect_success 'another conflicting merge' ' ' git show first:a1 | sed 's/To die: t/To die! T/' > expect -test_expect_success 'rerere kicked in' "! grep ======= a1" +test_expect_success 'rerere kicked in' "! grep ^=======$ a1" test_expect_success 'rerere prefers first change' 'test_cmp a1 expect' From 5b2fd95606cd6d564f96d9d253e7cd19263bc352 Mon Sep 17 00:00:00 2001 From: Stephan Beyer Date: Wed, 9 Jul 2008 14:58:57 +0200 Subject: [PATCH 54/95] rerere: Separate libgit and builtin functions This patch moves rerere()-related functions into a newly created rerere.c file. The setup_rerere() function is needed by both rerere() and cmd_rerere(), so this function is moved to rerere.c and declared non-static (and "extern") in newly created rerere.h file. Signed-off-by: Stephan Beyer Signed-off-by: Junio C Hamano --- Makefile | 2 + builtin-commit.c | 1 + builtin-rerere.c | 372 +++-------------------------------------------- commit.h | 1 - rerere.c | 360 +++++++++++++++++++++++++++++++++++++++++++++ rerere.h | 9 ++ 6 files changed, 390 insertions(+), 355 deletions(-) create mode 100644 rerere.c create mode 100644 rerere.h diff --git a/Makefile b/Makefile index 4796565ab3..de151638bb 100644 --- a/Makefile +++ b/Makefile @@ -363,6 +363,7 @@ LIB_H += quote.h LIB_H += reflog-walk.h LIB_H += refs.h LIB_H += remote.h +LIB_H += rerere.h LIB_H += revision.h LIB_H += run-command.h LIB_H += sha1-lookup.h @@ -447,6 +448,7 @@ LIB_OBJS += read-cache.o LIB_OBJS += reflog-walk.o LIB_OBJS += refs.o LIB_OBJS += remote.o +LIB_OBJS += rerere.o LIB_OBJS += revision.o LIB_OBJS += run-command.o LIB_OBJS += server-info.o diff --git a/builtin-commit.c b/builtin-commit.c index 745c11e773..bdc83df55b 100644 --- a/builtin-commit.c +++ b/builtin-commit.c @@ -22,6 +22,7 @@ #include "utf8.h" #include "parse-options.h" #include "path-list.h" +#include "rerere.h" #include "unpack-trees.h" static const char * const builtin_commit_usage[] = { diff --git a/builtin-rerere.c b/builtin-rerere.c index 69c3a52d5e..5d40e16932 100644 --- a/builtin-rerere.c +++ b/builtin-rerere.c @@ -1,11 +1,10 @@ #include "builtin.h" #include "cache.h" #include "path-list.h" +#include "rerere.h" #include "xdiff/xdiff.h" #include "xdiff-interface.h" -#include - static const char git_rerere_usage[] = "git-rerere [clear | status | diff | gc]"; @@ -13,14 +12,6 @@ static const char git_rerere_usage[] = static int cutoff_noresolve = 15; static int cutoff_resolve = 60; -/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */ -static int rerere_enabled = -1; - -/* automatically update cleanly resolved paths to the index */ -static int rerere_autoupdate; - -static char *merge_rr_path; - static const char *rr_path(const char *name, const char *file) { return git_path("rr-cache/%s/%s", name, file); @@ -38,189 +29,6 @@ static int has_resolution(const char *name) return !stat(rr_path(name, "postimage"), &st); } -static void read_rr(struct path_list *rr) -{ - unsigned char sha1[20]; - char buf[PATH_MAX]; - FILE *in = fopen(merge_rr_path, "r"); - if (!in) - return; - while (fread(buf, 40, 1, in) == 1) { - int i; - char *name; - if (get_sha1_hex(buf, sha1)) - die("corrupt MERGE_RR"); - buf[40] = '\0'; - name = xstrdup(buf); - if (fgetc(in) != '\t') - die("corrupt MERGE_RR"); - for (i = 0; i < sizeof(buf) && (buf[i] = fgetc(in)); i++) - ; /* do nothing */ - if (i == sizeof(buf)) - die("filename too long"); - path_list_insert(buf, rr)->util = name; - } - fclose(in); -} - -static struct lock_file write_lock; - -static int write_rr(struct path_list *rr, int out_fd) -{ - int i; - for (i = 0; i < rr->nr; i++) { - const char *path; - int length; - if (!rr->items[i].util) - continue; - path = rr->items[i].path; - length = strlen(path) + 1; - if (write_in_full(out_fd, rr->items[i].util, 40) != 40 || - write_in_full(out_fd, "\t", 1) != 1 || - write_in_full(out_fd, path, length) != length) - die("unable to write rerere record"); - } - if (commit_lock_file(&write_lock) != 0) - die("unable to write rerere record"); - return 0; -} - -static int handle_file(const char *path, - unsigned char *sha1, const char *output) -{ - SHA_CTX ctx; - char buf[1024]; - int hunk = 0, hunk_no = 0; - struct strbuf one, two; - FILE *f = fopen(path, "r"); - FILE *out = NULL; - - if (!f) - return error("Could not open %s", path); - - if (output) { - out = fopen(output, "w"); - if (!out) { - fclose(f); - return error("Could not write %s", output); - } - } - - if (sha1) - SHA1_Init(&ctx); - - strbuf_init(&one, 0); - strbuf_init(&two, 0); - while (fgets(buf, sizeof(buf), f)) { - if (!prefixcmp(buf, "<<<<<<< ")) { - if (hunk) - goto bad; - hunk = 1; - } else if (!prefixcmp(buf, "=======") && isspace(buf[7])) { - if (hunk != 1) - goto bad; - hunk = 2; - } else if (!prefixcmp(buf, ">>>>>>> ")) { - if (hunk != 2) - goto bad; - if (strbuf_cmp(&one, &two) > 0) - strbuf_swap(&one, &two); - hunk_no++; - hunk = 0; - if (out) { - fputs("<<<<<<<\n", out); - fwrite(one.buf, one.len, 1, out); - fputs("=======\n", out); - fwrite(two.buf, two.len, 1, out); - fputs(">>>>>>>\n", out); - } - if (sha1) { - SHA1_Update(&ctx, one.buf ? one.buf : "", - one.len + 1); - SHA1_Update(&ctx, two.buf ? two.buf : "", - two.len + 1); - } - strbuf_reset(&one); - strbuf_reset(&two); - } else if (hunk == 1) - strbuf_addstr(&one, buf); - else if (hunk == 2) - strbuf_addstr(&two, buf); - else if (out) - fputs(buf, out); - continue; - bad: - hunk = 99; /* force error exit */ - break; - } - strbuf_release(&one); - strbuf_release(&two); - - fclose(f); - if (out) - fclose(out); - if (sha1) - SHA1_Final(sha1, &ctx); - if (hunk) { - if (output) - unlink(output); - return error("Could not parse conflict hunks in %s", path); - } - return hunk_no; -} - -static int find_conflict(struct path_list *conflict) -{ - int i; - if (read_cache() < 0) - return error("Could not read index"); - for (i = 0; i+1 < active_nr; i++) { - struct cache_entry *e2 = active_cache[i]; - struct cache_entry *e3 = active_cache[i+1]; - if (ce_stage(e2) == 2 && - ce_stage(e3) == 3 && - ce_same_name(e2, e3) && - S_ISREG(e2->ce_mode) && - S_ISREG(e3->ce_mode)) { - path_list_insert((const char *)e2->name, conflict); - i++; /* skip over both #2 and #3 */ - } - } - return 0; -} - -static int merge(const char *name, const char *path) -{ - int ret; - mmfile_t cur, base, other; - mmbuffer_t result = {NULL, 0}; - xpparam_t xpp = {XDF_NEED_MINIMAL}; - - if (handle_file(path, NULL, rr_path(name, "thisimage")) < 0) - return 1; - - if (read_mmfile(&cur, rr_path(name, "thisimage")) || - read_mmfile(&base, rr_path(name, "preimage")) || - read_mmfile(&other, rr_path(name, "postimage"))) - return 1; - ret = xdl_merge(&base, &cur, "", &other, "", - &xpp, XDL_MERGE_ZEALOUS, &result); - if (!ret) { - FILE *f = fopen(path, "w"); - if (!f) - return error("Could not write to %s", path); - fwrite(result.ptr, result.size, 1, f); - fclose(f); - } - - free(cur.ptr); - free(base.ptr); - free(other.ptr); - free(result.ptr); - - return ret; -} - static void unlink_rr_item(const char *name) { unlink(rr_path(name, "thisimage")); @@ -229,6 +37,17 @@ static void unlink_rr_item(const char *name) rmdir(git_path("rr-cache/%s", name)); } +static int git_rerere_gc_config(const char *var, const char *value, void *cb) +{ + if (!strcmp(var, "gc.rerereresolved")) + cutoff_resolve = git_config_int(var, value); + else if (!strcmp(var, "gc.rerereunresolved")) + cutoff_noresolve = git_config_int(var, value); + else + return git_default_config(var, value, cb); + return 0; +} + static void garbage_collect(struct path_list *rr) { struct path_list to_remove = { NULL, 0, 0, 1 }; @@ -237,6 +56,7 @@ static void garbage_collect(struct path_list *rr) int i, cutoff; time_t now = time(NULL), then; + git_config(git_rerere_gc_config, NULL); dir = opendir(git_path("rr-cache")); while ((e = readdir(dir))) { const char *name = e->d_name; @@ -289,181 +109,25 @@ static int diff_two(const char *file1, const char *label1, return 0; } -static struct lock_file index_lock; - -static int update_paths(struct path_list *update) -{ - int i; - int fd = hold_locked_index(&index_lock, 0); - int status = 0; - - if (fd < 0) - return -1; - - for (i = 0; i < update->nr; i++) { - struct path_list_item *item = &update->items[i]; - if (add_file_to_cache(item->path, ADD_CACHE_IGNORE_ERRORS)) - status = -1; - } - - if (!status && active_cache_changed) { - if (write_cache(fd, active_cache, active_nr) || - commit_locked_index(&index_lock)) - die("Unable to write new index file"); - } else if (fd >= 0) - rollback_lock_file(&index_lock); - return status; -} - -static int do_plain_rerere(struct path_list *rr, int fd) -{ - struct path_list conflict = { NULL, 0, 0, 1 }; - struct path_list update = { NULL, 0, 0, 1 }; - int i; - - find_conflict(&conflict); - - /* - * MERGE_RR records paths with conflicts immediately after merge - * failed. Some of the conflicted paths might have been hand resolved - * in the working tree since then, but the initial run would catch all - * and register their preimages. - */ - - for (i = 0; i < conflict.nr; i++) { - const char *path = conflict.items[i].path; - if (!path_list_has_path(rr, path)) { - unsigned char sha1[20]; - char *hex; - int ret; - ret = handle_file(path, sha1, NULL); - if (ret < 1) - continue; - hex = xstrdup(sha1_to_hex(sha1)); - path_list_insert(path, rr)->util = hex; - if (mkdir(git_path("rr-cache/%s", hex), 0755)) - continue;; - handle_file(path, NULL, rr_path(hex, "preimage")); - fprintf(stderr, "Recorded preimage for '%s'\n", path); - } - } - - /* - * Now some of the paths that had conflicts earlier might have been - * hand resolved. Others may be similar to a conflict already that - * was resolved before. - */ - - for (i = 0; i < rr->nr; i++) { - int ret; - const char *path = rr->items[i].path; - const char *name = (const char *)rr->items[i].util; - - if (has_resolution(name)) { - if (!merge(name, path)) { - fprintf(stderr, "Resolved '%s' using " - "previous resolution.\n", path); - if (rerere_autoupdate) - path_list_insert(path, &update); - goto mark_resolved; - } - } - - /* Let's see if we have resolved it. */ - ret = handle_file(path, NULL, NULL); - if (ret) - continue; - - fprintf(stderr, "Recorded resolution for '%s'.\n", path); - copy_file(rr_path(name, "postimage"), path, 0666); - mark_resolved: - rr->items[i].util = NULL; - } - - if (update.nr) - update_paths(&update); - - return write_rr(rr, fd); -} - -static int git_rerere_config(const char *var, const char *value, void *cb) -{ - if (!strcmp(var, "gc.rerereresolved")) - cutoff_resolve = git_config_int(var, value); - else if (!strcmp(var, "gc.rerereunresolved")) - cutoff_noresolve = git_config_int(var, value); - else if (!strcmp(var, "rerere.enabled")) - rerere_enabled = git_config_bool(var, value); - else if (!strcmp(var, "rerere.autoupdate")) - rerere_autoupdate = git_config_bool(var, value); - else - return git_default_config(var, value, cb); - return 0; -} - -static int is_rerere_enabled(void) -{ - struct stat st; - const char *rr_cache; - int rr_cache_exists; - - if (!rerere_enabled) - return 0; - - rr_cache = git_path("rr-cache"); - rr_cache_exists = !stat(rr_cache, &st) && S_ISDIR(st.st_mode); - if (rerere_enabled < 0) - return rr_cache_exists; - - if (!rr_cache_exists && - (mkdir(rr_cache, 0777) || adjust_shared_perm(rr_cache))) - die("Could not create directory %s", rr_cache); - return 1; -} - -static int setup_rerere(struct path_list *merge_rr) -{ - int fd; - - git_config(git_rerere_config, NULL); - if (!is_rerere_enabled()) - return -1; - - merge_rr_path = xstrdup(git_path("rr-cache/MERGE_RR")); - fd = hold_lock_file_for_update(&write_lock, merge_rr_path, 1); - read_rr(merge_rr); - return fd; -} - -int rerere(void) -{ - struct path_list merge_rr = { NULL, 0, 0, 1 }; - int fd; - - fd = setup_rerere(&merge_rr); - if (fd < 0) - return 0; - return do_plain_rerere(&merge_rr, fd); -} - int cmd_rerere(int argc, const char **argv, const char *prefix) { struct path_list merge_rr = { NULL, 0, 0, 1 }; int i, fd; + if (argc < 2) + return rerere(); + fd = setup_rerere(&merge_rr); if (fd < 0) return 0; - if (argc < 2) - return do_plain_rerere(&merge_rr, fd); - else if (!strcmp(argv[1], "clear")) { + if (!strcmp(argv[1], "clear")) { for (i = 0; i < merge_rr.nr; i++) { const char *name = (const char *)merge_rr.items[i].util; if (!has_resolution(name)) unlink_rr_item(name); } - unlink(merge_rr_path); + unlink(git_path("rr-cache/MERGE_RR")); } else if (!strcmp(argv[1], "gc")) garbage_collect(&merge_rr); else if (!strcmp(argv[1], "status")) diff --git a/commit.h b/commit.h index 2d94d4148e..fda7ad03c0 100644 --- a/commit.h +++ b/commit.h @@ -131,7 +131,6 @@ extern struct commit_list *get_shallow_commits(struct object_array *heads, int in_merge_bases(struct commit *, struct commit **, int); extern int interactive_add(int argc, const char **argv, const char *prefix); -extern int rerere(void); static inline int single_parent(struct commit *commit) { diff --git a/rerere.c b/rerere.c new file mode 100644 index 0000000000..eec2b50107 --- /dev/null +++ b/rerere.c @@ -0,0 +1,360 @@ +#include "cache.h" +#include "path-list.h" +#include "rerere.h" +#include "xdiff/xdiff.h" +#include "xdiff-interface.h" + +/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */ +static int rerere_enabled = -1; + +/* automatically update cleanly resolved paths to the index */ +static int rerere_autoupdate; + +static char *merge_rr_path; + +static const char *rr_path(const char *name, const char *file) +{ + return git_path("rr-cache/%s/%s", name, file); +} + +static int has_resolution(const char *name) +{ + struct stat st; + return !stat(rr_path(name, "postimage"), &st); +} + +static void read_rr(struct path_list *rr) +{ + unsigned char sha1[20]; + char buf[PATH_MAX]; + FILE *in = fopen(merge_rr_path, "r"); + if (!in) + return; + while (fread(buf, 40, 1, in) == 1) { + int i; + char *name; + if (get_sha1_hex(buf, sha1)) + die("corrupt MERGE_RR"); + buf[40] = '\0'; + name = xstrdup(buf); + if (fgetc(in) != '\t') + die("corrupt MERGE_RR"); + for (i = 0; i < sizeof(buf) && (buf[i] = fgetc(in)); i++) + ; /* do nothing */ + if (i == sizeof(buf)) + die("filename too long"); + path_list_insert(buf, rr)->util = name; + } + fclose(in); +} + +static struct lock_file write_lock; + +static int write_rr(struct path_list *rr, int out_fd) +{ + int i; + for (i = 0; i < rr->nr; i++) { + const char *path; + int length; + if (!rr->items[i].util) + continue; + path = rr->items[i].path; + length = strlen(path) + 1; + if (write_in_full(out_fd, rr->items[i].util, 40) != 40 || + write_in_full(out_fd, "\t", 1) != 1 || + write_in_full(out_fd, path, length) != length) + die("unable to write rerere record"); + } + if (commit_lock_file(&write_lock) != 0) + die("unable to write rerere record"); + return 0; +} + +static int handle_file(const char *path, + unsigned char *sha1, const char *output) +{ + SHA_CTX ctx; + char buf[1024]; + int hunk = 0, hunk_no = 0; + struct strbuf one, two; + FILE *f = fopen(path, "r"); + FILE *out = NULL; + + if (!f) + return error("Could not open %s", path); + + if (output) { + out = fopen(output, "w"); + if (!out) { + fclose(f); + return error("Could not write %s", output); + } + } + + if (sha1) + SHA1_Init(&ctx); + + strbuf_init(&one, 0); + strbuf_init(&two, 0); + while (fgets(buf, sizeof(buf), f)) { + if (!prefixcmp(buf, "<<<<<<< ")) { + if (hunk) + goto bad; + hunk = 1; + } else if (!prefixcmp(buf, "=======") && isspace(buf[7])) { + if (hunk != 1) + goto bad; + hunk = 2; + } else if (!prefixcmp(buf, ">>>>>>> ")) { + if (hunk != 2) + goto bad; + if (strbuf_cmp(&one, &two) > 0) + strbuf_swap(&one, &two); + hunk_no++; + hunk = 0; + if (out) { + fputs("<<<<<<<\n", out); + fwrite(one.buf, one.len, 1, out); + fputs("=======\n", out); + fwrite(two.buf, two.len, 1, out); + fputs(">>>>>>>\n", out); + } + if (sha1) { + SHA1_Update(&ctx, one.buf ? one.buf : "", + one.len + 1); + SHA1_Update(&ctx, two.buf ? two.buf : "", + two.len + 1); + } + strbuf_reset(&one); + strbuf_reset(&two); + } else if (hunk == 1) + strbuf_addstr(&one, buf); + else if (hunk == 2) + strbuf_addstr(&two, buf); + else if (out) + fputs(buf, out); + continue; + bad: + hunk = 99; /* force error exit */ + break; + } + strbuf_release(&one); + strbuf_release(&two); + + fclose(f); + if (out) + fclose(out); + if (sha1) + SHA1_Final(sha1, &ctx); + if (hunk) { + if (output) + unlink(output); + return error("Could not parse conflict hunks in %s", path); + } + return hunk_no; +} + +static int find_conflict(struct path_list *conflict) +{ + int i; + if (read_cache() < 0) + return error("Could not read index"); + for (i = 0; i+1 < active_nr; i++) { + struct cache_entry *e2 = active_cache[i]; + struct cache_entry *e3 = active_cache[i+1]; + if (ce_stage(e2) == 2 && + ce_stage(e3) == 3 && + ce_same_name(e2, e3) && + S_ISREG(e2->ce_mode) && + S_ISREG(e3->ce_mode)) { + path_list_insert((const char *)e2->name, conflict); + i++; /* skip over both #2 and #3 */ + } + } + return 0; +} + +static int merge(const char *name, const char *path) +{ + int ret; + mmfile_t cur, base, other; + mmbuffer_t result = {NULL, 0}; + xpparam_t xpp = {XDF_NEED_MINIMAL}; + + if (handle_file(path, NULL, rr_path(name, "thisimage")) < 0) + return 1; + + if (read_mmfile(&cur, rr_path(name, "thisimage")) || + read_mmfile(&base, rr_path(name, "preimage")) || + read_mmfile(&other, rr_path(name, "postimage"))) + return 1; + ret = xdl_merge(&base, &cur, "", &other, "", + &xpp, XDL_MERGE_ZEALOUS, &result); + if (!ret) { + FILE *f = fopen(path, "w"); + if (!f) + return error("Could not write to %s", path); + fwrite(result.ptr, result.size, 1, f); + fclose(f); + } + + free(cur.ptr); + free(base.ptr); + free(other.ptr); + free(result.ptr); + + return ret; +} + +static struct lock_file index_lock; + +static int update_paths(struct path_list *update) +{ + int i; + int fd = hold_locked_index(&index_lock, 0); + int status = 0; + + if (fd < 0) + return -1; + + for (i = 0; i < update->nr; i++) { + struct path_list_item *item = &update->items[i]; + if (add_file_to_cache(item->path, ADD_CACHE_IGNORE_ERRORS)) + status = -1; + } + + if (!status && active_cache_changed) { + if (write_cache(fd, active_cache, active_nr) || + commit_locked_index(&index_lock)) + die("Unable to write new index file"); + } else if (fd >= 0) + rollback_lock_file(&index_lock); + return status; +} + +static int do_plain_rerere(struct path_list *rr, int fd) +{ + struct path_list conflict = { NULL, 0, 0, 1 }; + struct path_list update = { NULL, 0, 0, 1 }; + int i; + + find_conflict(&conflict); + + /* + * MERGE_RR records paths with conflicts immediately after merge + * failed. Some of the conflicted paths might have been hand resolved + * in the working tree since then, but the initial run would catch all + * and register their preimages. + */ + + for (i = 0; i < conflict.nr; i++) { + const char *path = conflict.items[i].path; + if (!path_list_has_path(rr, path)) { + unsigned char sha1[20]; + char *hex; + int ret; + ret = handle_file(path, sha1, NULL); + if (ret < 1) + continue; + hex = xstrdup(sha1_to_hex(sha1)); + path_list_insert(path, rr)->util = hex; + if (mkdir(git_path("rr-cache/%s", hex), 0755)) + continue;; + handle_file(path, NULL, rr_path(hex, "preimage")); + fprintf(stderr, "Recorded preimage for '%s'\n", path); + } + } + + /* + * Now some of the paths that had conflicts earlier might have been + * hand resolved. Others may be similar to a conflict already that + * was resolved before. + */ + + for (i = 0; i < rr->nr; i++) { + int ret; + const char *path = rr->items[i].path; + const char *name = (const char *)rr->items[i].util; + + if (has_resolution(name)) { + if (!merge(name, path)) { + fprintf(stderr, "Resolved '%s' using " + "previous resolution.\n", path); + if (rerere_autoupdate) + path_list_insert(path, &update); + goto mark_resolved; + } + } + + /* Let's see if we have resolved it. */ + ret = handle_file(path, NULL, NULL); + if (ret) + continue; + + fprintf(stderr, "Recorded resolution for '%s'.\n", path); + copy_file(rr_path(name, "postimage"), path, 0666); + mark_resolved: + rr->items[i].util = NULL; + } + + if (update.nr) + update_paths(&update); + + return write_rr(rr, fd); +} + +static int git_rerere_config(const char *var, const char *value, void *cb) +{ + if (!strcmp(var, "rerere.enabled")) + rerere_enabled = git_config_bool(var, value); + else if (!strcmp(var, "rerere.autoupdate")) + rerere_autoupdate = git_config_bool(var, value); + else + return git_default_config(var, value, cb); + return 0; +} + +static int is_rerere_enabled(void) +{ + struct stat st; + const char *rr_cache; + int rr_cache_exists; + + if (!rerere_enabled) + return 0; + + rr_cache = git_path("rr-cache"); + rr_cache_exists = !stat(rr_cache, &st) && S_ISDIR(st.st_mode); + if (rerere_enabled < 0) + return rr_cache_exists; + + if (!rr_cache_exists && + (mkdir(rr_cache, 0777) || adjust_shared_perm(rr_cache))) + die("Could not create directory %s", rr_cache); + return 1; +} + +int setup_rerere(struct path_list *merge_rr) +{ + int fd; + + git_config(git_rerere_config, NULL); + if (!is_rerere_enabled()) + return -1; + + merge_rr_path = xstrdup(git_path("rr-cache/MERGE_RR")); + fd = hold_lock_file_for_update(&write_lock, merge_rr_path, 1); + read_rr(merge_rr); + return fd; +} + +int rerere(void) +{ + struct path_list merge_rr = { NULL, 0, 0, 1 }; + int fd; + + fd = setup_rerere(&merge_rr); + if (fd < 0) + return 0; + return do_plain_rerere(&merge_rr, fd); +} diff --git a/rerere.h b/rerere.h new file mode 100644 index 0000000000..35b0fa86a3 --- /dev/null +++ b/rerere.h @@ -0,0 +1,9 @@ +#ifndef RERERE_H +#define RERERE_H + +#include "path-list.h" + +extern int setup_rerere(struct path_list *); +extern int rerere(void); + +#endif From 4393c2374101fef9053643f9b4ec638b05bd0b26 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Thu, 10 Jul 2008 00:50:59 -0700 Subject: [PATCH 55/95] Teach merge.log to "git-merge" again The command forgot the configuration variable when rewritten in C. Signed-off-by: Junio C Hamano --- builtin-merge.c | 2 ++ t/t7600-merge.sh | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/builtin-merge.c b/builtin-merge.c index b2e702a11f..2ee1674690 100644 --- a/builtin-merge.c +++ b/builtin-merge.c @@ -464,6 +464,8 @@ int git_merge_config(const char *k, const char *v, void *cb) return git_config_string(&pull_twohead, k, v); else if (!strcmp(k, "pull.octopus")) return git_config_string(&pull_octopus, k, v); + else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) + option_log = git_config_bool(k, v); return git_diff_ui_config(k, v, cb); } diff --git a/t/t7600-merge.sh b/t/t7600-merge.sh index d21cd290d3..72ef2e55d9 100755 --- a/t/t7600-merge.sh +++ b/t/t7600-merge.sh @@ -465,8 +465,15 @@ test_expect_success 'merge log message' ' git merge --no-log c2 && git show -s --pretty=format:%b HEAD >msg.act && verify_diff msg.nolog msg.act "[OOPS] bad merge log message" && + git merge --log c3 && git show -s --pretty=format:%b HEAD >msg.act && + verify_diff msg.log msg.act "[OOPS] bad merge log message" && + + git reset --hard HEAD^ && + git config merge.log yes && + git merge c3 && + git show -s --pretty=format:%b HEAD >msg.act && verify_diff msg.log msg.act "[OOPS] bad merge log message" ' From 8c6202d8696d2e3ae016042acd05f6a82763a5e3 Mon Sep 17 00:00:00 2001 From: Petr Baudis Date: Sat, 12 Jul 2008 03:15:03 +0200 Subject: [PATCH 56/95] Fix backwards-incompatible handling of core.sharedRepository 06cbe85 (Make core.sharedRepository more generic, 2008-04-16) broke the traditional setting of core.sharedRepository to true, which was to make the repository group writable: with umask 022, it would clear the permission bits for 'other'. (umask 002 did not exhibit this behaviour since pre-chmod() check in adjust_shared_perm() fails in that case.) The call to adjust_shared_perm() should only loosen the permission. If the user has umask like 022 or 002 that allow others to read, the resulting files should be made readable and writable by group, without restricting the readability by others. This patch fixes the adjust_shared_perm() mode tweak based on Junio's suggestion and adds the appropriate tests to t/t1301-shared-repo.sh. Cc: Heikki Orsila Signed-off-by: Petr Baudis Signed-off-by: Junio C Hamano --- path.c | 2 +- t/t1301-shared-repo.sh | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/path.c b/path.c index 6e3df18499..c1d567996d 100644 --- a/path.c +++ b/path.c @@ -272,7 +272,7 @@ int adjust_shared_perm(const char *path) int tweak = shared_repository; if (!(mode & S_IWUSR)) tweak &= ~0222; - mode = (mode & ~0777) | tweak; + mode |= tweak; } else { /* Preserve old PERM_UMASK behaviour */ if (mode & S_IWUSR) diff --git a/t/t1301-shared-repo.sh b/t/t1301-shared-repo.sh index 6c78c8bc9b..dc85e8b60a 100755 --- a/t/t1301-shared-repo.sh +++ b/t/t1301-shared-repo.sh @@ -17,6 +17,29 @@ test_expect_success 'shared = 0400 (faulty permission u-w)' ' test $ret != "0" ' +for u in 002 022 +do + test_expect_success "shared=1 does not clear bits preset by umask $u" ' + mkdir sub && ( + cd sub && + umask $u && + git init --shared=1 && + test 1 = "$(git config core.sharedrepository)" + ) && + actual=$(ls -l sub/.git/HEAD) + case "$actual" in + -rw-rw-r--*) + : happy + ;; + *) + echo Oops, .git/HEAD is not 0664 but $actual + false + ;; + esac + ' + rm -rf sub +done + test_expect_success 'shared=all' ' mkdir sub && cd sub && From b4958181a9afd0a7a2622d18416f88f9222123f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20Sandstr=C3=B6m?= Date: Thu, 10 Jul 2008 23:36:28 +0200 Subject: [PATCH 57/95] git-mailinfo: document the -n option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Lukas Sandström Signed-off-by: Junio C Hamano --- Documentation/git-mailinfo.txt | 5 ++++- builtin-mailinfo.c | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Documentation/git-mailinfo.txt b/Documentation/git-mailinfo.txt index 183dc1dd75..1e126f4a5c 100644 --- a/Documentation/git-mailinfo.txt +++ b/Documentation/git-mailinfo.txt @@ -8,7 +8,7 @@ git-mailinfo - Extracts patch and authorship from a single e-mail message SYNOPSIS -------- -'git-mailinfo' [-k] [-u | --encoding=] +'git-mailinfo' [-k] [-u | --encoding= | -n] DESCRIPTION @@ -46,6 +46,9 @@ conversion, even with this flag. from what is specified by i18n.commitencoding, this flag can be used to override it. +-n:: + Disable all charset re-coding of the metadata. + :: The commit log message extracted from e-mail, usually except the title line which comes from e-mail Subject. diff --git a/builtin-mailinfo.c b/builtin-mailinfo.c index fa6e8f90a4..962aa34c8e 100644 --- a/builtin-mailinfo.c +++ b/builtin-mailinfo.c @@ -960,7 +960,7 @@ static int mailinfo(FILE *in, FILE *out, int ks, const char *encoding, } static const char mailinfo_usage[] = - "git-mailinfo [-k] [-u | --encoding=] msg patch info"; + "git-mailinfo [-k] [-u | --encoding= | -n] msg patch info"; int cmd_mailinfo(int argc, const char **argv, const char *prefix) { From f9dd4bf4e58af0b4828c7e7013080dba59f8a6b9 Mon Sep 17 00:00:00 2001 From: Dmitry Kakurin Date: Fri, 11 Jul 2008 18:48:16 +0200 Subject: [PATCH 58/95] Fixed text file auto-detection: treat EOF character 032 at the end of file as printable Signed-off-by: Dmitry Kakurin Signed-off-by: Steffen Prohaska Signed-off-by: Junio C Hamano --- convert.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/convert.c b/convert.c index 352b69d4ce..78efed800d 100644 --- a/convert.c +++ b/convert.c @@ -61,6 +61,10 @@ static void gather_stats(const char *buf, unsigned long size, struct text_stat * else stats->printable++; } + + /* If file ends with EOF then don't count this EOF as non-printable. */ + if (size >= 1 && buf[size-1] == '\032') + stats->nonprintable--; } /* From c4adea82c5064971ff6d090be8db89c44456186b Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Fri, 11 Jul 2008 18:55:57 +0200 Subject: [PATCH 59/95] Convert CR/LF to LF in tag signatures On Windows, gpg outputs CR/LF signatures. But since the tag messages are already stripped of the CR by stripspace(), it is arguably nicer to do the same for the tag signature. Actually, this patch does not look for CR/LF, but strips all CRs from the signature. It does so not only on Windows but on all platforms to keep the code simpler. [ spr: ported code to use strbuf ] Signed-off-by: Johannes Schindelin Signed-off-by: Steffen Prohaska Signed-off-by: Junio C Hamano --- builtin-tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/builtin-tag.c b/builtin-tag.c index 3c97c696a5..a70922b21c 100644 --- a/builtin-tag.c +++ b/builtin-tag.c @@ -202,6 +202,7 @@ static int do_sign(struct strbuf *buffer) const char *args[4]; char *bracket; int len; + int i, j; if (!*signingkey) { if (strlcpy(signingkey, git_committer_info(IDENT_ERROR_ON_NO_NAME), @@ -241,6 +242,15 @@ static int do_sign(struct strbuf *buffer) if (finish_command(&gpg) || !len || len < 0) return error("gpg failed to sign the tag"); + /* Strip CR from the line endings, in case we are on Windows. */ + for (i = j = 0; i < buffer->len; i++) + if (buffer->buf[i] != '\r') { + if (i != j) + buffer->buf[j] = buffer->buf[i]; + j++; + } + strbuf_setlen(buffer, j); + return 0; } From fdfd20080239c8564e40498bbaae63c1b87ccdba Mon Sep 17 00:00:00 2001 From: Mike Pape Date: Fri, 11 Jul 2008 18:52:42 +0200 Subject: [PATCH 60/95] We need to check for msys as well as Windows in add--interactive. Signed-off-by: Mike Pape Signed-off-by: Steffen Prohaska Signed-off-by: Junio C Hamano --- git-add--interactive.perl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git-add--interactive.perl b/git-add--interactive.perl index 903953e68e..78a64e6e8a 100755 --- a/git-add--interactive.perl +++ b/git-add--interactive.perl @@ -42,7 +42,7 @@ sub colored { my $patch_mode; sub run_cmd_pipe { - if ($^O eq 'MSWin32') { + if ($^O eq 'MSWin32' || $^O eq 'msys') { my @invalid = grep {m/[":*]/} @_; die "$^O does not support: @invalid\n" if @invalid; my @args = map { m/ /o ? "\"$_\"": $_ } @_; From e0cbc39768884a1e7edcf2dbf6e6825c4b23485a Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Sat, 12 Jul 2008 00:28:18 +0100 Subject: [PATCH 61/95] Add pretty format %aN which gives the author name, respecting .mailmap The pretty format %an does not respect .mailmap, but gives the exact author name recorded in the commit. Sometimes it is more desirable, however, to look if the email has another name mapped to it in .mailmap. This commit adds %aN (and %cN for the committer name) to do exactly that. Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano --- Documentation/pretty-formats.txt | 2 ++ pretty.c | 27 +++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/Documentation/pretty-formats.txt b/Documentation/pretty-formats.txt index 69e6d2fa44..c11d495771 100644 --- a/Documentation/pretty-formats.txt +++ b/Documentation/pretty-formats.txt @@ -101,6 +101,7 @@ The placeholders are: - '%P': parent hashes - '%p': abbreviated parent hashes - '%an': author name +- '%aN': author name (respecting .mailmap) - '%ae': author email - '%ad': author date - '%aD': author date, RFC2822 style @@ -108,6 +109,7 @@ The placeholders are: - '%at': author date, UNIX timestamp - '%ai': author date, ISO 8601 format - '%cn': committer name +- '%cN': committer name (respecting .mailmap) - '%ce': committer email - '%cd': committer date - '%cD': committer date, RFC2822 style diff --git a/pretty.c b/pretty.c index 8eb39e915e..628a5201c1 100644 --- a/pretty.c +++ b/pretty.c @@ -3,6 +3,8 @@ #include "utf8.h" #include "diff.h" #include "revision.h" +#include "path-list.h" +#include "mailmap.h" static char *user_format; @@ -288,6 +290,25 @@ static char *logmsg_reencode(const struct commit *commit, return out; } +static int mailmap_name(struct strbuf *sb, const char *email) +{ + static struct path_list *mail_map; + char buffer[1024]; + + if (!mail_map) { + mail_map = xcalloc(1, sizeof(*mail_map)); + read_mailmap(mail_map, ".mailmap", NULL); + } + + if (!mail_map->nr) + return -1; + + if (!map_email(mail_map, email, buffer, sizeof(buffer))) + return -1; + strbuf_addstr(sb, buffer); + return 0; +} + static size_t format_person_part(struct strbuf *sb, char part, const char *msg, int len) { @@ -309,10 +330,12 @@ static size_t format_person_part(struct strbuf *sb, char part, if (end >= len - 2) goto skip; - if (part == 'n') { /* name */ + if (part == 'n' || part == 'N') { /* name */ while (end > 0 && isspace(msg[end - 1])) end--; - strbuf_add(sb, msg, end); + if (part != 'N' || !msg[end] || !msg[end + 1] || + mailmap_name(sb, msg + end + 2) < 0) + strbuf_add(sb, msg, end); return placeholder_len; } start = ++end; /* save email start position */ From 329636b435a792cb10df8d49b791cdafd6d8189b Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 12 Jul 2008 04:15:56 -0700 Subject: [PATCH 62/95] t0004: fix timing bug The test created an initial commit, made .git/objects unwritable and then exercised various codepaths to create loose commit, tree and blob objects to make sure the commands notice failures from these attempts. However, the initial commit was not preceded with test_tick, which made its object name depend on the timestamp. The names of all the later tree and blob objects the test tried to create were static. If the initial commit's object name happened to begin with the same two hexdigits as the tree or blob objects the test later attempted to create, the fan-out directory in which these tree or blob would be created is already created when the initial commit was made, and the object creation succeeds, and commands being tested should not notice any failure --- in short, the test was bogus. This makes the fan-out directories also unwritable, and adds test_tick before the commit object creation to make the test repeatable. The contents of the file to create a blob from "a" to "60" is to force the name of the blob object to begin with "1b", which shares the fan-out directory with the initial commit that is created with the test. This was useful when diagnosing the breakage of this test. Signed-off-by: Junio C Hamano --- t/t0004-unwritable.sh | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/t/t0004-unwritable.sh b/t/t0004-unwritable.sh index 9255c63c08..63e1217e71 100755 --- a/t/t0004-unwritable.sh +++ b/t/t0004-unwritable.sh @@ -8,6 +8,7 @@ test_expect_success setup ' >file && git add file && + test_tick && git commit -m initial && echo >file && git add file @@ -17,11 +18,11 @@ test_expect_success setup ' test_expect_success 'write-tree should notice unwritable repository' ' ( - chmod a-w .git/objects + chmod a-w .git/objects .git/objects/?? && test_must_fail git write-tree ) status=$? - chmod 775 .git/objects + chmod 775 .git/objects .git/objects/?? (exit $status) ' @@ -29,11 +30,11 @@ test_expect_success 'write-tree should notice unwritable repository' ' test_expect_success 'commit should notice unwritable repository' ' ( - chmod a-w .git/objects + chmod a-w .git/objects .git/objects/?? && test_must_fail git commit -m second ) status=$? - chmod 775 .git/objects + chmod 775 .git/objects .git/objects/?? (exit $status) ' @@ -41,12 +42,12 @@ test_expect_success 'commit should notice unwritable repository' ' test_expect_success 'update-index should notice unwritable repository' ' ( - echo a >file && - chmod a-w .git/objects + echo 6O >file && + chmod a-w .git/objects .git/objects/?? && test_must_fail git update-index file ) status=$? - chmod 775 .git/objects + chmod 775 .git/objects .git/objects/?? (exit $status) ' @@ -55,11 +56,11 @@ test_expect_success 'add should notice unwritable repository' ' ( echo b >file && - chmod a-w .git/objects + chmod a-w .git/objects .git/objects/?? && test_must_fail git add file ) status=$? - chmod 775 .git/objects + chmod 775 .git/objects .git/objects/?? (exit $status) ' From 0af0ac7ebbbd2afbc4399d5658e193460b4caaa3 Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Sat, 12 Jul 2008 15:56:19 +0100 Subject: [PATCH 63/95] Move MERGE_RR from .git/rr-cache/ into .git/ If you want to reuse the rerere cache in another repository, and set a symbolic link to it, you do not want to have the two repositories interfer with each other by accessing the _same_ MERGE_RR. For example, if you use contrib/git-new-workdir to set up a second working directory, and you have a conflict in one working directory, but commit in the other working directory first, the wrong "resolution" will be recorded. The easy solution is to move MERGE_RR out of the rr-cache/ directory, which also corresponds with the notion that rr-cache/ contains cached resolutions, not some intermediate temporary states. Noticed by Kalle Olavi Niemitalo. Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano --- branch.c | 2 +- builtin-rerere.c | 2 +- t/t4200-rerere.sh | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/branch.c b/branch.c index 56e949232c..b1e59f2196 100644 --- a/branch.c +++ b/branch.c @@ -166,7 +166,7 @@ void create_branch(const char *head, void remove_branch_state(void) { unlink(git_path("MERGE_HEAD")); - unlink(git_path("rr-cache/MERGE_RR")); + unlink(git_path("MERGE_RR")); unlink(git_path("MERGE_MSG")); unlink(git_path("SQUASH_MSG")); } diff --git a/builtin-rerere.c b/builtin-rerere.c index 69c3a52d5e..1db2e0c8fb 100644 --- a/builtin-rerere.c +++ b/builtin-rerere.c @@ -429,7 +429,7 @@ static int setup_rerere(struct path_list *merge_rr) if (!is_rerere_enabled()) return -1; - merge_rr_path = xstrdup(git_path("rr-cache/MERGE_RR")); + merge_rr_path = xstrdup(git_path("MERGE_RR")); fd = hold_lock_file_for_update(&write_lock, merge_rr_path, 1); read_rr(merge_rr); return fd; diff --git a/t/t4200-rerere.sh b/t/t4200-rerere.sh index cf10557dd2..b5a4202998 100755 --- a/t/t4200-rerere.sh +++ b/t/t4200-rerere.sh @@ -57,7 +57,7 @@ test_expect_success 'conflicting merge' ' ! git merge first ' -sha1=$(sed -e 's/ .*//' .git/rr-cache/MERGE_RR) +sha1=$(sed -e 's/ .*//' .git/MERGE_RR) rr=.git/rr-cache/$sha1 test_expect_success 'recorded preimage' "grep ^=======$ $rr/preimage" @@ -143,7 +143,7 @@ test_expect_success 'rerere kicked in' "! grep ^=======$ a1" test_expect_success 'rerere prefers first change' 'test_cmp a1 expect' rm $rr/postimage -echo "$sha1 a1" | perl -pe 'y/\012/\000/' > .git/rr-cache/MERGE_RR +echo "$sha1 a1" | perl -pe 'y/\012/\000/' > .git/MERGE_RR test_expect_success 'rerere clear' 'git rerere clear' @@ -190,7 +190,7 @@ test_expect_success 'file2 added differently in two branches' ' git add file2 && git commit -m version2 && ! git merge fourth && - sha1=$(sed -e "s/ .*//" .git/rr-cache/MERGE_RR) && + sha1=$(sed -e "s/ .*//" .git/MERGE_RR) && rr=.git/rr-cache/$sha1 && echo Cello > file2 && git add file2 && From ab02dfe533f55535bdb66e05776a4081020322c6 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 13 Jul 2008 02:37:42 +0000 Subject: [PATCH 64/95] bash completion: Improve responsiveness of git-log completion Junio noticed the bash completion has been taking a long time lately. Petr Baudis tracked it down to 72e5e989b ("bash: Add space after unique command name is completed."). Tracing the code showed we spent significant time inside of this loop within __gitcomp, due to the string copying overhead. [28.146109654] _git common over [28.164791148] gitrefs in [28.280302268] gitrefs dir out [28.300939737] gitcomp in [28.308378112] gitcomp pre-case * [28.313407453] gitcomp iter in * [28.701270296] gitcomp iter out [28.713370786] out normal Since __git_refs avoids this string copying by forking and using echo we use the same trick here when we need to finish generating the names for the caller. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano --- contrib/completion/git-completion.bash | 28 +++++++++++++++----------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash index cff28a88af..0734ea313c 100755 --- a/contrib/completion/git-completion.bash +++ b/contrib/completion/git-completion.bash @@ -114,9 +114,20 @@ __git_ps1 () fi } +__gitcomp_1 () +{ + local c IFS=' '$'\t'$'\n' + for c in $1; do + case "$c$2" in + --*=*) printf %s$'\n' "$c$2" ;; + *.) printf %s$'\n' "$c$2" ;; + *) printf %s$'\n' "$c$2 " ;; + esac + done +} + __gitcomp () { - local all c s=$'\n' IFS=' '$'\t'$'\n' local cur="${COMP_WORDS[COMP_CWORD]}" if [ $# -gt 2 ]; then cur="$3" @@ -124,21 +135,14 @@ __gitcomp () case "$cur" in --*=) COMPREPLY=() - return ;; *) - for c in $1; do - case "$c$4" in - --*=*) all="$all$c$4$s" ;; - *.) all="$all$c$4$s" ;; - *) all="$all$c$4 $s" ;; - esac - done + local IFS=$'\n' + COMPREPLY=($(compgen -P "$2" \ + -W "$(__gitcomp_1 "$1" "$4")" \ + -- "$cur")) ;; esac - IFS=$s - COMPREPLY=($(compgen -P "$2" -W "$all" -- "$cur")) - return } __git_heads () From 460abee5cd7d0cb06e5f424b1dae793af4e66cbb Mon Sep 17 00:00:00 2001 From: Stephan Beyer Date: Sat, 12 Jul 2008 17:46:59 +0200 Subject: [PATCH 65/95] git-am: Do not exit silently if committer is unset Signed-off-by: Stephan Beyer Signed-off-by: Junio C Hamano --- git-am.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/git-am.sh b/git-am.sh index 2c517ede59..83b277acfd 100755 --- a/git-am.sh +++ b/git-am.sh @@ -30,7 +30,8 @@ set_reflog_action am require_work_tree cd_to_toplevel -git var GIT_COMMITTER_IDENT >/dev/null || exit +git var GIT_COMMITTER_IDENT >/dev/null || + die "You need to set your committer info first" stop_here () { echo "$1" >"$dotest/next" From fce87ae53883d22a9912abb2d11a926de747006e Mon Sep 17 00:00:00 2001 From: "Alexander N. Gavrilov" Date: Sat, 12 Jul 2008 22:00:57 +0400 Subject: [PATCH 66/95] Fix quadratic performance in rewrite_one. Parent commits are usually older than their children. Thus, on each iteration of the loop in rewrite_one, add_parents_to_list traverses all commits previously processed by the loop. It performs very poorly in case of very long rewrite chains. Signed-off-by: Alexander Gavrilov Signed-off-by: Junio C Hamano --- revision.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/revision.c b/revision.c index fc66755259..d464f14d50 100644 --- a/revision.c +++ b/revision.c @@ -412,10 +412,26 @@ static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit) commit->object.flags |= TREESAME; } -static int add_parents_to_list(struct rev_info *revs, struct commit *commit, struct commit_list **list) +static void insert_by_date_cached(struct commit *p, struct commit_list **head, + struct commit_list *cached_base, struct commit_list **cache) +{ + struct commit_list *new_entry; + + if (cached_base && p->date < cached_base->item->date) + new_entry = insert_by_date(p, &cached_base->next); + else + new_entry = insert_by_date(p, head); + + if (cache && (!*cache || p->date < (*cache)->item->date)) + *cache = new_entry; +} + +static int add_parents_to_list(struct rev_info *revs, struct commit *commit, + struct commit_list **list, struct commit_list **cache_ptr) { struct commit_list *parent = commit->parents; unsigned left_flag; + struct commit_list *cached_base = cache_ptr ? *cache_ptr : NULL; if (commit->object.flags & ADDED) return 0; @@ -445,7 +461,7 @@ static int add_parents_to_list(struct rev_info *revs, struct commit *commit, str if (p->object.flags & SEEN) continue; p->object.flags |= SEEN; - insert_by_date(p, list); + insert_by_date_cached(p, list, cached_base, cache_ptr); } return 0; } @@ -470,7 +486,7 @@ static int add_parents_to_list(struct rev_info *revs, struct commit *commit, str p->object.flags |= left_flag; if (!(p->object.flags & SEEN)) { p->object.flags |= SEEN; - insert_by_date(p, list); + insert_by_date_cached(p, list, cached_base, cache_ptr); } if(revs->first_parent_only) break; @@ -611,7 +627,7 @@ static int limit_list(struct rev_info *revs) if (revs->max_age != -1 && (commit->date < revs->max_age)) obj->flags |= UNINTERESTING; - if (add_parents_to_list(revs, commit, &list) < 0) + if (add_parents_to_list(revs, commit, &list, NULL) < 0) return -1; if (obj->flags & UNINTERESTING) { mark_parents_uninteresting(commit); @@ -1458,10 +1474,12 @@ enum rewrite_result { static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp) { + struct commit_list *cache = NULL; + for (;;) { struct commit *p = *pp; if (!revs->limited) - if (add_parents_to_list(revs, p, &revs->commits) < 0) + if (add_parents_to_list(revs, p, &revs->commits, &cache) < 0) return rewrite_one_error; if (p->parents && p->parents->next) return rewrite_one_ok; @@ -1580,7 +1598,7 @@ static struct commit *get_revision_1(struct rev_info *revs) if (revs->max_age != -1 && (commit->date < revs->max_age)) continue; - if (add_parents_to_list(revs, commit, &revs->commits) < 0) + if (add_parents_to_list(revs, commit, &revs->commits, NULL) < 0) return NULL; } From 8ec0dd66fa277615fe79ad10096d81edb263d6d1 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Sat, 12 Jul 2008 20:42:10 +0200 Subject: [PATCH 67/95] t6021: add a new test for git-merge-resolve It should fail properly if there are multiple merge bases, but there were no test for this till now. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t6021-merge-criss-cross.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/t/t6021-merge-criss-cross.sh b/t/t6021-merge-criss-cross.sh index 0ab14a6e81..331b9b07d4 100755 --- a/t/t6021-merge-criss-cross.sh +++ b/t/t6021-merge-criss-cross.sh @@ -89,4 +89,8 @@ EOF test_expect_success 'Criss-cross merge result' 'cmp file file-expect' +test_expect_success 'Criss-cross merge fails (-s resolve)' \ +'git reset --hard A^ && +test_must_fail git merge -s resolve -m "final merge" B' + test_done From 3f4d1c639347317788f2c5080f89de53772499ce Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Sun, 13 Jul 2008 00:33:35 +0200 Subject: [PATCH 68/95] Add a new test for git-merge-resolve Actually this is a simple test, just to ensure merge-resolve properly calls read-tree. read-tree itself already has more complex tests. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano --- t/t7605-merge-resolve.sh | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 t/t7605-merge-resolve.sh diff --git a/t/t7605-merge-resolve.sh b/t/t7605-merge-resolve.sh new file mode 100755 index 0000000000..ee21a107fd --- /dev/null +++ b/t/t7605-merge-resolve.sh @@ -0,0 +1,46 @@ +#!/bin/sh + +test_description='git-merge + +Testing the resolve strategy.' + +. ./test-lib.sh + +test_expect_success 'setup' ' + echo c0 > c0.c && + git add c0.c && + git commit -m c0 && + git tag c0 && + echo c1 > c1.c && + git add c1.c && + git commit -m c1 && + git tag c1 && + git reset --hard c0 && + echo c2 > c2.c && + git add c2.c && + git commit -m c2 && + git tag c2 && + git reset --hard c0 && + echo c3 > c2.c && + git add c2.c && + git commit -m c3 && + git tag c3 +' + +test_expect_success 'merge c1 to c2' ' + git reset --hard c1 && + git merge -s resolve c2 && + test "$(git rev-parse c1)" != "$(git rev-parse HEAD)" && + test "$(git rev-parse c1)" = "$(git rev-parse HEAD^1)" && + test "$(git rev-parse c2)" = "$(git rev-parse HEAD^2)" && + git diff --exit-code && + test -f c0.c && + test -f c1.c && + test -f c2.c +' + +test_expect_success 'merge c2 to c3 (fails)' ' + git reset --hard c2 && + test_must_fail git merge -s resolve c3 +' +test_done From 3d1dd4728b83e4c08d9fa7aaf2aa946e1012e061 Mon Sep 17 00:00:00 2001 From: Sverre Hvammen Johansen Date: Sun, 13 Jul 2008 08:13:55 +0000 Subject: [PATCH 69/95] reduce_heads(): thinkofix When comparing two commit objects for equality, it is sufficient to compare their in-core pointers because the object layer guarantees the uniqueness. However, comparing pointers to two "struct commit_list" instances that point at the same commit does not make any sense. Spotted by Sverre Hvammen Johansen who wrote an additional test to expose the problem, fixed by Miklos Vajna. Signed-off-by: Junio C Hamano --- commit.c | 2 +- t/t7600-merge.sh | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/commit.c b/commit.c index d20b14ee3e..03e73f323a 100644 --- a/commit.c +++ b/commit.c @@ -747,7 +747,7 @@ struct commit_list *reduce_heads(struct commit_list *heads) num_other = 0; for (q = heads; q; q = q->next) { - if (p == q) + if (p->item == q->item) continue; other[num_other++] = q->item; } diff --git a/t/t7600-merge.sh b/t/t7600-merge.sh index 72ef2e55d9..f035ea376e 100755 --- a/t/t7600-merge.sh +++ b/t/t7600-merge.sh @@ -479,4 +479,15 @@ test_expect_success 'merge log message' ' test_debug 'gitk --all' +test_expect_success 'merge c1 with c0, c2, c0, and c1' ' + git reset --hard c1 && + git config branch.master.mergeoptions "" && + test_tick && + git merge c0 c2 c0 c1 && + verify_merge file result.1-5 && + verify_parents $c1 $c2 +' + +test_debug 'gitk --all' + test_done From f049e0944d32715ee8893d290d1c52888216fbe4 Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Sat, 12 Jul 2008 15:56:59 +0100 Subject: [PATCH 70/95] git-gui: MERGE_RR lives in .git/ directly with newer Git versions Now that MERGE_RR was moved out of .git/rr-cache/, we have to delete it somewhere else. Just in case somebody wants to use a newer git-gui with an older Git, the file .git/rr-cache/MERGE_RR is removed, too (if it exists). Signed-off-by: Johannes Schindelin Signed-off-by: Shawn O. Pearce --- lib/merge.tcl | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/merge.tcl b/lib/merge.tcl index cc26b07808..5c01875b05 100644 --- a/lib/merge.tcl +++ b/lib/merge.tcl @@ -257,6 +257,7 @@ proc _reset_wait {fd} { catch {file delete [gitdir MERGE_HEAD]} catch {file delete [gitdir rr-cache MERGE_RR]} + catch {file delete [gitdir MERGE_RR]} catch {file delete [gitdir SQUASH_MSG]} catch {file delete [gitdir MERGE_MSG]} catch {file delete [gitdir GITGUI_MSG]} From 191a8e32b38c7ff0dd884df7bd323b7a5bd4336c Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sun, 13 Jul 2008 15:23:43 -0700 Subject: [PATCH 71/95] GIT 1.5.6.3 Signed-off-by: Junio C Hamano --- Documentation/RelNotes-1.5.6.3.txt | 26 ++++++++++++++++++-------- Documentation/git.txt | 3 ++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Documentation/RelNotes-1.5.6.3.txt b/Documentation/RelNotes-1.5.6.3.txt index dd0559b64a..942611299d 100644 --- a/Documentation/RelNotes-1.5.6.3.txt +++ b/Documentation/RelNotes-1.5.6.3.txt @@ -4,8 +4,16 @@ GIT v1.5.6.3 Release Notes Fixes since v1.5.6.2 -------------------- +* Setting core.sharerepository to traditional "true" value was supposed to make + the repository group writable but should not affect permission for others. + However, since 1.5.6, it was broken to drop permission for others when umask is + 022, making the repository unreadable by others. + * Setting GIT_TRACE will report spawning of external process via run_command(). +* Using an object with very deep delta chain pinned memory needed for extracting + intermediate base objects unnecessarily long, leading to excess memory usage. + * Bash completion script did not notice '--' marker on the command line and tried the relatively slow "ref completion" even when completing arguments after one. @@ -14,6 +22,12 @@ Fixes since v1.5.6.2 tree file for it confused "racy-git avoidance" logic into thinking that the path is now unchanged. +* The section that describes attributes related to git-archive were placed + in a wrong place in the gitattributes(5) manual page. + +* "git am" was not helpful to the users when it detected that the committer + information is not set up properly yet. + * "git clone" had a leftover debugging fprintf(). * "git clone -q" was not quiet enough as it used to and gave object count @@ -23,8 +37,10 @@ Fixes since v1.5.6.2 good thing if the remote side is well packed but otherwise not, especially for a project that is not really big. -* The section that describes attributes related to git-archive were placed - in a wrong place in the gitattributes(5) manual page. +* "git daemon" used to call syslog() from a signal handler, which + could raise signals of its own but generally is not reentrant. This + was fixed by restructuring the code to report syslog() after the handler + returns. * When "git push" tries to remove a remote ref, and corresponding tracking ref is missing, we used to report error (i.e. failure to @@ -34,9 +50,3 @@ Fixes since v1.5.6.2 MIME multipart mail correctly. Contains other various documentation fixes. - --- -exec >/var/tmp/1 -O=v1.5.6.2-23-ge965647 -echo O=$(git describe maint) -git shortlog --no-merges $O..maint diff --git a/Documentation/git.txt b/Documentation/git.txt index 0d6fe9cf79..33ae79b9d5 100644 --- a/Documentation/git.txt +++ b/Documentation/git.txt @@ -43,9 +43,10 @@ unreleased) version of git, that is available from 'master' branch of the `git.git` repository. Documentation for older releases are available here: -* link:v1.5.6.2/git.html[documentation for release 1.5.6.2] +* link:v1.5.6.3/git.html[documentation for release 1.5.6.3] * release notes for + link:RelNotes-1.5.6.3.txt[1.5.6.3]. link:RelNotes-1.5.6.2.txt[1.5.6.2]. link:RelNotes-1.5.6.1.txt[1.5.6.1]. link:RelNotes-1.5.6.txt[1.5.6]. From 356a32a23a2118e12a62fa42876a261feb554b1a Mon Sep 17 00:00:00 2001 From: Stephan Beyer Date: Sat, 12 Jul 2008 17:47:16 +0200 Subject: [PATCH 72/95] git-am/git-mailsplit: correct synopsis for reading from stdin Invoking git-am or git-mailsplit without mbox or Maildir results in reading an mbox from stdin. Mention this in the synopsis and usage strings. Signed-off-by: Stephan Beyer Signed-off-by: Junio C Hamano --- Documentation/git-am.txt | 4 ++-- builtin-mailsplit.c | 2 +- git-am.sh | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Documentation/git-am.txt b/Documentation/git-am.txt index 3863eebcef..eeb23b25b0 100644 --- a/Documentation/git-am.txt +++ b/Documentation/git-am.txt @@ -12,8 +12,8 @@ SYNOPSIS 'git am' [--signoff] [--keep] [--utf8 | --no-utf8] [--3way] [--interactive] [--binary] [--whitespace=