From c89fb6b19a91add28a111cf257e01cba2c8de69c Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 19 Jan 2008 00:42:22 -0800 Subject: builtin-apply.c: refactor small part that matches context This moves three "if" conditions out of line from find_offset() function, which is responsible for finding the matching place in the preimage to apply the patch. There is no change in the logic of the program. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 15432b6..2c052f8 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1437,6 +1437,17 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf) } } +static int match_fragment(const char *buf, unsigned long size, + unsigned long try, + const char *fragment, unsigned long fragsize) +{ + if (try + fragsize > size) + return 0; + if (memcmp(buf + try, fragment, fragsize)) + return 0; + return 1; +} + static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines) @@ -1461,8 +1472,7 @@ static int find_offset(const char *buf, unsigned long size, } /* Exact line number? */ - if ((start + fragsize <= size) && - !memcmp(buf + start, fragment, fragsize)) + if (match_fragment(buf, size, start, fragment, fragsize)) return start; /* @@ -1494,9 +1504,7 @@ static int find_offset(const char *buf, unsigned long size, try = forwards; } - if (try + fragsize > size) - continue; - if (memcmp(buf + try, fragment, fragsize)) + if (!match_fragment(buf, size, try, fragment, fragsize)) continue; n = (i >> 1)+1; if (i & 1) -- cgit v0.10.2-6-g49f6 From fcb77bc57b4d2f63bd4d0c2fd36498f308d28cbe Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 19 Jan 2008 02:16:16 -0800 Subject: builtin-apply.c: restructure "offset" matching This restructures code to find matching location with offset in find_offset() function, so that there is need for only one call site of match_fragment() function. There still isn't a change in the logic of the program. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 2c052f8..0a304ab 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1452,8 +1452,8 @@ static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines) { - int i; - unsigned long start, backwards, forwards; + int i, no_more_backwards, no_more_forwards; + unsigned long start, backwards, forwards, try; if (fragsize > size) return -1; @@ -1471,32 +1471,44 @@ static int find_offset(const char *buf, unsigned long size, } } - /* Exact line number? */ - if (match_fragment(buf, size, start, fragment, fragsize)) - return start; - /* * There's probably some smart way to do this, but I'll leave * that to the smart and beautiful people. I'm simple and stupid. */ backwards = start; forwards = start; + try = start; + for (i = 0; ; i++) { - unsigned long try; - int n; + no_more_backwards = !backwards; + no_more_forwards = (forwards + fragsize > size); + + if (match_fragment(buf, size, try, fragment, fragsize)) { + int shift = ((i+1) >> 1); + if (i & 1) + shift = -shift; + *lines = shift; + return try; + } + + again: + if (no_more_backwards && no_more_forwards) + break; - /* "backward" */ if (i & 1) { - if (!backwards) { - if (forwards + fragsize > size) - break; - continue; + if (no_more_backwards) { + i++; + goto again; } do { --backwards; } while (backwards && buf[backwards-1] != '\n'); try = backwards; } else { + if (no_more_forwards) { + i++; + goto again; + } while (forwards + fragsize <= size) { if (buf[forwards++] == '\n') break; @@ -1504,18 +1516,7 @@ static int find_offset(const char *buf, unsigned long size, try = forwards; } - if (!match_fragment(buf, size, try, fragment, fragsize)) - continue; - n = (i >> 1)+1; - if (i & 1) - n = -n; - *lines = n; - return try; } - - /* - * We should start searching forward and backward. - */ return -1; } -- cgit v0.10.2-6-g49f6 From dc41976a3eed1d9c93fdc08c448bab969db4e0ec Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 19 Jan 2008 01:58:34 -0800 Subject: builtin-apply.c: push match-beginning/end logic down This moves the logic to force match at the beginning and/or at the end of the buffer to the actual function that finds the match from its caller. This is a necessary preparation for the next step to allow matching disregarding certain differences, such as whitespace changes. We probably could optimize this even more by taking advantage of the fact that match_beginning and match_end forces the match to be at an exact location (anchored at the beginning and/or the end), but that's for another commit. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 0a304ab..f84a405 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1439,18 +1439,36 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf) static int match_fragment(const char *buf, unsigned long size, unsigned long try, - const char *fragment, unsigned long fragsize) + const char *fragment, unsigned long fragsize, + int match_beginning, int match_end) { - if (try + fragsize > size) + if (match_beginning && try) return 0; - if (memcmp(buf + try, fragment, fragsize)) - return 0; - return 1; + + /* + * Do we have an exact match? If we were told to match + * at the end, size must be exactly at try+fragsize, + * otherwise try+fragsize must be still within the preimage, + * and either case, the old piece should match the preimage + * exactly. + */ + if ((match_end + ? (try + fragsize == size) + : (try + fragsize <= size)) && + !memcmp(buf + try, fragment, fragsize)) + return 1; + + /* + * NEEDSWORK: We can optionally match fuzzily here, but + * that is for a later round. + */ + return 0; } static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, - int line, int *lines) + int line, int *lines, + int match_beginning, int match_end) { int i, no_more_backwards, no_more_forwards; unsigned long start, backwards, forwards, try; @@ -1483,7 +1501,8 @@ static int find_offset(const char *buf, unsigned long size, no_more_backwards = !backwards; no_more_forwards = (forwards + fragsize > size); - if (match_fragment(buf, size, try, fragment, fragsize)) { + if (match_fragment(buf, size, try, fragment, fragsize, + match_beginning, match_end)) { int shift = ((i+1) >> 1); if (i & 1) shift = -shift; @@ -1765,17 +1784,16 @@ static int apply_one_fragment(struct strbuf *buf, struct fragment *frag, pos = frag->newpos; for (;;) { offset = find_offset(buf->buf, buf->len, - oldlines, oldsize, pos, &lines); - if (match_end && offset + oldsize != buf->len) - offset = -1; - if (match_beginning && offset) - offset = -1; + oldlines, oldsize, pos, &lines, + match_beginning, match_end); if (offset >= 0) { if (ws_error_action == correct_ws_error && - (buf->len - oldsize - offset == 0)) /* end of file? */ + (buf->len - oldsize - offset == 0)) + /* end of file? */ newsize -= new_blank_lines_at_end; - /* Warn if it was necessary to reduce the number + /* + * Warn if it was necessary to reduce the number * of context lines. */ if ((leading != frag->leading) || -- cgit v0.10.2-6-g49f6 From b94f2eda99646fea71f84ccd895d94b0001d0db6 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 26 Jan 2008 17:42:49 -0800 Subject: builtin-apply.c: make it more line oriented This changes the way git-apply internally works to be more line oriented. The logic to find where the patch applies with offset used to count line numbers by always counting LF from the beginning of the buffer, but it is simplified because we count the line length of the target file and the preimage snippet upfront now. The ultimate motivation is to allow applying patches whose preimage context has whitespace corruption that has already been corrected in the local copy. For that purpose, we introduce a table of line-hash that allows us to match lines that differ only in whitespaces. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index f84a405..e046e87 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -161,6 +161,92 @@ struct patch { struct patch *next; }; +/* + * A line in a file, len-bytes long (includes the terminating LF, + * except for an incomplete line at the end if the file ends with + * one), and its contents hashes to 'hash'. + */ +struct line { + size_t len; + unsigned hash : 24; + unsigned flag : 8; +}; + +/* + * This represents a "file", which is an array of "lines". + */ +struct image { + char *buf; + size_t len; + size_t nr; + struct line *line_allocated; + struct line *line; +}; + +static uint32_t hash_line(const char *cp, size_t len) +{ + size_t i; + uint32_t h; + for (i = 0, h = 0; i < len; i++) { + if (!isspace(cp[i])) { + h = h * 3 + (cp[i] & 0xff); + } + } + return h; +} + +static void prepare_image(struct image *image, char *buf, size_t len, + int prepare_linetable) +{ + const char *cp, *ep; + int n; + + image->buf = buf; + image->len = len; + + if (!prepare_linetable) { + image->line = NULL; + image->line_allocated = NULL; + image->nr = 0; + return; + } + + ep = image->buf + image->len; + + /* First count lines */ + cp = image->buf; + n = 0; + while (cp < ep) { + cp = strchrnul(cp, '\n'); + n++; + cp++; + } + + image->line_allocated = xcalloc(n, sizeof(struct line)); + image->line = image->line_allocated; + image->nr = n; + cp = image->buf; + n = 0; + while (cp < ep) { + const char *next; + for (next = cp; next < ep && *next != '\n'; next++) + ; + if (next < ep) + next++; + image->line[n].len = next - cp; + image->line[n].hash = hash_line(cp, next - cp); + cp = next; + n++; + } +} + +static void clear_image(struct image *image) +{ + free(image->buf); + image->buf = NULL; + image->len = 0; +} + static void say_patch_name(FILE *output, const char *pre, struct patch *patch, const char *post) { @@ -1437,14 +1523,29 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf) } } -static int match_fragment(const char *buf, unsigned long size, +static int match_fragment(struct image *img, + struct image *preimage, + struct image *postimage, unsigned long try, - const char *fragment, unsigned long fragsize, + int try_lno, int match_beginning, int match_end) { - if (match_beginning && try) + int i; + + if (preimage->nr + try_lno > img->nr) + return 0; + + if (match_beginning && try_lno) + return 0; + + if (match_end && preimage->nr + try_lno != img->nr) return 0; + /* Quick hash check */ + for (i = 0; i < preimage->nr; i++) + if (preimage->line[i].hash != img->line[try_lno + i].hash) + return 0; + /* * Do we have an exact match? If we were told to match * at the end, size must be exactly at try+fragsize, @@ -1453,9 +1554,9 @@ static int match_fragment(const char *buf, unsigned long size, * exactly. */ if ((match_end - ? (try + fragsize == size) - : (try + fragsize <= size)) && - !memcmp(buf + try, fragment, fragsize)) + ? (try + preimage->len == img->len) + : (try + preimage->len <= img->len)) && + !memcmp(img->buf + try, preimage->buf, preimage->len)) return 1; /* @@ -1465,105 +1566,78 @@ static int match_fragment(const char *buf, unsigned long size, return 0; } -static int find_offset(const char *buf, unsigned long size, - const char *fragment, unsigned long fragsize, - int line, int *lines, - int match_beginning, int match_end) +static int find_pos(struct image *img, + struct image *preimage, + struct image *postimage, + int line, + int match_beginning, int match_end) { - int i, no_more_backwards, no_more_forwards; - unsigned long start, backwards, forwards, try; + int i; + unsigned long backwards, forwards, try; + int backwards_lno, forwards_lno, try_lno; - if (fragsize > size) + if (preimage->nr > img->nr) return -1; - start = 0; - if (line > 1) { - unsigned long offset = 0; - i = line-1; - while (offset + fragsize <= size) { - if (buf[offset++] == '\n') { - start = offset; - if (!--i) - break; - } - } - } + try = 0; + for (i = 0; i < line; i++) + try += img->line[i].len; /* * There's probably some smart way to do this, but I'll leave * that to the smart and beautiful people. I'm simple and stupid. */ - backwards = start; - forwards = start; - try = start; + backwards = try; + backwards_lno = line; + forwards = try; + forwards_lno = line; + try_lno = line; for (i = 0; ; i++) { - no_more_backwards = !backwards; - no_more_forwards = (forwards + fragsize > size); - - if (match_fragment(buf, size, try, fragment, fragsize, - match_beginning, match_end)) { - int shift = ((i+1) >> 1); - if (i & 1) - shift = -shift; - *lines = shift; - return try; - } + if (match_fragment(img, preimage, postimage, + try, try_lno, + match_beginning, match_end)) + return try_lno; again: - if (no_more_backwards && no_more_forwards) + if (backwards_lno == 0 && forwards_lno == img->nr) break; if (i & 1) { - if (no_more_backwards) { + if (backwards_lno == 0) { i++; goto again; } - do { - --backwards; - } while (backwards && buf[backwards-1] != '\n'); + backwards_lno--; + backwards -= img->line[backwards_lno].len; try = backwards; + try_lno = backwards_lno; } else { - if (no_more_forwards) { + if (forwards_lno == img->nr) { i++; goto again; } - while (forwards + fragsize <= size) { - if (buf[forwards++] == '\n') - break; - } + forwards += img->line[forwards_lno].len; + forwards_lno++; try = forwards; + try_lno = forwards_lno; } } return -1; } -static void remove_first_line(const char **rbuf, int *rsize) +static void remove_first_line(struct image *img) { - const char *buf = *rbuf; - int size = *rsize; - unsigned long offset; - offset = 0; - while (offset <= size) { - if (buf[offset++] == '\n') - break; - } - *rsize = size - offset; - *rbuf = buf + offset; + img->buf += img->line[0].len; + img->len -= img->line[0].len; + img->line++; + img->nr--; } -static void remove_last_line(const char **rbuf, int *rsize) +static void remove_last_line(struct image *img) { - const char *buf = *rbuf; - int size = *rsize; - unsigned long offset; - offset = size - 1; - while (offset > 0) { - if (buf[--offset] == '\n') - break; - } - *rsize = offset + 1; + img->len -= img->line[--img->nr].len; } static int apply_line(char *output, const char *patch, int plen, @@ -1668,19 +1742,75 @@ static int apply_line(char *output, const char *patch, int plen, return output + plen - buf; } -static int apply_one_fragment(struct strbuf *buf, struct fragment *frag, +static void update_image(struct image *img, + int applied_pos, + struct image *preimage, + struct image *postimage) +{ + /* + * remove the copy of preimage at offset in img + * and replace it with postimage + */ + int i, nr; + size_t remove_count, insert_count, applied_at = 0; + char *result; + + for (i = 0; i < applied_pos; i++) + applied_at += img->line[i].len; + + remove_count = 0; + for (i = 0; i < preimage->nr; i++) + remove_count += img->line[applied_pos + i].len; + insert_count = postimage->len; + + /* Adjust the contents */ + result = xmalloc(img->len + insert_count - remove_count + 1); + memcpy(result, img->buf, applied_at); + memcpy(result + applied_at, postimage->buf, postimage->len); + memcpy(result + applied_at + postimage->len, + img->buf + (applied_at + remove_count), + img->len - (applied_at + remove_count)); + free(img->buf); + img->buf = result; + img->len += insert_count - remove_count; + result[img->len] = '\0'; + + /* Adjust the line table */ + nr = img->nr + postimage->nr - preimage->nr; + if (preimage->nr < postimage->nr) { + /* + * NOTE: this knows that we never call remove_first_line() + * on anything other than pre/post image. + */ + img->line = xrealloc(img->line, nr * sizeof(*img->line)); + img->line_allocated = img->line; + } + if (preimage->nr != postimage->nr) + memmove(img->line + applied_pos + postimage->nr, + img->line + applied_pos + preimage->nr, + (img->nr - (applied_pos + preimage->nr)) * + sizeof(*img->line)); + memcpy(img->line + applied_pos, + postimage->line, + postimage->nr * sizeof(*img->line)); + img->nr = nr; +} + +static int apply_one_fragment(struct image *img, struct fragment *frag, int inaccurate_eof, unsigned ws_rule) { int match_beginning, match_end; const char *patch = frag->patch; - int offset, size = frag->size; + int size = frag->size; char *old = xmalloc(size); char *new = xmalloc(size); - const char *oldlines, *newlines; + char *oldlines, *newlines; int oldsize = 0, newsize = 0; int new_blank_lines_at_end = 0; unsigned long leading, trailing; - int pos, lines; + int pos, applied_pos; + struct image preimage; + struct image postimage; while (size > 0) { char first; @@ -1780,32 +1910,16 @@ static int apply_one_fragment(struct strbuf *buf, struct fragment *frag, match_end = !trailing; } - lines = 0; - pos = frag->newpos; + pos = frag->newpos ? (frag->newpos - 1) : 0; + prepare_image(&preimage, oldlines, oldsize, 1); + prepare_image(&postimage, newlines, newsize, 1); for (;;) { - offset = find_offset(buf->buf, buf->len, - oldlines, oldsize, pos, &lines, - match_beginning, match_end); - if (offset >= 0) { - if (ws_error_action == correct_ws_error && - (buf->len - oldsize - offset == 0)) - /* end of file? */ - newsize -= new_blank_lines_at_end; - /* - * Warn if it was necessary to reduce the number - * of context lines. - */ - if ((leading != frag->leading) || - (trailing != frag->trailing)) - fprintf(stderr, "Context reduced to (%ld/%ld)" - " to apply fragment at %d\n", - leading, trailing, pos + lines); - - strbuf_splice(buf, offset, oldsize, newlines, newsize); - offset = 0; + applied_pos = find_pos(img, &preimage, &postimage, + pos, match_beginning, match_end); + + if (applied_pos >= 0) break; - } /* Am I at my context limits? */ if ((leading <= p_context) && (trailing <= p_context)) @@ -1814,33 +1928,63 @@ static int apply_one_fragment(struct strbuf *buf, struct fragment *frag, match_beginning = match_end = 0; continue; } + /* * Reduce the number of context lines; reduce both * leading and trailing if they are equal otherwise * just reduce the larger context. */ if (leading >= trailing) { - remove_first_line(&oldlines, &oldsize); - remove_first_line(&newlines, &newsize); + remove_first_line(&preimage); + remove_first_line(&postimage); pos--; leading--; } if (trailing > leading) { - remove_last_line(&oldlines, &oldsize); - remove_last_line(&newlines, &newsize); + remove_last_line(&preimage); + remove_last_line(&postimage); trailing--; } } - if (offset && apply_verbosely) - error("while searching for:\n%.*s", oldsize, oldlines); + if (applied_pos >= 0) { + if (ws_error_action == correct_ws_error && + new_blank_lines_at_end && + postimage.nr + applied_pos == img->nr) { + /* + * If the patch application adds blank lines + * at the end, and if the patch applies at the + * end of the image, remove those added blank + * lines. + */ + while (new_blank_lines_at_end--) + remove_last_line(&postimage); + } + + /* + * Warn if it was necessary to reduce the number + * of context lines. + */ + if ((leading != frag->leading) || + (trailing != frag->trailing)) + fprintf(stderr, "Context reduced to (%ld/%ld)" + " to apply fragment at %d\n", + leading, trailing, applied_pos+1); + update_image(img, applied_pos, &preimage, &postimage); + } else { + if (apply_verbosely) + error("while searching for:\n%.*s", oldsize, oldlines); + } free(old); free(new); - return offset; + free(preimage.line_allocated); + free(postimage.line_allocated); + + return (applied_pos < 0); } -static int apply_binary_fragment(struct strbuf *buf, struct patch *patch) +static int apply_binary_fragment(struct image *img, struct patch *patch) { struct fragment *fragment = patch->fragments; unsigned long len; @@ -1857,22 +2001,26 @@ static int apply_binary_fragment(struct strbuf *buf, struct patch *patch) } switch (fragment->binary_patch_method) { case BINARY_DELTA_DEFLATED: - dst = patch_delta(buf->buf, buf->len, fragment->patch, + dst = patch_delta(img->buf, img->len, fragment->patch, fragment->size, &len); if (!dst) return -1; - /* XXX patch_delta NUL-terminates */ - strbuf_attach(buf, dst, len, len + 1); + clear_image(img); + img->buf = dst; + img->len = len; return 0; case BINARY_LITERAL_DEFLATED: - strbuf_reset(buf); - strbuf_add(buf, fragment->patch, fragment->size); + clear_image(img); + img->len = fragment->size; + img->buf = xmalloc(img->len+1); + memcpy(img->buf, fragment->patch, img->len); + img->buf[img->len] = '\0'; return 0; } return -1; } -static int apply_binary(struct strbuf *buf, struct patch *patch) +static int apply_binary(struct image *img, struct patch *patch) { const char *name = patch->old_name ? patch->old_name : patch->new_name; unsigned char sha1[20]; @@ -1893,7 +2041,7 @@ static int apply_binary(struct strbuf *buf, struct patch *patch) * See if the old one matches what the patch * applies to. */ - hash_sha1_file(buf->buf, buf->len, blob_type, sha1); + hash_sha1_file(img->buf, img->len, blob_type, sha1); if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix)) return error("the patch applies to '%s' (%s), " "which does not match the " @@ -1902,14 +2050,14 @@ static int apply_binary(struct strbuf *buf, struct patch *patch) } else { /* Otherwise, the old one must be empty. */ - if (buf->len) + if (img->len) return error("the patch applies to an empty " "'%s' but it is not empty", name); } get_sha1_hex(patch->new_sha1_prefix, sha1); if (is_null_sha1(sha1)) { - strbuf_release(buf); + clear_image(img); return 0; /* deletion patch */ } @@ -1924,20 +2072,21 @@ static int apply_binary(struct strbuf *buf, struct patch *patch) return error("the necessary postimage %s for " "'%s' cannot be read", patch->new_sha1_prefix, name); - /* XXX read_sha1_file NUL-terminates */ - strbuf_attach(buf, result, size, size + 1); + clear_image(img); + img->buf = result; + img->len = size; } else { /* * We have verified buf matches the preimage; * apply the patch data to it, which is stored * in the patch->fragments->{patch,size}. */ - if (apply_binary_fragment(buf, patch)) + if (apply_binary_fragment(img, patch)) return error("binary patch does not apply to '%s'", name); /* verify that the result matches */ - hash_sha1_file(buf->buf, buf->len, blob_type, sha1); + hash_sha1_file(img->buf, img->len, blob_type, sha1); if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix)) return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name, patch->new_sha1_prefix, sha1_to_hex(sha1)); @@ -1946,7 +2095,7 @@ static int apply_binary(struct strbuf *buf, struct patch *patch) return 0; } -static int apply_fragments(struct strbuf *buf, struct patch *patch) +static int apply_fragments(struct image *img, struct patch *patch) { struct fragment *frag = patch->fragments; const char *name = patch->old_name ? patch->old_name : patch->new_name; @@ -1954,10 +2103,10 @@ static int apply_fragments(struct strbuf *buf, struct patch *patch) unsigned inaccurate_eof = patch->inaccurate_eof; if (patch->is_binary) - return apply_binary(buf, patch); + return apply_binary(img, patch); while (frag) { - if (apply_one_fragment(buf, frag, inaccurate_eof, ws_rule)) { + if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) { error("patch failed: %s:%ld", name, frag->oldpos); if (!apply_with_reject) return -1; @@ -1993,6 +2142,9 @@ static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf) static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce) { struct strbuf buf; + struct image image; + size_t len; + char *img; strbuf_init(&buf, 0); if (cached) { @@ -2015,9 +2167,14 @@ static int apply_data(struct patch *patch, struct stat *st, struct cache_entry * } } - if (apply_fragments(&buf, patch) < 0) + img = strbuf_detach(&buf, &len); + prepare_image(&image, img, len, !patch->is_binary); + + if (apply_fragments(&image, patch) < 0) return -1; /* note with --reject this succeeds. */ - patch->result = strbuf_detach(&buf, &patch->resultsize); + patch->result = image.buf; + patch->resultsize = image.len; + free(image.line_allocated); if (0 < patch->is_delete && patch->resultsize) return error("removal patch leaves file contents"); -- cgit v0.10.2-6-g49f6 From ecf4c2ec6ba6dc39e72c6b37f2a238e28fec2dc1 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Mon, 28 Jan 2008 03:04:30 -0800 Subject: builtin-apply.c: optimize match_beginning/end processing a bit. Wnen the caller knows the hunk needs to match at the beginning or at the end, there is no point starting from the line number that is found in the patch and trying match with increasing offset. The logic to find matching lines was made more line oriented with the previous patch and this optimization is now trivial. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index e046e87..dc650f1 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1579,6 +1579,16 @@ static int find_pos(struct image *img, if (preimage->nr > img->nr) return -1; + /* + * If match_begining or match_end is specified, there is no + * point starting from a wrong line that will never match and + * wander around and wait for a match at the specified end. + */ + if (match_beginning) + line = 0; + else if (match_end) + line = img->nr - preimage->nr; + try = 0; for (i = 0; i < line; i++) try += img->line[i].len; -- cgit v0.10.2-6-g49f6 From c330fdd42dc57127272534cd2a8dd9569334b219 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 29 Jan 2008 00:17:55 -0800 Subject: builtin-apply.c: mark common context lines in lineinfo structure. This updates the way preimage and postimage in a patch hunk is parsed and prepared for applying. By looking at image->line[n].flag, the code can tell if it is a common context line that is the same between the preimage and the postimage. This matters when we actually start applying a patch with contexts that have whitespace breakages that have already been fixed in the target file. diff --git a/builtin-apply.c b/builtin-apply.c index dc650f1..acd84f9 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -170,6 +170,7 @@ struct line { size_t len; unsigned hash : 24; unsigned flag : 8; +#define LINE_COMMON 1 }; /* @@ -179,6 +180,7 @@ struct image { char *buf; size_t len; size_t nr; + size_t alloc; struct line *line_allocated; struct line *line; }; @@ -195,49 +197,39 @@ static uint32_t hash_line(const char *cp, size_t len) return h; } +static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) +{ + ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); + img->line_allocated[img->nr].len = len; + img->line_allocated[img->nr].hash = hash_line(bol, len); + img->line_allocated[img->nr].flag = flag; + img->nr++; +} + static void prepare_image(struct image *image, char *buf, size_t len, int prepare_linetable) { const char *cp, *ep; - int n; + memset(image, 0, sizeof(*image)); image->buf = buf; image->len = len; - if (!prepare_linetable) { - image->line = NULL; - image->line_allocated = NULL; - image->nr = 0; + if (!prepare_linetable) return; - } ep = image->buf + image->len; - - /* First count lines */ cp = image->buf; - n = 0; - while (cp < ep) { - cp = strchrnul(cp, '\n'); - n++; - cp++; - } - - image->line_allocated = xcalloc(n, sizeof(struct line)); - image->line = image->line_allocated; - image->nr = n; - cp = image->buf; - n = 0; while (cp < ep) { const char *next; for (next = cp; next < ep && *next != '\n'; next++) ; if (next < ep) next++; - image->line[n].len = next - cp; - image->line[n].hash = hash_line(cp, next - cp); + add_line_info(image, cp, next - cp, 0); cp = next; - n++; } + image->line = image->line_allocated; } static void clear_image(struct image *image) @@ -1822,6 +1814,9 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, struct image preimage; struct image postimage; + memset(&preimage, 0, sizeof(preimage)); + memset(&postimage, 0, sizeof(postimage)); + while (size > 0) { char first; int len = linelen(patch, size); @@ -1857,10 +1852,14 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, break; old[oldsize++] = '\n'; new[newsize++] = '\n'; + add_line_info(&preimage, "\n", 1, LINE_COMMON); + add_line_info(&postimage, "\n", 1, LINE_COMMON); break; case ' ': case '-': memcpy(old + oldsize, patch + 1, plen); + add_line_info(&preimage, old + oldsize, plen, + (first == ' ' ? LINE_COMMON : 0)); oldsize += plen; if (first == '-') break; @@ -1869,6 +1868,9 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, if (first != '+' || !no_add) { int added = apply_line(new + newsize, patch, plen, ws_rule); + add_line_info(&postimage, new + newsize, added, + (first == '+' ? 0 : LINE_COMMON)); + newsize += added; if (first == '+' && added == 1 && new[newsize-1] == '\n') @@ -1921,8 +1923,13 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, } pos = frag->newpos ? (frag->newpos - 1) : 0; - prepare_image(&preimage, oldlines, oldsize, 1); - prepare_image(&postimage, newlines, newsize, 1); + preimage.buf = old; + preimage.len = oldsize; + postimage.buf = new; + postimage.len = newsize; + preimage.line = preimage.line_allocated; + postimage.line = postimage.line_allocated; + for (;;) { applied_pos = find_pos(img, &preimage, &postimage, -- cgit v0.10.2-6-g49f6 From 61e08ccacbfdc6046ccabdfdb01f7755ed5ad8b1 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 30 Jan 2008 13:12:25 -0800 Subject: builtin-apply.c: clean-up apply_one_fragment() We had two pointer variables pointing to the same buffer and an integer variable used to index into its tail part that was active (old, oldlines and oldsize for the preimage, and their 'new' counterparts for the postimage). To help readability, use 'oldlines' as the allocated pointer, and use 'old' as the pointer to the tail that advances while the code builds up the contents in the buffer. The size 'oldsize' can be computed as (old-oldines). Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index acd84f9..7fb3305 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1804,10 +1804,7 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, int match_beginning, match_end; const char *patch = frag->patch; int size = frag->size; - char *old = xmalloc(size); - char *new = xmalloc(size); - char *oldlines, *newlines; - int oldsize = 0, newsize = 0; + char *old, *new, *oldlines, *newlines; int new_blank_lines_at_end = 0; unsigned long leading, trailing; int pos, applied_pos; @@ -1816,7 +1813,11 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, memset(&preimage, 0, sizeof(preimage)); memset(&postimage, 0, sizeof(postimage)); + oldlines = xmalloc(size); + newlines = xmalloc(size); + old = oldlines; + new = newlines; while (size > 0) { char first; int len = linelen(patch, size); @@ -1833,7 +1834,7 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, * followed by "\ No newline", then we also remove the * last one (which is the newline, of course). */ - plen = len-1; + plen = len - 1; if (len < size && patch[len] == '\\') plen--; first = *patch; @@ -1850,30 +1851,30 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, if (plen < 0) /* ... followed by '\No newline'; nothing */ break; - old[oldsize++] = '\n'; - new[newsize++] = '\n'; + *old++ = '\n'; + *new++ = '\n'; add_line_info(&preimage, "\n", 1, LINE_COMMON); add_line_info(&postimage, "\n", 1, LINE_COMMON); break; case ' ': case '-': - memcpy(old + oldsize, patch + 1, plen); - add_line_info(&preimage, old + oldsize, plen, + memcpy(old, patch + 1, plen); + add_line_info(&preimage, old, plen, (first == ' ' ? LINE_COMMON : 0)); - oldsize += plen; + old += plen; if (first == '-') break; /* Fall-through for ' ' */ case '+': if (first != '+' || !no_add) { - int added = apply_line(new + newsize, patch, + int added = apply_line(new, patch, plen, ws_rule); - add_line_info(&postimage, new + newsize, added, + add_line_info(&postimage, new, added, (first == '+' ? 0 : LINE_COMMON)); - newsize += added; + new += added; if (first == '+' && - added == 1 && new[newsize-1] == '\n') + added == 1 && new[-1] == '\n') added_blank_line = 1; } break; @@ -1892,16 +1893,13 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, patch += len; size -= len; } - if (inaccurate_eof && - oldsize > 0 && old[oldsize - 1] == '\n' && - newsize > 0 && new[newsize - 1] == '\n') { - oldsize--; - newsize--; + old > oldlines && old[-1] == '\n' && + new > newlines && new[-1] == '\n') { + old--; + new--; } - oldlines = old; - newlines = new; leading = frag->leading; trailing = frag->trailing; @@ -1923,10 +1921,10 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, } pos = frag->newpos ? (frag->newpos - 1) : 0; - preimage.buf = old; - preimage.len = oldsize; - postimage.buf = new; - postimage.len = newsize; + preimage.buf = oldlines; + preimage.len = old - oldlines; + postimage.buf = newlines; + postimage.len = new - newlines; preimage.line = preimage.line_allocated; postimage.line = postimage.line_allocated; @@ -1990,11 +1988,12 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, update_image(img, applied_pos, &preimage, &postimage); } else { if (apply_verbosely) - error("while searching for:\n%.*s", oldsize, oldlines); + error("while searching for:\n%.*s", + (int)(old - oldlines), oldlines); } - free(old); - free(new); + free(oldlines); + free(newlines); free(preimage.line_allocated); free(postimage.line_allocated); -- cgit v0.10.2-6-g49f6 From 8441a9a84278718e9bfd49112dcc55136cea394f Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 30 Jan 2008 13:19:58 -0800 Subject: builtin-apply.c: simplify calling site to apply_line() The function apply_line() changed its behaviour depending on the ws_error_action, whitespace_error and if the input was a context. Make its caller responsible for such checking so that we can convert the function to copy the contents of line while fixing whitespace breakage more easily. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 7fb3305..d0d008f 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1642,7 +1642,7 @@ static void remove_last_line(struct image *img) img->len -= img->line[--img->nr].len; } -static int apply_line(char *output, const char *patch, int plen, +static int copy_wsfix(char *output, const char *patch, int plen, unsigned ws_rule) { /* @@ -1659,12 +1659,6 @@ static int apply_line(char *output, const char *patch, int plen, int need_fix_leading_space = 0; char *buf; - if ((ws_error_action != correct_ws_error) || !whitespace_error || - *patch != '+') { - memcpy(output, patch + 1, plen); - return plen; - } - /* * Strip trailing whitespace */ @@ -1821,7 +1815,7 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, while (size > 0) { char first; int len = linelen(patch, size); - int plen; + int plen, added; int added_blank_line = 0; if (!len) @@ -1866,17 +1860,25 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, break; /* Fall-through for ' ' */ case '+': - if (first != '+' || !no_add) { - int added = apply_line(new, patch, - plen, ws_rule); - add_line_info(&postimage, new, added, - (first == '+' ? 0 : LINE_COMMON)); - - new += added; - if (first == '+' && - added == 1 && new[-1] == '\n') - added_blank_line = 1; + /* --no-add does not add new lines */ + if (first == '+' && no_add) + break; + + if (first != '+' || + !whitespace_error || + ws_error_action != correct_ws_error) { + memcpy(new, patch + 1, plen); + added = plen; + } + else { + added = copy_wsfix(new, patch, plen, ws_rule); } + add_line_info(&postimage, new, added, + (first == '+' ? 0 : LINE_COMMON)); + new += added; + if (first == '+' && + added == 1 && new[-1] == '\n') + added_blank_line = 1; break; case '@': case '\\': /* Ignore it, we already handled it */ -- cgit v0.10.2-6-g49f6 From 42ab241cfacdcbae910d51c06fa2870cc94b0af3 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 30 Jan 2008 14:27:50 -0800 Subject: builtin-apply.c: do not feed copy_wsfix() leading '+' The "patch" parameter used to include leading '+' of an added line in the patch, and the array was treated as 1-based. Make it accept the contents of the line alone and simplify the code. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index d0d008f..0bc33bd 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1646,16 +1646,15 @@ static int copy_wsfix(char *output, const char *patch, int plen, unsigned ws_rule) { /* - * plen is number of bytes to be copied from patch, - * starting at patch+1 (patch[0] is '+'). Typically - * patch[plen] is '\n', unless this is the incomplete - * last line. + * plen is number of bytes to be copied from patch, starting + * at patch. Typically patch[plen-1] is '\n', unless this is + * the incomplete last line. */ int i; int add_nl_to_tail = 0; int fixed = 0; - int last_tab_in_indent = 0; - int last_space_in_indent = 0; + int last_tab_in_indent = -1; + int last_space_in_indent = -1; int need_fix_leading_space = 0; char *buf; @@ -1663,11 +1662,11 @@ static int copy_wsfix(char *output, const char *patch, int plen, * Strip trailing whitespace */ if ((ws_rule & WS_TRAILING_SPACE) && - (1 < plen && isspace(patch[plen-1]))) { - if (patch[plen] == '\n') + (2 < plen && isspace(patch[plen-2]))) { + if (patch[plen-1] == '\n') add_nl_to_tail = 1; plen--; - while (0 < plen && isspace(patch[plen])) + while (0 < plen && isspace(patch[plen-1])) plen--; fixed = 1; } @@ -1675,25 +1674,25 @@ static int copy_wsfix(char *output, const char *patch, int plen, /* * Check leading whitespaces (indent) */ - for (i = 1; i < plen; i++) { + for (i = 0; i < plen; i++) { char ch = patch[i]; if (ch == '\t') { last_tab_in_indent = i; if ((ws_rule & WS_SPACE_BEFORE_TAB) && - 0 < last_space_in_indent) + 0 <= last_space_in_indent) need_fix_leading_space = 1; } else if (ch == ' ') { last_space_in_indent = i; if ((ws_rule & WS_INDENT_WITH_NON_TAB) && 8 <= i - last_tab_in_indent) need_fix_leading_space = 1; - } - else + } else break; } buf = output; if (need_fix_leading_space) { + /* Process indent ourselves */ int consecutive_spaces = 0; int last = last_tab_in_indent + 1; @@ -1706,10 +1705,10 @@ static int copy_wsfix(char *output, const char *patch, int plen, } /* - * between patch[1..last], strip the funny spaces, + * between patch[0..last-1], strip the funny spaces, * updating them to tab as needed. */ - for (i = 1; i < last; i++, plen--) { + for (i = 0; i < last; i++) { char ch = patch[i]; if (ch != ' ') { consecutive_spaces = 0; @@ -1724,13 +1723,12 @@ static int copy_wsfix(char *output, const char *patch, int plen, } while (0 < consecutive_spaces--) *output++ = ' '; + plen -= last; + patch += last; fixed = 1; - i = last; } - else - i = 1; - memcpy(output, patch + i, plen); + memcpy(output, patch, plen); if (add_nl_to_tail) output[plen++] = '\n'; if (fixed) @@ -1871,7 +1869,7 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, added = plen; } else { - added = copy_wsfix(new, patch, plen, ws_rule); + added = copy_wsfix(new, patch + 1, plen, ws_rule); } add_line_info(&postimage, new, added, (first == '+' ? 0 : LINE_COMMON)); -- cgit v0.10.2-6-g49f6 From ee810b715912347775fa06a0d5b16092b4908d66 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 30 Jan 2008 15:11:23 -0800 Subject: builtin-apply.c: move copy_wsfix() function a bit higher. I'll be calling this from match_fragment() in later rounds. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 0bc33bd..2af625a 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1515,6 +1515,100 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf) } } +static int copy_wsfix(char *output, const char *patch, int plen, + unsigned ws_rule) +{ + /* + * plen is number of bytes to be copied from patch, starting + * at patch. Typically patch[plen-1] is '\n', unless this is + * the incomplete last line. + */ + int i; + int add_nl_to_tail = 0; + int fixed = 0; + int last_tab_in_indent = -1; + int last_space_in_indent = -1; + int need_fix_leading_space = 0; + char *buf; + + /* + * Strip trailing whitespace + */ + if ((ws_rule & WS_TRAILING_SPACE) && + (2 < plen && isspace(patch[plen-2]))) { + if (patch[plen-1] == '\n') + add_nl_to_tail = 1; + plen--; + while (0 < plen && isspace(patch[plen-1])) + plen--; + fixed = 1; + } + + /* + * Check leading whitespaces (indent) + */ + for (i = 0; i < plen; i++) { + char ch = patch[i]; + if (ch == '\t') { + last_tab_in_indent = i; + if ((ws_rule & WS_SPACE_BEFORE_TAB) && + 0 <= last_space_in_indent) + need_fix_leading_space = 1; + } else if (ch == ' ') { + last_space_in_indent = i; + if ((ws_rule & WS_INDENT_WITH_NON_TAB) && + 8 <= i - last_tab_in_indent) + need_fix_leading_space = 1; + } else + break; + } + + buf = output; + if (need_fix_leading_space) { + /* Process indent ourselves */ + int consecutive_spaces = 0; + int last = last_tab_in_indent + 1; + + if (ws_rule & WS_INDENT_WITH_NON_TAB) { + /* have "last" point at one past the indent */ + if (last_tab_in_indent < last_space_in_indent) + last = last_space_in_indent + 1; + else + last = last_tab_in_indent + 1; + } + + /* + * between patch[0..last-1], strip the funny spaces, + * updating them to tab as needed. + */ + for (i = 0; i < last; i++) { + char ch = patch[i]; + if (ch != ' ') { + consecutive_spaces = 0; + *output++ = ch; + } else { + consecutive_spaces++; + if (consecutive_spaces == 8) { + *output++ = '\t'; + consecutive_spaces = 0; + } + } + } + while (0 < consecutive_spaces--) + *output++ = ' '; + plen -= last; + patch += last; + fixed = 1; + } + + memcpy(output, patch, plen); + if (add_nl_to_tail) + output[plen++] = '\n'; + if (fixed) + applied_after_fixing_ws++; + return output + plen - buf; +} + static int match_fragment(struct image *img, struct image *preimage, struct image *postimage, @@ -1642,100 +1736,6 @@ static void remove_last_line(struct image *img) img->len -= img->line[--img->nr].len; } -static int copy_wsfix(char *output, const char *patch, int plen, - unsigned ws_rule) -{ - /* - * plen is number of bytes to be copied from patch, starting - * at patch. Typically patch[plen-1] is '\n', unless this is - * the incomplete last line. - */ - int i; - int add_nl_to_tail = 0; - int fixed = 0; - int last_tab_in_indent = -1; - int last_space_in_indent = -1; - int need_fix_leading_space = 0; - char *buf; - - /* - * Strip trailing whitespace - */ - if ((ws_rule & WS_TRAILING_SPACE) && - (2 < plen && isspace(patch[plen-2]))) { - if (patch[plen-1] == '\n') - add_nl_to_tail = 1; - plen--; - while (0 < plen && isspace(patch[plen-1])) - plen--; - fixed = 1; - } - - /* - * Check leading whitespaces (indent) - */ - for (i = 0; i < plen; i++) { - char ch = patch[i]; - if (ch == '\t') { - last_tab_in_indent = i; - if ((ws_rule & WS_SPACE_BEFORE_TAB) && - 0 <= last_space_in_indent) - need_fix_leading_space = 1; - } else if (ch == ' ') { - last_space_in_indent = i; - if ((ws_rule & WS_INDENT_WITH_NON_TAB) && - 8 <= i - last_tab_in_indent) - need_fix_leading_space = 1; - } else - break; - } - - buf = output; - if (need_fix_leading_space) { - /* Process indent ourselves */ - int consecutive_spaces = 0; - int last = last_tab_in_indent + 1; - - if (ws_rule & WS_INDENT_WITH_NON_TAB) { - /* have "last" point at one past the indent */ - if (last_tab_in_indent < last_space_in_indent) - last = last_space_in_indent + 1; - else - last = last_tab_in_indent + 1; - } - - /* - * between patch[0..last-1], strip the funny spaces, - * updating them to tab as needed. - */ - for (i = 0; i < last; i++) { - char ch = patch[i]; - if (ch != ' ') { - consecutive_spaces = 0; - *output++ = ch; - } else { - consecutive_spaces++; - if (consecutive_spaces == 8) { - *output++ = '\t'; - consecutive_spaces = 0; - } - } - } - while (0 < consecutive_spaces--) - *output++ = ' '; - plen -= last; - patch += last; - fixed = 1; - } - - memcpy(output, patch, plen); - if (add_nl_to_tail) - output[plen++] = '\n'; - if (fixed) - applied_after_fixing_ws++; - return output + plen - buf; -} - static void update_image(struct image *img, int applied_pos, struct image *preimage, -- cgit v0.10.2-6-g49f6 From c607aaa2f05b4dc38a6573f44b6f71db05dd8b39 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 30 Jan 2008 15:13:37 -0800 Subject: builtin-apply.c: pass ws_rule down to match_fragment() This is necessary to allow match_fragment() to attempt a match with a preimage that is based on a version before whitespace errors were fixed. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 2af625a..5f3c047 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1614,6 +1614,7 @@ static int match_fragment(struct image *img, struct image *postimage, unsigned long try, int try_lno, + unsigned ws_rule, int match_beginning, int match_end) { int i; @@ -1656,6 +1657,7 @@ static int find_pos(struct image *img, struct image *preimage, struct image *postimage, int line, + unsigned ws_rule, int match_beginning, int match_end) { int i; @@ -1691,7 +1693,7 @@ static int find_pos(struct image *img, for (i = 0; ; i++) { if (match_fragment(img, preimage, postimage, - try, try_lno, + try, try_lno, ws_rule, match_beginning, match_end)) return try_lno; @@ -1930,8 +1932,8 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, for (;;) { - applied_pos = find_pos(img, &preimage, &postimage, - pos, match_beginning, match_end); + applied_pos = find_pos(img, &preimage, &postimage, pos, + ws_rule, match_beginning, match_end); if (applied_pos >= 0) break; -- cgit v0.10.2-6-g49f6 From c1beba5b479a39143ebef96ba10103bbd9a70089 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 30 Jan 2008 15:24:34 -0800 Subject: git-apply --whitespace=fix: fix whitespace fuzz introduced by previous run When you have more than one patch series, an earlier one of which tries to introduce whitespace breakages and a later one of which has such a new line in its context, "git-apply --whitespace=fix" will apply and fix the whitespace breakages in the earlier one, making the resulting file not to match the context of the later patch. A short demonstration is in the new test, t4125. For example, suppose the first patch is: diff a/hello.txt b/hello.txt --- a/hello.txt +++ b/hello.txt @@ -20,3 +20,3 @@ Hello world.$ -How Are you$ -Today?$ +How are you $ +today? $ to fix broken case in the string, but it introduces unwanted trailing whitespaces to the result (pretend you are looking at "cat -e" output of the patch --- '$' signs are not in the patch but are shown to make the EOL stand out). And the second patch is to change the wording of the greeting further: diff a/hello.txt b/hello.txt --- a/hello.txt +++ b/hello.txt @@ -18,5 +18,5 @@ Greetings $ -Hello world.$ +Hello, everybody. $ How are you $ -today? $ +these days? $ If you apply the first one with --whitespace=fix, you will get this as the result: Hello world.$ How are you$ today?$ and this does not match the preimage of the second patch, which demands extra whitespace after "How are you" and "today?". This series is about teaching "git apply --whitespace=fix" to cope with this situation better. If the patch does not apply, it rewrites the second patch like this and retries: diff a/hello.txt b/hello.txt --- a/hello.txt +++ b/hello.txt @@ -18,5 +18,5 @@ Greetings$ -Hello world.$ +Hello, everybody.$ How are you$ -today?$ +these days?$ This is done by rewriting the preimage lines in the hunk (i.e. the lines that begin with ' ' or '-'), using the same whitespace fixing rules as it is using to apply the patches, so that it can notice what it did to the previous ones in the series. A careful reader may notice that the first patch in the example did not touch the "Greetings" line, so the trailing whitespace that is in the original preimage of the second patch is not from the series. Is rewriting this context line a problem? If you think about it, you will realize that the reason for the difference is because the submitter's tree was based on an earlier version of the file that had whitespaces wrong on that "Greetings" line, and the change that introduced the "Greetings" line was added independently of this two-patch series to our tree already with an earlier "git apply --whitespace=fix". So it may appear this logic is rewriting too much, it is not so. It is just rewriting what we would have rewritten in the past. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 5f3c047..fccf4a4 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1516,7 +1516,7 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf) } static int copy_wsfix(char *output, const char *patch, int plen, - unsigned ws_rule) + unsigned ws_rule, int count_error) { /* * plen is number of bytes to be copied from patch, starting @@ -1604,11 +1604,74 @@ static int copy_wsfix(char *output, const char *patch, int plen, memcpy(output, patch, plen); if (add_nl_to_tail) output[plen++] = '\n'; - if (fixed) + if (fixed && count_error) applied_after_fixing_ws++; return output + plen - buf; } +static void update_pre_post_images(struct image *preimage, + struct image *postimage, + char *buf, + size_t len) +{ + int i, ctx; + char *new, *old, *fixed; + struct image fixed_preimage; + + /* + * Update the preimage with whitespace fixes. Note that we + * are not losing preimage->buf -- apply_one_fragment() will + * free "oldlines". + */ + prepare_image(&fixed_preimage, buf, len, 1); + assert(fixed_preimage.nr == preimage->nr); + for (i = 0; i < preimage->nr; i++) + fixed_preimage.line[i].flag = preimage->line[i].flag; + free(preimage->line_allocated); + *preimage = fixed_preimage; + + /* + * Adjust the common context lines in postimage, in place. + * This is possible because whitespace fixing does not make + * the string grow. + */ + new = old = postimage->buf; + fixed = preimage->buf; + for (i = ctx = 0; i < postimage->nr; i++) { + size_t len = postimage->line[i].len; + if (!(postimage->line[i].flag & LINE_COMMON)) { + /* an added line -- no counterparts in preimage */ + memmove(new, old, len); + old += len; + new += len; + continue; + } + + /* a common context -- skip it in the original postimage */ + old += len; + + /* and find the corresponding one in the fixed preimage */ + while (ctx < preimage->nr && + !(preimage->line[ctx].flag & LINE_COMMON)) { + fixed += preimage->line[ctx].len; + ctx++; + } + if (preimage->nr <= ctx) + die("oops"); + + /* and copy it in, while fixing the line length */ + len = preimage->line[ctx].len; + memcpy(new, fixed, len); + new += len; + fixed += len; + postimage->line[i].len = len; + ctx++; + } + + /* Fix the length of the whole thing */ + postimage->len = new - postimage->buf; +} + static int match_fragment(struct image *img, struct image *preimage, struct image *postimage, @@ -1618,6 +1681,7 @@ static int match_fragment(struct image *img, int match_beginning, int match_end) { int i; + char *fixed_buf, *buf, *orig, *target; if (preimage->nr + try_lno > img->nr) return 0; @@ -1646,10 +1710,68 @@ static int match_fragment(struct image *img, !memcmp(img->buf + try, preimage->buf, preimage->len)) return 1; + if (ws_error_action != correct_ws_error) + return 0; + + /* + * The hunk does not apply byte-by-byte, but the hash says + * it might with whitespace fuzz. + */ + fixed_buf = xmalloc(preimage->len + 1); + buf = fixed_buf; + orig = preimage->buf; + target = img->buf + try; + for (i = 0; i < preimage->nr; i++) { + size_t fixlen; /* length after fixing the preimage */ + size_t oldlen = preimage->line[i].len; + size_t tgtlen = img->line[try_lno + i].len; + size_t tgtfixlen; /* length after fixing the target line */ + char tgtfixbuf[1024], *tgtfix; + int match; + + /* Try fixing the line in the preimage */ + fixlen = copy_wsfix(buf, orig, oldlen, ws_rule, 0); + + /* Try fixing the line in the target */ + if (sizeof(tgtfixbuf) < tgtlen) + tgtfix = tgtfixbuf; + else + tgtfix = xmalloc(tgtlen); + tgtfixlen = copy_wsfix(tgtfix, target, tgtlen, ws_rule, 0); + + /* + * If they match, either the preimage was based on + * a version before our tree fixed whitespace breakage, + * or we are lacking a whitespace-fix patch the tree + * the preimage was based on already had (i.e. target + * has whitespace breakage, the preimage doesn't). + * In either case, we are fixing the whitespace breakages + * so we might as well take the fix together with their + * real change. + */ + match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen)); + + if (tgtfix != tgtfixbuf) + free(tgtfix); + if (!match) + goto unmatch_exit; + + orig += oldlen; + buf += fixlen; + target += tgtlen; + } + /* - * NEEDSWORK: We can optionally match fuzzily here, but - * that is for a later round. + * Yes, the preimage is based on an older version that still + * has whitespace breakages unfixed, and fixing them makes the + * hunk match. Update the context lines in the postimage. */ + update_pre_post_images(preimage, postimage, + fixed_buf, buf - fixed_buf); + return 1; + + unmatch_exit: + free(fixed_buf); return 0; } @@ -1871,7 +1993,8 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, added = plen; } else { - added = copy_wsfix(new, patch + 1, plen, ws_rule); + added = copy_wsfix(new, patch + 1, plen, + ws_rule, 1); } add_line_info(&postimage, new, added, (first == '+' ? 0 : LINE_COMMON)); diff --git a/t/t4125-apply-ws-fuzz.sh b/t/t4125-apply-ws-fuzz.sh new file mode 100755 index 0000000..d6f15be --- /dev/null +++ b/t/t4125-apply-ws-fuzz.sh @@ -0,0 +1,103 @@ +#!/bin/sh + +test_description='applying patch that has broken whitespaces in context' + +. ./test-lib.sh + +test_expect_success setup ' + + >file && + git add file && + + # file-0 is full of whitespace breakages + for l in a bb c d eeee f ggg h + do + echo "$l " + done >file-0 && + + # patch-0 creates a whitespace broken file + cat file-0 >file && + git diff >patch-0 && + git add file && + + # file-1 is still full of whitespace breakages, + # but has one line updated, without fixing any + # whitespaces. + # patch-1 records that change. + sed -e "s/d/D/" file-0 >file-1 && + cat file-1 >file && + git diff >patch-1 && + + # patch-all is the effect of both patch-0 and patch-1 + >file && + git add file && + cat file-1 >file && + git diff >patch-all && + + # patch-2 is the same as patch-1 but is based + # on a version that already has whitespace fixed, + # and does not introduce whitespace breakages. + sed -e "s/ $//" patch-1 >patch-2 && + + # If all whitespace breakages are fixed the contents + # should look like file-fixed + sed -e "s/ $//" file-1 >file-fixed + +' + +test_expect_success nofix ' + + >file && + git add file && + + # Baseline. Applying without fixing any whitespace + # breakages. + git apply --whitespace=nowarn patch-0 && + git apply --whitespace=nowarn patch-1 && + + # The result should obviously match. + diff -u file-1 file +' + +test_expect_success 'withfix (forward)' ' + + >file && + git add file && + + # The first application will munge the context lines + # the second patch depends on. We should be able to + # adjust and still apply. + git apply --whitespace=fix patch-0 && + git apply --whitespace=fix patch-1 && + + diff -u file-fixed file +' + +test_expect_success 'withfix (backward)' ' + + >file && + git add file && + + # Now we have a whitespace breakages on our side. + git apply --whitespace=nowarn patch-0 && + + # And somebody sends in a patch based on image + # with whitespace already fixed. + git apply --whitespace=fix patch-2 && + + # The result should accept the whitespace fixed + # postimage. But the line with "h" is beyond context + # horizon and left unfixed. + + sed -e /h/d file-fixed >fixed-head && + sed -e /h/d file >file-head && + diff -u fixed-head file-head && + + sed -n -e /h/p file-fixed >fixed-tail && + sed -n -e /h/p file >file-tail && + + ! diff -u fixed-tail file-tail + +' + +test_done -- cgit v0.10.2-6-g49f6 From b2979ff599a6bcf9dbf5e2ef1e32b81a1b88e115 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 15 Jan 2008 00:59:05 -0800 Subject: core.whitespace: cr-at-eol This new error mode allows a line to have a carriage return at the end of the line when checking and fixing trailing whitespace errors. Some people like to keep CRLF line ending recorded in the repository, and still want to take advantage of the automated trailing whitespace stripping. We still show ^M in the diff output piped to "less" to remind them that they do have the CR at the end, but these carriage return characters at the end are no longer flagged as errors. Signed-off-by: Junio C Hamano diff --git a/Documentation/config.txt b/Documentation/config.txt index 4e222f1..44cb640 100644 --- a/Documentation/config.txt +++ b/Documentation/config.txt @@ -308,6 +308,10 @@ core.whitespace:: error (enabled by default). * `indent-with-non-tab` treats a line that is indented with 8 or more space characters as an error (not enabled by default). +* `cr-at-eol` treats a carriage-return at the end of line as + part of the line terminator, i.e. with it, `trailing-space` + does not trigger if the character before such a carriage-return + is not a whitespace (not enabled by default). alias.*:: Command aliases for the linkgit:git[1] command wrapper - e.g. diff --git a/builtin-apply.c b/builtin-apply.c index fccf4a4..2b8ba81 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1525,6 +1525,7 @@ static int copy_wsfix(char *output, const char *patch, int plen, */ int i; int add_nl_to_tail = 0; + int add_cr_to_tail = 0; int fixed = 0; int last_tab_in_indent = -1; int last_space_in_indent = -1; @@ -1536,12 +1537,19 @@ static int copy_wsfix(char *output, const char *patch, int plen, */ if ((ws_rule & WS_TRAILING_SPACE) && (2 < plen && isspace(patch[plen-2]))) { - if (patch[plen-1] == '\n') + if (patch[plen - 1] == '\n') { add_nl_to_tail = 1; - plen--; - while (0 < plen && isspace(patch[plen-1])) plen--; - fixed = 1; + if (1 < plen && patch[plen - 1] == '\r') { + add_cr_to_tail = !!(ws_rule & WS_CR_AT_EOL); + plen--; + } + } + if (0 < plen && isspace(patch[plen - 1])) { + while (0 < plen && isspace(patch[plen-1])) + plen--; + fixed = 1; + } } /* @@ -1602,6 +1610,8 @@ static int copy_wsfix(char *output, const char *patch, int plen, } memcpy(output, patch, plen); + if (add_cr_to_tail) + output[plen++] = '\r'; if (add_nl_to_tail) output[plen++] = '\n'; if (fixed && count_error) diff --git a/cache.h b/cache.h index 549f4bb..ad11c90 100644 --- a/cache.h +++ b/cache.h @@ -652,6 +652,7 @@ void shift_tree(const unsigned char *, const unsigned char *, unsigned char *, i #define WS_TRAILING_SPACE 01 #define WS_SPACE_BEFORE_TAB 02 #define WS_INDENT_WITH_NON_TAB 04 +#define WS_CR_AT_EOL 010 #define WS_DEFAULT_RULE (WS_TRAILING_SPACE|WS_SPACE_BEFORE_TAB) extern unsigned whitespace_rule_cfg; extern unsigned whitespace_rule(const char *); diff --git a/t/t4019-diff-wserror.sh b/t/t4019-diff-wserror.sh index 67e080b..0d9cbb6 100755 --- a/t/t4019-diff-wserror.sh +++ b/t/t4019-diff-wserror.sh @@ -12,6 +12,7 @@ test_expect_success setup ' echo " Eight SP indent" >>F && echo " HT and SP indent" >>F && echo "With trailing SP " >>F && + echo "Carriage ReturnQ" | tr Q "\015" >>F && echo "No problem" >>F ' @@ -27,6 +28,7 @@ test_expect_success default ' grep Eight normal >/dev/null && grep HT error >/dev/null && grep With error >/dev/null && + grep Return error >/dev/null && grep No normal >/dev/null ' @@ -41,6 +43,7 @@ test_expect_success 'without -trail' ' grep Eight normal >/dev/null && grep HT error >/dev/null && grep With normal >/dev/null && + grep Return normal >/dev/null && grep No normal >/dev/null ' @@ -56,6 +59,7 @@ test_expect_success 'without -trail (attribute)' ' grep Eight normal >/dev/null && grep HT error >/dev/null && grep With normal >/dev/null && + grep Return normal >/dev/null && grep No normal >/dev/null ' @@ -71,6 +75,7 @@ test_expect_success 'without -space' ' grep Eight normal >/dev/null && grep HT normal >/dev/null && grep With error >/dev/null && + grep Return error >/dev/null && grep No normal >/dev/null ' @@ -86,6 +91,7 @@ test_expect_success 'without -space (attribute)' ' grep Eight normal >/dev/null && grep HT normal >/dev/null && grep With error >/dev/null && + grep Return error >/dev/null && grep No normal >/dev/null ' @@ -101,6 +107,7 @@ test_expect_success 'with indent-non-tab only' ' grep Eight error >/dev/null && grep HT normal >/dev/null && grep With normal >/dev/null && + grep Return normal >/dev/null && grep No normal >/dev/null ' @@ -116,6 +123,39 @@ test_expect_success 'with indent-non-tab only (attribute)' ' grep Eight error >/dev/null && grep HT normal >/dev/null && grep With normal >/dev/null && + grep Return normal >/dev/null && + grep No normal >/dev/null + +' + +test_expect_success 'with cr-at-eol' ' + + rm -f .gitattributes + git config core.whitespace cr-at-eol + git diff --color >output + grep "$blue_grep" output >error + grep -v "$blue_grep" output >normal + + grep Eight normal >/dev/null && + grep HT error >/dev/null && + grep With error >/dev/null && + grep Return normal >/dev/null && + grep No normal >/dev/null + +' + +test_expect_success 'with cr-at-eol (attribute)' ' + + git config --unset core.whitespace + echo "F whitespace=trailing,cr-at-eol" >.gitattributes + git diff --color >output + grep "$blue_grep" output >error + grep -v "$blue_grep" output >normal + + grep Eight normal >/dev/null && + grep HT error >/dev/null && + grep With error >/dev/null && + grep Return normal >/dev/null && grep No normal >/dev/null ' diff --git a/ws.c b/ws.c index d09b9df..5a9ac45 100644 --- a/ws.c +++ b/ws.c @@ -14,6 +14,7 @@ static struct whitespace_rule { { "trailing-space", WS_TRAILING_SPACE }, { "space-before-tab", WS_SPACE_BEFORE_TAB }, { "indent-with-non-tab", WS_INDENT_WITH_NON_TAB }, + { "cr-at-eol", WS_CR_AT_EOL }, }; unsigned parse_whitespace_rule(const char *string) @@ -124,6 +125,7 @@ unsigned check_and_emit_line(const char *line, int len, unsigned ws_rule, int written = 0; int trailing_whitespace = -1; int trailing_newline = 0; + int trailing_carriage_return = 0; int i; /* Logic is simpler if we temporarily ignore the trailing newline. */ @@ -131,6 +133,11 @@ unsigned check_and_emit_line(const char *line, int len, unsigned ws_rule, trailing_newline = 1; len--; } + if ((ws_rule & WS_CR_AT_EOL) && + len > 0 && line[len - 1] == '\r') { + trailing_carriage_return = 1; + len--; + } /* Check for trailing whitespace. */ if (ws_rule & WS_TRAILING_SPACE) { @@ -176,8 +183,10 @@ unsigned check_and_emit_line(const char *line, int len, unsigned ws_rule, } if (stream) { - /* Now the rest of the line starts at written. - * The non-highlighted part ends at trailing_whitespace. */ + /* + * Now the rest of the line starts at "written". + * The non-highlighted part ends at "trailing_whitespace". + */ if (trailing_whitespace == -1) trailing_whitespace = len; @@ -196,6 +205,8 @@ unsigned check_and_emit_line(const char *line, int len, unsigned ws_rule, len - trailing_whitespace, 1, stream); fputs(reset, stream); } + if (trailing_carriage_return) + fputc('\r', stream); if (trailing_newline) fputc('\n', stream); } -- cgit v0.10.2-6-g49f6 From 203a2fe117070964a5bf7cc940a742cad7a19fca Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:39:48 -0500 Subject: Allow callers of unpack_trees() to handle failure Return an error from unpack_trees() instead of calling die(), and exit with an error in read-tree, builtin-commit, and diff-lib. merge-recursive already expected an error return from unpack_trees, so it doesn't need to be changed. The merge function can return negative to abort. This will be used in builtin-checkout -m. Signed-off-by: Daniel Barkalow diff --git a/builtin-commit.c b/builtin-commit.c index c63ff82..5b5b7c0 100644 --- a/builtin-commit.c +++ b/builtin-commit.c @@ -200,7 +200,8 @@ static void create_base_index(void) die("failed to unpack HEAD tree object"); parse_tree(tree); init_tree_desc(&t, tree->buffer, tree->size); - unpack_trees(1, &t, &opts); + if (unpack_trees(1, &t, &opts)) + exit(128); /* We've already reported the error, finish dying */ } static char *prepare_index(int argc, const char **argv, const char *prefix) diff --git a/builtin-read-tree.c b/builtin-read-tree.c index 5785401..1d9d125 100644 --- a/builtin-read-tree.c +++ b/builtin-read-tree.c @@ -268,7 +268,8 @@ int cmd_read_tree(int argc, const char **argv, const char *unused_prefix) parse_tree(tree); init_tree_desc(t+i, tree->buffer, tree->size); } - unpack_trees(nr_trees, t, &opts); + if (unpack_trees(nr_trees, t, &opts)) + return 128; /* * When reading only one tree (either the most basic form, diff --git a/diff-lib.c b/diff-lib.c index 03eaa7c..94b150e 100644 --- a/diff-lib.c +++ b/diff-lib.c @@ -737,7 +737,8 @@ int run_diff_index(struct rev_info *revs, int cached) opts.unpack_data = revs; init_tree_desc(&t, tree->buffer, tree->size); - unpack_trees(1, &t, &opts); + if (unpack_trees(1, &t, &opts)) + exit(128); diffcore_std(&revs->diffopt); diff_flush(&revs->diffopt); @@ -789,6 +790,7 @@ int do_diff_cache(const unsigned char *tree_sha1, struct diff_options *opt) opts.unpack_data = &revs; init_tree_desc(&t, tree->buffer, tree->size); - unpack_trees(1, &t, &opts); + if (unpack_trees(1, &t, &opts)) + exit(128); return 0; } diff --git a/unpack-trees.c b/unpack-trees.c index ff46fd6..9e6587f 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -219,6 +219,8 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, } #endif ret = o->fn(src, o, remove); + if (ret < 0) + return ret; #if DBRT_DEBUG > 1 printf("Added %d entries\n", ret); @@ -359,7 +361,7 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options } if (o->trivial_merges_only && o->nontrivial_merge) - die("Merge requires file-level merging"); + return error("Merge requires file-level merging"); check_updates(active_cache, active_nr, o); return 0; @@ -367,10 +369,10 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options /* Here come the merge functions */ -static void reject_merge(struct cache_entry *ce) +static int reject_merge(struct cache_entry *ce) { - die("Entry '%s' would be overwritten by merge. Cannot merge.", - ce->name); + return error("Entry '%s' would be overwritten by merge. Cannot merge.", + ce->name); } static int same(struct cache_entry *a, struct cache_entry *b) @@ -388,18 +390,18 @@ static int same(struct cache_entry *a, struct cache_entry *b) * When a CE gets turned into an unmerged entry, we * want it to be up-to-date */ -static void verify_uptodate(struct cache_entry *ce, +static int verify_uptodate(struct cache_entry *ce, struct unpack_trees_options *o) { struct stat st; if (o->index_only || o->reset) - return; + return 0; if (!lstat(ce->name, &st)) { unsigned changed = ce_match_stat(ce, &st, CE_MATCH_IGNORE_VALID); if (!changed) - return; + return 0; /* * NEEDSWORK: the current default policy is to allow * submodule to be out of sync wrt the supermodule @@ -408,12 +410,12 @@ static void verify_uptodate(struct cache_entry *ce, * checked out. */ if (S_ISGITLINK(ce->ce_mode)) - return; + return 0; errno = 0; } if (errno == ENOENT) - return; - die("Entry '%s' not uptodate. Cannot merge.", ce->name); + return 0; + return error("Entry '%s' not uptodate. Cannot merge.", ce->name); } static void invalidate_ce_path(struct cache_entry *ce) @@ -479,7 +481,8 @@ static int verify_clean_subdirectory(struct cache_entry *ce, const char *action, * ce->name is an entry in the subdirectory. */ if (!ce_stage(ce)) { - verify_uptodate(ce, o); + if (verify_uptodate(ce, o)) + return -1; ce->ce_flags |= CE_REMOVE; } cnt++; @@ -498,8 +501,8 @@ static int verify_clean_subdirectory(struct cache_entry *ce, const char *action, d.exclude_per_dir = o->dir->exclude_per_dir; i = read_directory(&d, ce->name, pathbuf, namelen+1, NULL); if (i) - die("Updating '%s' would lose untracked files in it", - ce->name); + return error("Updating '%s' would lose untracked files in it", + ce->name); free(pathbuf); return cnt; } @@ -508,16 +511,16 @@ static int verify_clean_subdirectory(struct cache_entry *ce, const char *action, * We do not want to remove or overwrite a working tree file that * is not tracked, unless it is ignored. */ -static void verify_absent(struct cache_entry *ce, const char *action, - struct unpack_trees_options *o) +static int verify_absent(struct cache_entry *ce, const char *action, + struct unpack_trees_options *o) { struct stat st; if (o->index_only || o->reset || !o->update) - return; + return 0; if (has_symlink_leading_path(ce->name, NULL)) - return; + return 0; if (!lstat(ce->name, &st)) { int cnt; @@ -527,7 +530,7 @@ static void verify_absent(struct cache_entry *ce, const char *action, * ce->name is explicitly excluded, so it is Ok to * overwrite it. */ - return; + return 0; if (S_ISDIR(st.st_mode)) { /* * We are checking out path "foo" and @@ -556,7 +559,7 @@ static void verify_absent(struct cache_entry *ce, const char *action, * deleted entries here. */ o->pos += cnt; - return; + return 0; } /* @@ -568,12 +571,13 @@ static void verify_absent(struct cache_entry *ce, const char *action, if (0 <= cnt) { struct cache_entry *ce = active_cache[cnt]; if (ce->ce_flags & CE_REMOVE) - return; + return 0; } - die("Untracked working tree file '%s' " - "would be %s by merge.", ce->name, action); + return error("Untracked working tree file '%s' " + "would be %s by merge.", ce->name, action); } + return 0; } static int merged_entry(struct cache_entry *merge, struct cache_entry *old, @@ -591,12 +595,14 @@ static int merged_entry(struct cache_entry *merge, struct cache_entry *old, if (same(old, merge)) { memcpy(merge, old, offsetof(struct cache_entry, name)); } else { - verify_uptodate(old, o); + if (verify_uptodate(old, o)) + return -1; invalidate_ce_path(old); } } else { - verify_absent(merge, "overwritten", o); + if (verify_absent(merge, "overwritten", o)) + return -1; invalidate_ce_path(merge); } @@ -608,10 +614,12 @@ static int merged_entry(struct cache_entry *merge, struct cache_entry *old, static int deleted_entry(struct cache_entry *ce, struct cache_entry *old, struct unpack_trees_options *o) { - if (old) - verify_uptodate(old, o); - else - verify_absent(ce, "removed", o); + if (old) { + if (verify_uptodate(old, o)) + return -1; + } else + if (verify_absent(ce, "removed", o)) + return -1; ce->ce_flags |= CE_REMOVE; add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE); invalidate_ce_path(ce); @@ -699,7 +707,7 @@ int threeway_merge(struct cache_entry **stages, /* #14, #14ALT, #2ALT */ if (remote && !df_conflict_head && head_match && !remote_match) { if (index && !same(index, remote) && !same(index, head)) - reject_merge(index); + return reject_merge(index); return merged_entry(remote, index, o); } /* @@ -707,7 +715,7 @@ int threeway_merge(struct cache_entry **stages, * make sure that it matches head. */ if (index && !same(index, head)) { - reject_merge(index); + return reject_merge(index); } if (head) { @@ -758,8 +766,10 @@ int threeway_merge(struct cache_entry **stages, remove_entry(remove); if (index) return deleted_entry(index, index, o); - else if (ce && !head_deleted) - verify_absent(ce, "removed", o); + else if (ce && !head_deleted) { + if (verify_absent(ce, "removed", o)) + return -1; + } return 0; } /* @@ -775,7 +785,8 @@ int threeway_merge(struct cache_entry **stages, * conflict resolution files. */ if (index) { - verify_uptodate(index, o); + if (verify_uptodate(index, o)) + return -1; } remove_entry(remove); @@ -855,11 +866,11 @@ int twoway_merge(struct cache_entry **src, /* all other failures */ remove_entry(remove); if (oldtree) - reject_merge(oldtree); + return reject_merge(oldtree); if (current) - reject_merge(current); + return reject_merge(current); if (newtree) - reject_merge(newtree); + return reject_merge(newtree); return -1; } } @@ -886,7 +897,7 @@ int bind_merge(struct cache_entry **src, return error("Cannot do a bind merge of %d trees\n", o->merge_size); if (a && old) - die("Entry '%s' overlaps. Cannot bind.", a->name); + return error("Entry '%s' overlaps. Cannot bind.", a->name); if (!a) return keep_entry(old, o); else -- cgit v0.10.2-6-g49f6 From 17e464266701bc1453f60a80cd71d8ba55b528e6 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:39:52 -0500 Subject: Add flag to make unpack_trees() not print errors. (This applies only to errors where a plausible operation is impossible due to the particular data, not to errors resulting from misuse of the merge functions.) This will allow builtin-checkout to suppress merge errors if it's going to try more merging methods. Additionally, if unpack_trees() returns with an error, but without printing anything, it will roll back any changes to the index (by rereading the index, currently). This obviously could be done by the caller, but chances are that the caller would forget and debugging this is difficult. Also, future implementations may give unpack_trees() a more efficient way of undoing its changes than the caller could. Signed-off-by: Daniel Barkalow diff --git a/unpack-trees.c b/unpack-trees.c index 9e6587f..45f40c2 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -356,12 +356,23 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options posns[i] = create_tree_entry_list(t+i); if (unpack_trees_rec(posns, len, o->prefix ? o->prefix : "", - o, &df_conflict_list)) + o, &df_conflict_list)) { + if (o->gently) { + discard_cache(); + read_cache(); + } return -1; + } } - if (o->trivial_merges_only && o->nontrivial_merge) - return error("Merge requires file-level merging"); + if (o->trivial_merges_only && o->nontrivial_merge) { + if (o->gently) { + discard_cache(); + read_cache(); + } + return o->gently ? -1 : + error("Merge requires file-level merging"); + } check_updates(active_cache, active_nr, o); return 0; @@ -415,7 +426,8 @@ static int verify_uptodate(struct cache_entry *ce, } if (errno == ENOENT) return 0; - return error("Entry '%s' not uptodate. Cannot merge.", ce->name); + return o->gently ? -1 : + error("Entry '%s' not uptodate. Cannot merge.", ce->name); } static void invalidate_ce_path(struct cache_entry *ce) @@ -501,8 +513,9 @@ static int verify_clean_subdirectory(struct cache_entry *ce, const char *action, d.exclude_per_dir = o->dir->exclude_per_dir; i = read_directory(&d, ce->name, pathbuf, namelen+1, NULL); if (i) - return error("Updating '%s' would lose untracked files in it", - ce->name); + return o->gently ? -1 : + error("Updating '%s' would lose untracked files in it", + ce->name); free(pathbuf); return cnt; } @@ -574,8 +587,9 @@ static int verify_absent(struct cache_entry *ce, const char *action, return 0; } - return error("Untracked working tree file '%s' " - "would be %s by merge.", ce->name, action); + return o->gently ? -1 : + error("Untracked working tree file '%s' " + "would be %s by merge.", ce->name, action); } return 0; } @@ -707,7 +721,7 @@ int threeway_merge(struct cache_entry **stages, /* #14, #14ALT, #2ALT */ if (remote && !df_conflict_head && head_match && !remote_match) { if (index && !same(index, remote) && !same(index, head)) - return reject_merge(index); + return o->gently ? -1 : reject_merge(index); return merged_entry(remote, index, o); } /* @@ -715,7 +729,7 @@ int threeway_merge(struct cache_entry **stages, * make sure that it matches head. */ if (index && !same(index, head)) { - return reject_merge(index); + return o->gently ? -1 : reject_merge(index); } if (head) { @@ -866,11 +880,11 @@ int twoway_merge(struct cache_entry **src, /* all other failures */ remove_entry(remove); if (oldtree) - return reject_merge(oldtree); + return o->gently ? -1 : reject_merge(oldtree); if (current) - return reject_merge(current); + return o->gently ? -1 : reject_merge(current); if (newtree) - return reject_merge(newtree); + return o->gently ? -1 : reject_merge(newtree); return -1; } } @@ -897,7 +911,8 @@ int bind_merge(struct cache_entry **src, return error("Cannot do a bind merge of %d trees\n", o->merge_size); if (a && old) - return error("Entry '%s' overlaps. Cannot bind.", a->name); + return o->gently ? -1 : + error("Entry '%s' overlaps. Cannot bind.", a->name); if (!a) return keep_entry(old, o); else diff --git a/unpack-trees.h b/unpack-trees.h index 197a004..83d1229 100644 --- a/unpack-trees.h +++ b/unpack-trees.h @@ -16,6 +16,7 @@ struct unpack_trees_options { int trivial_merges_only; int verbose_update; int aggressive; + int gently; const char *prefix; int pos; struct dir_struct *dir; -- cgit v0.10.2-6-g49f6 From b05c6dff8aa8af5a03717e8d863b911cede213a0 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:39:56 -0500 Subject: Send unpack-trees debugging output to stderr This is to keep git-stash from getting confused if you're debugging unpack-trees. Signed-off-by: Daniel Barkalow diff --git a/unpack-trees.c b/unpack-trees.c index 45f40c2..f462a56 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -122,13 +122,13 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, #if DBRT_DEBUG > 1 if (first) - printf("index %s\n", first); + fprintf(stderr, "index %s\n", first); #endif for (i = 0; i < len; i++) { if (!posns[i] || posns[i] == df_conflict_list) continue; #if DBRT_DEBUG > 1 - printf("%d %s\n", i + 1, posns[i]->name); + fprintf(stderr, "%d %s\n", i + 1, posns[i]->name); #endif if (!first || entcmp(first, firstdir, posns[i]->name, @@ -209,13 +209,13 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, int ret; #if DBRT_DEBUG > 1 - printf("%s:\n", first); + fprintf(stderr, "%s:\n", first); for (i = 0; i < src_size; i++) { - printf(" %d ", i); + fprintf(stderr, " %d ", i); if (src[i]) - printf("%s\n", sha1_to_hex(src[i]->sha1)); + fprintf(stderr, "%06x %s\n", src[i]->ce_mode, sha1_to_hex(src[i]->sha1)); else - printf("\n"); + fprintf(stderr, "\n"); } #endif ret = o->fn(src, o, remove); @@ -223,7 +223,7 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, return ret; #if DBRT_DEBUG > 1 - printf("Added %d entries\n", ret); + fprintf(stderr, "Added %d entries\n", ret); #endif o->pos += ret; } else { -- cgit v0.10.2-6-g49f6 From 33ecf7eb6143143711ccaf828134beb2dacbe5c9 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:39:59 -0500 Subject: Discard "deleted" cache entries after using them to update the working tree Way back in read-tree.c, we used a mode 0 cache entry to indicate that an entry had been deleted, so that the update code would remove the working tree file, and we would just skip it when writing out the index file afterward. These days, unpack_trees is a library function, and it is still leaving these entries in the active cache. Furthermore, unpack_trees doesn't correctly ignore those entries, and who knows what other code wouldn't expect them to be there, but just isn't yet called after a call to unpack_trees. To avoid having other code trip over these entries, have check_updates() remove them after it removes the working tree files. While we're at it, simplify the loop in check_updates(), and avoid passing global variables as parameters to check_updates(): there is only one call site anyway. Signed-off-by: Daniel Barkalow diff --git a/unpack-trees.c b/unpack-trees.c index f462a56..40d4130 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -288,16 +288,16 @@ static void unlink_entry(char *name, char *last_symlink) } static struct checkout state; -static void check_updates(struct cache_entry **src, int nr, - struct unpack_trees_options *o) +static void check_updates(struct unpack_trees_options *o) { unsigned cnt = 0, total = 0; struct progress *progress = NULL; char last_symlink[PATH_MAX]; + int i; if (o->update && o->verbose_update) { - for (total = cnt = 0; cnt < nr; cnt++) { - struct cache_entry *ce = src[cnt]; + for (total = cnt = 0; cnt < active_nr; cnt++) { + struct cache_entry *ce = active_cache[cnt]; if (ce->ce_flags & (CE_UPDATE | CE_REMOVE)) total++; } @@ -308,14 +308,16 @@ static void check_updates(struct cache_entry **src, int nr, } *last_symlink = '\0'; - while (nr--) { - struct cache_entry *ce = *src++; + for (i = 0; i < active_nr; i++) { + struct cache_entry *ce = active_cache[i]; if (ce->ce_flags & (CE_UPDATE | CE_REMOVE)) display_progress(progress, ++cnt); if (ce->ce_flags & CE_REMOVE) { if (o->update) unlink_entry(ce->name, last_symlink); + remove_cache_entry_at(i); + i--; continue; } if (ce->ce_flags & CE_UPDATE) { @@ -374,7 +376,7 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options error("Merge requires file-level merging"); } - check_updates(active_cache, active_nr, o); + check_updates(o); return 0; } -- cgit v0.10.2-6-g49f6 From 4e7c4571b8b31d6a09de2826361540caa76d3526 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:02 -0500 Subject: Add "skip_unmerged" option to unpack_trees. This option allows the caller to reset everything that isn't unmerged, leaving the unmerged things to be resolved. If, after a merge of "working" and "HEAD", this is used with "HEAD" (reset, !update), the result will be that all of the changes from "local" are in the working tree but not added to the index (either with the index clean but unchanged, or with the index unmerged, depending on whether there are conflicts). This will be used in checkout -m. Signed-off-by: Daniel Barkalow diff --git a/unpack-trees.c b/unpack-trees.c index 40d4130..470fa02 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -85,6 +85,7 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, int any_dirs = 0; char *cache_name; int ce_stage; + int skip_entry = 0; /* Find the first name in the input. */ @@ -153,6 +154,8 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, any_files = 1; src[0] = active_cache[o->pos]; remove = o->pos; + if (o->skip_unmerged && ce_stage(src[0])) + skip_entry = 1; } for (i = 0; i < len; i++) { @@ -181,6 +184,12 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, continue; } + if (skip_entry) { + subposns[i] = df_conflict_list; + posns[i] = posns[i]->next; + continue; + } + if (!o->merge) ce_stage = 0; else if (i + 1 < o->head_idx) @@ -205,7 +214,13 @@ static int unpack_trees_rec(struct tree_entry_list **posns, int len, posns[i] = posns[i]->next; } if (any_files) { - if (o->merge) { + if (skip_entry) { + o->pos++; + while (o->pos < active_nr && + !strcmp(active_cache[o->pos]->name, + src[0]->name)) + o->pos++; + } else if (o->merge) { int ret; #if DBRT_DEBUG > 1 @@ -730,9 +745,8 @@ int threeway_merge(struct cache_entry **stages, * If we have an entry in the index cache, then we want to * make sure that it matches head. */ - if (index && !same(index, head)) { + if (index && !same(index, head)) return o->gently ? -1 : reject_merge(index); - } if (head) { /* #5ALT, #15 */ diff --git a/unpack-trees.h b/unpack-trees.h index 83d1229..a2df544 100644 --- a/unpack-trees.h +++ b/unpack-trees.h @@ -16,6 +16,7 @@ struct unpack_trees_options { int trivial_merges_only; int verbose_update; int aggressive; + int skip_unmerged; int gently; const char *prefix; int pos; -- cgit v0.10.2-6-g49f6 From e1b3a2cad79a8138d18593c6eb3c46906ad2ee42 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:05 -0500 Subject: Build-in merge-recursive This makes write_tree_from_memory(), which writes the active cache as a tree and returns the struct tree for it, available to other code. It also makes available merge_trees(), which does the internal merge of two trees with a known base, and merge_recursive(), which does the recursive internal merge of two commits with a list of common ancestors. The first two of these will be used by checkout -m, and the third is presumably useful in general, although the implementation of checkout -m which entirely matches the behavior of the shell version does not use it (since it ignores the difference of ancestry between the old branch and the new branch). Signed-off-by: Daniel Barkalow diff --git a/Makefile b/Makefile index 5aac0c0..6f08bcc 100644 --- a/Makefile +++ b/Makefile @@ -256,7 +256,6 @@ PROGRAMS = \ git-upload-pack$X \ git-pack-redundant$X git-var$X \ git-merge-tree$X git-imap-send$X \ - git-merge-recursive$X \ $(EXTRA_PROGRAMS) # Empty... @@ -360,6 +359,7 @@ BUILTIN_OBJS = \ builtin-merge-base.o \ builtin-merge-file.o \ builtin-merge-ours.o \ + builtin-merge-recursive.o \ builtin-mv.o \ builtin-name-rev.o \ builtin-pack-objects.o \ diff --git a/builtin-merge-recursive.c b/builtin-merge-recursive.c new file mode 100644 index 0000000..45d4601 --- /dev/null +++ b/builtin-merge-recursive.c @@ -0,0 +1,1762 @@ +/* + * Recursive Merge algorithm stolen from git-merge-recursive.py by + * Fredrik Kuivinen. + * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006 + */ +#include "cache.h" +#include "cache-tree.h" +#include "commit.h" +#include "blob.h" +#include "builtin.h" +#include "tree-walk.h" +#include "diff.h" +#include "diffcore.h" +#include "run-command.h" +#include "tag.h" +#include "unpack-trees.h" +#include "path-list.h" +#include "xdiff-interface.h" +#include "interpolate.h" +#include "attr.h" +#include "merge-recursive.h" + +static int subtree_merge; + +static struct tree *shift_tree_object(struct tree *one, struct tree *two) +{ + unsigned char shifted[20]; + + /* + * NEEDSWORK: this limits the recursion depth to hardcoded + * value '2' to avoid excessive overhead. + */ + shift_tree(one->object.sha1, two->object.sha1, shifted, 2); + if (!hashcmp(two->object.sha1, shifted)) + return two; + return lookup_tree(shifted); +} + +/* + * A virtual commit has + * - (const char *)commit->util set to the name, and + * - *(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)); + static unsigned virtual_id = 1; + commit->tree = tree; + commit->util = (void*)comment; + *(int*)commit->object.sha1 = virtual_id++; + /* avoid warnings */ + commit->object.parsed = 1; + return commit; +} + +/* + * Since we use get_tree_entry(), which does not put the read object into + * the object pool, we cannot rely on a == b. + */ +static int sha_eq(const unsigned char *a, const unsigned char *b) +{ + if (!a && !b) + return 2; + return a && b && hashcmp(a, b) == 0; +} + +/* + * Since we want to write the index eventually, we cannot reuse the index + * for these (temporary) data. + */ +struct stage_data +{ + struct + { + unsigned mode; + unsigned char sha[20]; + } stages[4]; + unsigned processed:1; +}; + +static struct path_list current_file_set = {NULL, 0, 0, 1}; +static struct path_list current_directory_set = {NULL, 0, 0, 1}; + +static int call_depth = 0; +static int verbosity = 2; +static int rename_limit = -1; +static int buffer_output = 1; +static struct strbuf obuf = STRBUF_INIT; + +static int show(int v) +{ + return (!call_depth && verbosity >= v) || verbosity >= 5; +} + +static void flush_output(void) +{ + if (obuf.len) { + fputs(obuf.buf, stdout); + strbuf_reset(&obuf); + } +} + +static void output(int v, const char *fmt, ...) +{ + int len; + va_list ap; + + if (!show(v)) + return; + + strbuf_grow(&obuf, call_depth * 2 + 2); + memset(obuf.buf + obuf.len, ' ', call_depth * 2); + strbuf_setlen(&obuf, obuf.len + call_depth * 2); + + va_start(ap, fmt); + len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap); + va_end(ap); + + if (len < 0) + len = 0; + if (len >= strbuf_avail(&obuf)) { + strbuf_grow(&obuf, len + 2); + va_start(ap, fmt); + len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap); + va_end(ap); + if (len >= strbuf_avail(&obuf)) { + die("this should not happen, your snprintf is broken"); + } + } + strbuf_setlen(&obuf, obuf.len + len); + strbuf_add(&obuf, "\n", 1); + if (!buffer_output) + flush_output(); +} + +static void output_commit_title(struct commit *commit) +{ + int i; + flush_output(); + for (i = call_depth; i--;) + fputs(" ", stdout); + if (commit->util) + printf("virtual %s\n", (char *)commit->util); + else { + printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV)); + if (parse_commit(commit) != 0) + printf("(bad commit)\n"); + else { + const char *s; + int len; + for (s = commit->buffer; *s; s++) + if (*s == '\n' && s[1] == '\n') { + s += 2; + break; + } + for (len = 0; s[len] && '\n' != s[len]; len++) + ; /* do nothing */ + printf("%.*s\n", len, s); + } + } +} + +static int add_cacheinfo(unsigned int mode, const unsigned char *sha1, + const char *path, int stage, int refresh, int options) +{ + struct cache_entry *ce; + ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh); + if (!ce) + return error("addinfo_cache failed for path '%s'", path); + return add_cache_entry(ce, options); +} + +/* + * This is a global variable which is used in a number of places but + * only written to in the 'merge' function. + * + * index_only == 1 => Don't leave any non-stage 0 entries in the cache and + * don't update the working directory. + * 0 => Leave unmerged entries in the cache and update + * the working directory. + */ +static int index_only = 0; + +static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree) +{ + parse_tree(tree); + init_tree_desc(desc, tree->buffer, tree->size); +} + +static int git_merge_trees(int index_only, + struct tree *common, + struct tree *head, + struct tree *merge) +{ + int rc; + struct tree_desc t[3]; + struct unpack_trees_options opts; + + memset(&opts, 0, sizeof(opts)); + if (index_only) + opts.index_only = 1; + else + opts.update = 1; + opts.merge = 1; + opts.head_idx = 2; + opts.fn = threeway_merge; + + init_tree_desc_from_tree(t+0, common); + init_tree_desc_from_tree(t+1, head); + init_tree_desc_from_tree(t+2, merge); + + rc = unpack_trees(3, t, &opts); + cache_tree_free(&active_cache_tree); + return rc; +} + +static int unmerged_index(void) +{ + int i; + for (i = 0; i < active_nr; i++) { + struct cache_entry *ce = active_cache[i]; + if (ce_stage(ce)) + return 1; + } + return 0; +} + +struct tree *write_tree_from_memory(void) +{ + struct tree *result = NULL; + + if (unmerged_index()) { + int i; + output(0, "There are unmerged index entries:"); + for (i = 0; i < active_nr; i++) { + struct cache_entry *ce = active_cache[i]; + if (ce_stage(ce)) + output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name); + } + return NULL; + } + + if (!active_cache_tree) + active_cache_tree = cache_tree(); + + if (!cache_tree_fully_valid(active_cache_tree) && + cache_tree_update(active_cache_tree, + active_cache, active_nr, 0, 0) < 0) + die("error building trees"); + + result = lookup_tree(active_cache_tree->sha1); + + return result; +} + +static int save_files_dirs(const unsigned char *sha1, + const char *base, int baselen, const char *path, + unsigned int mode, int stage) +{ + int len = strlen(path); + char *newpath = xmalloc(baselen + len + 1); + memcpy(newpath, base, baselen); + memcpy(newpath + baselen, path, len); + newpath[baselen + len] = '\0'; + + if (S_ISDIR(mode)) + path_list_insert(newpath, ¤t_directory_set); + else + path_list_insert(newpath, ¤t_file_set); + free(newpath); + + return READ_TREE_RECURSIVE; +} + +static int get_files_dirs(struct tree *tree) +{ + int n; + if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0) + return 0; + n = current_file_set.nr + current_directory_set.nr; + return n; +} + +/* + * Returns an index_entry instance which doesn't have to correspond to + * a real cache entry in Git's index. + */ +static struct stage_data *insert_stage_data(const char *path, + struct tree *o, struct tree *a, struct tree *b, + struct path_list *entries) +{ + struct path_list_item *item; + struct stage_data *e = xcalloc(1, sizeof(struct stage_data)); + get_tree_entry(o->object.sha1, path, + e->stages[1].sha, &e->stages[1].mode); + get_tree_entry(a->object.sha1, path, + e->stages[2].sha, &e->stages[2].mode); + get_tree_entry(b->object.sha1, path, + e->stages[3].sha, &e->stages[3].mode); + item = path_list_insert(path, entries); + item->util = e; + return e; +} + +/* + * Create a dictionary mapping file names to stage_data objects. The + * dictionary contains one entry for every path with a non-zero stage entry. + */ +static struct path_list *get_unmerged(void) +{ + struct path_list *unmerged = xcalloc(1, sizeof(struct path_list)); + int i; + + unmerged->strdup_paths = 1; + + for (i = 0; i < active_nr; i++) { + struct path_list_item *item; + struct stage_data *e; + struct cache_entry *ce = active_cache[i]; + if (!ce_stage(ce)) + continue; + + item = path_list_lookup(ce->name, unmerged); + if (!item) { + item = path_list_insert(ce->name, unmerged); + item->util = xcalloc(1, sizeof(struct stage_data)); + } + e = item->util; + e->stages[ce_stage(ce)].mode = ce->ce_mode; + hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1); + } + + return unmerged; +} + +struct rename +{ + struct diff_filepair *pair; + struct stage_data *src_entry; + struct stage_data *dst_entry; + unsigned processed:1; +}; + +/* + * Get information of all renames which occurred between 'o_tree' and + * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and + * 'b_tree') to be able to associate the correct cache entries with + * the rename information. 'tree' is always equal to either a_tree or b_tree. + */ +static struct path_list *get_renames(struct tree *tree, + struct tree *o_tree, + struct tree *a_tree, + struct tree *b_tree, + struct path_list *entries) +{ + int i; + struct path_list *renames; + struct diff_options opts; + + renames = xcalloc(1, sizeof(struct path_list)); + diff_setup(&opts); + DIFF_OPT_SET(&opts, RECURSIVE); + opts.detect_rename = DIFF_DETECT_RENAME; + opts.rename_limit = rename_limit; + opts.output_format = DIFF_FORMAT_NO_OUTPUT; + if (diff_setup_done(&opts) < 0) + die("diff setup failed"); + diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts); + diffcore_std(&opts); + for (i = 0; i < diff_queued_diff.nr; ++i) { + struct path_list_item *item; + struct rename *re; + struct diff_filepair *pair = diff_queued_diff.queue[i]; + if (pair->status != 'R') { + diff_free_filepair(pair); + continue; + } + re = xmalloc(sizeof(*re)); + re->processed = 0; + re->pair = pair; + item = path_list_lookup(re->pair->one->path, entries); + if (!item) + re->src_entry = insert_stage_data(re->pair->one->path, + o_tree, a_tree, b_tree, entries); + else + re->src_entry = item->util; + + item = path_list_lookup(re->pair->two->path, entries); + if (!item) + re->dst_entry = insert_stage_data(re->pair->two->path, + o_tree, a_tree, b_tree, entries); + else + re->dst_entry = item->util; + item = path_list_insert(pair->one->path, renames); + item->util = re; + } + opts.output_format = DIFF_FORMAT_NO_OUTPUT; + diff_queued_diff.nr = 0; + diff_flush(&opts); + return renames; +} + +static int update_stages(const char *path, struct diff_filespec *o, + struct diff_filespec *a, struct diff_filespec *b, + int clear) +{ + int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE; + if (clear) + if (remove_file_from_cache(path)) + return -1; + if (o) + if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options)) + return -1; + if (a) + if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options)) + return -1; + if (b) + if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options)) + return -1; + return 0; +} + +static int remove_path(const char *name) +{ + int ret; + char *slash, *dirs; + + ret = unlink(name); + if (ret) + return ret; + dirs = xstrdup(name); + while ((slash = strrchr(name, '/'))) { + *slash = '\0'; + if (rmdir(name) != 0) + break; + } + free(dirs); + return ret; +} + +static int remove_file(int clean, const char *path, int no_wd) +{ + int update_cache = index_only || clean; + int update_working_directory = !index_only && !no_wd; + + if (update_cache) { + if (remove_file_from_cache(path)) + return -1; + } + if (update_working_directory) { + unlink(path); + if (errno != ENOENT || errno != EISDIR) + return -1; + remove_path(path); + } + return 0; +} + +static char *unique_path(const char *path, const char *branch) +{ + char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1); + int suffix = 0; + struct stat st; + char *p = newpath + strlen(path); + strcpy(newpath, path); + *(p++) = '~'; + strcpy(p, branch); + for (; *p; ++p) + if ('/' == *p) + *p = '_'; + while (path_list_has_path(¤t_file_set, newpath) || + path_list_has_path(¤t_directory_set, newpath) || + lstat(newpath, &st) == 0) + sprintf(p, "_%d", suffix++); + + path_list_insert(newpath, ¤t_file_set); + return newpath; +} + +static int mkdir_p(const char *path, unsigned long mode) +{ + /* path points to cache entries, so xstrdup before messing with it */ + char *buf = xstrdup(path); + int result = safe_create_leading_directories(buf); + free(buf); + return result; +} + +static void flush_buffer(int fd, const char *buf, unsigned long size) +{ + while (size > 0) { + long ret = write_in_full(fd, buf, size); + if (ret < 0) { + /* Ignore epipe */ + if (errno == EPIPE) + break; + die("merge-recursive: %s", strerror(errno)); + } else if (!ret) { + die("merge-recursive: disk full?"); + } + size -= ret; + buf += ret; + } +} + +static int make_room_for_path(const char *path) +{ + int status; + const char *msg = "failed to create path '%s'%s"; + + status = mkdir_p(path, 0777); + if (status) { + if (status == -3) { + /* something else exists */ + error(msg, path, ": perhaps a D/F conflict?"); + return -1; + } + die(msg, path, ""); + } + + /* Successful unlink is good.. */ + if (!unlink(path)) + return 0; + /* .. and so is no existing file */ + if (errno == ENOENT) + return 0; + /* .. but not some other error (who really cares what?) */ + return error(msg, path, ": perhaps a D/F conflict?"); +} + +static void update_file_flags(const unsigned char *sha, + unsigned mode, + const char *path, + int update_cache, + int update_wd) +{ + if (index_only) + update_wd = 0; + + if (update_wd) { + enum object_type type; + void *buf; + unsigned long size; + + if (S_ISGITLINK(mode)) + die("cannot read object %s '%s': It is a submodule!", + sha1_to_hex(sha), path); + + buf = read_sha1_file(sha, &type, &size); + if (!buf) + die("cannot read object %s '%s'", sha1_to_hex(sha), path); + if (type != OBJ_BLOB) + die("blob expected for %s '%s'", sha1_to_hex(sha), path); + + if (make_room_for_path(path) < 0) { + update_wd = 0; + goto update_index; + } + if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) { + int fd; + if (mode & 0100) + mode = 0777; + else + mode = 0666; + fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); + if (fd < 0) + die("failed to open %s: %s", path, strerror(errno)); + flush_buffer(fd, buf, size); + close(fd); + } else if (S_ISLNK(mode)) { + char *lnk = xmemdupz(buf, size); + mkdir_p(path, 0777); + unlink(path); + symlink(lnk, path); + free(lnk); + } else + die("do not know what to do with %06o %s '%s'", + mode, sha1_to_hex(sha), path); + } + update_index: + if (update_cache) + add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD); +} + +static void update_file(int clean, + const unsigned char *sha, + unsigned mode, + const char *path) +{ + update_file_flags(sha, mode, path, index_only || clean, !index_only); +} + +/* Low level file merging, update and removal */ + +struct merge_file_info +{ + unsigned char sha[20]; + unsigned mode; + unsigned clean:1, + merge:1; +}; + +static void fill_mm(const unsigned char *sha1, mmfile_t *mm) +{ + unsigned long size; + enum object_type type; + + if (!hashcmp(sha1, null_sha1)) { + mm->ptr = xstrdup(""); + mm->size = 0; + return; + } + + mm->ptr = read_sha1_file(sha1, &type, &size); + if (!mm->ptr || type != OBJ_BLOB) + die("unable to read blob object %s", sha1_to_hex(sha1)); + mm->size = size; +} + +/* + * Customizable low-level merge drivers support. + */ + +struct ll_merge_driver; +typedef int (*ll_merge_fn)(const struct ll_merge_driver *, + const char *path, + mmfile_t *orig, + mmfile_t *src1, const char *name1, + mmfile_t *src2, const char *name2, + mmbuffer_t *result); + +struct ll_merge_driver { + const char *name; + const char *description; + ll_merge_fn fn; + const char *recursive; + struct ll_merge_driver *next; + char *cmdline; +}; + +/* + * Built-in low-levels + */ +static int ll_binary_merge(const struct ll_merge_driver *drv_unused, + const char *path_unused, + mmfile_t *orig, + mmfile_t *src1, const char *name1, + mmfile_t *src2, const char *name2, + mmbuffer_t *result) +{ + /* + * The tentative merge result is "ours" for the final round, + * or common ancestor for an internal merge. Still return + * "conflicted merge" status. + */ + mmfile_t *stolen = index_only ? orig : src1; + + result->ptr = stolen->ptr; + result->size = stolen->size; + stolen->ptr = NULL; + return 1; +} + +static int ll_xdl_merge(const struct ll_merge_driver *drv_unused, + const char *path_unused, + mmfile_t *orig, + mmfile_t *src1, const char *name1, + mmfile_t *src2, const char *name2, + mmbuffer_t *result) +{ + xpparam_t xpp; + + if (buffer_is_binary(orig->ptr, orig->size) || + buffer_is_binary(src1->ptr, src1->size) || + buffer_is_binary(src2->ptr, src2->size)) { + warning("Cannot merge binary files: %s vs. %s\n", + name1, name2); + return ll_binary_merge(drv_unused, path_unused, + orig, src1, name1, + src2, name2, + result); + } + + memset(&xpp, 0, sizeof(xpp)); + return xdl_merge(orig, + src1, name1, + src2, name2, + &xpp, XDL_MERGE_ZEALOUS, + result); +} + +static int ll_union_merge(const struct ll_merge_driver *drv_unused, + const char *path_unused, + mmfile_t *orig, + mmfile_t *src1, const char *name1, + mmfile_t *src2, const char *name2, + mmbuffer_t *result) +{ + char *src, *dst; + long size; + const int marker_size = 7; + + int status = ll_xdl_merge(drv_unused, path_unused, + orig, src1, NULL, src2, NULL, result); + if (status <= 0) + return status; + size = result->size; + src = dst = result->ptr; + while (size) { + char ch; + if ((marker_size < size) && + (*src == '<' || *src == '=' || *src == '>')) { + int i; + ch = *src; + for (i = 0; i < marker_size; i++) + if (src[i] != ch) + goto not_a_marker; + if (src[marker_size] != '\n') + goto not_a_marker; + src += marker_size + 1; + size -= marker_size + 1; + continue; + } + not_a_marker: + do { + ch = *src++; + *dst++ = ch; + size--; + } while (ch != '\n' && size); + } + result->size = dst - result->ptr; + return 0; +} + +#define LL_BINARY_MERGE 0 +#define LL_TEXT_MERGE 1 +#define LL_UNION_MERGE 2 +static struct ll_merge_driver ll_merge_drv[] = { + { "binary", "built-in binary merge", ll_binary_merge }, + { "text", "built-in 3-way text merge", ll_xdl_merge }, + { "union", "built-in union merge", ll_union_merge }, +}; + +static void create_temp(mmfile_t *src, char *path) +{ + int fd; + + strcpy(path, ".merge_file_XXXXXX"); + fd = xmkstemp(path); + if (write_in_full(fd, src->ptr, src->size) != src->size) + die("unable to write temp-file"); + close(fd); +} + +/* + * User defined low-level merge driver support. + */ +static int ll_ext_merge(const struct ll_merge_driver *fn, + const char *path, + mmfile_t *orig, + mmfile_t *src1, const char *name1, + mmfile_t *src2, const char *name2, + mmbuffer_t *result) +{ + char temp[3][50]; + char cmdbuf[2048]; + struct interp table[] = { + { "%O" }, + { "%A" }, + { "%B" }, + }; + struct child_process child; + const char *args[20]; + int status, fd, i; + struct stat st; + + if (fn->cmdline == NULL) + die("custom merge driver %s lacks command line.", fn->name); + + result->ptr = NULL; + result->size = 0; + create_temp(orig, temp[0]); + create_temp(src1, temp[1]); + create_temp(src2, temp[2]); + + interp_set_entry(table, 0, temp[0]); + interp_set_entry(table, 1, temp[1]); + interp_set_entry(table, 2, temp[2]); + + output(1, "merging %s using %s", path, + fn->description ? fn->description : fn->name); + + interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3); + + memset(&child, 0, sizeof(child)); + child.argv = args; + args[0] = "sh"; + args[1] = "-c"; + args[2] = cmdbuf; + args[3] = NULL; + + status = run_command(&child); + if (status < -ERR_RUN_COMMAND_FORK) + ; /* failure in run-command */ + else + status = -status; + fd = open(temp[1], O_RDONLY); + if (fd < 0) + goto bad; + if (fstat(fd, &st)) + goto close_bad; + result->size = st.st_size; + result->ptr = xmalloc(result->size + 1); + if (read_in_full(fd, result->ptr, result->size) != result->size) { + free(result->ptr); + result->ptr = NULL; + result->size = 0; + } + close_bad: + close(fd); + bad: + for (i = 0; i < 3; i++) + unlink(temp[i]); + return status; +} + +/* + * merge.default and merge.driver configuration items + */ +static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail; +static const char *default_ll_merge; + +static int read_merge_config(const char *var, const char *value) +{ + struct ll_merge_driver *fn; + const char *ep, *name; + int namelen; + + if (!strcmp(var, "merge.default")) { + if (value) + default_ll_merge = strdup(value); + return 0; + } + + /* + * We are not interested in anything but "merge..variable"; + * especially, we do not want to look at variables such as + * "merge.summary", "merge.tool", and "merge.verbosity". + */ + if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 5) + return 0; + + /* + * Find existing one as we might be processing merge..var2 + * after seeing merge..var1. + */ + name = var + 6; + namelen = ep - name; + for (fn = ll_user_merge; fn; fn = fn->next) + if (!strncmp(fn->name, name, namelen) && !fn->name[namelen]) + break; + if (!fn) { + fn = xcalloc(1, sizeof(struct ll_merge_driver)); + fn->name = xmemdupz(name, namelen); + fn->fn = ll_ext_merge; + *ll_user_merge_tail = fn; + ll_user_merge_tail = &(fn->next); + } + + ep++; + + if (!strcmp("name", ep)) { + if (!value) + return error("%s: lacks value", var); + fn->description = strdup(value); + return 0; + } + + if (!strcmp("driver", ep)) { + if (!value) + return error("%s: lacks value", var); + /* + * merge..driver specifies the command line: + * + * command-line + * + * The command-line will be interpolated with the following + * tokens and is given to the shell: + * + * %O - temporary file name for the merge base. + * %A - temporary file name for our version. + * %B - temporary file name for the other branches' version. + * + * The external merge driver should write the results in the + * file named by %A, and signal that it has done with zero exit + * status. + */ + fn->cmdline = strdup(value); + return 0; + } + + if (!strcmp("recursive", ep)) { + if (!value) + return error("%s: lacks value", var); + fn->recursive = strdup(value); + return 0; + } + + return 0; +} + +static void initialize_ll_merge(void) +{ + if (ll_user_merge_tail) + return; + ll_user_merge_tail = &ll_user_merge; + git_config(read_merge_config); +} + +static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr) +{ + struct ll_merge_driver *fn; + const char *name; + int i; + + initialize_ll_merge(); + + if (ATTR_TRUE(merge_attr)) + return &ll_merge_drv[LL_TEXT_MERGE]; + else if (ATTR_FALSE(merge_attr)) + return &ll_merge_drv[LL_BINARY_MERGE]; + else if (ATTR_UNSET(merge_attr)) { + if (!default_ll_merge) + return &ll_merge_drv[LL_TEXT_MERGE]; + else + name = default_ll_merge; + } + else + name = merge_attr; + + for (fn = ll_user_merge; fn; fn = fn->next) + if (!strcmp(fn->name, name)) + return fn; + + for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++) + if (!strcmp(ll_merge_drv[i].name, name)) + return &ll_merge_drv[i]; + + /* default to the 3-way */ + return &ll_merge_drv[LL_TEXT_MERGE]; +} + +static const char *git_path_check_merge(const char *path) +{ + static struct git_attr_check attr_merge_check; + + if (!attr_merge_check.attr) + attr_merge_check.attr = git_attr("merge", 5); + + if (git_checkattr(path, 1, &attr_merge_check)) + return NULL; + return attr_merge_check.value; +} + +static int ll_merge(mmbuffer_t *result_buf, + struct diff_filespec *o, + struct diff_filespec *a, + struct diff_filespec *b, + const char *branch1, + const char *branch2) +{ + mmfile_t orig, src1, src2; + char *name1, *name2; + int merge_status; + const char *ll_driver_name; + const struct ll_merge_driver *driver; + + name1 = xstrdup(mkpath("%s:%s", branch1, a->path)); + name2 = xstrdup(mkpath("%s:%s", branch2, b->path)); + + fill_mm(o->sha1, &orig); + fill_mm(a->sha1, &src1); + fill_mm(b->sha1, &src2); + + ll_driver_name = git_path_check_merge(a->path); + driver = find_ll_merge_driver(ll_driver_name); + + if (index_only && driver->recursive) + driver = find_ll_merge_driver(driver->recursive); + merge_status = driver->fn(driver, a->path, + &orig, &src1, name1, &src2, name2, + result_buf); + + free(name1); + free(name2); + free(orig.ptr); + free(src1.ptr); + free(src2.ptr); + return merge_status; +} + +static struct merge_file_info merge_file(struct diff_filespec *o, + struct diff_filespec *a, struct diff_filespec *b, + const char *branch1, const char *branch2) +{ + struct merge_file_info result; + result.merge = 0; + result.clean = 1; + + if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) { + result.clean = 0; + if (S_ISREG(a->mode)) { + result.mode = a->mode; + hashcpy(result.sha, a->sha1); + } else { + result.mode = b->mode; + hashcpy(result.sha, b->sha1); + } + } else { + if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1)) + result.merge = 1; + + result.mode = a->mode == o->mode ? b->mode: a->mode; + + if (sha_eq(a->sha1, o->sha1)) + hashcpy(result.sha, b->sha1); + else if (sha_eq(b->sha1, o->sha1)) + hashcpy(result.sha, a->sha1); + else if (S_ISREG(a->mode)) { + mmbuffer_t result_buf; + int merge_status; + + merge_status = ll_merge(&result_buf, o, a, b, + branch1, branch2); + + if ((merge_status < 0) || !result_buf.ptr) + die("Failed to execute internal merge"); + + if (write_sha1_file(result_buf.ptr, result_buf.size, + blob_type, result.sha)) + die("Unable to add %s to database", + a->path); + + free(result_buf.ptr); + result.clean = (merge_status == 0); + } else if (S_ISGITLINK(a->mode)) { + result.clean = 0; + hashcpy(result.sha, a->sha1); + } else if (S_ISLNK(a->mode)) { + hashcpy(result.sha, a->sha1); + + if (!sha_eq(a->sha1, b->sha1)) + result.clean = 0; + } else { + die("unsupported object type in the tree"); + } + } + + return result; +} + +static void conflict_rename_rename(struct rename *ren1, + const char *branch1, + struct rename *ren2, + const char *branch2) +{ + char *del[2]; + int delp = 0; + const char *ren1_dst = ren1->pair->two->path; + const char *ren2_dst = ren2->pair->two->path; + const char *dst_name1 = ren1_dst; + const char *dst_name2 = ren2_dst; + if (path_list_has_path(¤t_directory_set, ren1_dst)) { + dst_name1 = del[delp++] = unique_path(ren1_dst, branch1); + output(1, "%s is a directory in %s added as %s instead", + ren1_dst, branch2, dst_name1); + remove_file(0, ren1_dst, 0); + } + if (path_list_has_path(¤t_directory_set, ren2_dst)) { + dst_name2 = del[delp++] = unique_path(ren2_dst, branch2); + output(1, "%s is a directory in %s added as %s instead", + ren2_dst, branch1, dst_name2); + remove_file(0, ren2_dst, 0); + } + if (index_only) { + remove_file_from_cache(dst_name1); + remove_file_from_cache(dst_name2); + /* + * Uncomment to leave the conflicting names in the resulting tree + * + * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1); + * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2); + */ + } else { + update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1); + update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1); + } + while (delp--) + free(del[delp]); +} + +static void conflict_rename_dir(struct rename *ren1, + const char *branch1) +{ + char *new_path = unique_path(ren1->pair->two->path, branch1); + output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path); + remove_file(0, ren1->pair->two->path, 0); + update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path); + free(new_path); +} + +static void conflict_rename_rename_2(struct rename *ren1, + const char *branch1, + struct rename *ren2, + const char *branch2) +{ + char *new_path1 = unique_path(ren1->pair->two->path, branch1); + char *new_path2 = unique_path(ren2->pair->two->path, branch2); + output(1, "Renamed %s to %s and %s to %s instead", + ren1->pair->one->path, new_path1, + ren2->pair->one->path, new_path2); + remove_file(0, ren1->pair->two->path, 0); + update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1); + update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2); + free(new_path2); + free(new_path1); +} + +static int process_renames(struct path_list *a_renames, + struct path_list *b_renames, + const char *a_branch, + const char *b_branch) +{ + int clean_merge = 1, i, j; + struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0}; + const struct rename *sre; + + for (i = 0; i < a_renames->nr; i++) { + sre = a_renames->items[i].util; + path_list_insert(sre->pair->two->path, &a_by_dst)->util + = sre->dst_entry; + } + for (i = 0; i < b_renames->nr; i++) { + sre = b_renames->items[i].util; + path_list_insert(sre->pair->two->path, &b_by_dst)->util + = sre->dst_entry; + } + + for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) { + int compare; + char *src; + struct path_list *renames1, *renames2, *renames2Dst; + struct rename *ren1 = NULL, *ren2 = NULL; + const char *branch1, *branch2; + const char *ren1_src, *ren1_dst; + + if (i >= a_renames->nr) { + compare = 1; + ren2 = b_renames->items[j++].util; + } else if (j >= b_renames->nr) { + compare = -1; + ren1 = a_renames->items[i++].util; + } else { + compare = strcmp(a_renames->items[i].path, + b_renames->items[j].path); + if (compare <= 0) + ren1 = a_renames->items[i++].util; + if (compare >= 0) + ren2 = b_renames->items[j++].util; + } + + /* TODO: refactor, so that 1/2 are not needed */ + if (ren1) { + renames1 = a_renames; + renames2 = b_renames; + renames2Dst = &b_by_dst; + branch1 = a_branch; + branch2 = b_branch; + } else { + struct rename *tmp; + renames1 = b_renames; + renames2 = a_renames; + renames2Dst = &a_by_dst; + branch1 = b_branch; + branch2 = a_branch; + tmp = ren2; + ren2 = ren1; + ren1 = tmp; + } + src = ren1->pair->one->path; + + ren1->dst_entry->processed = 1; + ren1->src_entry->processed = 1; + + if (ren1->processed) + continue; + ren1->processed = 1; + + ren1_src = ren1->pair->one->path; + ren1_dst = ren1->pair->two->path; + + if (ren2) { + const char *ren2_src = ren2->pair->one->path; + const char *ren2_dst = ren2->pair->two->path; + /* Renamed in 1 and renamed in 2 */ + if (strcmp(ren1_src, ren2_src) != 0) + die("ren1.src != ren2.src"); + ren2->dst_entry->processed = 1; + ren2->processed = 1; + if (strcmp(ren1_dst, ren2_dst) != 0) { + clean_merge = 0; + output(1, "CONFLICT (rename/rename): " + "Rename \"%s\"->\"%s\" in branch \"%s\" " + "rename \"%s\"->\"%s\" in \"%s\"%s", + src, ren1_dst, branch1, + src, ren2_dst, branch2, + index_only ? " (left unresolved)": ""); + if (index_only) { + remove_file_from_cache(src); + update_file(0, ren1->pair->one->sha1, + ren1->pair->one->mode, src); + } + conflict_rename_rename(ren1, branch1, ren2, branch2); + } else { + struct merge_file_info mfi; + remove_file(1, ren1_src, 1); + mfi = merge_file(ren1->pair->one, + ren1->pair->two, + ren2->pair->two, + branch1, + branch2); + if (mfi.merge || !mfi.clean) + output(1, "Renamed %s->%s", src, ren1_dst); + + if (mfi.merge) + output(2, "Auto-merged %s", ren1_dst); + + if (!mfi.clean) { + output(1, "CONFLICT (content): merge conflict in %s", + ren1_dst); + clean_merge = 0; + + if (!index_only) + update_stages(ren1_dst, + ren1->pair->one, + ren1->pair->two, + ren2->pair->two, + 1 /* clear */); + } + update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst); + } + } else { + /* Renamed in 1, maybe changed in 2 */ + struct path_list_item *item; + /* we only use sha1 and mode of these */ + struct diff_filespec src_other, dst_other; + int try_merge, stage = a_renames == renames1 ? 3: 2; + + remove_file(1, ren1_src, index_only || stage == 3); + + hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha); + src_other.mode = ren1->src_entry->stages[stage].mode; + hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha); + dst_other.mode = ren1->dst_entry->stages[stage].mode; + + try_merge = 0; + + if (path_list_has_path(¤t_directory_set, ren1_dst)) { + clean_merge = 0; + output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s " + " directory %s added in %s", + ren1_src, ren1_dst, branch1, + ren1_dst, branch2); + conflict_rename_dir(ren1, branch1); + } else if (sha_eq(src_other.sha1, null_sha1)) { + clean_merge = 0; + output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s " + "and deleted in %s", + ren1_src, ren1_dst, branch1, + branch2); + update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst); + } else if (!sha_eq(dst_other.sha1, null_sha1)) { + const char *new_path; + clean_merge = 0; + try_merge = 1; + output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. " + "%s added in %s", + ren1_src, ren1_dst, branch1, + ren1_dst, branch2); + new_path = unique_path(ren1_dst, branch2); + output(1, "Added as %s instead", new_path); + update_file(0, dst_other.sha1, dst_other.mode, new_path); + } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) { + ren2 = item->util; + clean_merge = 0; + ren2->processed = 1; + output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. " + "Renamed %s->%s in %s", + ren1_src, ren1_dst, branch1, + ren2->pair->one->path, ren2->pair->two->path, branch2); + conflict_rename_rename_2(ren1, branch1, ren2, branch2); + } else + try_merge = 1; + + if (try_merge) { + struct diff_filespec *o, *a, *b; + struct merge_file_info mfi; + src_other.path = (char *)ren1_src; + + o = ren1->pair->one; + if (a_renames == renames1) { + a = ren1->pair->two; + b = &src_other; + } else { + b = ren1->pair->two; + a = &src_other; + } + mfi = merge_file(o, a, b, + a_branch, b_branch); + + if (mfi.clean && + sha_eq(mfi.sha, ren1->pair->two->sha1) && + mfi.mode == ren1->pair->two->mode) + /* + * This messaged is part of + * t6022 test. If you change + * it update the test too. + */ + output(3, "Skipped %s (merged same as existing)", ren1_dst); + else { + if (mfi.merge || !mfi.clean) + output(1, "Renamed %s => %s", ren1_src, ren1_dst); + if (mfi.merge) + output(2, "Auto-merged %s", ren1_dst); + if (!mfi.clean) { + output(1, "CONFLICT (rename/modify): Merge conflict in %s", + ren1_dst); + clean_merge = 0; + + if (!index_only) + update_stages(ren1_dst, + o, a, b, 1); + } + update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst); + } + } + } + } + path_list_clear(&a_by_dst, 0); + path_list_clear(&b_by_dst, 0); + + return clean_merge; +} + +static unsigned char *stage_sha(const unsigned char *sha, unsigned mode) +{ + return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha; +} + +/* Per entry merge function */ +static int process_entry(const char *path, struct stage_data *entry, + const char *branch1, + const char *branch2) +{ + /* + printf("processing entry, clean cache: %s\n", index_only ? "yes": "no"); + print_index_entry("\tpath: ", entry); + */ + int clean_merge = 1; + unsigned o_mode = entry->stages[1].mode; + unsigned a_mode = entry->stages[2].mode; + unsigned b_mode = entry->stages[3].mode; + unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode); + unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode); + unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode); + + if (o_sha && (!a_sha || !b_sha)) { + /* Case A: Deleted in one */ + if ((!a_sha && !b_sha) || + (sha_eq(a_sha, o_sha) && !b_sha) || + (!a_sha && sha_eq(b_sha, o_sha))) { + /* Deleted in both or deleted in one and + * unchanged in the other */ + if (a_sha) + output(2, "Removed %s", path); + /* do not touch working file if it did not exist */ + remove_file(1, path, !a_sha); + } else { + /* Deleted in one and changed in the other */ + clean_merge = 0; + if (!a_sha) { + output(1, "CONFLICT (delete/modify): %s deleted in %s " + "and modified in %s. Version %s of %s left in tree.", + path, branch1, + branch2, branch2, path); + update_file(0, b_sha, b_mode, path); + } else { + output(1, "CONFLICT (delete/modify): %s deleted in %s " + "and modified in %s. Version %s of %s left in tree.", + path, branch2, + branch1, branch1, path); + update_file(0, a_sha, a_mode, path); + } + } + + } else if ((!o_sha && a_sha && !b_sha) || + (!o_sha && !a_sha && b_sha)) { + /* Case B: Added in one. */ + const char *add_branch; + const char *other_branch; + unsigned mode; + const unsigned char *sha; + const char *conf; + + if (a_sha) { + add_branch = branch1; + other_branch = branch2; + mode = a_mode; + sha = a_sha; + conf = "file/directory"; + } else { + add_branch = branch2; + other_branch = branch1; + mode = b_mode; + sha = b_sha; + conf = "directory/file"; + } + if (path_list_has_path(¤t_directory_set, path)) { + const char *new_path = unique_path(path, add_branch); + clean_merge = 0; + output(1, "CONFLICT (%s): There is a directory with name %s in %s. " + "Added %s as %s", + conf, path, other_branch, path, new_path); + remove_file(0, path, 0); + update_file(0, sha, mode, new_path); + } else { + output(2, "Added %s", path); + update_file(1, sha, mode, path); + } + } else if (a_sha && b_sha) { + /* Case C: Added in both (check for same permissions) and */ + /* case D: Modified in both, but differently. */ + const char *reason = "content"; + struct merge_file_info mfi; + struct diff_filespec o, a, b; + + if (!o_sha) { + reason = "add/add"; + o_sha = (unsigned char *)null_sha1; + } + output(2, "Auto-merged %s", path); + o.path = a.path = b.path = (char *)path; + hashcpy(o.sha1, o_sha); + o.mode = o_mode; + hashcpy(a.sha1, a_sha); + a.mode = a_mode; + hashcpy(b.sha1, b_sha); + b.mode = b_mode; + + mfi = merge_file(&o, &a, &b, + branch1, branch2); + + clean_merge = mfi.clean; + if (mfi.clean) + update_file(1, mfi.sha, mfi.mode, path); + else if (S_ISGITLINK(mfi.mode)) + output(1, "CONFLICT (submodule): Merge conflict in %s " + "- needs %s", path, sha1_to_hex(b.sha1)); + else { + output(1, "CONFLICT (%s): Merge conflict in %s", + reason, path); + + if (index_only) + update_file(0, mfi.sha, mfi.mode, path); + else + update_file_flags(mfi.sha, mfi.mode, path, + 0 /* update_cache */, 1 /* update_working_directory */); + } + } else if (!o_sha && !a_sha && !b_sha) { + /* + * this entry was deleted altogether. a_mode == 0 means + * we had that path and want to actively remove it. + */ + remove_file(1, path, !a_mode); + } else + die("Fatal merge failure, shouldn't happen."); + + return clean_merge; +} + +int merge_trees(struct tree *head, + struct tree *merge, + struct tree *common, + const char *branch1, + const char *branch2, + struct tree **result) +{ + int code, clean; + + if (subtree_merge) { + merge = shift_tree_object(head, merge); + common = shift_tree_object(head, common); + } + + if (sha_eq(common->object.sha1, merge->object.sha1)) { + output(0, "Already uptodate!"); + *result = head; + return 1; + } + + code = git_merge_trees(index_only, common, head, merge); + + if (code != 0) + die("merging of trees %s and %s failed", + sha1_to_hex(head->object.sha1), + sha1_to_hex(merge->object.sha1)); + + if (unmerged_index()) { + struct path_list *entries, *re_head, *re_merge; + int i; + path_list_clear(¤t_file_set, 1); + path_list_clear(¤t_directory_set, 1); + get_files_dirs(head); + get_files_dirs(merge); + + entries = get_unmerged(); + re_head = get_renames(head, common, head, merge, entries); + re_merge = get_renames(merge, common, head, merge, entries); + clean = process_renames(re_head, re_merge, + branch1, branch2); + for (i = 0; i < entries->nr; i++) { + const char *path = entries->items[i].path; + struct stage_data *e = entries->items[i].util; + if (!e->processed + && !process_entry(path, e, branch1, branch2)) + clean = 0; + } + + path_list_clear(re_merge, 0); + path_list_clear(re_head, 0); + path_list_clear(entries, 1); + + } + else + clean = 1; + + if (index_only) + *result = write_tree_from_memory(); + + return clean; +} + +static struct commit_list *reverse_commit_list(struct commit_list *list) +{ + struct commit_list *next = NULL, *current, *backup; + for (current = list; current; current = backup) { + backup = current->next; + current->next = next; + next = current; + } + return next; +} + +/* + * Merge the commits h1 and h2, return the resulting virtual + * commit object and a flag indicating the cleanness of the merge. + */ +int merge_recursive(struct commit *h1, + struct commit *h2, + const char *branch1, + const char *branch2, + struct commit_list *ca, + struct commit **result) +{ + struct commit_list *iter; + struct commit *merged_common_ancestors; + struct tree *mrtree = mrtree; + int clean; + + if (show(4)) { + output(4, "Merging:"); + output_commit_title(h1); + output_commit_title(h2); + } + + if (!ca) { + ca = get_merge_bases(h1, h2, 1); + ca = reverse_commit_list(ca); + } + + if (show(5)) { + output(5, "found %u common ancestor(s):", commit_list_count(ca)); + for (iter = ca; iter; iter = iter->next) + output_commit_title(iter->item); + } + + merged_common_ancestors = pop_commit(&ca); + if (merged_common_ancestors == NULL) { + /* if there is no common ancestor, make an empty tree */ + struct tree *tree = xcalloc(1, sizeof(struct tree)); + + tree->object.parsed = 1; + tree->object.type = OBJ_TREE; + pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1); + merged_common_ancestors = make_virtual_commit(tree, "ancestor"); + } + + for (iter = ca; iter; iter = iter->next) { + call_depth++; + /* + * When the merge fails, the result contains files + * with conflict markers. The cleanness flag is + * ignored, it was never actually used, as result of + * merge_trees has always overwritten it: the committed + * "conflicts" were already resolved. + */ + discard_cache(); + merge_recursive(merged_common_ancestors, iter->item, + "Temporary merge branch 1", + "Temporary merge branch 2", + NULL, + &merged_common_ancestors); + call_depth--; + + if (!merged_common_ancestors) + die("merge returned no commit"); + } + + discard_cache(); + if (!call_depth) { + read_cache(); + index_only = 0; + } else + index_only = 1; + + clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree, + branch1, branch2, &mrtree); + + if (index_only) { + *result = make_virtual_commit(mrtree, "merged tree"); + commit_list_insert(h1, &(*result)->parents); + commit_list_insert(h2, &(*result)->parents->next); + } + flush_output(); + return clean; +} + +static const char *better_branch_name(const char *branch) +{ + static char githead_env[8 + 40 + 1]; + char *name; + + if (strlen(branch) != 40) + return branch; + sprintf(githead_env, "GITHEAD_%s", branch); + name = getenv(githead_env); + return name ? name : branch; +} + +static struct commit *get_ref(const char *ref) +{ + unsigned char sha1[20]; + struct object *object; + + if (get_sha1(ref, sha1)) + die("Could not resolve ref '%s'", ref); + object = deref_tag(parse_object(sha1), ref, strlen(ref)); + if (object->type == OBJ_TREE) + return make_virtual_commit((struct tree*)object, + better_branch_name(ref)); + if (object->type != OBJ_COMMIT) + return NULL; + if (parse_commit((struct commit *)object)) + die("Could not parse commit '%s'", sha1_to_hex(object->sha1)); + return (struct commit *)object; +} + +static int merge_config(const char *var, const char *value) +{ + if (!strcasecmp(var, "merge.verbosity")) { + verbosity = git_config_int(var, value); + return 0; + } + if (!strcasecmp(var, "diff.renamelimit")) { + rename_limit = git_config_int(var, value); + return 0; + } + return git_default_config(var, value); +} + +int cmd_merge_recursive(int argc, const char **argv, const char *prefix) +{ + static const char *bases[20]; + static unsigned bases_count = 0; + int i, clean; + const char *branch1, *branch2; + struct commit *result, *h1, *h2; + struct commit_list *ca = NULL; + struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); + int index_fd; + + if (argv[0]) { + int namelen = strlen(argv[0]); + if (8 < namelen && + !strcmp(argv[0] + namelen - 8, "-subtree")) + subtree_merge = 1; + } + + git_config(merge_config); + if (getenv("GIT_MERGE_VERBOSITY")) + verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10); + + if (argc < 4) + die("Usage: %s ... -- ...\n", argv[0]); + + for (i = 1; i < argc; ++i) { + if (!strcmp(argv[i], "--")) + break; + if (bases_count < sizeof(bases)/sizeof(*bases)) + bases[bases_count++] = argv[i]; + } + if (argc - i != 3) /* "--" "" "" */ + die("Not handling anything other than two heads merge."); + if (verbosity >= 5) + buffer_output = 0; + + branch1 = argv[++i]; + branch2 = argv[++i]; + + h1 = get_ref(branch1); + h2 = get_ref(branch2); + + branch1 = better_branch_name(branch1); + branch2 = better_branch_name(branch2); + + if (show(3)) + printf("Merging %s with %s\n", branch1, branch2); + + index_fd = hold_locked_index(lock, 1); + + for (i = 0; i < bases_count; i++) { + struct commit *ancestor = get_ref(bases[i]); + ca = commit_list_insert(ancestor, &ca); + } + clean = merge_recursive(h1, h2, branch1, branch2, ca, &result); + + if (active_cache_changed && + (write_cache(index_fd, active_cache, active_nr) || + commit_locked_index(lock))) + die ("unable to write %s", get_index_file()); + + return clean ? 0: 1; +} diff --git a/builtin.h b/builtin.h index cb675c4..428160d 100644 --- a/builtin.h +++ b/builtin.h @@ -57,6 +57,7 @@ extern int cmd_mailsplit(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); +extern int cmd_merge_recursive(int argc, const char **argv, const char *prefix); extern int cmd_mv(int argc, const char **argv, const char *prefix); extern int cmd_name_rev(int argc, const char **argv, const char *prefix); extern int cmd_pack_objects(int argc, const char **argv, const char *prefix); diff --git a/git.c b/git.c index 15fec89..114ea75 100644 --- a/git.c +++ b/git.c @@ -330,6 +330,7 @@ static void handle_internal_command(int argc, const char **argv) { "merge-base", cmd_merge_base, RUN_SETUP }, { "merge-file", cmd_merge_file }, { "merge-ours", cmd_merge_ours, RUN_SETUP }, + { "merge-recursive", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE }, { "mv", cmd_mv, RUN_SETUP | NEED_WORK_TREE }, { "name-rev", cmd_name_rev, RUN_SETUP }, { "pack-objects", cmd_pack_objects, RUN_SETUP }, diff --git a/merge-recursive.c b/merge-recursive.c deleted file mode 100644 index bdf03b1..0000000 --- a/merge-recursive.c +++ /dev/null @@ -1,1760 +0,0 @@ -/* - * Recursive Merge algorithm stolen from git-merge-recursive.py by - * Fredrik Kuivinen. - * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006 - */ -#include "cache.h" -#include "cache-tree.h" -#include "commit.h" -#include "blob.h" -#include "tree-walk.h" -#include "diff.h" -#include "diffcore.h" -#include "run-command.h" -#include "tag.h" -#include "unpack-trees.h" -#include "path-list.h" -#include "xdiff-interface.h" -#include "interpolate.h" -#include "attr.h" - -static int subtree_merge; - -static struct tree *shift_tree_object(struct tree *one, struct tree *two) -{ - unsigned char shifted[20]; - - /* - * NEEDSWORK: this limits the recursion depth to hardcoded - * value '2' to avoid excessive overhead. - */ - shift_tree(one->object.sha1, two->object.sha1, shifted, 2); - if (!hashcmp(two->object.sha1, shifted)) - return two; - return lookup_tree(shifted); -} - -/* - * A virtual commit has - * - (const char *)commit->util set to the name, and - * - *(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)); - static unsigned virtual_id = 1; - commit->tree = tree; - commit->util = (void*)comment; - *(int*)commit->object.sha1 = virtual_id++; - /* avoid warnings */ - commit->object.parsed = 1; - return commit; -} - -/* - * Since we use get_tree_entry(), which does not put the read object into - * the object pool, we cannot rely on a == b. - */ -static int sha_eq(const unsigned char *a, const unsigned char *b) -{ - if (!a && !b) - return 2; - return a && b && hashcmp(a, b) == 0; -} - -/* - * Since we want to write the index eventually, we cannot reuse the index - * for these (temporary) data. - */ -struct stage_data -{ - struct - { - unsigned mode; - unsigned char sha[20]; - } stages[4]; - unsigned processed:1; -}; - -static struct path_list current_file_set = {NULL, 0, 0, 1}; -static struct path_list current_directory_set = {NULL, 0, 0, 1}; - -static int call_depth = 0; -static int verbosity = 2; -static int rename_limit = -1; -static int buffer_output = 1; -static struct strbuf obuf = STRBUF_INIT; - -static int show(int v) -{ - return (!call_depth && verbosity >= v) || verbosity >= 5; -} - -static void flush_output(void) -{ - if (obuf.len) { - fputs(obuf.buf, stdout); - strbuf_reset(&obuf); - } -} - -static void output(int v, const char *fmt, ...) -{ - int len; - va_list ap; - - if (!show(v)) - return; - - strbuf_grow(&obuf, call_depth * 2 + 2); - memset(obuf.buf + obuf.len, ' ', call_depth * 2); - strbuf_setlen(&obuf, obuf.len + call_depth * 2); - - va_start(ap, fmt); - len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap); - va_end(ap); - - if (len < 0) - len = 0; - if (len >= strbuf_avail(&obuf)) { - strbuf_grow(&obuf, len + 2); - va_start(ap, fmt); - len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap); - va_end(ap); - if (len >= strbuf_avail(&obuf)) { - die("this should not happen, your snprintf is broken"); - } - } - strbuf_setlen(&obuf, obuf.len + len); - strbuf_add(&obuf, "\n", 1); - if (!buffer_output) - flush_output(); -} - -static void output_commit_title(struct commit *commit) -{ - int i; - flush_output(); - for (i = call_depth; i--;) - fputs(" ", stdout); - if (commit->util) - printf("virtual %s\n", (char *)commit->util); - else { - printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV)); - if (parse_commit(commit) != 0) - printf("(bad commit)\n"); - else { - const char *s; - int len; - for (s = commit->buffer; *s; s++) - if (*s == '\n' && s[1] == '\n') { - s += 2; - break; - } - for (len = 0; s[len] && '\n' != s[len]; len++) - ; /* do nothing */ - printf("%.*s\n", len, s); - } - } -} - -static int add_cacheinfo(unsigned int mode, const unsigned char *sha1, - const char *path, int stage, int refresh, int options) -{ - struct cache_entry *ce; - ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh); - if (!ce) - return error("addinfo_cache failed for path '%s'", path); - return add_cache_entry(ce, options); -} - -/* - * This is a global variable which is used in a number of places but - * only written to in the 'merge' function. - * - * index_only == 1 => Don't leave any non-stage 0 entries in the cache and - * don't update the working directory. - * 0 => Leave unmerged entries in the cache and update - * the working directory. - */ -static int index_only = 0; - -static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree) -{ - parse_tree(tree); - init_tree_desc(desc, tree->buffer, tree->size); -} - -static int git_merge_trees(int index_only, - struct tree *common, - struct tree *head, - struct tree *merge) -{ - int rc; - struct tree_desc t[3]; - struct unpack_trees_options opts; - - memset(&opts, 0, sizeof(opts)); - if (index_only) - opts.index_only = 1; - else - opts.update = 1; - opts.merge = 1; - opts.head_idx = 2; - opts.fn = threeway_merge; - - init_tree_desc_from_tree(t+0, common); - init_tree_desc_from_tree(t+1, head); - init_tree_desc_from_tree(t+2, merge); - - rc = unpack_trees(3, t, &opts); - cache_tree_free(&active_cache_tree); - return rc; -} - -static int unmerged_index(void) -{ - int i; - for (i = 0; i < active_nr; i++) { - struct cache_entry *ce = active_cache[i]; - if (ce_stage(ce)) - return 1; - } - return 0; -} - -static struct tree *git_write_tree(void) -{ - struct tree *result = NULL; - - if (unmerged_index()) { - int i; - output(0, "There are unmerged index entries:"); - for (i = 0; i < active_nr; i++) { - struct cache_entry *ce = active_cache[i]; - if (ce_stage(ce)) - output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name); - } - return NULL; - } - - if (!active_cache_tree) - active_cache_tree = cache_tree(); - - if (!cache_tree_fully_valid(active_cache_tree) && - cache_tree_update(active_cache_tree, - active_cache, active_nr, 0, 0) < 0) - die("error building trees"); - - result = lookup_tree(active_cache_tree->sha1); - - return result; -} - -static int save_files_dirs(const unsigned char *sha1, - const char *base, int baselen, const char *path, - unsigned int mode, int stage) -{ - int len = strlen(path); - char *newpath = xmalloc(baselen + len + 1); - memcpy(newpath, base, baselen); - memcpy(newpath + baselen, path, len); - newpath[baselen + len] = '\0'; - - if (S_ISDIR(mode)) - path_list_insert(newpath, ¤t_directory_set); - else - path_list_insert(newpath, ¤t_file_set); - free(newpath); - - return READ_TREE_RECURSIVE; -} - -static int get_files_dirs(struct tree *tree) -{ - int n; - if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0) - return 0; - n = current_file_set.nr + current_directory_set.nr; - return n; -} - -/* - * Returns an index_entry instance which doesn't have to correspond to - * a real cache entry in Git's index. - */ -static struct stage_data *insert_stage_data(const char *path, - struct tree *o, struct tree *a, struct tree *b, - struct path_list *entries) -{ - struct path_list_item *item; - struct stage_data *e = xcalloc(1, sizeof(struct stage_data)); - get_tree_entry(o->object.sha1, path, - e->stages[1].sha, &e->stages[1].mode); - get_tree_entry(a->object.sha1, path, - e->stages[2].sha, &e->stages[2].mode); - get_tree_entry(b->object.sha1, path, - e->stages[3].sha, &e->stages[3].mode); - item = path_list_insert(path, entries); - item->util = e; - return e; -} - -/* - * Create a dictionary mapping file names to stage_data objects. The - * dictionary contains one entry for every path with a non-zero stage entry. - */ -static struct path_list *get_unmerged(void) -{ - struct path_list *unmerged = xcalloc(1, sizeof(struct path_list)); - int i; - - unmerged->strdup_paths = 1; - - for (i = 0; i < active_nr; i++) { - struct path_list_item *item; - struct stage_data *e; - struct cache_entry *ce = active_cache[i]; - if (!ce_stage(ce)) - continue; - - item = path_list_lookup(ce->name, unmerged); - if (!item) { - item = path_list_insert(ce->name, unmerged); - item->util = xcalloc(1, sizeof(struct stage_data)); - } - e = item->util; - e->stages[ce_stage(ce)].mode = ce->ce_mode; - hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1); - } - - return unmerged; -} - -struct rename -{ - struct diff_filepair *pair; - struct stage_data *src_entry; - struct stage_data *dst_entry; - unsigned processed:1; -}; - -/* - * Get information of all renames which occurred between 'o_tree' and - * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and - * 'b_tree') to be able to associate the correct cache entries with - * the rename information. 'tree' is always equal to either a_tree or b_tree. - */ -static struct path_list *get_renames(struct tree *tree, - struct tree *o_tree, - struct tree *a_tree, - struct tree *b_tree, - struct path_list *entries) -{ - int i; - struct path_list *renames; - struct diff_options opts; - - renames = xcalloc(1, sizeof(struct path_list)); - diff_setup(&opts); - DIFF_OPT_SET(&opts, RECURSIVE); - opts.detect_rename = DIFF_DETECT_RENAME; - opts.rename_limit = rename_limit; - opts.output_format = DIFF_FORMAT_NO_OUTPUT; - if (diff_setup_done(&opts) < 0) - die("diff setup failed"); - diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts); - diffcore_std(&opts); - for (i = 0; i < diff_queued_diff.nr; ++i) { - struct path_list_item *item; - struct rename *re; - struct diff_filepair *pair = diff_queued_diff.queue[i]; - if (pair->status != 'R') { - diff_free_filepair(pair); - continue; - } - re = xmalloc(sizeof(*re)); - re->processed = 0; - re->pair = pair; - item = path_list_lookup(re->pair->one->path, entries); - if (!item) - re->src_entry = insert_stage_data(re->pair->one->path, - o_tree, a_tree, b_tree, entries); - else - re->src_entry = item->util; - - item = path_list_lookup(re->pair->two->path, entries); - if (!item) - re->dst_entry = insert_stage_data(re->pair->two->path, - o_tree, a_tree, b_tree, entries); - else - re->dst_entry = item->util; - item = path_list_insert(pair->one->path, renames); - item->util = re; - } - opts.output_format = DIFF_FORMAT_NO_OUTPUT; - diff_queued_diff.nr = 0; - diff_flush(&opts); - return renames; -} - -static int update_stages(const char *path, struct diff_filespec *o, - struct diff_filespec *a, struct diff_filespec *b, - int clear) -{ - int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE; - if (clear) - if (remove_file_from_cache(path)) - return -1; - if (o) - if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options)) - return -1; - if (a) - if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options)) - return -1; - if (b) - if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options)) - return -1; - return 0; -} - -static int remove_path(const char *name) -{ - int ret; - char *slash, *dirs; - - ret = unlink(name); - if (ret) - return ret; - dirs = xstrdup(name); - while ((slash = strrchr(name, '/'))) { - *slash = '\0'; - if (rmdir(name) != 0) - break; - } - free(dirs); - return ret; -} - -static int remove_file(int clean, const char *path, int no_wd) -{ - int update_cache = index_only || clean; - int update_working_directory = !index_only && !no_wd; - - if (update_cache) { - if (remove_file_from_cache(path)) - return -1; - } - if (update_working_directory) { - unlink(path); - if (errno != ENOENT || errno != EISDIR) - return -1; - remove_path(path); - } - return 0; -} - -static char *unique_path(const char *path, const char *branch) -{ - char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1); - int suffix = 0; - struct stat st; - char *p = newpath + strlen(path); - strcpy(newpath, path); - *(p++) = '~'; - strcpy(p, branch); - for (; *p; ++p) - if ('/' == *p) - *p = '_'; - while (path_list_has_path(¤t_file_set, newpath) || - path_list_has_path(¤t_directory_set, newpath) || - lstat(newpath, &st) == 0) - sprintf(p, "_%d", suffix++); - - path_list_insert(newpath, ¤t_file_set); - return newpath; -} - -static int mkdir_p(const char *path, unsigned long mode) -{ - /* path points to cache entries, so xstrdup before messing with it */ - char *buf = xstrdup(path); - int result = safe_create_leading_directories(buf); - free(buf); - return result; -} - -static void flush_buffer(int fd, const char *buf, unsigned long size) -{ - while (size > 0) { - long ret = write_in_full(fd, buf, size); - if (ret < 0) { - /* Ignore epipe */ - if (errno == EPIPE) - break; - die("merge-recursive: %s", strerror(errno)); - } else if (!ret) { - die("merge-recursive: disk full?"); - } - size -= ret; - buf += ret; - } -} - -static int make_room_for_path(const char *path) -{ - int status; - const char *msg = "failed to create path '%s'%s"; - - status = mkdir_p(path, 0777); - if (status) { - if (status == -3) { - /* something else exists */ - error(msg, path, ": perhaps a D/F conflict?"); - return -1; - } - die(msg, path, ""); - } - - /* Successful unlink is good.. */ - if (!unlink(path)) - return 0; - /* .. and so is no existing file */ - if (errno == ENOENT) - return 0; - /* .. but not some other error (who really cares what?) */ - return error(msg, path, ": perhaps a D/F conflict?"); -} - -static void update_file_flags(const unsigned char *sha, - unsigned mode, - const char *path, - int update_cache, - int update_wd) -{ - if (index_only) - update_wd = 0; - - if (update_wd) { - enum object_type type; - void *buf; - unsigned long size; - - if (S_ISGITLINK(mode)) - die("cannot read object %s '%s': It is a submodule!", - sha1_to_hex(sha), path); - - buf = read_sha1_file(sha, &type, &size); - if (!buf) - die("cannot read object %s '%s'", sha1_to_hex(sha), path); - if (type != OBJ_BLOB) - die("blob expected for %s '%s'", sha1_to_hex(sha), path); - - if (make_room_for_path(path) < 0) { - update_wd = 0; - goto update_index; - } - if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) { - int fd; - if (mode & 0100) - mode = 0777; - else - mode = 0666; - fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); - if (fd < 0) - die("failed to open %s: %s", path, strerror(errno)); - flush_buffer(fd, buf, size); - close(fd); - } else if (S_ISLNK(mode)) { - char *lnk = xmemdupz(buf, size); - mkdir_p(path, 0777); - unlink(path); - symlink(lnk, path); - free(lnk); - } else - die("do not know what to do with %06o %s '%s'", - mode, sha1_to_hex(sha), path); - } - update_index: - if (update_cache) - add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD); -} - -static void update_file(int clean, - const unsigned char *sha, - unsigned mode, - const char *path) -{ - update_file_flags(sha, mode, path, index_only || clean, !index_only); -} - -/* Low level file merging, update and removal */ - -struct merge_file_info -{ - unsigned char sha[20]; - unsigned mode; - unsigned clean:1, - merge:1; -}; - -static void fill_mm(const unsigned char *sha1, mmfile_t *mm) -{ - unsigned long size; - enum object_type type; - - if (!hashcmp(sha1, null_sha1)) { - mm->ptr = xstrdup(""); - mm->size = 0; - return; - } - - mm->ptr = read_sha1_file(sha1, &type, &size); - if (!mm->ptr || type != OBJ_BLOB) - die("unable to read blob object %s", sha1_to_hex(sha1)); - mm->size = size; -} - -/* - * Customizable low-level merge drivers support. - */ - -struct ll_merge_driver; -typedef int (*ll_merge_fn)(const struct ll_merge_driver *, - const char *path, - mmfile_t *orig, - mmfile_t *src1, const char *name1, - mmfile_t *src2, const char *name2, - mmbuffer_t *result); - -struct ll_merge_driver { - const char *name; - const char *description; - ll_merge_fn fn; - const char *recursive; - struct ll_merge_driver *next; - char *cmdline; -}; - -/* - * Built-in low-levels - */ -static int ll_binary_merge(const struct ll_merge_driver *drv_unused, - const char *path_unused, - mmfile_t *orig, - mmfile_t *src1, const char *name1, - mmfile_t *src2, const char *name2, - mmbuffer_t *result) -{ - /* - * The tentative merge result is "ours" for the final round, - * or common ancestor for an internal merge. Still return - * "conflicted merge" status. - */ - mmfile_t *stolen = index_only ? orig : src1; - - result->ptr = stolen->ptr; - result->size = stolen->size; - stolen->ptr = NULL; - return 1; -} - -static int ll_xdl_merge(const struct ll_merge_driver *drv_unused, - const char *path_unused, - mmfile_t *orig, - mmfile_t *src1, const char *name1, - mmfile_t *src2, const char *name2, - mmbuffer_t *result) -{ - xpparam_t xpp; - - if (buffer_is_binary(orig->ptr, orig->size) || - buffer_is_binary(src1->ptr, src1->size) || - buffer_is_binary(src2->ptr, src2->size)) { - warning("Cannot merge binary files: %s vs. %s\n", - name1, name2); - return ll_binary_merge(drv_unused, path_unused, - orig, src1, name1, - src2, name2, - result); - } - - memset(&xpp, 0, sizeof(xpp)); - return xdl_merge(orig, - src1, name1, - src2, name2, - &xpp, XDL_MERGE_ZEALOUS, - result); -} - -static int ll_union_merge(const struct ll_merge_driver *drv_unused, - const char *path_unused, - mmfile_t *orig, - mmfile_t *src1, const char *name1, - mmfile_t *src2, const char *name2, - mmbuffer_t *result) -{ - char *src, *dst; - long size; - const int marker_size = 7; - - int status = ll_xdl_merge(drv_unused, path_unused, - orig, src1, NULL, src2, NULL, result); - if (status <= 0) - return status; - size = result->size; - src = dst = result->ptr; - while (size) { - char ch; - if ((marker_size < size) && - (*src == '<' || *src == '=' || *src == '>')) { - int i; - ch = *src; - for (i = 0; i < marker_size; i++) - if (src[i] != ch) - goto not_a_marker; - if (src[marker_size] != '\n') - goto not_a_marker; - src += marker_size + 1; - size -= marker_size + 1; - continue; - } - not_a_marker: - do { - ch = *src++; - *dst++ = ch; - size--; - } while (ch != '\n' && size); - } - result->size = dst - result->ptr; - return 0; -} - -#define LL_BINARY_MERGE 0 -#define LL_TEXT_MERGE 1 -#define LL_UNION_MERGE 2 -static struct ll_merge_driver ll_merge_drv[] = { - { "binary", "built-in binary merge", ll_binary_merge }, - { "text", "built-in 3-way text merge", ll_xdl_merge }, - { "union", "built-in union merge", ll_union_merge }, -}; - -static void create_temp(mmfile_t *src, char *path) -{ - int fd; - - strcpy(path, ".merge_file_XXXXXX"); - fd = xmkstemp(path); - if (write_in_full(fd, src->ptr, src->size) != src->size) - die("unable to write temp-file"); - close(fd); -} - -/* - * User defined low-level merge driver support. - */ -static int ll_ext_merge(const struct ll_merge_driver *fn, - const char *path, - mmfile_t *orig, - mmfile_t *src1, const char *name1, - mmfile_t *src2, const char *name2, - mmbuffer_t *result) -{ - char temp[3][50]; - char cmdbuf[2048]; - struct interp table[] = { - { "%O" }, - { "%A" }, - { "%B" }, - }; - struct child_process child; - const char *args[20]; - int status, fd, i; - struct stat st; - - if (fn->cmdline == NULL) - die("custom merge driver %s lacks command line.", fn->name); - - result->ptr = NULL; - result->size = 0; - create_temp(orig, temp[0]); - create_temp(src1, temp[1]); - create_temp(src2, temp[2]); - - interp_set_entry(table, 0, temp[0]); - interp_set_entry(table, 1, temp[1]); - interp_set_entry(table, 2, temp[2]); - - output(1, "merging %s using %s", path, - fn->description ? fn->description : fn->name); - - interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3); - - memset(&child, 0, sizeof(child)); - child.argv = args; - args[0] = "sh"; - args[1] = "-c"; - args[2] = cmdbuf; - args[3] = NULL; - - status = run_command(&child); - if (status < -ERR_RUN_COMMAND_FORK) - ; /* failure in run-command */ - else - status = -status; - fd = open(temp[1], O_RDONLY); - if (fd < 0) - goto bad; - if (fstat(fd, &st)) - goto close_bad; - result->size = st.st_size; - result->ptr = xmalloc(result->size + 1); - if (read_in_full(fd, result->ptr, result->size) != result->size) { - free(result->ptr); - result->ptr = NULL; - result->size = 0; - } - close_bad: - close(fd); - bad: - for (i = 0; i < 3; i++) - unlink(temp[i]); - return status; -} - -/* - * merge.default and merge.driver configuration items - */ -static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail; -static const char *default_ll_merge; - -static int read_merge_config(const char *var, const char *value) -{ - struct ll_merge_driver *fn; - const char *ep, *name; - int namelen; - - if (!strcmp(var, "merge.default")) { - if (value) - default_ll_merge = strdup(value); - return 0; - } - - /* - * We are not interested in anything but "merge..variable"; - * especially, we do not want to look at variables such as - * "merge.summary", "merge.tool", and "merge.verbosity". - */ - if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 5) - return 0; - - /* - * Find existing one as we might be processing merge..var2 - * after seeing merge..var1. - */ - name = var + 6; - namelen = ep - name; - for (fn = ll_user_merge; fn; fn = fn->next) - if (!strncmp(fn->name, name, namelen) && !fn->name[namelen]) - break; - if (!fn) { - fn = xcalloc(1, sizeof(struct ll_merge_driver)); - fn->name = xmemdupz(name, namelen); - fn->fn = ll_ext_merge; - *ll_user_merge_tail = fn; - ll_user_merge_tail = &(fn->next); - } - - ep++; - - if (!strcmp("name", ep)) { - if (!value) - return error("%s: lacks value", var); - fn->description = strdup(value); - return 0; - } - - if (!strcmp("driver", ep)) { - if (!value) - return error("%s: lacks value", var); - /* - * merge..driver specifies the command line: - * - * command-line - * - * The command-line will be interpolated with the following - * tokens and is given to the shell: - * - * %O - temporary file name for the merge base. - * %A - temporary file name for our version. - * %B - temporary file name for the other branches' version. - * - * The external merge driver should write the results in the - * file named by %A, and signal that it has done with zero exit - * status. - */ - fn->cmdline = strdup(value); - return 0; - } - - if (!strcmp("recursive", ep)) { - if (!value) - return error("%s: lacks value", var); - fn->recursive = strdup(value); - return 0; - } - - return 0; -} - -static void initialize_ll_merge(void) -{ - if (ll_user_merge_tail) - return; - ll_user_merge_tail = &ll_user_merge; - git_config(read_merge_config); -} - -static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr) -{ - struct ll_merge_driver *fn; - const char *name; - int i; - - initialize_ll_merge(); - - if (ATTR_TRUE(merge_attr)) - return &ll_merge_drv[LL_TEXT_MERGE]; - else if (ATTR_FALSE(merge_attr)) - return &ll_merge_drv[LL_BINARY_MERGE]; - else if (ATTR_UNSET(merge_attr)) { - if (!default_ll_merge) - return &ll_merge_drv[LL_TEXT_MERGE]; - else - name = default_ll_merge; - } - else - name = merge_attr; - - for (fn = ll_user_merge; fn; fn = fn->next) - if (!strcmp(fn->name, name)) - return fn; - - for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++) - if (!strcmp(ll_merge_drv[i].name, name)) - return &ll_merge_drv[i]; - - /* default to the 3-way */ - return &ll_merge_drv[LL_TEXT_MERGE]; -} - -static const char *git_path_check_merge(const char *path) -{ - static struct git_attr_check attr_merge_check; - - if (!attr_merge_check.attr) - attr_merge_check.attr = git_attr("merge", 5); - - if (git_checkattr(path, 1, &attr_merge_check)) - return NULL; - return attr_merge_check.value; -} - -static int ll_merge(mmbuffer_t *result_buf, - struct diff_filespec *o, - struct diff_filespec *a, - struct diff_filespec *b, - const char *branch1, - const char *branch2) -{ - mmfile_t orig, src1, src2; - char *name1, *name2; - int merge_status; - const char *ll_driver_name; - const struct ll_merge_driver *driver; - - name1 = xstrdup(mkpath("%s:%s", branch1, a->path)); - name2 = xstrdup(mkpath("%s:%s", branch2, b->path)); - - fill_mm(o->sha1, &orig); - fill_mm(a->sha1, &src1); - fill_mm(b->sha1, &src2); - - ll_driver_name = git_path_check_merge(a->path); - driver = find_ll_merge_driver(ll_driver_name); - - if (index_only && driver->recursive) - driver = find_ll_merge_driver(driver->recursive); - merge_status = driver->fn(driver, a->path, - &orig, &src1, name1, &src2, name2, - result_buf); - - free(name1); - free(name2); - free(orig.ptr); - free(src1.ptr); - free(src2.ptr); - return merge_status; -} - -static struct merge_file_info merge_file(struct diff_filespec *o, - struct diff_filespec *a, struct diff_filespec *b, - const char *branch1, const char *branch2) -{ - struct merge_file_info result; - result.merge = 0; - result.clean = 1; - - if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) { - result.clean = 0; - if (S_ISREG(a->mode)) { - result.mode = a->mode; - hashcpy(result.sha, a->sha1); - } else { - result.mode = b->mode; - hashcpy(result.sha, b->sha1); - } - } else { - if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1)) - result.merge = 1; - - result.mode = a->mode == o->mode ? b->mode: a->mode; - - if (sha_eq(a->sha1, o->sha1)) - hashcpy(result.sha, b->sha1); - else if (sha_eq(b->sha1, o->sha1)) - hashcpy(result.sha, a->sha1); - else if (S_ISREG(a->mode)) { - mmbuffer_t result_buf; - int merge_status; - - merge_status = ll_merge(&result_buf, o, a, b, - branch1, branch2); - - if ((merge_status < 0) || !result_buf.ptr) - die("Failed to execute internal merge"); - - if (write_sha1_file(result_buf.ptr, result_buf.size, - blob_type, result.sha)) - die("Unable to add %s to database", - a->path); - - free(result_buf.ptr); - result.clean = (merge_status == 0); - } else if (S_ISGITLINK(a->mode)) { - result.clean = 0; - hashcpy(result.sha, a->sha1); - } else if (S_ISLNK(a->mode)) { - hashcpy(result.sha, a->sha1); - - if (!sha_eq(a->sha1, b->sha1)) - result.clean = 0; - } else { - die("unsupported object type in the tree"); - } - } - - return result; -} - -static void conflict_rename_rename(struct rename *ren1, - const char *branch1, - struct rename *ren2, - const char *branch2) -{ - char *del[2]; - int delp = 0; - const char *ren1_dst = ren1->pair->two->path; - const char *ren2_dst = ren2->pair->two->path; - const char *dst_name1 = ren1_dst; - const char *dst_name2 = ren2_dst; - if (path_list_has_path(¤t_directory_set, ren1_dst)) { - dst_name1 = del[delp++] = unique_path(ren1_dst, branch1); - output(1, "%s is a directory in %s added as %s instead", - ren1_dst, branch2, dst_name1); - remove_file(0, ren1_dst, 0); - } - if (path_list_has_path(¤t_directory_set, ren2_dst)) { - dst_name2 = del[delp++] = unique_path(ren2_dst, branch2); - output(1, "%s is a directory in %s added as %s instead", - ren2_dst, branch1, dst_name2); - remove_file(0, ren2_dst, 0); - } - if (index_only) { - remove_file_from_cache(dst_name1); - remove_file_from_cache(dst_name2); - /* - * Uncomment to leave the conflicting names in the resulting tree - * - * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1); - * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2); - */ - } else { - update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1); - update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1); - } - while (delp--) - free(del[delp]); -} - -static void conflict_rename_dir(struct rename *ren1, - const char *branch1) -{ - char *new_path = unique_path(ren1->pair->two->path, branch1); - output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path); - remove_file(0, ren1->pair->two->path, 0); - update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path); - free(new_path); -} - -static void conflict_rename_rename_2(struct rename *ren1, - const char *branch1, - struct rename *ren2, - const char *branch2) -{ - char *new_path1 = unique_path(ren1->pair->two->path, branch1); - char *new_path2 = unique_path(ren2->pair->two->path, branch2); - output(1, "Renamed %s to %s and %s to %s instead", - ren1->pair->one->path, new_path1, - ren2->pair->one->path, new_path2); - remove_file(0, ren1->pair->two->path, 0); - update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1); - update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2); - free(new_path2); - free(new_path1); -} - -static int process_renames(struct path_list *a_renames, - struct path_list *b_renames, - const char *a_branch, - const char *b_branch) -{ - int clean_merge = 1, i, j; - struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0}; - const struct rename *sre; - - for (i = 0; i < a_renames->nr; i++) { - sre = a_renames->items[i].util; - path_list_insert(sre->pair->two->path, &a_by_dst)->util - = sre->dst_entry; - } - for (i = 0; i < b_renames->nr; i++) { - sre = b_renames->items[i].util; - path_list_insert(sre->pair->two->path, &b_by_dst)->util - = sre->dst_entry; - } - - for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) { - int compare; - char *src; - struct path_list *renames1, *renames2, *renames2Dst; - struct rename *ren1 = NULL, *ren2 = NULL; - const char *branch1, *branch2; - const char *ren1_src, *ren1_dst; - - if (i >= a_renames->nr) { - compare = 1; - ren2 = b_renames->items[j++].util; - } else if (j >= b_renames->nr) { - compare = -1; - ren1 = a_renames->items[i++].util; - } else { - compare = strcmp(a_renames->items[i].path, - b_renames->items[j].path); - if (compare <= 0) - ren1 = a_renames->items[i++].util; - if (compare >= 0) - ren2 = b_renames->items[j++].util; - } - - /* TODO: refactor, so that 1/2 are not needed */ - if (ren1) { - renames1 = a_renames; - renames2 = b_renames; - renames2Dst = &b_by_dst; - branch1 = a_branch; - branch2 = b_branch; - } else { - struct rename *tmp; - renames1 = b_renames; - renames2 = a_renames; - renames2Dst = &a_by_dst; - branch1 = b_branch; - branch2 = a_branch; - tmp = ren2; - ren2 = ren1; - ren1 = tmp; - } - src = ren1->pair->one->path; - - ren1->dst_entry->processed = 1; - ren1->src_entry->processed = 1; - - if (ren1->processed) - continue; - ren1->processed = 1; - - ren1_src = ren1->pair->one->path; - ren1_dst = ren1->pair->two->path; - - if (ren2) { - const char *ren2_src = ren2->pair->one->path; - const char *ren2_dst = ren2->pair->two->path; - /* Renamed in 1 and renamed in 2 */ - if (strcmp(ren1_src, ren2_src) != 0) - die("ren1.src != ren2.src"); - ren2->dst_entry->processed = 1; - ren2->processed = 1; - if (strcmp(ren1_dst, ren2_dst) != 0) { - clean_merge = 0; - output(1, "CONFLICT (rename/rename): " - "Rename \"%s\"->\"%s\" in branch \"%s\" " - "rename \"%s\"->\"%s\" in \"%s\"%s", - src, ren1_dst, branch1, - src, ren2_dst, branch2, - index_only ? " (left unresolved)": ""); - if (index_only) { - remove_file_from_cache(src); - update_file(0, ren1->pair->one->sha1, - ren1->pair->one->mode, src); - } - conflict_rename_rename(ren1, branch1, ren2, branch2); - } else { - struct merge_file_info mfi; - remove_file(1, ren1_src, 1); - mfi = merge_file(ren1->pair->one, - ren1->pair->two, - ren2->pair->two, - branch1, - branch2); - if (mfi.merge || !mfi.clean) - output(1, "Renamed %s->%s", src, ren1_dst); - - if (mfi.merge) - output(2, "Auto-merged %s", ren1_dst); - - if (!mfi.clean) { - output(1, "CONFLICT (content): merge conflict in %s", - ren1_dst); - clean_merge = 0; - - if (!index_only) - update_stages(ren1_dst, - ren1->pair->one, - ren1->pair->two, - ren2->pair->two, - 1 /* clear */); - } - update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst); - } - } else { - /* Renamed in 1, maybe changed in 2 */ - struct path_list_item *item; - /* we only use sha1 and mode of these */ - struct diff_filespec src_other, dst_other; - int try_merge, stage = a_renames == renames1 ? 3: 2; - - remove_file(1, ren1_src, index_only || stage == 3); - - hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha); - src_other.mode = ren1->src_entry->stages[stage].mode; - hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha); - dst_other.mode = ren1->dst_entry->stages[stage].mode; - - try_merge = 0; - - if (path_list_has_path(¤t_directory_set, ren1_dst)) { - clean_merge = 0; - output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s " - " directory %s added in %s", - ren1_src, ren1_dst, branch1, - ren1_dst, branch2); - conflict_rename_dir(ren1, branch1); - } else if (sha_eq(src_other.sha1, null_sha1)) { - clean_merge = 0; - output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s " - "and deleted in %s", - ren1_src, ren1_dst, branch1, - branch2); - update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst); - } else if (!sha_eq(dst_other.sha1, null_sha1)) { - const char *new_path; - clean_merge = 0; - try_merge = 1; - output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. " - "%s added in %s", - ren1_src, ren1_dst, branch1, - ren1_dst, branch2); - new_path = unique_path(ren1_dst, branch2); - output(1, "Added as %s instead", new_path); - update_file(0, dst_other.sha1, dst_other.mode, new_path); - } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) { - ren2 = item->util; - clean_merge = 0; - ren2->processed = 1; - output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. " - "Renamed %s->%s in %s", - ren1_src, ren1_dst, branch1, - ren2->pair->one->path, ren2->pair->two->path, branch2); - conflict_rename_rename_2(ren1, branch1, ren2, branch2); - } else - try_merge = 1; - - if (try_merge) { - struct diff_filespec *o, *a, *b; - struct merge_file_info mfi; - src_other.path = (char *)ren1_src; - - o = ren1->pair->one; - if (a_renames == renames1) { - a = ren1->pair->two; - b = &src_other; - } else { - b = ren1->pair->two; - a = &src_other; - } - mfi = merge_file(o, a, b, - a_branch, b_branch); - - if (mfi.clean && - sha_eq(mfi.sha, ren1->pair->two->sha1) && - mfi.mode == ren1->pair->two->mode) - /* - * This messaged is part of - * t6022 test. If you change - * it update the test too. - */ - output(3, "Skipped %s (merged same as existing)", ren1_dst); - else { - if (mfi.merge || !mfi.clean) - output(1, "Renamed %s => %s", ren1_src, ren1_dst); - if (mfi.merge) - output(2, "Auto-merged %s", ren1_dst); - if (!mfi.clean) { - output(1, "CONFLICT (rename/modify): Merge conflict in %s", - ren1_dst); - clean_merge = 0; - - if (!index_only) - update_stages(ren1_dst, - o, a, b, 1); - } - update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst); - } - } - } - } - path_list_clear(&a_by_dst, 0); - path_list_clear(&b_by_dst, 0); - - return clean_merge; -} - -static unsigned char *stage_sha(const unsigned char *sha, unsigned mode) -{ - return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha; -} - -/* Per entry merge function */ -static int process_entry(const char *path, struct stage_data *entry, - const char *branch1, - const char *branch2) -{ - /* - printf("processing entry, clean cache: %s\n", index_only ? "yes": "no"); - print_index_entry("\tpath: ", entry); - */ - int clean_merge = 1; - unsigned o_mode = entry->stages[1].mode; - unsigned a_mode = entry->stages[2].mode; - unsigned b_mode = entry->stages[3].mode; - unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode); - unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode); - unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode); - - if (o_sha && (!a_sha || !b_sha)) { - /* Case A: Deleted in one */ - if ((!a_sha && !b_sha) || - (sha_eq(a_sha, o_sha) && !b_sha) || - (!a_sha && sha_eq(b_sha, o_sha))) { - /* Deleted in both or deleted in one and - * unchanged in the other */ - if (a_sha) - output(2, "Removed %s", path); - /* do not touch working file if it did not exist */ - remove_file(1, path, !a_sha); - } else { - /* Deleted in one and changed in the other */ - clean_merge = 0; - if (!a_sha) { - output(1, "CONFLICT (delete/modify): %s deleted in %s " - "and modified in %s. Version %s of %s left in tree.", - path, branch1, - branch2, branch2, path); - update_file(0, b_sha, b_mode, path); - } else { - output(1, "CONFLICT (delete/modify): %s deleted in %s " - "and modified in %s. Version %s of %s left in tree.", - path, branch2, - branch1, branch1, path); - update_file(0, a_sha, a_mode, path); - } - } - - } else if ((!o_sha && a_sha && !b_sha) || - (!o_sha && !a_sha && b_sha)) { - /* Case B: Added in one. */ - const char *add_branch; - const char *other_branch; - unsigned mode; - const unsigned char *sha; - const char *conf; - - if (a_sha) { - add_branch = branch1; - other_branch = branch2; - mode = a_mode; - sha = a_sha; - conf = "file/directory"; - } else { - add_branch = branch2; - other_branch = branch1; - mode = b_mode; - sha = b_sha; - conf = "directory/file"; - } - if (path_list_has_path(¤t_directory_set, path)) { - const char *new_path = unique_path(path, add_branch); - clean_merge = 0; - output(1, "CONFLICT (%s): There is a directory with name %s in %s. " - "Added %s as %s", - conf, path, other_branch, path, new_path); - remove_file(0, path, 0); - update_file(0, sha, mode, new_path); - } else { - output(2, "Added %s", path); - update_file(1, sha, mode, path); - } - } else if (a_sha && b_sha) { - /* Case C: Added in both (check for same permissions) and */ - /* case D: Modified in both, but differently. */ - const char *reason = "content"; - struct merge_file_info mfi; - struct diff_filespec o, a, b; - - if (!o_sha) { - reason = "add/add"; - o_sha = (unsigned char *)null_sha1; - } - output(2, "Auto-merged %s", path); - o.path = a.path = b.path = (char *)path; - hashcpy(o.sha1, o_sha); - o.mode = o_mode; - hashcpy(a.sha1, a_sha); - a.mode = a_mode; - hashcpy(b.sha1, b_sha); - b.mode = b_mode; - - mfi = merge_file(&o, &a, &b, - branch1, branch2); - - clean_merge = mfi.clean; - if (mfi.clean) - update_file(1, mfi.sha, mfi.mode, path); - else if (S_ISGITLINK(mfi.mode)) - output(1, "CONFLICT (submodule): Merge conflict in %s " - "- needs %s", path, sha1_to_hex(b.sha1)); - else { - output(1, "CONFLICT (%s): Merge conflict in %s", - reason, path); - - if (index_only) - update_file(0, mfi.sha, mfi.mode, path); - else - update_file_flags(mfi.sha, mfi.mode, path, - 0 /* update_cache */, 1 /* update_working_directory */); - } - } else if (!o_sha && !a_sha && !b_sha) { - /* - * this entry was deleted altogether. a_mode == 0 means - * we had that path and want to actively remove it. - */ - remove_file(1, path, !a_mode); - } else - die("Fatal merge failure, shouldn't happen."); - - return clean_merge; -} - -static int merge_trees(struct tree *head, - struct tree *merge, - struct tree *common, - const char *branch1, - const char *branch2, - struct tree **result) -{ - int code, clean; - - if (subtree_merge) { - merge = shift_tree_object(head, merge); - common = shift_tree_object(head, common); - } - - if (sha_eq(common->object.sha1, merge->object.sha1)) { - output(0, "Already uptodate!"); - *result = head; - return 1; - } - - code = git_merge_trees(index_only, common, head, merge); - - if (code != 0) - die("merging of trees %s and %s failed", - sha1_to_hex(head->object.sha1), - sha1_to_hex(merge->object.sha1)); - - if (unmerged_index()) { - struct path_list *entries, *re_head, *re_merge; - int i; - path_list_clear(¤t_file_set, 1); - path_list_clear(¤t_directory_set, 1); - get_files_dirs(head); - get_files_dirs(merge); - - entries = get_unmerged(); - re_head = get_renames(head, common, head, merge, entries); - re_merge = get_renames(merge, common, head, merge, entries); - clean = process_renames(re_head, re_merge, - branch1, branch2); - for (i = 0; i < entries->nr; i++) { - const char *path = entries->items[i].path; - struct stage_data *e = entries->items[i].util; - if (!e->processed - && !process_entry(path, e, branch1, branch2)) - clean = 0; - } - - path_list_clear(re_merge, 0); - path_list_clear(re_head, 0); - path_list_clear(entries, 1); - - } - else - clean = 1; - - if (index_only) - *result = git_write_tree(); - - return clean; -} - -static struct commit_list *reverse_commit_list(struct commit_list *list) -{ - struct commit_list *next = NULL, *current, *backup; - for (current = list; current; current = backup) { - backup = current->next; - current->next = next; - next = current; - } - return next; -} - -/* - * Merge the commits h1 and h2, return the resulting virtual - * commit object and a flag indicating the cleanness of the merge. - */ -static int merge(struct commit *h1, - struct commit *h2, - const char *branch1, - const char *branch2, - struct commit_list *ca, - struct commit **result) -{ - struct commit_list *iter; - struct commit *merged_common_ancestors; - struct tree *mrtree = mrtree; - int clean; - - if (show(4)) { - output(4, "Merging:"); - output_commit_title(h1); - output_commit_title(h2); - } - - if (!ca) { - ca = get_merge_bases(h1, h2, 1); - ca = reverse_commit_list(ca); - } - - if (show(5)) { - output(5, "found %u common ancestor(s):", commit_list_count(ca)); - for (iter = ca; iter; iter = iter->next) - output_commit_title(iter->item); - } - - merged_common_ancestors = pop_commit(&ca); - if (merged_common_ancestors == NULL) { - /* if there is no common ancestor, make an empty tree */ - struct tree *tree = xcalloc(1, sizeof(struct tree)); - - tree->object.parsed = 1; - tree->object.type = OBJ_TREE; - pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1); - merged_common_ancestors = make_virtual_commit(tree, "ancestor"); - } - - for (iter = ca; iter; iter = iter->next) { - call_depth++; - /* - * When the merge fails, the result contains files - * with conflict markers. The cleanness flag is - * ignored, it was never actually used, as result of - * merge_trees has always overwritten it: the committed - * "conflicts" were already resolved. - */ - discard_cache(); - merge(merged_common_ancestors, iter->item, - "Temporary merge branch 1", - "Temporary merge branch 2", - NULL, - &merged_common_ancestors); - call_depth--; - - if (!merged_common_ancestors) - die("merge returned no commit"); - } - - discard_cache(); - if (!call_depth) { - read_cache(); - index_only = 0; - } else - index_only = 1; - - clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree, - branch1, branch2, &mrtree); - - if (index_only) { - *result = make_virtual_commit(mrtree, "merged tree"); - commit_list_insert(h1, &(*result)->parents); - commit_list_insert(h2, &(*result)->parents->next); - } - flush_output(); - return clean; -} - -static const char *better_branch_name(const char *branch) -{ - static char githead_env[8 + 40 + 1]; - char *name; - - if (strlen(branch) != 40) - return branch; - sprintf(githead_env, "GITHEAD_%s", branch); - name = getenv(githead_env); - return name ? name : branch; -} - -static struct commit *get_ref(const char *ref) -{ - unsigned char sha1[20]; - struct object *object; - - if (get_sha1(ref, sha1)) - die("Could not resolve ref '%s'", ref); - object = deref_tag(parse_object(sha1), ref, strlen(ref)); - if (object->type == OBJ_TREE) - return make_virtual_commit((struct tree*)object, - better_branch_name(ref)); - if (object->type != OBJ_COMMIT) - return NULL; - if (parse_commit((struct commit *)object)) - die("Could not parse commit '%s'", sha1_to_hex(object->sha1)); - return (struct commit *)object; -} - -static int merge_config(const char *var, const char *value) -{ - if (!strcasecmp(var, "merge.verbosity")) { - verbosity = git_config_int(var, value); - return 0; - } - if (!strcasecmp(var, "diff.renamelimit")) { - rename_limit = git_config_int(var, value); - return 0; - } - return git_default_config(var, value); -} - -int main(int argc, char *argv[]) -{ - static const char *bases[20]; - static unsigned bases_count = 0; - int i, clean; - const char *branch1, *branch2; - struct commit *result, *h1, *h2; - struct commit_list *ca = NULL; - struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); - int index_fd; - - if (argv[0]) { - int namelen = strlen(argv[0]); - if (8 < namelen && - !strcmp(argv[0] + namelen - 8, "-subtree")) - subtree_merge = 1; - } - - git_config(merge_config); - if (getenv("GIT_MERGE_VERBOSITY")) - verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10); - - if (argc < 4) - die("Usage: %s ... -- ...\n", argv[0]); - - for (i = 1; i < argc; ++i) { - if (!strcmp(argv[i], "--")) - break; - if (bases_count < sizeof(bases)/sizeof(*bases)) - bases[bases_count++] = argv[i]; - } - if (argc - i != 3) /* "--" "" "" */ - die("Not handling anything other than two heads merge."); - if (verbosity >= 5) - buffer_output = 0; - - branch1 = argv[++i]; - branch2 = argv[++i]; - - h1 = get_ref(branch1); - h2 = get_ref(branch2); - - branch1 = better_branch_name(branch1); - branch2 = better_branch_name(branch2); - - if (show(3)) - printf("Merging %s with %s\n", branch1, branch2); - - index_fd = hold_locked_index(lock, 1); - - for (i = 0; i < bases_count; i++) { - struct commit *ancestor = get_ref(bases[i]); - ca = commit_list_insert(ancestor, &ca); - } - clean = merge(h1, h2, branch1, branch2, ca, &result); - - if (active_cache_changed && - (write_cache(index_fd, active_cache, active_nr) || - commit_locked_index(lock))) - die ("unable to write %s", get_index_file()); - - return clean ? 0: 1; -} diff --git a/merge-recursive.h b/merge-recursive.h new file mode 100644 index 0000000..f37630a --- /dev/null +++ b/merge-recursive.h @@ -0,0 +1,20 @@ +#ifndef MERGE_RECURSIVE_H +#define MERGE_RECURSIVE_H + +int merge_recursive(struct commit *h1, + struct commit *h2, + const char *branch1, + const char *branch2, + struct commit_list *ancestors, + struct commit **result); + +int merge_trees(struct tree *head, + struct tree *merge, + struct tree *common, + const char *branch1, + const char *branch2, + struct tree **result); + +struct tree *write_tree_from_memory(void); + +#endif -- cgit v0.10.2-6-g49f6 From e496c00348140e73bdd202443df52192f6928541 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:08 -0500 Subject: Move create_branch into a library file You can also create branches, in exactly the same way, with checkout -b. This introduces branch.{c,h} library files for doing porcelain-level operations on branches (such as creating them with their appropriate default configuration). Signed-off-by: Daniel Barkalow diff --git a/Makefile b/Makefile index 6f08bcc..5cfadfd 100644 --- a/Makefile +++ b/Makefile @@ -317,7 +317,7 @@ LIB_OBJS = \ alloc.o merge-file.o path-list.o help.o unpack-trees.o $(DIFF_OBJS) \ color.o wt-status.o archive-zip.o archive-tar.o shallow.o utf8.o \ convert.o attr.o decorate.o progress.o mailmap.o symlinks.o remote.o \ - transport.o bundle.o walker.o parse-options.o ws.o archive.o + transport.o bundle.o walker.o parse-options.o ws.o archive.o branch.o BUILTIN_OBJS = \ builtin-add.o \ diff --git a/branch.c b/branch.c new file mode 100644 index 0000000..45ab820 --- /dev/null +++ b/branch.c @@ -0,0 +1,140 @@ +#include "cache.h" +#include "branch.h" +#include "refs.h" +#include "remote.h" +#include "commit.h" + +struct tracking { + struct refspec spec; + char *src; + const char *remote; + int matches; +}; + +static int find_tracked_branch(struct remote *remote, void *priv) +{ + struct tracking *tracking = priv; + + if (!remote_find_tracking(remote, &tracking->spec)) { + if (++tracking->matches == 1) { + tracking->src = tracking->spec.src; + tracking->remote = remote->name; + } else { + free(tracking->spec.src); + if (tracking->src) { + free(tracking->src); + tracking->src = NULL; + } + } + tracking->spec.src = NULL; + } + + return 0; +} + +/* + * This is called when new_ref is branched off of orig_ref, and tries + * to infer the settings for branch..{remote,merge} from the + * config. + */ +static int setup_tracking(const char *new_ref, const char *orig_ref) +{ + char key[1024]; + struct tracking tracking; + + if (strlen(new_ref) > 1024 - 7 - 7 - 1) + return error("Tracking not set up: name too long: %s", + new_ref); + + memset(&tracking, 0, sizeof(tracking)); + tracking.spec.dst = (char *)orig_ref; + if (for_each_remote(find_tracked_branch, &tracking) || + !tracking.matches) + return 1; + + if (tracking.matches > 1) + return error("Not tracking: ambiguous information for ref %s", + orig_ref); + + if (tracking.matches == 1) { + sprintf(key, "branch.%s.remote", new_ref); + git_config_set(key, tracking.remote ? tracking.remote : "."); + sprintf(key, "branch.%s.merge", new_ref); + git_config_set(key, tracking.src); + free(tracking.src); + printf("Branch %s set up to track remote branch %s.\n", + new_ref, orig_ref); + } + + return 0; +} + +void create_branch(const char *head, + const char *name, const char *start_name, + int force, int reflog, int track) +{ + struct ref_lock *lock; + struct commit *commit; + unsigned char sha1[20]; + char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20]; + int forcing = 0; + + snprintf(ref, sizeof ref, "refs/heads/%s", name); + if (check_ref_format(ref)) + die("'%s' is not a valid branch name.", name); + + if (resolve_ref(ref, sha1, 1, NULL)) { + if (!force) + die("A branch named '%s' already exists.", name); + else if (!is_bare_repository() && !strcmp(head, name)) + die("Cannot force update the current branch."); + forcing = 1; + } + + real_ref = NULL; + if (get_sha1(start_name, sha1)) + die("Not a valid object name: '%s'.", start_name); + + switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) { + case 0: + /* Not branching from any existing branch */ + real_ref = NULL; + break; + case 1: + /* Unique completion -- good */ + break; + default: + die("Ambiguous object name: '%s'.", start_name); + break; + } + + if ((commit = lookup_commit_reference(sha1)) == NULL) + die("Not a valid branch point: '%s'.", start_name); + hashcpy(sha1, commit->object.sha1); + + lock = lock_any_ref_for_update(ref, NULL, 0); + if (!lock) + die("Failed to lock ref for update: %s.", strerror(errno)); + + if (reflog) + log_all_ref_updates = 1; + + if (forcing) + snprintf(msg, sizeof msg, "branch: Reset from %s", + start_name); + else + snprintf(msg, sizeof msg, "branch: Created from %s", + start_name); + + /* When branching off a remote branch, set up so that git-pull + automatically merges from there. So far, this is only done for + remotes registered via .git/config. */ + if (real_ref && track) + setup_tracking(name, real_ref); + + if (write_ref_sha1(lock, sha1, msg) < 0) + die("Failed to write ref: %s.", strerror(errno)); + + if (real_ref) + free(real_ref); +} diff --git a/branch.h b/branch.h new file mode 100644 index 0000000..8bcd9dc --- /dev/null +++ b/branch.h @@ -0,0 +1,8 @@ +#ifndef BRANCH_H +#define BRANCH_H + +void create_branch(const char *head, + const char *name, const char *start_name, + int force, int reflog, int track); + +#endif diff --git a/builtin-branch.c b/builtin-branch.c index 089cae5..1e0c9de 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -12,6 +12,7 @@ #include "builtin.h" #include "remote.h" #include "parse-options.h" +#include "branch.h" static const char * const builtin_branch_usage[] = { "git-branch [options] [-r | -a]", @@ -356,141 +357,6 @@ static void print_ref_list(int kinds, int detached, int verbose, int abbrev, str free_ref_list(&ref_list); } -struct tracking { - struct refspec spec; - char *src; - const char *remote; - int matches; -}; - -static int find_tracked_branch(struct remote *remote, void *priv) -{ - struct tracking *tracking = priv; - - if (!remote_find_tracking(remote, &tracking->spec)) { - if (++tracking->matches == 1) { - tracking->src = tracking->spec.src; - tracking->remote = remote->name; - } else { - free(tracking->spec.src); - if (tracking->src) { - free(tracking->src); - tracking->src = NULL; - } - } - tracking->spec.src = NULL; - } - - return 0; -} - - -/* - * This is called when new_ref is branched off of orig_ref, and tries - * to infer the settings for branch..{remote,merge} from the - * config. - */ -static int setup_tracking(const char *new_ref, const char *orig_ref) -{ - char key[1024]; - struct tracking tracking; - - if (strlen(new_ref) > 1024 - 7 - 7 - 1) - return error("Tracking not set up: name too long: %s", - new_ref); - - memset(&tracking, 0, sizeof(tracking)); - tracking.spec.dst = (char *)orig_ref; - if (for_each_remote(find_tracked_branch, &tracking) || - !tracking.matches) - return 1; - - if (tracking.matches > 1) - return error("Not tracking: ambiguous information for ref %s", - orig_ref); - - if (tracking.matches == 1) { - sprintf(key, "branch.%s.remote", new_ref); - git_config_set(key, tracking.remote ? tracking.remote : "."); - sprintf(key, "branch.%s.merge", new_ref); - git_config_set(key, tracking.src); - free(tracking.src); - printf("Branch %s set up to track remote branch %s.\n", - new_ref, orig_ref); - } - - return 0; -} - -static void create_branch(const char *name, const char *start_name, - int force, int reflog, int track) -{ - struct ref_lock *lock; - struct commit *commit; - unsigned char sha1[20]; - char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20]; - int forcing = 0; - - snprintf(ref, sizeof ref, "refs/heads/%s", name); - if (check_ref_format(ref)) - die("'%s' is not a valid branch name.", name); - - if (resolve_ref(ref, sha1, 1, NULL)) { - if (!force) - die("A branch named '%s' already exists.", name); - else if (!is_bare_repository() && !strcmp(head, name)) - die("Cannot force update the current branch."); - forcing = 1; - } - - real_ref = NULL; - if (get_sha1(start_name, sha1)) - die("Not a valid object name: '%s'.", start_name); - - switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) { - case 0: - /* Not branching from any existing branch */ - real_ref = NULL; - break; - case 1: - /* Unique completion -- good */ - break; - default: - die("Ambiguous object name: '%s'.", start_name); - break; - } - - if ((commit = lookup_commit_reference(sha1)) == NULL) - die("Not a valid branch point: '%s'.", start_name); - hashcpy(sha1, commit->object.sha1); - - lock = lock_any_ref_for_update(ref, NULL, 0); - if (!lock) - die("Failed to lock ref for update: %s.", strerror(errno)); - - if (reflog) - log_all_ref_updates = 1; - - if (forcing) - snprintf(msg, sizeof msg, "branch: Reset from %s", - start_name); - else - snprintf(msg, sizeof msg, "branch: Created from %s", - start_name); - - /* When branching off a remote branch, set up so that git-pull - automatically merges from there. So far, this is only done for - remotes registered via .git/config. */ - if (real_ref && track) - setup_tracking(name, real_ref); - - if (write_ref_sha1(lock, sha1, msg) < 0) - die("Failed to write ref: %s.", strerror(errno)); - - if (real_ref) - free(real_ref); -} - static void rename_branch(const char *oldname, const char *newname, int force) { char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100]; @@ -611,7 +477,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix) else if (rename && (argc == 2)) rename_branch(argv[0], argv[1], rename > 1); else if (argc <= 2) - create_branch(argv[0], (argc == 2) ? argv[1] : head, + create_branch(head, argv[0], (argc == 2) ? argv[1] : head, force_create, reflog, track); else usage_with_options(builtin_branch_usage, options); -- cgit v0.10.2-6-g49f6 From 922d87f92f79d76ee1d9027d4a0f8a0cf36d5340 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:11 -0500 Subject: Use diff -u instead of diff in t7201 If the test failed, it was giving really unclear ed script output. Instead, give a diff that sort of suggests the problem. Also replaces the use of "git diff" for this purpose with "diff -u". Signed-off-by: Daniel Barkalow diff --git a/t/t7201-co.sh b/t/t7201-co.sh index 73d8a00..3d8e01c 100755 --- a/t/t7201-co.sh +++ b/t/t7201-co.sh @@ -83,13 +83,13 @@ test_expect_success "checkout with unrelated dirty tree without -m" ' fill 0 1 2 3 4 5 6 7 8 >same && cp same kept git checkout side >messages && - git diff same kept + diff -u same kept (cat > messages.expect <expect.master && git diff --name-status master >current.master && - diff expect.master current.master && + diff -u expect.master current.master && fill "M one" >expect.side && git diff --name-status side >current.side && - diff expect.side current.side && + diff -u expect.side current.side && : >expect.index && git diff --cached >current.index && - diff expect.index current.index + diff -u expect.index current.index ' test_expect_success "checkout -m with dirty tree, renamed" ' @@ -143,7 +143,7 @@ test_expect_success "checkout -m with dirty tree, renamed" ' git checkout -m renamer && fill 1 3 4 5 7 8 >expect && - diff expect uno && + diff -u expect uno && ! test -f one && git diff --cached >current && ! test -s current @@ -168,7 +168,7 @@ test_expect_success 'checkout -m with merge conflict' ' git diff master:one :3:uno | sed -e "1,/^@@/d" -e "/^ /d" -e "s/^-/d/" -e "s/^+/a/" >current && fill d2 aT d7 aS >expect && - diff current expect && + diff -u current expect && git diff --cached two >current && ! test -s current ' @@ -185,7 +185,7 @@ If you want to create a new branch from this checkout, you may do so HEAD is now at 7329388... Initial A one, A two EOF ) && - git diff messages.expect messages && + diff -u messages.expect messages && H=$(git rev-parse --verify HEAD) && M=$(git show-ref -s --verify refs/heads/master) && test "z$H" = "z$M" && -- cgit v0.10.2-6-g49f6 From 94a5728cfb593d80164620f8fa7e1ef322ad0025 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:13 -0500 Subject: Library function to check for unmerged index entries It's small, but it was in three places already, so it should be in the library. Signed-off-by: Daniel Barkalow diff --git a/builtin-merge-recursive.c b/builtin-merge-recursive.c index 45d4601..558a58e 100644 --- a/builtin-merge-recursive.c +++ b/builtin-merge-recursive.c @@ -223,22 +223,11 @@ static int git_merge_trees(int index_only, return rc; } -static int unmerged_index(void) -{ - int i; - for (i = 0; i < active_nr; i++) { - struct cache_entry *ce = active_cache[i]; - if (ce_stage(ce)) - return 1; - } - return 0; -} - struct tree *write_tree_from_memory(void) { struct tree *result = NULL; - if (unmerged_index()) { + if (unmerged_cache()) { int i; output(0, "There are unmerged index entries:"); for (i = 0; i < active_nr; i++) { @@ -1524,7 +1513,7 @@ int merge_trees(struct tree *head, sha1_to_hex(head->object.sha1), sha1_to_hex(merge->object.sha1)); - if (unmerged_index()) { + if (unmerged_cache()) { struct path_list *entries, *re_head, *re_merge; int i; path_list_clear(¤t_file_set, 1); diff --git a/builtin-reset.c b/builtin-reset.c index 7ee811f..3bec06b 100644 --- a/builtin-reset.c +++ b/builtin-reset.c @@ -44,18 +44,6 @@ static inline int is_merge(void) return !access(git_path("MERGE_HEAD"), F_OK); } -static int unmerged_files(void) -{ - int i; - read_cache(); - for (i = 0; i < active_nr; i++) { - struct cache_entry *ce = active_cache[i]; - if (ce_stage(ce)) - return 1; - } - return 0; -} - static int reset_index_file(const unsigned char *sha1, int is_hard_reset) { int i = 0; @@ -250,7 +238,7 @@ int cmd_reset(int argc, const char **argv, const char *prefix) * at all, but requires them in a good order. Other resets reset * the index file to the tree object we are switching to. */ if (reset_type == SOFT) { - if (is_merge() || unmerged_files()) + if (is_merge() || read_cache() < 0 || unmerged_cache()) die("Cannot do a soft reset in the middle of a merge."); } else if (reset_index_file(sha1, (reset_type == HARD))) diff --git a/cache.h b/cache.h index e4aeff0..888895a 100644 --- a/cache.h +++ b/cache.h @@ -208,6 +208,7 @@ extern struct index_state the_index; #define read_cache_from(path) read_index_from(&the_index, (path)) #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) #define cache_name_pos(name, namelen) index_name_pos(&the_index,(name),(namelen)) #define add_cache_entry(ce, option) add_index_entry(&the_index, (ce), (option)) #define remove_cache_entry_at(pos) remove_index_entry_at(&the_index, (pos)) @@ -302,6 +303,7 @@ extern int read_index(struct index_state *); extern int read_index_from(struct index_state *, const char *path); extern int write_index(struct index_state *, int newfd); extern int discard_index(struct index_state *); +extern int unmerged_index(struct index_state *); extern int verify_path(const char *path); extern int index_name_exists(struct index_state *istate, const char *name, int namelen); extern int index_name_pos(struct index_state *, const char *name, int namelen); diff --git a/read-cache.c b/read-cache.c index e45f4b3..22d7b46 100644 --- a/read-cache.c +++ b/read-cache.c @@ -1176,6 +1176,16 @@ int discard_index(struct index_state *istate) return 0; } +int unmerged_index(struct index_state *istate) +{ + int i; + for (i = 0; i < istate->cache_nr; i++) { + if (ce_stage(istate->cache[i])) + return 1; + } + return 0; +} + #define WRITE_BUFFER_SIZE 8192 static unsigned char write_buffer[WRITE_BUFFER_SIZE]; static unsigned long write_buffer_len; -- cgit v0.10.2-6-g49f6 From c369e7b805f927bb87fcf345dd19a55c8b9e6b8e Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:16 -0500 Subject: Move code to clean up after a branch change to branch.c Signed-off-by: Daniel Barkalow diff --git a/branch.c b/branch.c index 45ab820..1fc8788 100644 --- a/branch.c +++ b/branch.c @@ -138,3 +138,11 @@ void create_branch(const char *head, if (real_ref) free(real_ref); } + +void remove_branch_state(void) +{ + unlink(git_path("MERGE_HEAD")); + unlink(git_path("rr-cache/MERGE_RR")); + unlink(git_path("MERGE_MSG")); + unlink(git_path("SQUASH_MSG")); +} diff --git a/branch.h b/branch.h index 8bcd9dc..d30abe0 100644 --- a/branch.h +++ b/branch.h @@ -1,8 +1,24 @@ #ifndef BRANCH_H #define BRANCH_H -void create_branch(const char *head, - const char *name, const char *start_name, +/* Functions for acting on the information about branches. */ + +/* + * Creates a new branch, where head is the branch currently checked + * out, name is the new branch name, start_name is the name of the + * existing branch that the new branch should start from, force + * enables overwriting an existing (non-head) branch, reflog creates a + * reflog for the branch, and track causes the new branch to be + * configured to merge the remote branch that start_name is a tracking + * branch for (if any). + */ +void create_branch(const char *head, const char *name, const char *start_name, int force, int reflog, int track); +/* + * Remove information about the state of working on the current + * branch. (E.g., MERGE_HEAD) + */ +void remove_branch_state(void); + #endif diff --git a/builtin-reset.c b/builtin-reset.c index 3bec06b..af0037e 100644 --- a/builtin-reset.c +++ b/builtin-reset.c @@ -16,6 +16,7 @@ #include "diff.h" #include "diffcore.h" #include "tree.h" +#include "branch.h" static const char builtin_reset_usage[] = "git-reset [--mixed | --soft | --hard] [-q] [] [ [--] ...]"; @@ -270,10 +271,7 @@ int cmd_reset(int argc, const char **argv, const char *prefix) break; } - unlink(git_path("MERGE_HEAD")); - unlink(git_path("rr-cache/MERGE_RR")); - unlink(git_path("MERGE_MSG")); - unlink(git_path("SQUASH_MSG")); + remove_branch_state(); free(reflog_action); -- cgit v0.10.2-6-g49f6 From 52f3c81a9d41af019ab8f05051c5251f078b12e5 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Mon, 11 Feb 2008 15:32:29 -0800 Subject: apply: do not barf on patch with too large an offset Previously a patch that records too large a line number caused the offset matching code in git-apply to overstep its internal buffer. Noticed by Johannes Schindelin. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 2b8ba81..5ed4e91 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1809,6 +1809,9 @@ static int find_pos(struct image *img, else if (match_end) line = img->nr - preimage->nr; + if (line > img->nr) + line = img->nr; + try = 0; for (i = 0; i < line; i++) try += img->line[i].len; diff --git a/t/t4105-apply-fuzz.sh b/t/t4105-apply-fuzz.sh new file mode 100755 index 0000000..0e8d25f --- /dev/null +++ b/t/t4105-apply-fuzz.sh @@ -0,0 +1,57 @@ +#!/bin/sh + +test_description='apply with fuzz and offset' + +. ./test-lib.sh + +dotest () { + name="$1" && shift && + test_expect_success "$name" " + git checkout-index -f -q -u file && + git apply $* && + diff -u expect file + " +} + +test_expect_success setup ' + + for i in 1 2 3 4 5 6 7 8 9 10 11 12 + do + echo $i + done >file && + git update-index --add file && + for i in 1 2 3 4 5 6 7 a b c d e 8 9 10 11 12 + do + echo $i + done >file && + cat file >expect && + git diff >O0.diff && + + sed -e "s/@@ -5,6 +5,11 @@/@@ -2,6 +2,11 @@/" >O1.diff O0.diff && + sed -e "s/@@ -5,6 +5,11 @@/@@ -7,6 +7,11 @@/" >O2.diff O0.diff && + sed -e "s/@@ -5,6 +5,11 @@/@@ -19,6 +19,11 @@/" >O3.diff O0.diff && + + sed -e "s/^ 5/ S/" >F0.diff O0.diff && + sed -e "s/^ 5/ S/" >F1.diff O1.diff && + sed -e "s/^ 5/ S/" >F2.diff O2.diff && + sed -e "s/^ 5/ S/" >F3.diff O3.diff + +' + +dotest 'unmodified patch' O0.diff + +dotest 'minus offset' O1.diff + +dotest 'plus offset' O2.diff + +dotest 'big offset' O3.diff + +dotest 'fuzz with no offset' -C2 F0.diff + +dotest 'fuzz with minus offset' -C2 F1.diff + +dotest 'fuzz with plus offset' -C2 F2.diff + +dotest 'fuzz with big offset' -C2 F3.diff + +test_done -- cgit v0.10.2-6-g49f6 From 7df7c019c2a46672c12a11a45600cdc698e03029 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Tue, 12 Feb 2008 13:26:31 -0800 Subject: Add "--dirstat" for some directory statistics This adds a new form of overview diffstat output, doing something that I have occasionally ended up doing manually (and badly, because it's actually pretty nasty to do), and that I think is very useful for an project like the kernel that has a fairly deep and well-separated directory structure with semantic meaning. What I mean by that is that it's often interesting to see exactly which sub-directories are impacted by a patch, and to what degree - even if you don't perhaps care so much about the individual files themselves. What makes the concept more interesting is that the "impact" is often hierarchical: in the kernel, for example, something could either have a very localized impact to "fs/ext3/" and then it's interesting to see that such a patch changes mostly that subdirectory, but you could have another patch that changes some generic VFS-layer issue which affects _many_ subdirectories that are all under "fs/", but none - or perhaps just a couple of them - of the individual filesystems are interesting in themselves. So what commonly happens is that you may have big changes in a specific sub-subdirectory, but still also significant separate changes to the subdirectory leading up to that - maybe you have significant VFS-level changes, but *also* changes under that VFS layer in the NFS-specific directories, for example. In that case, you do want the low-level parts that are significant to show up, but then the insignificant ones should show up as under the more generic top-level directory. This patch shows all of that with "--dirstat". The output can be either something simple like commit 81772fe... Author: Thomas Gleixner Date: Sun Feb 10 23:57:36 2008 +0100 x86: remove over noisy debug printk pageattr-test.c contains a noisy debug printk that people reported. The condition under which it prints (randomly tapping into a mem_map[] hole and not being able to c_p_a() there) is valid behavior and not interesting to report. Remove it. Signed-off-by: Thomas Gleixner Acked-by: Ingo Molnar Signed-off-by: Linus Torvalds 100.0% arch/x86/mm/ or something much more complex like commit e231c2e... Author: David Howells Date: Thu Feb 7 00:15:26 2008 -0800 Convert ERR_PTR(PTR_ERR(p)) instances to ERR_CAST(p) 20.5% crypto/ 7.6% fs/afs/ 7.6% fs/fuse/ 7.6% fs/gfs2/ 5.1% fs/jffs2/ 5.1% fs/nfs/ 5.1% fs/nfsd/ 7.6% fs/reiserfs/ 15.3% fs/ 7.6% net/rxrpc/ 10.2% security/keys/ where that latter example is an example of significant work in some individual fs/*/ subdirectories (like the patches to reiserfs accounting for 7.6% of the whole), but then discounting those individual filesystems, there's also 15.3% other "random" things that weren't worth reporting on their oen left over under fs/ in general (either in that directory itself, or in subdirectories of fs/ that didn't have enough changes to be reported individually). I'd like to stress that the "15.3% fs/" mentioned above is the stuff that is under fs/ but that was _not_ significant enough to report on its own. So the above does _not_ mean that 15.3% of the work was under fs/ per se, because that 15.3% does *not* include the already-reported 7.6% of afs, 7.6% of fuse etc. If you want to enable "cumulative" directory statistics, you can use the "--cumulative" flag, which adds up percentages recursively even when they have been already reported for a sub-directory. That cumulative output is disabled if *all* of the changes in one subdirectory come from a deeper subdirectory, to avoid repeating subdirectories all the way to the root. For an example of the cumulative reporting, the above commit becomes commit e231c2e... Author: David Howells Date: Thu Feb 7 00:15:26 2008 -0800 Convert ERR_PTR(PTR_ERR(p)) instances to ERR_CAST(p) 20.5% crypto/ 7.6% fs/afs/ 7.6% fs/fuse/ 7.6% fs/gfs2/ 5.1% fs/jffs2/ 5.1% fs/nfs/ 5.1% fs/nfsd/ 7.6% fs/reiserfs/ 61.5% fs/ 7.6% net/rxrpc/ 10.2% security/keys/ in which the commit percentages now obviously add up to much more than 100%: now the changes that were already reported for the sub-directories under fs/ are then cumulatively included in the whole percentage of fs/ (ie now shows 61.5% as opposed to the 15.3% without the cumulative reporting). The default reporting limit has been arbitrarily set at 3%, which seems to be a pretty good cut-off, but you can specify the cut-off manually by giving it as an option parameter (eg "--dirstat=5" makes the cut-off be at 5% instead) NOTE! The percentages are purely about the total lines added and removed, not anything smarter (or dumber) than that. Also note that you should not generally expect things to add up to 100%: not only does it round down, we don't report leftover scraps (they add up to the top-level change count, but we don't even bother reporting that, it only reports subdirectories). Quite frankly, as a top-level manager this is really convenient for me, but it's going to be very boring for git itself since there are few subdirectories. Also, don't expect things to make tons of sense if you combine this with "-M" and there are cross-directory renames etc. But even for git itself, you can get some fun statistics. Try out git log --dirstat and see the occasional mentions of things like Documentation/, git-gui/, gitweb/ and gitk-git/. Or try out something like git diff --dirstat v1.5.0..v1.5.4 which does kind of git an overview that shows *something*. But in general, the output is more exciting for big projects with deeper structure, and doing a git diff --dirstat v2.6.24..v2.6.25-rc1 on the kernel is what I actually wrote this for! Signed-off-by: Linus Torvalds Signed-off-by: Junio C Hamano diff --git a/diff.c b/diff.c index cd8bc4d..dd374d4 100644 --- a/diff.c +++ b/diff.c @@ -990,6 +990,85 @@ static void show_numstat(struct diffstat_t* data, struct diff_options *options) } } +struct diffstat_dir { + struct diffstat_file **files; + int nr, percent, cumulative; +}; + +static long gather_dirstat(struct diffstat_dir *dir, unsigned long changed, const char *base, int baselen) +{ + unsigned long this_dir = 0; + unsigned int sources = 0; + + while (dir->nr) { + struct diffstat_file *f = *dir->files; + int namelen = strlen(f->name); + unsigned long this; + char *slash; + + if (namelen < baselen) + break; + if (memcmp(f->name, base, baselen)) + break; + slash = strchr(f->name + baselen, '/'); + if (slash) { + int newbaselen = slash + 1 - f->name; + this = gather_dirstat(dir, changed, f->name, newbaselen); + sources++; + } else { + this = f->added + f->deleted; + dir->files++; + dir->nr--; + sources += 2; + } + this_dir += this; + } + + /* + * We don't report dirstat's for + * - the top level + * - or cases where everything came from a single directory + * under this directory (sources == 1). + */ + if (baselen && sources != 1) { + int permille = this_dir * 1000 / changed; + if (permille) { + int percent = permille / 10; + if (percent >= dir->percent) { + printf("%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base); + if (!dir->cumulative) + return 0; + } + } + } + return this_dir; +} + +static void show_dirstat(struct diffstat_t *data, struct diff_options *options) +{ + int i; + unsigned long changed; + struct diffstat_dir dir; + + /* Calculate total changes */ + changed = 0; + for (i = 0; i < data->nr; i++) { + changed += data->files[i]->added; + changed += data->files[i]->deleted; + } + + /* This can happen even with many files, if everything was renames */ + if (!changed) + return; + + /* Show all directories with more than x% of the changes */ + dir.files = data->files; + dir.nr = data->nr; + dir.percent = options->dirstat_percent; + dir.cumulative = options->output_format & DIFF_FORMAT_CUMULATIVE; + gather_dirstat(&dir, changed, "", 0); +} + static void free_diffstat_info(struct diffstat_t *diffstat) { int i; @@ -2058,6 +2137,7 @@ void diff_setup(struct diff_options *options) options->line_termination = '\n'; options->break_opt = -1; options->rename_limit = -1; + options->dirstat_percent = 3; options->context = 3; options->msg_sep = ""; @@ -2099,6 +2179,7 @@ int diff_setup_done(struct diff_options *options) DIFF_FORMAT_NUMSTAT | DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SHORTSTAT | + DIFF_FORMAT_DIRSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH); @@ -2110,6 +2191,7 @@ int diff_setup_done(struct diff_options *options) DIFF_FORMAT_NUMSTAT | DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SHORTSTAT | + DIFF_FORMAT_DIRSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_CHECKDIFF)) DIFF_OPT_SET(options, RECURSIVE); @@ -2220,6 +2302,10 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac) options->output_format |= DIFF_FORMAT_NUMSTAT; else if (!strcmp(arg, "--shortstat")) options->output_format |= DIFF_FORMAT_SHORTSTAT; + else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent)) + options->output_format |= DIFF_FORMAT_DIRSTAT; + else if (!strcmp(arg, "--cumulative")) + options->output_format |= DIFF_FORMAT_CUMULATIVE; else if (!strcmp(arg, "--check")) options->output_format |= DIFF_FORMAT_CHECKDIFF; else if (!strcmp(arg, "--summary")) @@ -2938,7 +3024,7 @@ void diff_flush(struct diff_options *options) separator++; } - if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) { + if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT|DIFF_FORMAT_DIRSTAT)) { struct diffstat_t diffstat; memset(&diffstat, 0, sizeof(struct diffstat_t)); @@ -2948,6 +3034,8 @@ void diff_flush(struct diff_options *options) if (check_pair_status(p)) diff_flush_stat(p, options, &diffstat); } + if (output_format & DIFF_FORMAT_DIRSTAT) + show_dirstat(&diffstat, options); if (output_format & DIFF_FORMAT_NUMSTAT) show_numstat(&diffstat, options); if (output_format & DIFF_FORMAT_DIFFSTAT) diff --git a/diff.h b/diff.h index 073d5cb..8c6bb54 100644 --- a/diff.h +++ b/diff.h @@ -30,6 +30,8 @@ typedef void (*diff_format_fn_t)(struct diff_queue_struct *q, #define DIFF_FORMAT_SUMMARY 0x0008 #define DIFF_FORMAT_PATCH 0x0010 #define DIFF_FORMAT_SHORTSTAT 0x0020 +#define DIFF_FORMAT_DIRSTAT 0x0040 +#define DIFF_FORMAT_CUMULATIVE 0x0080 /* These override all above */ #define DIFF_FORMAT_NAME 0x0100 @@ -80,6 +82,7 @@ struct diff_options { int pickaxe_opts; int rename_score; int rename_limit; + int dirstat_percent; int setup; int abbrev; const char *msg_sep; -- cgit v0.10.2-6-g49f6 From cd676a513672eeb9663c6d4de276a1c860a4b879 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 12 Feb 2008 14:26:02 -0800 Subject: diff --relative: output paths as relative to the current subdirectory This adds --relative option to the diff family. When you start from a subdirectory: $ git diff --relative shows only the diff that is inside your current subdirectory, and without $prefix part. People who usually live in subdirectories may like it. There are a few things I should also mention about the change: - This works not just with diff but also works with the log family of commands, but the history pruning is not affected. In other words, if you go to a subdirectory, you can say: $ git log --relative -p but it will show the log message even for commits that do not touch the current directory. You can limit it by giving pathspec yourself: $ git log --relative -p . This originally was not a conscious design choice, but we have a way to affect diff pathspec and pruning pathspec independently. IOW "git log --full-diff -p ." tells it to prune history to commits that affect the current subdirectory but show the changes with full context. I think it makes more sense to leave pruning independent from --relative than the obvious alternative of always pruning with the current subdirectory, which would break the symmetry. - Because this works also with the log family, you could format-patch a single change, limiting the effect to your subdirectory, like so: $ cd gitk-git $ git format-patch -1 --relative 911f1eb But because that is a special purpose usage, this option will never become the default, with or without repository or user preference configuration. The risk of producing a partial patch and sending it out by mistake is too great if we did so. - This is inherently incompatible with --no-index, which is a bolted-on hack that does not have much to do with git itself. I didn't bother checking and erroring out on the combined use of the options, but probably I should. Signed-off-by: Junio C Hamano diff --git a/Documentation/diff-options.txt b/Documentation/diff-options.txt index 8d35cbd..286c30c 100644 --- a/Documentation/diff-options.txt +++ b/Documentation/diff-options.txt @@ -170,6 +170,11 @@ endif::git-format-patch[] Swap two inputs; that is, show differences from index or on-disk file to tree contents. +--relative:: + When run from a subdirectory of the project, it can be + told to exclude changes outside the directory and show + pathnames relative to it with this option. + --text:: Treat all files as text. diff --git a/builtin-diff.c b/builtin-diff.c index 8d7a569..19fa668 100644 --- a/builtin-diff.c +++ b/builtin-diff.c @@ -43,12 +43,17 @@ static void stuff_change(struct diff_options *opt, tmp_u = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_u; tmp_c = old_name; old_name = new_name; new_name = tmp_c; } + + if (opt->prefix && + (strncmp(old_name, opt->prefix, opt->prefix_length) || + strncmp(new_name, opt->prefix, opt->prefix_length))) + return; + one = alloc_filespec(old_name); two = alloc_filespec(new_name); fill_filespec(one, old_sha1, old_mode); fill_filespec(two, new_sha1, new_mode); - /* NEEDSWORK: shouldn't this part of diffopt??? */ diff_queue(&diff_queued_diff, one, two); } @@ -241,6 +246,10 @@ int cmd_diff(int argc, const char **argv, const char *prefix) if (diff_setup_done(&rev.diffopt) < 0) die("diff_setup_done failed"); } + if (rev.diffopt.prefix && nongit) { + rev.diffopt.prefix = NULL; + rev.diffopt.prefix_length = 0; + } DIFF_OPT_SET(&rev.diffopt, ALLOW_EXTERNAL); DIFF_OPT_SET(&rev.diffopt, RECURSIVE); diff --git a/diff.c b/diff.c index 5b8afdc..db4bd55 100644 --- a/diff.c +++ b/diff.c @@ -1397,6 +1397,7 @@ static void builtin_diffstat(const char *name_a, const char *name_b, } static void builtin_checkdiff(const char *name_a, const char *name_b, + const char *attr_path, struct diff_filespec *one, struct diff_filespec *two, struct diff_options *o) { @@ -1411,7 +1412,7 @@ static void builtin_checkdiff(const char *name_a, const char *name_b, data.filename = name_b ? name_b : name_a; data.lineno = 0; data.color_diff = DIFF_OPT_TST(o, COLOR_DIFF); - data.ws_rule = whitespace_rule(data.filename); + data.ws_rule = whitespace_rule(attr_path); if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0) die("unable to read files to diff"); @@ -1831,6 +1832,9 @@ static const char *external_diff_attr(const char *name) { struct git_attr_check attr_diff_check; + if (!name) + return NULL; + setup_diff_attr_check(&attr_diff_check); if (!git_checkattr(name, 1, &attr_diff_check)) { const char *value = attr_diff_check.value; @@ -1850,6 +1854,7 @@ static const char *external_diff_attr(const char *name) static void run_diff_cmd(const char *pgm, const char *name, const char *other, + const char *attr_path, struct diff_filespec *one, struct diff_filespec *two, const char *xfrm_msg, @@ -1859,7 +1864,7 @@ static void run_diff_cmd(const char *pgm, if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL)) pgm = NULL; else { - const char *cmd = external_diff_attr(name); + const char *cmd = external_diff_attr(attr_path); if (cmd) pgm = cmd; } @@ -1900,6 +1905,15 @@ static int similarity_index(struct diff_filepair *p) return p->score * 100 / MAX_SCORE; } +static void strip_prefix(int prefix_length, const char **namep, const char **otherp) +{ + /* Strip the prefix but do not molest /dev/null and absolute paths */ + if (*namep && **namep != '/') + *namep += prefix_length; + if (*otherp && **otherp != '/') + *otherp += prefix_length; +} + static void run_diff(struct diff_filepair *p, struct diff_options *o) { const char *pgm = external_diff(); @@ -1909,16 +1923,21 @@ static void run_diff(struct diff_filepair *p, struct diff_options *o) struct diff_filespec *two = p->two; const char *name; const char *other; + const char *attr_path; int complete_rewrite = 0; + name = p->one->path; + other = (strcmp(name, p->two->path) ? p->two->path : NULL); + attr_path = name; + if (o->prefix_length) + strip_prefix(o->prefix_length, &name, &other); if (DIFF_PAIR_UNMERGED(p)) { - run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0); + run_diff_cmd(pgm, name, NULL, attr_path, + NULL, NULL, NULL, o, 0); return; } - name = p->one->path; - other = (strcmp(name, p->two->path) ? p->two->path : NULL); diff_fill_sha1_info(one); diff_fill_sha1_info(two); @@ -1981,15 +2000,17 @@ static void run_diff(struct diff_filepair *p, struct diff_options *o) * needs to be split into deletion and creation. */ struct diff_filespec *null = alloc_filespec(two->path); - run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0); + run_diff_cmd(NULL, name, other, attr_path, + one, null, xfrm_msg, o, 0); free(null); null = alloc_filespec(one->path); - run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0); + run_diff_cmd(NULL, name, other, attr_path, + null, two, xfrm_msg, o, 0); free(null); } else - run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o, - complete_rewrite); + run_diff_cmd(pgm, name, other, attr_path, + one, two, xfrm_msg, o, complete_rewrite); strbuf_release(&msg); } @@ -2010,6 +2031,9 @@ static void run_diffstat(struct diff_filepair *p, struct diff_options *o, name = p->one->path; other = (strcmp(name, p->two->path) ? p->two->path : NULL); + if (o->prefix_length) + strip_prefix(o->prefix_length, &name, &other); + diff_fill_sha1_info(p->one); diff_fill_sha1_info(p->two); @@ -2022,6 +2046,7 @@ static void run_checkdiff(struct diff_filepair *p, struct diff_options *o) { const char *name; const char *other; + const char *attr_path; if (DIFF_PAIR_UNMERGED(p)) { /* unmerged */ @@ -2030,11 +2055,15 @@ static void run_checkdiff(struct diff_filepair *p, struct diff_options *o) name = p->one->path; other = (strcmp(name, p->two->path) ? p->two->path : NULL); + attr_path = other ? other : name; + + if (o->prefix_length) + strip_prefix(o->prefix_length, &name, &other); diff_fill_sha1_info(p->one); diff_fill_sha1_info(p->two); - builtin_checkdiff(name, other, p->one, p->two, o); + builtin_checkdiff(name, other, attr_path, p->one, p->two, o); } void diff_setup(struct diff_options *options) @@ -2076,6 +2105,13 @@ int diff_setup_done(struct diff_options *options) if (DIFF_OPT_TST(options, FIND_COPIES_HARDER)) options->detect_rename = DIFF_DETECT_COPY; + if (!DIFF_OPT_TST(options, RELATIVE_NAME)) + options->prefix = NULL; + if (options->prefix) + options->prefix_length = strlen(options->prefix); + else + options->prefix_length = 0; + if (options->output_format & (DIFF_FORMAT_NAME | DIFF_FORMAT_NAME_STATUS | DIFF_FORMAT_CHECKDIFF | @@ -2264,6 +2300,8 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac) } else if (!strcmp(arg, "--no-renames")) options->detect_rename = 0; + else if (!strcmp(arg, "--relative")) + DIFF_OPT_SET(options, RELATIVE_NAME); /* xdiff options */ else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space")) @@ -2475,12 +2513,20 @@ static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt) printf("%c%c", p->status, inter_name_termination); } - if (p->status == DIFF_STATUS_COPIED || p->status == DIFF_STATUS_RENAMED) { - write_name_quoted(p->one->path, stdout, inter_name_termination); - write_name_quoted(p->two->path, stdout, line_termination); + if (p->status == DIFF_STATUS_COPIED || + p->status == DIFF_STATUS_RENAMED) { + const char *name_a, *name_b; + name_a = p->one->path; + name_b = p->two->path; + strip_prefix(opt->prefix_length, &name_a, &name_b); + write_name_quoted(name_a, stdout, inter_name_termination); + write_name_quoted(name_b, stdout, line_termination); } else { - const char *path = p->one->mode ? p->one->path : p->two->path; - write_name_quoted(path, stdout, line_termination); + const char *name_a, *name_b; + name_a = p->one->mode ? p->one->path : p->two->path; + name_b = NULL; + strip_prefix(opt->prefix_length, &name_a, &name_b); + write_name_quoted(name_a, stdout, line_termination); } } @@ -2677,8 +2723,13 @@ static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt) diff_flush_checkdiff(p, opt); else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS)) diff_flush_raw(p, opt); - else if (fmt & DIFF_FORMAT_NAME) - write_name_quoted(p->two->path, stdout, opt->line_termination); + else if (fmt & DIFF_FORMAT_NAME) { + const char *name_a, *name_b; + name_a = p->two->path; + name_b = NULL; + strip_prefix(opt->prefix_length, &name_a, &name_b); + write_name_quoted(name_a, stdout, opt->line_termination); + } } static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs) @@ -3164,6 +3215,11 @@ void diff_addremove(struct diff_options *options, if (!path) path = ""; sprintf(concatpath, "%s%s", base, path); + + if (options->prefix && + strncmp(concatpath, options->prefix, options->prefix_length)) + return; + one = alloc_filespec(concatpath); two = alloc_filespec(concatpath); @@ -3193,6 +3249,11 @@ void diff_change(struct diff_options *options, } if (!path) path = ""; sprintf(concatpath, "%s%s", base, path); + + if (options->prefix && + strncmp(concatpath, options->prefix, options->prefix_length)) + return; + one = alloc_filespec(concatpath); two = alloc_filespec(concatpath); fill_filespec(one, old_sha1, old_mode); @@ -3207,6 +3268,11 @@ void diff_unmerge(struct diff_options *options, unsigned mode, const unsigned char *sha1) { struct diff_filespec *one, *two; + + if (options->prefix && + strncmp(path, options->prefix, options->prefix_length)) + return; + one = alloc_filespec(path); two = alloc_filespec(path); fill_filespec(one, sha1, mode); diff --git a/diff.h b/diff.h index 073d5cb..fcd9653 100644 --- a/diff.h +++ b/diff.h @@ -60,6 +60,7 @@ typedef void (*diff_format_fn_t)(struct diff_queue_struct *q, #define DIFF_OPT_EXIT_WITH_STATUS (1 << 14) #define DIFF_OPT_REVERSE_DIFF (1 << 15) #define DIFF_OPT_CHECK_FAILED (1 << 16) +#define DIFF_OPT_RELATIVE_NAME (1 << 17) #define DIFF_OPT_TST(opts, flag) ((opts)->flags & DIFF_OPT_##flag) #define DIFF_OPT_SET(opts, flag) ((opts)->flags |= DIFF_OPT_##flag) #define DIFF_OPT_CLR(opts, flag) ((opts)->flags &= ~DIFF_OPT_##flag) @@ -82,6 +83,8 @@ struct diff_options { int rename_limit; int setup; int abbrev; + const char *prefix; + int prefix_length; const char *msg_sep; const char *stat_sep; long xdl_opts; diff --git a/revision.c b/revision.c index 6e85aaa..6d9188b 100644 --- a/revision.c +++ b/revision.c @@ -720,6 +720,10 @@ void init_revisions(struct rev_info *revs, const char *prefix) revs->commit_format = CMIT_FMT_DEFAULT; diff_setup(&revs->diffopt); + if (prefix) { + revs->diffopt.prefix = prefix; + revs->diffopt.prefix_length = strlen(prefix); + } } static void add_pending_commit_list(struct rev_info *revs, -- cgit v0.10.2-6-g49f6 From c0cb4a067972700f0682fbab13768bcc7dc7a3c3 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 13 Feb 2008 00:34:39 -0800 Subject: diff --relative: help working in a bare repository This allows the --relative option to say which subdirectory to pretend to be in, so that in a bare repository, you can say: $ git log --relative=drivers/ v2.6.20..v2.6.22 -- drivers/scsi/ Signed-off-by: Junio C Hamano diff --git a/Documentation/diff-options.txt b/Documentation/diff-options.txt index 286c30c..8dc5b00 100644 --- a/Documentation/diff-options.txt +++ b/Documentation/diff-options.txt @@ -170,10 +170,13 @@ endif::git-format-patch[] Swap two inputs; that is, show differences from index or on-disk file to tree contents. ---relative:: +--relative[=]:: When run from a subdirectory of the project, it can be told to exclude changes outside the directory and show - pathnames relative to it with this option. + pathnames relative to it with this option. When you are + not in a subdirectory (e.g. in a bare repository), you + can name which subdirectory to make the output relative + to by giving a as an argument. --text:: Treat all files as text. diff --git a/diff.c b/diff.c index db4bd55..2b89b16 100644 --- a/diff.c +++ b/diff.c @@ -2302,6 +2302,10 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac) options->detect_rename = 0; else if (!strcmp(arg, "--relative")) DIFF_OPT_SET(options, RELATIVE_NAME); + else if (!prefixcmp(arg, "--relative=")) { + DIFF_OPT_SET(options, RELATIVE_NAME); + options->prefix = arg + 11; + } /* xdiff options */ else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space")) diff --git a/revision.c b/revision.c index 6d9188b..4d6f57b 100644 --- a/revision.c +++ b/revision.c @@ -720,7 +720,7 @@ void init_revisions(struct rev_info *revs, const char *prefix) revs->commit_format = CMIT_FMT_DEFAULT; diff_setup(&revs->diffopt); - if (prefix) { + if (prefix && !revs->diffopt.prefix) { revs->diffopt.prefix = prefix; revs->diffopt.prefix_length = strlen(prefix); } -- cgit v0.10.2-6-g49f6 From 782c2d65c24066a5d83453efb52763bc34c10f81 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 7 Feb 2008 11:40:23 -0500 Subject: Build in checkout The only differences in behavior should be: - git checkout -m with non-trivial merging won't print out merge-recursive messages (see the change in t7201-co.sh) - git checkout -- paths... will give a sensible error message if HEAD is invalid as a commit. - some intermediate states which were written to disk in the shell version (in particular, index states) are only kept in memory in this version, and therefore these can no longer be revealed by later write operations becoming impossible. - when we change branches, we discard MERGE_MSG, SQUASH_MSG, and rr-cache/MERGE_RR, like reset always has. I'm not 100% sure I got the merge recursive setup exactly right; the base for a non-trivial merge in the shell code doesn't seem theoretically justified to me, but I tried to match it anyway, and the tests all pass this way. Other than these items, the results should be identical to the shell version, so far as I can tell. [jc: squashed lock-file fix from Dscho in] Signed-off-by: Daniel Barkalow Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano diff --git a/Makefile b/Makefile index 5cfadfd..90c0dd8 100644 --- a/Makefile +++ b/Makefile @@ -217,7 +217,7 @@ BASIC_CFLAGS = BASIC_LDFLAGS = SCRIPT_SH = \ - git-bisect.sh git-checkout.sh \ + git-bisect.sh \ git-clone.sh \ git-merge-one-file.sh git-mergetool.sh git-parse-remote.sh \ git-pull.sh git-rebase.sh git-rebase--interactive.sh \ @@ -329,6 +329,7 @@ BUILTIN_OBJS = \ builtin-bundle.o \ builtin-cat-file.o \ builtin-check-attr.o \ + builtin-checkout.o \ builtin-checkout-index.o \ builtin-check-ref-format.o \ builtin-clean.o \ diff --git a/builtin-checkout.c b/builtin-checkout.c new file mode 100644 index 0000000..59a0ef4 --- /dev/null +++ b/builtin-checkout.c @@ -0,0 +1,477 @@ +#include "cache.h" +#include "builtin.h" +#include "parse-options.h" +#include "refs.h" +#include "commit.h" +#include "tree.h" +#include "tree-walk.h" +#include "unpack-trees.h" +#include "dir.h" +#include "run-command.h" +#include "merge-recursive.h" +#include "branch.h" +#include "diff.h" +#include "revision.h" + +static const char * const checkout_usage[] = { + "git checkout [options] ", + "git checkout [options] [] -- ...", + NULL, +}; + +static int post_checkout_hook(struct commit *old, struct commit *new, + int changed) +{ + struct child_process proc; + const char *name = git_path("hooks/post-checkout"); + const char *argv[5]; + + if (access(name, X_OK) < 0) + return 0; + + memset(&proc, 0, sizeof(proc)); + argv[0] = name; + argv[1] = xstrdup(sha1_to_hex(old->object.sha1)); + argv[2] = xstrdup(sha1_to_hex(new->object.sha1)); + argv[3] = changed ? "1" : "0"; + argv[4] = NULL; + proc.argv = argv; + proc.no_stdin = 1; + proc.stdout_to_stderr = 1; + return run_command(&proc); +} + +static int update_some(const unsigned char *sha1, const char *base, int baselen, + const char *pathname, unsigned mode, int stage) +{ + int len; + struct cache_entry *ce; + + if (S_ISGITLINK(mode)) + return 0; + + if (S_ISDIR(mode)) + return READ_TREE_RECURSIVE; + + len = baselen + strlen(pathname); + ce = xcalloc(1, cache_entry_size(len)); + hashcpy(ce->sha1, sha1); + memcpy(ce->name, base, baselen); + memcpy(ce->name + baselen, pathname, len - baselen); + ce->ce_flags = create_ce_flags(len, 0); + ce->ce_mode = create_ce_mode(mode); + add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); + return 0; +} + +static int read_tree_some(struct tree *tree, const char **pathspec) +{ + int newfd; + struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file)); + newfd = hold_locked_index(lock_file, 1); + read_cache(); + + read_tree_recursive(tree, "", 0, 0, pathspec, update_some); + + if (write_cache(newfd, active_cache, active_nr) || + commit_locked_index(lock_file)) + die("unable to write new index file"); + + /* update the index with the given tree's info + * for all args, expanding wildcards, and exit + * with any non-zero return code. + */ + return 0; +} + +static int checkout_paths(const char **pathspec) +{ + int pos; + struct checkout state; + static char *ps_matched; + unsigned char rev[20]; + int flag; + struct commit *head; + + for (pos = 0; pathspec[pos]; pos++) + ; + ps_matched = xcalloc(1, pos); + + for (pos = 0; pos < active_nr; pos++) { + struct cache_entry *ce = active_cache[pos]; + pathspec_match(pathspec, ps_matched, ce->name, 0); + } + + if (report_path_error(ps_matched, pathspec, 0)) + return 1; + + memset(&state, 0, sizeof(state)); + state.force = 1; + state.refresh_cache = 1; + for (pos = 0; pos < active_nr; pos++) { + struct cache_entry *ce = active_cache[pos]; + if (pathspec_match(pathspec, NULL, ce->name, 0)) { + checkout_entry(ce, &state, NULL); + } + } + + resolve_ref("HEAD", rev, 0, &flag); + head = lookup_commit_reference_gently(rev, 1); + + return post_checkout_hook(head, head, 0); +} + +static void show_local_changes(struct object *head) +{ + struct rev_info rev; + /* I think we want full paths, even if we're in a subdirectory. */ + init_revisions(&rev, NULL); + rev.abbrev = 0; + rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; + add_pending_object(&rev, head, NULL); + run_diff_index(&rev, 0); +} + +static void describe_detached_head(char *msg, struct commit *commit) +{ + struct strbuf sb; + strbuf_init(&sb, 0); + parse_commit(commit); + pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, "", "", 0, 0); + fprintf(stderr, "%s %s... %s\n", msg, + find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf); + strbuf_release(&sb); +} + +static int reset_to_new(struct tree *tree, int quiet) +{ + struct unpack_trees_options opts; + struct tree_desc tree_desc; + memset(&opts, 0, sizeof(opts)); + opts.head_idx = -1; + opts.update = 1; + opts.reset = 1; + opts.merge = 1; + opts.fn = oneway_merge; + opts.verbose_update = !quiet; + parse_tree(tree); + init_tree_desc(&tree_desc, tree->buffer, tree->size); + if (unpack_trees(1, &tree_desc, &opts)) + return 128; + return 0; +} + +static void reset_clean_to_new(struct tree *tree, int quiet) +{ + struct unpack_trees_options opts; + struct tree_desc tree_desc; + memset(&opts, 0, sizeof(opts)); + opts.head_idx = -1; + opts.skip_unmerged = 1; + opts.reset = 1; + opts.merge = 1; + opts.fn = oneway_merge; + opts.verbose_update = !quiet; + parse_tree(tree); + init_tree_desc(&tree_desc, tree->buffer, tree->size); + if (unpack_trees(1, &tree_desc, &opts)) + exit(128); +} + +struct checkout_opts { + int quiet; + int merge; + int force; + + char *new_branch; + int new_branch_log; + int track; +}; + +struct branch_info { + const char *name; /* The short name used */ + const char *path; /* The full name of a real branch */ + struct commit *commit; /* The named commit */ +}; + +static void setup_branch_path(struct branch_info *branch) +{ + struct strbuf buf; + strbuf_init(&buf, 0); + strbuf_addstr(&buf, "refs/heads/"); + strbuf_addstr(&buf, branch->name); + branch->path = strbuf_detach(&buf, NULL); +} + +static int merge_working_tree(struct checkout_opts *opts, + struct branch_info *old, struct branch_info *new, + const char *prefix) +{ + int ret; + struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file)); + int newfd = hold_locked_index(lock_file, 1); + read_cache(); + + if (opts->force) { + ret = reset_to_new(new->commit->tree, opts->quiet); + if (ret) + return ret; + } else { + struct tree_desc trees[2]; + struct tree *tree; + struct unpack_trees_options topts; + memset(&topts, 0, sizeof(topts)); + topts.head_idx = -1; + + refresh_cache(REFRESH_QUIET); + + if (unmerged_cache()) { + ret = opts->merge ? -1 : + error("you need to resolve your current index first"); + } else { + topts.update = 1; + topts.merge = 1; + topts.gently = opts->merge; + topts.fn = twoway_merge; + topts.dir = xcalloc(1, sizeof(*topts.dir)); + topts.dir->show_ignored = 1; + topts.dir->exclude_per_dir = ".gitignore"; + topts.prefix = prefix; + tree = parse_tree_indirect(old->commit->object.sha1); + init_tree_desc(&trees[0], tree->buffer, tree->size); + tree = parse_tree_indirect(new->commit->object.sha1); + init_tree_desc(&trees[1], tree->buffer, tree->size); + ret = unpack_trees(2, trees, &topts); + } + if (ret) { + /* + * Unpack couldn't do a trivial merge; either + * give up or do a real merge, depending on + * whether the merge flag was used. + */ + struct tree *result; + struct tree *work; + if (!opts->merge) + return 1; + parse_commit(old->commit); + + /* Do more real merge */ + + /* + * We update the index fully, then write the + * tree from the index, then merge the new + * branch with the current tree, with the old + * branch as the base. Then we reset the index + * (but not the working tree) to the new + * branch, leaving the working tree as the + * merged version, but skipping unmerged + * entries in the index. + */ + + add_files_to_cache(0, NULL, NULL); + work = write_tree_from_memory(); + + ret = reset_to_new(new->commit->tree, opts->quiet); + if (ret) + return ret; + merge_trees(new->commit->tree, work, old->commit->tree, + new->name, "local", &result); + reset_clean_to_new(new->commit->tree, opts->quiet); + } + } + + if (write_cache(newfd, active_cache, active_nr) || + commit_locked_index(lock_file)) + die("unable to write new index file"); + + if (!opts->force) + show_local_changes(&new->commit->object); + + return 0; +} + +static void update_refs_for_switch(struct checkout_opts *opts, + struct branch_info *old, + struct branch_info *new) +{ + struct strbuf msg; + const char *old_desc; + if (opts->new_branch) { + create_branch(old->name, opts->new_branch, new->name, 0, + opts->new_branch_log, opts->track); + new->name = opts->new_branch; + setup_branch_path(new); + } + + strbuf_init(&msg, 0); + old_desc = old->name; + if (!old_desc) + old_desc = sha1_to_hex(old->commit->object.sha1); + strbuf_addf(&msg, "checkout: moving from %s to %s", + old_desc, new->name); + + if (new->path) { + create_symref("HEAD", new->path, msg.buf); + if (!opts->quiet) { + if (old->path && !strcmp(new->path, old->path)) + fprintf(stderr, "Already on \"%s\"\n", + new->name); + else + fprintf(stderr, "Switched to%s branch \"%s\"\n", + opts->new_branch ? " a new" : "", + new->name); + } + } else if (strcmp(new->name, "HEAD")) { + update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL, + REF_NODEREF, DIE_ON_ERR); + if (!opts->quiet) { + if (old->path) + fprintf(stderr, "Note: moving to \"%s\" which isn't a local branch\nIf you want to create a new branch from this checkout, you may do so\n(now or later) by using -b with the checkout command again. Example:\n git checkout -b \n", new->name); + describe_detached_head("HEAD is now at", new->commit); + } + } + remove_branch_state(); + strbuf_release(&msg); +} + +static int switch_branches(struct checkout_opts *opts, + struct branch_info *new, const char *prefix) +{ + int ret = 0; + struct branch_info old; + unsigned char rev[20]; + int flag; + memset(&old, 0, sizeof(old)); + old.path = resolve_ref("HEAD", rev, 0, &flag); + old.commit = lookup_commit_reference_gently(rev, 1); + if (!(flag & REF_ISSYMREF)) + old.path = NULL; + + if (old.path && !prefixcmp(old.path, "refs/heads/")) + old.name = old.path + strlen("refs/heads/"); + + if (!new->name) { + new->name = "HEAD"; + new->commit = old.commit; + if (!new->commit) + die("You are on a branch yet to be born"); + parse_commit(new->commit); + } + + /* + * If the new thing isn't a branch and isn't HEAD and we're + * not starting a new branch, and we want messages, and we + * weren't on a branch, and we're moving to a new commit, + * describe the old commit. + */ + if (!new->path && strcmp(new->name, "HEAD") && !opts->new_branch && + !opts->quiet && !old.path && new->commit != old.commit) + describe_detached_head("Previous HEAD position was", old.commit); + + if (!old.commit) { + if (!opts->quiet) { + fprintf(stderr, "warning: You appear to be on a branch yet to be born.\n"); + fprintf(stderr, "warning: Forcing checkout of %s.\n", new->name); + } + opts->force = 1; + } + + ret = merge_working_tree(opts, &old, new, prefix); + if (ret) + return ret; + + update_refs_for_switch(opts, &old, new); + + return post_checkout_hook(old.commit, new->commit, 1); +} + +static int branch_track = 0; + +static int git_checkout_config(const char *var, const char *value) +{ + if (!strcmp(var, "branch.autosetupmerge")) + branch_track = git_config_bool(var, value); + + return git_default_config(var, value); +} + +int cmd_checkout(int argc, const char **argv, const char *prefix) +{ + struct checkout_opts opts; + unsigned char rev[20]; + const char *arg; + struct branch_info new; + struct tree *source_tree = NULL; + struct option options[] = { + OPT__QUIET(&opts.quiet), + OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"), + OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"), + OPT_BOOLEAN( 0 , "track", &opts.track, "track"), + OPT_BOOLEAN('f', NULL, &opts.force, "force"), + OPT_BOOLEAN('m', NULL, &opts.merge, "merge"), + }; + + memset(&opts, 0, sizeof(opts)); + memset(&new, 0, sizeof(new)); + + git_config(git_checkout_config); + + opts.track = branch_track; + + argc = parse_options(argc, argv, options, checkout_usage, 0); + if (argc) { + arg = argv[0]; + if (get_sha1(arg, rev)) + ; + else if ((new.commit = lookup_commit_reference_gently(rev, 1))) { + new.name = arg; + setup_branch_path(&new); + if (resolve_ref(new.path, rev, 1, NULL)) + new.commit = lookup_commit_reference(rev); + else + new.path = NULL; + parse_commit(new.commit); + source_tree = new.commit->tree; + argv++; + argc--; + } else if ((source_tree = parse_tree_indirect(rev))) { + argv++; + argc--; + } + } + + if (argc && !strcmp(argv[0], "--")) { + argv++; + argc--; + } + + if (!opts.new_branch && (opts.track != branch_track)) + die("git checkout: --track and --no-track require -b"); + + if (opts.force && opts.merge) + die("git checkout: -f and -m are incompatible"); + + if (argc) { + const char **pathspec = get_pathspec(prefix, argv); + /* Checkout paths */ + if (opts.new_branch || opts.force || opts.merge) { + if (argc == 1) { + die("git checkout: updating paths is incompatible with switching branches/forcing\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]); + } else { + die("git checkout: updating paths is incompatible with switching branches/forcing"); + } + } + + if (source_tree) + read_tree_some(source_tree, pathspec); + else + read_cache(); + return checkout_paths(pathspec); + } + + if (new.name && !new.commit) { + die("Cannot switch branch to a non-commit."); + } + + return switch_branches(&opts, &new, prefix); +} diff --git a/builtin.h b/builtin.h index 428160d..25d91bb 100644 --- a/builtin.h +++ b/builtin.h @@ -19,6 +19,7 @@ extern int cmd_blame(int argc, const char **argv, const char *prefix); extern int cmd_branch(int argc, const char **argv, const char *prefix); extern int cmd_bundle(int argc, const char **argv, const char *prefix); extern int cmd_cat_file(int argc, const char **argv, const char *prefix); +extern int cmd_checkout(int argc, const char **argv, const char *prefix); extern int cmd_checkout_index(int argc, const char **argv, const char *prefix); extern int cmd_check_attr(int argc, const char **argv, const char *prefix); extern int cmd_check_ref_format(int argc, const char **argv, const char *prefix); diff --git a/contrib/examples/git-checkout.sh b/contrib/examples/git-checkout.sh new file mode 100755 index 0000000..5621c69 --- /dev/null +++ b/contrib/examples/git-checkout.sh @@ -0,0 +1,298 @@ +#!/bin/sh + +OPTIONS_KEEPDASHDASH=t +OPTIONS_SPEC="\ +git-checkout [options] [] [...] +-- +b= create a new branch started at +l create the new branch's reflog +track arrange that the new branch tracks the remote branch +f proceed even if the index or working tree is not HEAD +m merge local modifications into the new branch +q,quiet be quiet +" +SUBDIRECTORY_OK=Sometimes +. git-sh-setup +require_work_tree + +old_name=HEAD +old=$(git rev-parse --verify $old_name 2>/dev/null) +oldbranch=$(git symbolic-ref $old_name 2>/dev/null) +new= +new_name= +force= +branch= +track= +newbranch= +newbranch_log= +merge= +quiet= +v=-v +LF=' +' + +while test $# != 0; do + case "$1" in + -b) + shift + newbranch="$1" + [ -z "$newbranch" ] && + die "git checkout: -b needs a branch name" + git show-ref --verify --quiet -- "refs/heads/$newbranch" && + die "git checkout: branch $newbranch already exists" + git check-ref-format "heads/$newbranch" || + die "git checkout: we do not like '$newbranch' as a branch name." + ;; + -l) + newbranch_log=-l + ;; + --track|--no-track) + track="$1" + ;; + -f) + force=1 + ;; + -m) + merge=1 + ;; + -q|--quiet) + quiet=1 + v= + ;; + --) + shift + break + ;; + *) + usage + ;; + esac + shift +done + +arg="$1" +if rev=$(git rev-parse --verify "$arg^0" 2>/dev/null) +then + [ -z "$rev" ] && die "unknown flag $arg" + new_name="$arg" + if git show-ref --verify --quiet -- "refs/heads/$arg" + then + rev=$(git rev-parse --verify "refs/heads/$arg^0") + branch="$arg" + fi + new="$rev" + shift +elif rev=$(git rev-parse --verify "$arg^{tree}" 2>/dev/null) +then + # checking out selected paths from a tree-ish. + new="$rev" + new_name="$arg^{tree}" + shift +fi +[ "$1" = "--" ] && shift + +case "$newbranch,$track" in +,--*) + die "git checkout: --track and --no-track require -b" +esac + +case "$force$merge" in +11) + die "git checkout: -f and -m are incompatible" +esac + +# The behaviour of the command with and without explicit path +# parameters is quite different. +# +# Without paths, we are checking out everything in the work tree, +# possibly switching branches. This is the traditional behaviour. +# +# With paths, we are _never_ switching branch, but checking out +# the named paths from either index (when no rev is given), +# or the named tree-ish (when rev is given). + +if test "$#" -ge 1 +then + hint= + if test "$#" -eq 1 + then + hint=" +Did you intend to checkout '$@' which can not be resolved as commit?" + fi + if test '' != "$newbranch$force$merge" + then + die "git checkout: updating paths is incompatible with switching branches/forcing$hint" + fi + if test '' != "$new" + then + # from a specific tree-ish; note that this is for + # rescuing paths and is never meant to remove what + # is not in the named tree-ish. + git ls-tree --full-name -r "$new" "$@" | + git update-index --index-info || exit $? + fi + + # Make sure the request is about existing paths. + git ls-files --full-name --error-unmatch -- "$@" >/dev/null || exit + git ls-files --full-name -- "$@" | + (cd_to_toplevel && git checkout-index -f -u --stdin) + + # Run a post-checkout hook -- the HEAD does not change so the + # current HEAD is passed in for both args + if test -x "$GIT_DIR"/hooks/post-checkout; then + "$GIT_DIR"/hooks/post-checkout $old $old 0 + fi + + exit $? +else + # Make sure we did not fall back on $arg^{tree} codepath + # since we are not checking out from an arbitrary tree-ish, + # but switching branches. + if test '' != "$new" + then + git rev-parse --verify "$new^{commit}" >/dev/null 2>&1 || + die "Cannot switch branch to a non-commit." + fi +fi + +# We are switching branches and checking out trees, so +# we *NEED* to be at the toplevel. +cd_to_toplevel + +[ -z "$new" ] && new=$old && new_name="$old_name" + +# If we don't have an existing branch that we're switching to, +# and we don't have a new branch name for the target we +# are switching to, then we are detaching our HEAD from any +# branch. However, if "git checkout HEAD" detaches the HEAD +# from the current branch, even though that may be logically +# correct, it feels somewhat funny. More importantly, we do not +# want "git checkout" nor "git checkout -f" to detach HEAD. + +detached= +detach_warn= + +describe_detached_head () { + test -n "$quiet" || { + printf >&2 "$1 " + GIT_PAGER= git log >&2 -1 --pretty=oneline --abbrev-commit "$2" -- + } +} + +if test -z "$branch$newbranch" && test "$new_name" != "$old_name" +then + detached="$new" + if test -n "$oldbranch" && test -z "$quiet" + then + detach_warn="Note: moving to \"$new_name\" which isn't a local branch +If you want to create a new branch from this checkout, you may do so +(now or later) by using -b with the checkout command again. Example: + git checkout -b " + fi +elif test -z "$oldbranch" && test "$new" != "$old" +then + describe_detached_head 'Previous HEAD position was' "$old" +fi + +if [ "X$old" = X ] +then + if test -z "$quiet" + then + echo >&2 "warning: You appear to be on a branch yet to be born." + echo >&2 "warning: Forcing checkout of $new_name." + fi + force=1 +fi + +if [ "$force" ] +then + git read-tree $v --reset -u $new +else + git update-index --refresh >/dev/null + merge_error=$(git read-tree -m -u --exclude-per-directory=.gitignore $old $new 2>&1) || ( + case "$merge" in + '') + echo >&2 "$merge_error" + exit 1 ;; + esac + + # Match the index to the working tree, and do a three-way. + git diff-files --name-only | git update-index --remove --stdin && + work=`git write-tree` && + git read-tree $v --reset -u $new || exit + + eval GITHEAD_$new='${new_name:-${branch:-$new}}' && + eval GITHEAD_$work=local && + export GITHEAD_$new GITHEAD_$work && + git merge-recursive $old -- $new $work + + # Do not register the cleanly merged paths in the index yet. + # this is not a real merge before committing, but just carrying + # the working tree changes along. + unmerged=`git ls-files -u` + git read-tree $v --reset $new + case "$unmerged" in + '') ;; + *) + ( + z40=0000000000000000000000000000000000000000 + echo "$unmerged" | + sed -e 's/^[0-7]* [0-9a-f]* /'"0 $z40 /" + echo "$unmerged" + ) | git update-index --index-info + ;; + esac + exit 0 + ) + saved_err=$? + if test "$saved_err" = 0 && test -z "$quiet" + then + git diff-index --name-status "$new" + fi + (exit $saved_err) +fi + +# +# Switch the HEAD pointer to the new branch if we +# checked out a branch head, and remove any potential +# old MERGE_HEAD's (subsequent commits will clearly not +# be based on them, since we re-set the index) +# +if [ "$?" -eq 0 ]; then + if [ "$newbranch" ]; then + git branch $track $newbranch_log "$newbranch" "$new_name" || exit + branch="$newbranch" + fi + if test -n "$branch" + then + old_branch_name=`expr "z$oldbranch" : 'zrefs/heads/\(.*\)'` + GIT_DIR="$GIT_DIR" git symbolic-ref -m "checkout: moving from ${old_branch_name:-$old} to $branch" HEAD "refs/heads/$branch" + if test -n "$quiet" + then + true # nothing + elif test "refs/heads/$branch" = "$oldbranch" + then + echo >&2 "Already on branch \"$branch\"" + else + echo >&2 "Switched to${newbranch:+ a new} branch \"$branch\"" + fi + elif test -n "$detached" + then + old_branch_name=`expr "z$oldbranch" : 'zrefs/heads/\(.*\)'` + git update-ref --no-deref -m "checkout: moving from ${old_branch_name:-$old} to $arg" HEAD "$detached" || + die "Cannot detach HEAD" + if test -n "$detach_warn" + then + echo >&2 "$detach_warn" + fi + describe_detached_head 'HEAD is now at' HEAD + fi + rm -f "$GIT_DIR/MERGE_HEAD" +else + exit 1 +fi + +# Run a post-checkout hook +if test -x "$GIT_DIR"/hooks/post-checkout; then + "$GIT_DIR"/hooks/post-checkout $old $new 1 +fi diff --git a/git-checkout.sh b/git-checkout.sh deleted file mode 100755 index 5621c69..0000000 --- a/git-checkout.sh +++ /dev/null @@ -1,298 +0,0 @@ -#!/bin/sh - -OPTIONS_KEEPDASHDASH=t -OPTIONS_SPEC="\ -git-checkout [options] [] [...] --- -b= create a new branch started at -l create the new branch's reflog -track arrange that the new branch tracks the remote branch -f proceed even if the index or working tree is not HEAD -m merge local modifications into the new branch -q,quiet be quiet -" -SUBDIRECTORY_OK=Sometimes -. git-sh-setup -require_work_tree - -old_name=HEAD -old=$(git rev-parse --verify $old_name 2>/dev/null) -oldbranch=$(git symbolic-ref $old_name 2>/dev/null) -new= -new_name= -force= -branch= -track= -newbranch= -newbranch_log= -merge= -quiet= -v=-v -LF=' -' - -while test $# != 0; do - case "$1" in - -b) - shift - newbranch="$1" - [ -z "$newbranch" ] && - die "git checkout: -b needs a branch name" - git show-ref --verify --quiet -- "refs/heads/$newbranch" && - die "git checkout: branch $newbranch already exists" - git check-ref-format "heads/$newbranch" || - die "git checkout: we do not like '$newbranch' as a branch name." - ;; - -l) - newbranch_log=-l - ;; - --track|--no-track) - track="$1" - ;; - -f) - force=1 - ;; - -m) - merge=1 - ;; - -q|--quiet) - quiet=1 - v= - ;; - --) - shift - break - ;; - *) - usage - ;; - esac - shift -done - -arg="$1" -if rev=$(git rev-parse --verify "$arg^0" 2>/dev/null) -then - [ -z "$rev" ] && die "unknown flag $arg" - new_name="$arg" - if git show-ref --verify --quiet -- "refs/heads/$arg" - then - rev=$(git rev-parse --verify "refs/heads/$arg^0") - branch="$arg" - fi - new="$rev" - shift -elif rev=$(git rev-parse --verify "$arg^{tree}" 2>/dev/null) -then - # checking out selected paths from a tree-ish. - new="$rev" - new_name="$arg^{tree}" - shift -fi -[ "$1" = "--" ] && shift - -case "$newbranch,$track" in -,--*) - die "git checkout: --track and --no-track require -b" -esac - -case "$force$merge" in -11) - die "git checkout: -f and -m are incompatible" -esac - -# The behaviour of the command with and without explicit path -# parameters is quite different. -# -# Without paths, we are checking out everything in the work tree, -# possibly switching branches. This is the traditional behaviour. -# -# With paths, we are _never_ switching branch, but checking out -# the named paths from either index (when no rev is given), -# or the named tree-ish (when rev is given). - -if test "$#" -ge 1 -then - hint= - if test "$#" -eq 1 - then - hint=" -Did you intend to checkout '$@' which can not be resolved as commit?" - fi - if test '' != "$newbranch$force$merge" - then - die "git checkout: updating paths is incompatible with switching branches/forcing$hint" - fi - if test '' != "$new" - then - # from a specific tree-ish; note that this is for - # rescuing paths and is never meant to remove what - # is not in the named tree-ish. - git ls-tree --full-name -r "$new" "$@" | - git update-index --index-info || exit $? - fi - - # Make sure the request is about existing paths. - git ls-files --full-name --error-unmatch -- "$@" >/dev/null || exit - git ls-files --full-name -- "$@" | - (cd_to_toplevel && git checkout-index -f -u --stdin) - - # Run a post-checkout hook -- the HEAD does not change so the - # current HEAD is passed in for both args - if test -x "$GIT_DIR"/hooks/post-checkout; then - "$GIT_DIR"/hooks/post-checkout $old $old 0 - fi - - exit $? -else - # Make sure we did not fall back on $arg^{tree} codepath - # since we are not checking out from an arbitrary tree-ish, - # but switching branches. - if test '' != "$new" - then - git rev-parse --verify "$new^{commit}" >/dev/null 2>&1 || - die "Cannot switch branch to a non-commit." - fi -fi - -# We are switching branches and checking out trees, so -# we *NEED* to be at the toplevel. -cd_to_toplevel - -[ -z "$new" ] && new=$old && new_name="$old_name" - -# If we don't have an existing branch that we're switching to, -# and we don't have a new branch name for the target we -# are switching to, then we are detaching our HEAD from any -# branch. However, if "git checkout HEAD" detaches the HEAD -# from the current branch, even though that may be logically -# correct, it feels somewhat funny. More importantly, we do not -# want "git checkout" nor "git checkout -f" to detach HEAD. - -detached= -detach_warn= - -describe_detached_head () { - test -n "$quiet" || { - printf >&2 "$1 " - GIT_PAGER= git log >&2 -1 --pretty=oneline --abbrev-commit "$2" -- - } -} - -if test -z "$branch$newbranch" && test "$new_name" != "$old_name" -then - detached="$new" - if test -n "$oldbranch" && test -z "$quiet" - then - detach_warn="Note: moving to \"$new_name\" which isn't a local branch -If you want to create a new branch from this checkout, you may do so -(now or later) by using -b with the checkout command again. Example: - git checkout -b " - fi -elif test -z "$oldbranch" && test "$new" != "$old" -then - describe_detached_head 'Previous HEAD position was' "$old" -fi - -if [ "X$old" = X ] -then - if test -z "$quiet" - then - echo >&2 "warning: You appear to be on a branch yet to be born." - echo >&2 "warning: Forcing checkout of $new_name." - fi - force=1 -fi - -if [ "$force" ] -then - git read-tree $v --reset -u $new -else - git update-index --refresh >/dev/null - merge_error=$(git read-tree -m -u --exclude-per-directory=.gitignore $old $new 2>&1) || ( - case "$merge" in - '') - echo >&2 "$merge_error" - exit 1 ;; - esac - - # Match the index to the working tree, and do a three-way. - git diff-files --name-only | git update-index --remove --stdin && - work=`git write-tree` && - git read-tree $v --reset -u $new || exit - - eval GITHEAD_$new='${new_name:-${branch:-$new}}' && - eval GITHEAD_$work=local && - export GITHEAD_$new GITHEAD_$work && - git merge-recursive $old -- $new $work - - # Do not register the cleanly merged paths in the index yet. - # this is not a real merge before committing, but just carrying - # the working tree changes along. - unmerged=`git ls-files -u` - git read-tree $v --reset $new - case "$unmerged" in - '') ;; - *) - ( - z40=0000000000000000000000000000000000000000 - echo "$unmerged" | - sed -e 's/^[0-7]* [0-9a-f]* /'"0 $z40 /" - echo "$unmerged" - ) | git update-index --index-info - ;; - esac - exit 0 - ) - saved_err=$? - if test "$saved_err" = 0 && test -z "$quiet" - then - git diff-index --name-status "$new" - fi - (exit $saved_err) -fi - -# -# Switch the HEAD pointer to the new branch if we -# checked out a branch head, and remove any potential -# old MERGE_HEAD's (subsequent commits will clearly not -# be based on them, since we re-set the index) -# -if [ "$?" -eq 0 ]; then - if [ "$newbranch" ]; then - git branch $track $newbranch_log "$newbranch" "$new_name" || exit - branch="$newbranch" - fi - if test -n "$branch" - then - old_branch_name=`expr "z$oldbranch" : 'zrefs/heads/\(.*\)'` - GIT_DIR="$GIT_DIR" git symbolic-ref -m "checkout: moving from ${old_branch_name:-$old} to $branch" HEAD "refs/heads/$branch" - if test -n "$quiet" - then - true # nothing - elif test "refs/heads/$branch" = "$oldbranch" - then - echo >&2 "Already on branch \"$branch\"" - else - echo >&2 "Switched to${newbranch:+ a new} branch \"$branch\"" - fi - elif test -n "$detached" - then - old_branch_name=`expr "z$oldbranch" : 'zrefs/heads/\(.*\)'` - git update-ref --no-deref -m "checkout: moving from ${old_branch_name:-$old} to $arg" HEAD "$detached" || - die "Cannot detach HEAD" - if test -n "$detach_warn" - then - echo >&2 "$detach_warn" - fi - describe_detached_head 'HEAD is now at' HEAD - fi - rm -f "$GIT_DIR/MERGE_HEAD" -else - exit 1 -fi - -# Run a post-checkout hook -if test -x "$GIT_DIR"/hooks/post-checkout; then - "$GIT_DIR"/hooks/post-checkout $old $new 1 -fi diff --git a/git.c b/git.c index 114ea75..fc15686 100644 --- a/git.c +++ b/git.c @@ -287,6 +287,7 @@ static void handle_internal_command(int argc, const char **argv) { "branch", cmd_branch, RUN_SETUP }, { "bundle", cmd_bundle }, { "cat-file", cmd_cat_file, RUN_SETUP }, + { "checkout", cmd_checkout, RUN_SETUP | NEED_WORK_TREE }, { "checkout-index", cmd_checkout_index, RUN_SETUP | NEED_WORK_TREE}, { "check-ref-format", cmd_check_ref_format }, diff --git a/t/t7201-co.sh b/t/t7201-co.sh index 3d8e01c..5492f21 100755 --- a/t/t7201-co.sh +++ b/t/t7201-co.sh @@ -103,13 +103,6 @@ test_expect_success "checkout -m with dirty tree" ' test "$(git symbolic-ref HEAD)" = "refs/heads/side" && (cat >expect.messages < Date: Sat, 16 Feb 2008 17:17:09 -0800 Subject: checkout: notice when the switched branch is behind or forked When you are switching to a branch that is marked to merge from somewhere else, e.g. when you have: [branch "next"] remote = upstream merge = refs/heads/next [remote "upstream"] url = ... fetch = refs/heads/*:refs/remotes/linus/* and you say "git checkout next", the branch you checked out may be behind, and you may want to update from the upstream before continuing to work. This patch makes the command to check the upstream (in this example, "refs/remotes/linus/next") and our branch "next", and: (1) if they match, nothing happens; (2) if you are ahead (i.e. the upstream is a strict ancestor of you), one line message tells you so; (3) otherwise, you are either behind or you and the upstream have forked. One line message will tell you which and then you will see a "log --pretty=oneline --left-right". We could enhance this with an option that tells the command to check if there is no local change, and automatically fast forward when you are truly behind. But I ripped out that change because I was unsure what the right way should be to allow users to control it (issues include that checkout should not become automatically interactive). Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 59a0ef4..9370ba0 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -12,6 +12,7 @@ #include "branch.h" #include "diff.h" #include "revision.h" +#include "remote.h" static const char * const checkout_usage[] = { "git checkout [options] ", @@ -290,6 +291,139 @@ static int merge_working_tree(struct checkout_opts *opts, return 0; } +/* + * We really should allow cb_data... Yuck + */ +static const char *branch_name; +static int branch_name_len; +static char *found_remote; +static char *found_merge; +static int read_branch_config(const char *var, const char *value) +{ + const char *name; + if (prefixcmp(var, "branch.")) + return 0; /* not ours */ + name = var + strlen("branch."); + if (strncmp(name, branch_name, branch_name_len) || + name[branch_name_len] != '.') + return 0; /* not ours either */ + if (!strcmp(name + branch_name_len, ".remote")) { + /* + * Yeah, I know Christian's clean-up should + * be used here, but the topic is based on an + * older fork point. + */ + if (!value) + return error("'%s' not string", var); + found_remote = xstrdup(value); + return 0; + } + if (!strcmp(name + branch_name_len, ".merge")) { + if (!value) + return error("'%s' not string", var); + found_merge = xstrdup(value); + return 0; + } + return 0; /* not ours */ +} + +static int find_build_base(const char *ours, char **base) +{ + struct remote *remote; + struct refspec spec; + + *base = NULL; + + branch_name = ours + strlen("refs/heads/"); + branch_name_len = strlen(branch_name); + found_remote = NULL; + found_merge = NULL; + git_config(read_branch_config); + + if (!found_remote || !found_merge) { + cleanup: + free(found_remote); + free(found_merge); + return 0; + } + + remote = remote_get(found_remote); + memset(&spec, 0, sizeof(spec)); + spec.src = found_merge; + if (remote_find_tracking(remote, &spec)) + goto cleanup; + *base = spec.dst; + return 1; +} + +static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *opts) +{ + /* + * 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; + const char *msgfmt; + char symmetric[84]; + int show_log; + + if (!resolve_ref(new->path, sha1, 1, NULL)) + return; + ours = lookup_commit(sha1); + + if (!find_build_base(new->path, &base)) + return; + + sprintf(symmetric, "%s", sha1_to_hex(sha1)); + + /* + * Ok, it is tracking base; is it ahead of us? + */ + if (!resolve_ref(base, sha1, 1, NULL)) + return; + theirs = lookup_commit(sha1); + + sprintf(symmetric + 40, "...%s", sha1_to_hex(sha1)); + + if (!hashcmp(sha1, ours->object.sha1)) + return; /* we are the same */ + + show_log = 1; + if (in_merge_bases(theirs, &ours, 1)) { + msgfmt = "You are ahead of the tracked branch '%s'\n"; + show_log = 0; + } + else if (in_merge_bases(ours, &theirs, 1)) + msgfmt = "Your branch can be fast-forwarded to the tracked branch '%s'\n"; + else + msgfmt = "Both your branch and the tracked branch '%s' have own changes, you would eventually need to merge\n"; + + if (!prefixcmp(base, "refs/remotes/")) + base += strlen("refs/remotes/"); + fprintf(stderr, msgfmt, base); + + if (show_log) { + const char *args[32]; + int ac; + + ac = 0; + args[ac++] = "log"; + args[ac++] = "--pretty=oneline"; + args[ac++] = "--abbrev-commit"; + args[ac++] = "--left-right"; + args[ac++] = "--boundary"; + args[ac++] = symmetric; + args[ac++] = "--"; + args[ac] = NULL; + + run_command_v_opt(args, RUN_GIT_CMD); + } +} + + static void update_refs_for_switch(struct checkout_opts *opts, struct branch_info *old, struct branch_info *new) @@ -332,6 +466,8 @@ static void update_refs_for_switch(struct checkout_opts *opts, } remove_branch_state(); strbuf_release(&msg); + if (new->path) + adjust_to_tracking(new, opts); } static int switch_branches(struct checkout_opts *opts, -- cgit v0.10.2-6-g49f6 From f407f14deaa14ebddd0d27238523ced8eca74393 Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Sun, 17 Feb 2008 19:07:19 +0000 Subject: xdl_merge(): make XDL_MERGE_ZEALOUS output simpler When a merge conflicts, there are often less than three common lines between two conflicting regions. Since a conflict takes up as many lines as are conflicting, plus three lines for the commit markers, the output will be shorter (and thus, simpler) in this case, if the common lines will be merged into the conflicting regions. This patch merges up to three common lines into the conflicts. For example, what looked like this before this patch: <<<<<<< if (a == 1) ======= if (a != 0) >>>>>>> { int i; <<<<<<< a = 0; ======= a = !a; >>>>>>> will now look like this: <<<<<<< if (a == 1) { int i; a = 0; ======= if (a != 0) { int i; a = !a; >>>>>>> Suggested Linus (based on ideas by "Voltage Spike" -- if that name is real, it is mighty cool). Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano diff --git a/t/t6023-merge-file.sh b/t/t6023-merge-file.sh index 8641996..869e8d5 100755 --- a/t/t6023-merge-file.sh +++ b/t/t6023-merge-file.sh @@ -139,4 +139,14 @@ test_expect_success 'binary files cannot be merged' ' grep "Cannot merge binary files" merge.err ' +sed -e "s/deerit.$/deerit;/" -e "s/me;$/me./" < new5.txt > new6.txt +sed -e "s/deerit.$/deerit,/" -e "s/me;$/me,/" < new5.txt > new7.txt + +test_expect_success 'MERGE_ZEALOUS simplifies non-conflicts' ' + + ! git merge-file -p new6.txt new5.txt new7.txt > output && + test 1 = $(grep ======= < output | wc -l) + +' + test_done diff --git a/xdiff/xmerge.c b/xdiff/xmerge.c index b83b334..ecbdae5 100644 --- a/xdiff/xmerge.c +++ b/xdiff/xmerge.c @@ -249,6 +249,49 @@ static int xdl_refine_conflicts(xdfenv_t *xe1, xdfenv_t *xe2, xdmerge_t *m, } /* + * This function merges m and m->next, marking everything between those hunks + * as conflicting, too. + */ +static void xdl_merge_two_conflicts(xdmerge_t *m) +{ + xdmerge_t *next_m = m->next; + m->chg1 = next_m->i1 + next_m->chg1 - m->i1; + m->chg2 = next_m->i2 + next_m->chg2 - m->i2; + m->next = next_m->next; + free(next_m); +} + +/* + * If there are less than 3 non-conflicting lines between conflicts, + * it appears simpler -- because it takes up less (or as many) lines -- + * if the lines are moved into the conflicts. + */ +static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m) +{ + int result = 0; + + if (!m) + return result; + for (;;) { + xdmerge_t *next_m = m->next; + int begin, end; + + if (!next_m) + return result; + + begin = m->i1 + m->chg1; + end = next_m->i1; + + if (m->mode != 0 || next_m->mode != 0 || end - begin > 3) + m = next_m; + else { + result++; + xdl_merge_two_conflicts(m); + } + } +} + +/* * level == 0: mark all overlapping changes as conflict * level == 1: mark overlapping changes as conflict only if not identical * level == 2: analyze non-identical changes for minimal conflict set @@ -355,7 +398,9 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, if (!changes) changes = c; /* refine conflicts */ - if (level > 1 && xdl_refine_conflicts(xe1, xe2, changes, xpp) < 0) { + if (level > 1 && + (xdl_refine_conflicts(xe1, xe2, changes, xpp) < 0 || + xdl_simplify_non_conflicts(xe1, changes) < 0)) { xdl_cleanup_merge(changes); return -1; } -- cgit v0.10.2-6-g49f6 From ee95ec5d58d536243966de6ee810d345074b755e Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Sun, 17 Feb 2008 19:07:40 +0000 Subject: xdl_merge(): introduce XDL_MERGE_ZEALOUS_ALNUM When a merge conflicts, there are often common lines that are not really common, such as empty lines or lines containing a single curly bracket. With XDL_MERGE_ZEALOUS_ALNUM, we use the following heuristics: when a hunk does not contain any letters or digits, it is treated as conflicting. In other words, a conflict which used to look like this: <<<<<<< a = 1; ======= output(); >>>>>>> } } } <<<<<<< output(); ======= b = 1; >>>>>>> will look like this with ZEALOUS_ALNUM: <<<<<<< a = 1; } } } output(); ======= output(); } } } b = 1; >>>>>>> To demonstrate this, git-merge-file has been switched from XDL_MERGE_ZEALOUS to XDL_MERGE_ZEALOUS_ALNUM. Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano diff --git a/builtin-merge-file.c b/builtin-merge-file.c index 58deb62..adce6d4 100644 --- a/builtin-merge-file.c +++ b/builtin-merge-file.c @@ -46,7 +46,7 @@ int cmd_merge_file(int argc, const char **argv, const char *prefix) } ret = xdl_merge(mmfs + 1, mmfs + 0, names[0], mmfs + 2, names[2], - &xpp, XDL_MERGE_ZEALOUS, &result); + &xpp, XDL_MERGE_ZEALOUS_ALNUM, &result); for (i = 0; i < 3; i++) free(mmfs[i].ptr); diff --git a/t/t6023-merge-file.sh b/t/t6023-merge-file.sh index 869e8d5..79dc58b 100755 --- a/t/t6023-merge-file.sh +++ b/t/t6023-merge-file.sh @@ -149,4 +149,14 @@ test_expect_success 'MERGE_ZEALOUS simplifies non-conflicts' ' ' +sed -e 's/deerit./&\n\n\n\n/' -e "s/locavit,/locavit;/" < new6.txt > new8.txt +sed -e 's/deerit./&\n\n\n\n/' -e "s/locavit,/locavit --/" < new7.txt > new9.txt + +test_expect_success 'ZEALOUS_ALNUM' ' + + ! git merge-file -p new8.txt new5.txt new9.txt > merge.out && + test 1 = $(grep ======= < merge.out | wc -l) + +' + test_done diff --git a/xdiff/xdiff.h b/xdiff/xdiff.h index c00ddaa..413082e 100644 --- a/xdiff/xdiff.h +++ b/xdiff/xdiff.h @@ -53,6 +53,7 @@ extern "C" { #define XDL_MERGE_MINIMAL 0 #define XDL_MERGE_EAGER 1 #define XDL_MERGE_ZEALOUS 2 +#define XDL_MERGE_ZEALOUS_ALNUM 3 typedef struct s_mmfile { char *ptr; diff --git a/xdiff/xmerge.c b/xdiff/xmerge.c index ecbdae5..82b3573 100644 --- a/xdiff/xmerge.c +++ b/xdiff/xmerge.c @@ -248,6 +248,23 @@ static int xdl_refine_conflicts(xdfenv_t *xe1, xdfenv_t *xe2, xdmerge_t *m, return 0; } +static int line_contains_alnum(const char *ptr, long size) +{ + while (size--) + if (isalnum(*(ptr++))) + return 1; + return 0; +} + +static int lines_contain_alnum(xdfenv_t *xe, int i, int chg) +{ + for (; chg; chg--, i++) + if (line_contains_alnum(xe->xdf2.recs[i]->ptr, + xe->xdf2.recs[i]->size)) + return 1; + return 0; +} + /* * This function merges m and m->next, marking everything between those hunks * as conflicting, too. @@ -266,7 +283,8 @@ static void xdl_merge_two_conflicts(xdmerge_t *m) * it appears simpler -- because it takes up less (or as many) lines -- * if the lines are moved into the conflicts. */ -static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m) +static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m, + int simplify_if_no_alnum) { int result = 0; @@ -282,9 +300,12 @@ static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m) begin = m->i1 + m->chg1; end = next_m->i1; - if (m->mode != 0 || next_m->mode != 0 || end - begin > 3) + if (m->mode != 0 || next_m->mode != 0 || + (end - begin > 3 && + (!simplify_if_no_alnum || + lines_contain_alnum(xe1, begin, end - begin)))) { m = next_m; - else { + } else { result++; xdl_merge_two_conflicts(m); } @@ -295,6 +316,8 @@ static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m) * level == 0: mark all overlapping changes as conflict * level == 1: mark overlapping changes as conflict only if not identical * level == 2: analyze non-identical changes for minimal conflict set + * level == 3: analyze non-identical changes for minimal conflict set, but + * treat hunks not containing any letter or number as conflicting * * returns < 0 on error, == 0 for no conflicts, else number of conflicts */ @@ -400,7 +423,7 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, /* refine conflicts */ if (level > 1 && (xdl_refine_conflicts(xe1, xe2, changes, xpp) < 0 || - xdl_simplify_non_conflicts(xe1, changes) < 0)) { + xdl_simplify_non_conflicts(xe1, changes, level > 2) < 0)) { xdl_cleanup_merge(changes); return -1; } -- cgit v0.10.2-6-g49f6 From b249b552e012824f1bd5026187bf9b895c2132c6 Mon Sep 17 00:00:00 2001 From: Jay Soffian Date: Mon, 18 Feb 2008 05:20:20 -0500 Subject: builtin-checkout.c: fix possible usage segfault Not terminating the options[] array with OPT_END can cause usage ("git checkout -h") output to segfault. Signed-off-by: Jay Soffian Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 9370ba0..0d19835 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -545,6 +545,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) OPT_BOOLEAN( 0 , "track", &opts.track, "track"), OPT_BOOLEAN('f', NULL, &opts.force, "force"), OPT_BOOLEAN('m', NULL, &opts.merge, "merge"), + OPT_END(), }; memset(&opts, 0, sizeof(opts)); -- cgit v0.10.2-6-g49f6 From 569012bf91ddb25220483e8912e079ce8a501525 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Tue, 19 Feb 2008 02:52:14 -0500 Subject: Clean up reporting differences on branch switch This also changes it such that: $ git checkout will give the same information without changing branches. This is good for finding out if the fetch you did recently had anything to say about the branch you've been on, whose name you don't remember at the moment. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 0d19835..5291f72 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -291,71 +291,6 @@ static int merge_working_tree(struct checkout_opts *opts, return 0; } -/* - * We really should allow cb_data... Yuck - */ -static const char *branch_name; -static int branch_name_len; -static char *found_remote; -static char *found_merge; -static int read_branch_config(const char *var, const char *value) -{ - const char *name; - if (prefixcmp(var, "branch.")) - return 0; /* not ours */ - name = var + strlen("branch."); - if (strncmp(name, branch_name, branch_name_len) || - name[branch_name_len] != '.') - return 0; /* not ours either */ - if (!strcmp(name + branch_name_len, ".remote")) { - /* - * Yeah, I know Christian's clean-up should - * be used here, but the topic is based on an - * older fork point. - */ - if (!value) - return error("'%s' not string", var); - found_remote = xstrdup(value); - return 0; - } - if (!strcmp(name + branch_name_len, ".merge")) { - if (!value) - return error("'%s' not string", var); - found_merge = xstrdup(value); - return 0; - } - return 0; /* not ours */ -} - -static int find_build_base(const char *ours, char **base) -{ - struct remote *remote; - struct refspec spec; - - *base = NULL; - - branch_name = ours + strlen("refs/heads/"); - branch_name_len = strlen(branch_name); - found_remote = NULL; - found_merge = NULL; - git_config(read_branch_config); - - if (!found_remote || !found_merge) { - cleanup: - free(found_remote); - free(found_merge); - return 0; - } - - remote = remote_get(found_remote); - memset(&spec, 0, sizeof(spec)); - spec.src = found_merge; - if (remote_find_tracking(remote, &spec)) - goto cleanup; - *base = spec.dst; - return 1; -} - static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *opts) { /* @@ -369,15 +304,16 @@ static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *op const char *msgfmt; char symmetric[84]; int show_log; + struct branch *branch = branch_get(NULL); - if (!resolve_ref(new->path, sha1, 1, NULL)) + if (!branch || !branch->merge) return; - ours = lookup_commit(sha1); - if (!find_build_base(new->path, &base)) - return; + base = branch->merge[0]->dst; + + ours = new->commit; - sprintf(symmetric, "%s", sha1_to_hex(sha1)); + sprintf(symmetric, "%s", sha1_to_hex(ours->object.sha1)); /* * Ok, it is tracking base; is it ahead of us? @@ -466,7 +402,7 @@ static void update_refs_for_switch(struct checkout_opts *opts, } remove_branch_state(); strbuf_release(&msg); - if (new->path) + if (new->path || !strcmp(new->name, "HEAD")) adjust_to_tracking(new, opts); } -- cgit v0.10.2-6-g49f6 From 7d812145ba7f8df825de618b277186c512d04cfa Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 18 Feb 2008 22:56:02 -0500 Subject: Add more tests for format-patch Tests -o, and an excessively long subject, and --thread, with and without --in-reply-to= Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index 0a6fe53..6e8b5f4 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -88,4 +88,49 @@ test_expect_success 'replay did not screw up the log message' ' ' +test_expect_success 'multiple files' ' + + rm -rf patches/ && + git checkout side && + git format-patch -o patches/ master && + ls patches/0001-Side-changes-1.patch patches/0002-Side-changes-2.patch patches/0003-Side-changes-3-with-n-backslash-n-in-it.patch +' + +test_expect_success 'thread' ' + + rm -rf patches/ && + git checkout side && + git format-patch --thread -o patches/ master && + FIRST_MID=$(grep "Message-Id:" patches/0001-* | sed "s/^[^<]*\(<[^>]*>\).*$/\1/") && + for i in patches/0002-* patches/0003-* + do + grep "References: $FIRST_MID" $i && + grep "In-Reply-To: $FIRST_MID" $i + done +' + +test_expect_success 'thread in-reply-to' ' + + rm -rf patches/ && + git checkout side && + git format-patch --in-reply-to="" --thread -o patches/ master && + FIRST_MID="" && + for i in patches/* + do + grep "References: $FIRST_MID" $i && + grep "In-Reply-To: $FIRST_MID" $i + done +' + +test_expect_success 'excessive subject' ' + + rm -rf patches/ && + git checkout side && + for i in 5 6 1 2 3 A 4 B C 7 8 9 10 D E F; do echo "$i"; done >>file && + git update-index file && + git commit -m "This is an excessively long subject line for a message due to the habit some projects have of not having a short, one-line subject at the start of the commit message, but rather sticking a whole paragraph right at the start as the only thing in the commit message. It had better not become the filename for the patch." && + git format-patch -o patches/ master..side && + ls patches/0004-This-is-an-excessively-long-subject-line-for-a-messa.patch +' + test_done -- cgit v0.10.2-6-g49f6 From e1a37346210da8b165037984e02f750a6a135480 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 18 Feb 2008 22:56:06 -0500 Subject: Improve message-id generation flow control for format-patch Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-log.c b/builtin-log.c index 99d69f0..4f08ca4 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -575,16 +575,19 @@ static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const cha o2->flags = flags2; } -static void gen_message_id(char *dest, unsigned int length, char *base) +static void gen_message_id(struct rev_info *info, char *base) { const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME); const char *email_start = strrchr(committer, '<'); const char *email_end = strrchr(committer, '>'); - if(!email_start || !email_end || email_start > email_end - 1) + struct strbuf buf; + if (!email_start || !email_end || email_start > email_end - 1) die("Could not extract email from committer identity."); - snprintf(dest, length, "%s.%lu.git.%.*s", base, - (unsigned long) time(NULL), - (int)(email_end - email_start - 1), email_start + 1); + strbuf_init(&buf, 0); + strbuf_addf(&buf, "%s.%lu.git.%.*s", base, + (unsigned long) time(NULL), + (int)(email_end - email_start - 1), email_start + 1); + info->message_id = strbuf_detach(&buf, NULL); } static const char *clean_message_id(const char *msg_id) @@ -625,8 +628,6 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) const char *in_reply_to = NULL; struct patch_ids ids; char *add_signoff = NULL; - char message_id[1024]; - char ref_message_id[1024]; git_config(git_format_config); init_revisions(&rev, prefix); @@ -809,15 +810,13 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) rev.nr = total - nr + (start_number - 1); /* Make the second and subsequent mails replies to the first */ if (thread) { - if (nr == (total - 2)) { - strncpy(ref_message_id, message_id, - sizeof(ref_message_id)); - ref_message_id[sizeof(ref_message_id)-1]='\0'; - rev.ref_message_id = ref_message_id; + if (rev.message_id) { + if (rev.ref_message_id) + free(rev.message_id); + else + rev.ref_message_id = rev.message_id; } - gen_message_id(message_id, sizeof(message_id), - sha1_to_hex(commit->object.sha1)); - rev.message_id = message_id; + gen_message_id(&rev, sha1_to_hex(commit->object.sha1)); } if (!use_stdout) if (reopen_stdout(commit, rev.nr, keep_subject, diff --git a/revision.h b/revision.h index 8572315..e3559d0 100644 --- a/revision.h +++ b/revision.h @@ -74,7 +74,7 @@ struct rev_info { struct log_info *loginfo; int nr, total; const char *mime_boundary; - const char *message_id; + char *message_id; const char *ref_message_id; const char *add_signoff; const char *extra_headers; -- cgit v0.10.2-6-g49f6 From b02bd65f679024ce25afeddf7e96d6d7aea5fca6 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 18 Feb 2008 22:56:08 -0500 Subject: Export some email and pretty-printing functions These will be used for generating the cover letter in addition to the patch emails. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/commit.h b/commit.h index 10e2b5d..80d65b9 100644 --- a/commit.h +++ b/commit.h @@ -71,6 +71,21 @@ extern void pretty_print_commit(enum cmit_fmt fmt, const struct commit*, int abbrev, const char *subject, const char *after_subject, enum date_mode, int non_ascii_present); +void pp_user_info(const char *what, enum cmit_fmt fmt, struct strbuf *sb, + const char *line, enum date_mode dmode, + const char *encoding); +void pp_title_line(enum cmit_fmt fmt, + const char **msg_p, + struct strbuf *sb, + const char *subject, + const char *after_subject, + const char *encoding, + int plain_non_ascii); +void pp_remainder(enum cmit_fmt fmt, + const char **msg_p, + struct strbuf *sb, + int indent); + /** Removes the first commit from a list sorted by date, and adds all * of its parents. diff --git a/log-tree.c b/log-tree.c index 1f3fcf1..1b084dc 100644 --- a/log-tree.c +++ b/log-tree.c @@ -137,6 +137,72 @@ static int has_non_ascii(const char *s) return 0; } +void log_write_email_headers(struct rev_info *opt, const char *name, + const char **subject_p, const char **extra_headers_p) +{ + const char *subject = NULL; + const char *extra_headers = opt->extra_headers; + if (opt->total > 0) { + static char buffer[64]; + snprintf(buffer, sizeof(buffer), + "Subject: [%s %0*d/%d] ", + opt->subject_prefix, + digits_in_number(opt->total), + opt->nr, opt->total); + subject = buffer; + } else if (opt->total == 0 && opt->subject_prefix && *opt->subject_prefix) { + static char buffer[256]; + snprintf(buffer, sizeof(buffer), + "Subject: [%s] ", + opt->subject_prefix); + subject = buffer; + } else { + subject = "Subject: "; + } + + printf("From %s Mon Sep 17 00:00:00 2001\n", name); + if (opt->message_id) + printf("Message-Id: <%s>\n", opt->message_id); + if (opt->ref_message_id) + printf("In-Reply-To: <%s>\nReferences: <%s>\n", + opt->ref_message_id, opt->ref_message_id); + if (opt->mime_boundary) { + static char subject_buffer[1024]; + static char buffer[1024]; + snprintf(subject_buffer, sizeof(subject_buffer) - 1, + "%s" + "MIME-Version: 1.0\n" + "Content-Type: multipart/mixed;" + " boundary=\"%s%s\"\n" + "\n" + "This is a multi-part message in MIME " + "format.\n" + "--%s%s\n" + "Content-Type: text/plain; " + "charset=UTF-8; format=fixed\n" + "Content-Transfer-Encoding: 8bit\n\n", + extra_headers ? extra_headers : "", + mime_boundary_leader, opt->mime_boundary, + mime_boundary_leader, opt->mime_boundary); + extra_headers = subject_buffer; + + snprintf(buffer, sizeof(buffer) - 1, + "--%s%s\n" + "Content-Type: text/x-patch;" + " name=\"%s.diff\"\n" + "Content-Transfer-Encoding: 8bit\n" + "Content-Disposition: %s;" + " filename=\"%s.diff\"\n\n", + mime_boundary_leader, opt->mime_boundary, + name, + opt->no_inline ? "attachment" : "inline", + name); + opt->diffopt.stat_sep = buffer; + } + *subject_p = subject; + *extra_headers_p = extra_headers; +} + void show_log(struct rev_info *opt, const char *sep) { struct strbuf msgbuf; @@ -186,64 +252,8 @@ void show_log(struct rev_info *opt, const char *sep) */ if (opt->commit_format == CMIT_FMT_EMAIL) { - char *sha1 = sha1_to_hex(commit->object.sha1); - if (opt->total > 0) { - static char buffer[64]; - snprintf(buffer, sizeof(buffer), - "Subject: [%s %0*d/%d] ", - opt->subject_prefix, - digits_in_number(opt->total), - opt->nr, opt->total); - subject = buffer; - } else if (opt->total == 0 && opt->subject_prefix && *opt->subject_prefix) { - static char buffer[256]; - snprintf(buffer, sizeof(buffer), - "Subject: [%s] ", - opt->subject_prefix); - subject = buffer; - } else { - subject = "Subject: "; - } - - printf("From %s Mon Sep 17 00:00:00 2001\n", sha1); - if (opt->message_id) - printf("Message-Id: <%s>\n", opt->message_id); - if (opt->ref_message_id) - printf("In-Reply-To: <%s>\nReferences: <%s>\n", - opt->ref_message_id, opt->ref_message_id); - if (opt->mime_boundary) { - static char subject_buffer[1024]; - static char buffer[1024]; - snprintf(subject_buffer, sizeof(subject_buffer) - 1, - "%s" - "MIME-Version: 1.0\n" - "Content-Type: multipart/mixed;" - " boundary=\"%s%s\"\n" - "\n" - "This is a multi-part message in MIME " - "format.\n" - "--%s%s\n" - "Content-Type: text/plain; " - "charset=UTF-8; format=fixed\n" - "Content-Transfer-Encoding: 8bit\n\n", - extra_headers ? extra_headers : "", - mime_boundary_leader, opt->mime_boundary, - mime_boundary_leader, opt->mime_boundary); - extra_headers = subject_buffer; - - snprintf(buffer, sizeof(buffer) - 1, - "--%s%s\n" - "Content-Type: text/x-patch;" - " name=\"%s.diff\"\n" - "Content-Transfer-Encoding: 8bit\n" - "Content-Disposition: %s;" - " filename=\"%s.diff\"\n\n", - mime_boundary_leader, opt->mime_boundary, - sha1, - opt->no_inline ? "attachment" : "inline", - sha1); - opt->diffopt.stat_sep = buffer; - } + log_write_email_headers(opt, sha1_to_hex(commit->object.sha1), + &subject, &extra_headers); } else if (opt->commit_format != CMIT_FMT_USERFORMAT) { fputs(diff_get_color_opt(&opt->diffopt, DIFF_COMMIT), stdout); if (opt->commit_format != CMIT_FMT_ONELINE) diff --git a/log-tree.h b/log-tree.h index b33f7cd..0cc9344 100644 --- a/log-tree.h +++ b/log-tree.h @@ -13,5 +13,7 @@ int log_tree_commit(struct rev_info *, struct commit *); int log_tree_opt_parse(struct rev_info *, const char **, int); void show_log(struct rev_info *opt, const char *sep); void show_decorations(struct commit *commit); +void log_write_email_headers(struct rev_info *opt, const char *name, + const char **subject_p, const char **extra_headers_p); #endif diff --git a/pretty.c b/pretty.c index b987ff2..d5db1bd 100644 --- a/pretty.c +++ b/pretty.c @@ -110,9 +110,9 @@ needquote: strbuf_addstr(sb, "?="); } -static void add_user_info(const char *what, enum cmit_fmt fmt, struct strbuf *sb, - const char *line, enum date_mode dmode, - const char *encoding) +void pp_user_info(const char *what, enum cmit_fmt fmt, struct strbuf *sb, + const char *line, enum date_mode dmode, + const char *encoding) { char *date; int namelen; @@ -295,7 +295,7 @@ static void format_person_part(struct strbuf *sb, char part, /* * If it does not even have a '<' and '>', that is * quite a bogus commit author and we discard it; - * this is in line with add_user_info() that is used + * this is in line with pp_user_info() that is used * in the normal codepath. When end points at the '<' * that we found, it should have matching '>' later, * which means start (beginning of email address) must @@ -643,23 +643,23 @@ static void pp_header(enum cmit_fmt fmt, */ if (!memcmp(line, "author ", 7)) { strbuf_grow(sb, linelen + 80); - add_user_info("Author", fmt, sb, line + 7, dmode, encoding); + pp_user_info("Author", fmt, sb, line + 7, dmode, encoding); } if (!memcmp(line, "committer ", 10) && (fmt == CMIT_FMT_FULL || fmt == CMIT_FMT_FULLER)) { strbuf_grow(sb, linelen + 80); - add_user_info("Commit", fmt, sb, line + 10, dmode, encoding); + pp_user_info("Commit", fmt, sb, line + 10, dmode, encoding); } } } -static void pp_title_line(enum cmit_fmt fmt, - const char **msg_p, - struct strbuf *sb, - const char *subject, - const char *after_subject, - const char *encoding, - int plain_non_ascii) +void pp_title_line(enum cmit_fmt fmt, + const char **msg_p, + struct strbuf *sb, + const char *subject, + const char *after_subject, + const char *encoding, + int plain_non_ascii) { struct strbuf title; @@ -708,10 +708,10 @@ static void pp_title_line(enum cmit_fmt fmt, strbuf_release(&title); } -static void pp_remainder(enum cmit_fmt fmt, - const char **msg_p, - struct strbuf *sb, - int indent) +void pp_remainder(enum cmit_fmt fmt, + const char **msg_p, + struct strbuf *sb, + int indent) { int first = 1; for (;;) { -- cgit v0.10.2-6-g49f6 From 2d31347ba5c56d43d64dfdfe04a924178ee55b75 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 18 Feb 2008 23:41:41 -0500 Subject: Use ALLOC_GROW in remote.{c,h} Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/remote.c b/remote.c index 6b56473..457d8a4 100644 --- a/remote.c +++ b/remote.c @@ -3,10 +3,12 @@ #include "refs.h" static struct remote **remotes; -static int allocated_remotes; +static int remotes_alloc; +static int remotes_nr; static struct branch **branches; -static int allocated_branches; +static int branches_alloc; +static int branches_nr; static struct branch *current_branch; static const char *default_remote_name; @@ -16,109 +18,81 @@ static char buffer[BUF_SIZE]; static void add_push_refspec(struct remote *remote, const char *ref) { - int nr = remote->push_refspec_nr + 1; - remote->push_refspec = - xrealloc(remote->push_refspec, nr * sizeof(char *)); - remote->push_refspec[nr-1] = ref; - remote->push_refspec_nr = nr; + ALLOC_GROW(remote->push_refspec, + remote->push_refspec_nr + 1, + remote->push_refspec_alloc); + remote->push_refspec[remote->push_refspec_nr++] = ref; } static void add_fetch_refspec(struct remote *remote, const char *ref) { - int nr = remote->fetch_refspec_nr + 1; - remote->fetch_refspec = - xrealloc(remote->fetch_refspec, nr * sizeof(char *)); - remote->fetch_refspec[nr-1] = ref; - remote->fetch_refspec_nr = nr; + ALLOC_GROW(remote->fetch_refspec, + remote->fetch_refspec_nr + 1, + remote->fetch_refspec_alloc); + remote->fetch_refspec[remote->fetch_refspec_nr++] = ref; } static void add_url(struct remote *remote, const char *url) { - int nr = remote->url_nr + 1; - remote->url = - xrealloc(remote->url, nr * sizeof(char *)); - remote->url[nr-1] = url; - remote->url_nr = nr; + ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc); + remote->url[remote->url_nr++] = url; } static struct remote *make_remote(const char *name, int len) { - int i, empty = -1; + struct remote *ret; + int i; - for (i = 0; i < allocated_remotes; i++) { - if (!remotes[i]) { - if (empty < 0) - empty = i; - } else { - if (len ? (!strncmp(name, remotes[i]->name, len) && - !remotes[i]->name[len]) : - !strcmp(name, remotes[i]->name)) - return remotes[i]; - } + for (i = 0; i < remotes_nr; i++) { + if (len ? (!strncmp(name, remotes[i]->name, len) && + !remotes[i]->name[len]) : + !strcmp(name, remotes[i]->name)) + return remotes[i]; } - if (empty < 0) { - empty = allocated_remotes; - allocated_remotes += allocated_remotes ? allocated_remotes : 1; - remotes = xrealloc(remotes, - sizeof(*remotes) * allocated_remotes); - memset(remotes + empty, 0, - (allocated_remotes - empty) * sizeof(*remotes)); - } - remotes[empty] = xcalloc(1, sizeof(struct remote)); + ret = xcalloc(1, sizeof(struct remote)); + ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc); + remotes[remotes_nr++] = ret; if (len) - remotes[empty]->name = xstrndup(name, len); + ret->name = xstrndup(name, len); else - remotes[empty]->name = xstrdup(name); - return remotes[empty]; + ret->name = xstrdup(name); + return ret; } static void add_merge(struct branch *branch, const char *name) { - int nr = branch->merge_nr + 1; - branch->merge_name = - xrealloc(branch->merge_name, nr * sizeof(char *)); - branch->merge_name[nr-1] = name; - branch->merge_nr = nr; + ALLOC_GROW(branch->merge_name, branch->merge_nr + 1, + branch->merge_alloc); + branch->merge_name[branch->merge_nr++] = name; } static struct branch *make_branch(const char *name, int len) { - int i, empty = -1; + struct branch *ret; + int i; char *refname; - for (i = 0; i < allocated_branches; i++) { - if (!branches[i]) { - if (empty < 0) - empty = i; - } else { - if (len ? (!strncmp(name, branches[i]->name, len) && - !branches[i]->name[len]) : - !strcmp(name, branches[i]->name)) - return branches[i]; - } + for (i = 0; i < branches_nr; i++) { + if (len ? (!strncmp(name, branches[i]->name, len) && + !branches[i]->name[len]) : + !strcmp(name, branches[i]->name)) + return branches[i]; } - if (empty < 0) { - empty = allocated_branches; - allocated_branches += allocated_branches ? allocated_branches : 1; - branches = xrealloc(branches, - sizeof(*branches) * allocated_branches); - memset(branches + empty, 0, - (allocated_branches - empty) * sizeof(*branches)); - } - branches[empty] = xcalloc(1, sizeof(struct branch)); + ALLOC_GROW(branches, branches_nr + 1, branches_alloc); + ret = xcalloc(1, sizeof(struct branch)); + branches[branches_nr++] = ret; if (len) - branches[empty]->name = xstrndup(name, len); + ret->name = xstrndup(name, len); else - branches[empty]->name = xstrdup(name); + ret->name = xstrdup(name); refname = malloc(strlen(name) + strlen("refs/heads/") + 1); strcpy(refname, "refs/heads/"); - strcpy(refname + strlen("refs/heads/"), - branches[empty]->name); - branches[empty]->refname = refname; + strcpy(refname + strlen("refs/heads/"), ret->name); + ret->refname = refname; - return branches[empty]; + return ret; } static void read_remotes_file(struct remote *remote) @@ -380,7 +354,7 @@ int for_each_remote(each_remote_fn fn, void *priv) { int i, result = 0; read_config(); - for (i = 0; i < allocated_remotes && !result; i++) { + for (i = 0; i < remotes_nr && !result; i++) { struct remote *r = remotes[i]; if (!r) continue; diff --git a/remote.h b/remote.h index 86e036d..0f6033f 100644 --- a/remote.h +++ b/remote.h @@ -6,14 +6,17 @@ struct remote { const char **url; int url_nr; + int url_alloc; const char **push_refspec; struct refspec *push; int push_refspec_nr; + int push_refspec_alloc; const char **fetch_refspec; struct refspec *fetch; int fetch_refspec_nr; + int fetch_refspec_alloc; /* * -1 to never fetch tags @@ -100,6 +103,7 @@ struct branch { const char **merge_name; struct refspec **merge; int merge_nr; + int merge_alloc; }; struct branch *branch_get(const char *name); -- cgit v0.10.2-6-g49f6 From 2c2a3782c5092f232e71e8d97272b82cdca0664e Mon Sep 17 00:00:00 2001 From: Wincent Colaiuta Date: Mon, 18 Feb 2008 09:36:33 +0100 Subject: git-gui: relax "dirty" version detection "git gui" would complain at launch if the local version of Git was "1.5.4.2.dirty". Loosen the regular expression to look for either "-dirty" or ".dirty", thus eliminating spurious warnings. Signed-off-by: Wincent Colaiuta Signed-off-by: Shawn O. Pearce diff --git a/git-gui.sh b/git-gui.sh index f42e461..04bd425 100755 --- a/git-gui.sh +++ b/git-gui.sh @@ -662,7 +662,7 @@ if {![regsub {^git version } $_git_version {} _git_version]} { } set _real_git_version $_git_version -regsub -- {-dirty$} $_git_version {} _git_version +regsub -- {[\-\.]dirty$} $_git_version {} _git_version regsub {\.[0-9]+\.g[0-9a-f]+$} $_git_version {} _git_version regsub {\.rc[0-9]+$} $_git_version {} _git_version regsub {\.GIT$} $_git_version {} _git_version -- cgit v0.10.2-6-g49f6 From 9ed36cfa35cfbd09c454f12194a91cd50ba284d1 Mon Sep 17 00:00:00 2001 From: Jay Soffian Date: Tue, 19 Feb 2008 11:24:37 -0500 Subject: branch: optionally setup branch.*.merge from upstream local branches "git branch" and "git checkout -b" now honor --track option even when the upstream branch is local. Previously --track was silently ignored when forking from a local branch. Also the command did not error out when --track was explicitly asked for but the forked point specified was not an existing branch (i.e. when there is no way to set up the tracking configuration), but now it correctly does. The configuration setting branch.autosetupmerge can now be set to "always", which is equivalent to using --track from the command line. Setting branch.autosetupmerge to "true" will retain the former behavior of only setting up branch.*.merge for remote upstream branches. Includes test cases for the new functionality. Signed-off-by: Jay Soffian Signed-off-by: Junio C Hamano diff --git a/branch.c b/branch.c index 1fc8788..daf862e 100644 --- a/branch.c +++ b/branch.c @@ -37,7 +37,8 @@ static int find_tracked_branch(struct remote *remote, void *priv) * to infer the settings for branch..{remote,merge} from the * config. */ -static int setup_tracking(const char *new_ref, const char *orig_ref) +static int setup_tracking(const char *new_ref, const char *orig_ref, + enum branch_track track) { char key[1024]; struct tracking tracking; @@ -48,30 +49,36 @@ static int setup_tracking(const char *new_ref, const char *orig_ref) memset(&tracking, 0, sizeof(tracking)); tracking.spec.dst = (char *)orig_ref; - if (for_each_remote(find_tracked_branch, &tracking) || - !tracking.matches) + if (for_each_remote(find_tracked_branch, &tracking)) return 1; + if (!tracking.matches) + switch (track) { + case BRANCH_TRACK_ALWAYS: + case BRANCH_TRACK_EXPLICIT: + break; + default: + return 1; + } + if (tracking.matches > 1) return error("Not tracking: ambiguous information for ref %s", orig_ref); - if (tracking.matches == 1) { - sprintf(key, "branch.%s.remote", new_ref); - git_config_set(key, tracking.remote ? tracking.remote : "."); - sprintf(key, "branch.%s.merge", new_ref); - git_config_set(key, tracking.src); - free(tracking.src); - printf("Branch %s set up to track remote branch %s.\n", - new_ref, orig_ref); - } + sprintf(key, "branch.%s.remote", new_ref); + git_config_set(key, tracking.remote ? tracking.remote : "."); + sprintf(key, "branch.%s.merge", new_ref); + git_config_set(key, tracking.src ? tracking.src : orig_ref); + free(tracking.src); + printf("Branch %s set up to track %s branch %s.\n", new_ref, + tracking.remote ? "remote" : "local", orig_ref); return 0; } void create_branch(const char *head, const char *name, const char *start_name, - int force, int reflog, int track) + int force, int reflog, enum branch_track track) { struct ref_lock *lock; struct commit *commit; @@ -98,7 +105,8 @@ void create_branch(const char *head, switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) { case 0: /* Not branching from any existing branch */ - real_ref = NULL; + if (track == BRANCH_TRACK_EXPLICIT) + die("Cannot setup tracking information; starting point is not a branch."); break; case 1: /* Unique completion -- good */ @@ -126,17 +134,13 @@ void create_branch(const char *head, snprintf(msg, sizeof msg, "branch: Created from %s", start_name); - /* When branching off a remote branch, set up so that git-pull - automatically merges from there. So far, this is only done for - remotes registered via .git/config. */ if (real_ref && track) - setup_tracking(name, real_ref); + setup_tracking(name, real_ref, track); if (write_ref_sha1(lock, sha1, msg) < 0) die("Failed to write ref: %s.", strerror(errno)); - if (real_ref) - free(real_ref); + free(real_ref); } void remove_branch_state(void) diff --git a/branch.h b/branch.h index d30abe0..9f0c2a2 100644 --- a/branch.h +++ b/branch.h @@ -13,7 +13,7 @@ * branch for (if any). */ void create_branch(const char *head, const char *name, const char *start_name, - int force, int reflog, int track); + int force, int reflog, enum branch_track track); /* * Remove information about the state of working on the current diff --git a/builtin-branch.c b/builtin-branch.c index 1e0c9de..32eaf0d 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -30,8 +30,6 @@ static const char * const builtin_branch_usage[] = { static const char *head; static unsigned char head_sha1[20]; -static int branch_track = 1; - static int branch_use_color; static char branch_colors[][COLOR_MAXLEN] = { "\033[m", /* reset */ @@ -74,9 +72,6 @@ static int git_branch_config(const char *var, const char *value) color_parse(value, var, branch_colors[slot]); return 0; } - if (!strcmp(var, "branch.autosetupmerge")) - branch_track = git_config_bool(var, value); - return git_default_config(var, value); } @@ -417,14 +412,16 @@ int cmd_branch(int argc, const char **argv, const char *prefix) { int delete = 0, rename = 0, force_create = 0; int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0; - int reflog = 0, track; + int reflog = 0; + enum branch_track track; int kinds = REF_LOCAL_BRANCH; struct commit_list *with_commit = NULL; struct option options[] = { OPT_GROUP("Generic options"), OPT__VERBOSE(&verbose), - OPT_BOOLEAN( 0 , "track", &track, "set up tracking mode (see git-pull(1))"), + OPT_SET_INT( 0 , "track", &track, "set up tracking mode (see git-pull(1))", + BRANCH_TRACK_EXPLICIT), OPT_BOOLEAN( 0 , "color", &branch_use_color, "use colored output"), OPT_SET_INT('r', NULL, &kinds, "act on remote-tracking branches", REF_REMOTE_BRANCH), @@ -451,7 +448,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix) }; git_config(git_branch_config); - track = branch_track; + 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); diff --git a/builtin-checkout.c b/builtin-checkout.c index 5291f72..b1820a4 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -186,7 +186,7 @@ struct checkout_opts { char *new_branch; int new_branch_log; - int track; + enum branch_track track; }; struct branch_info { @@ -457,13 +457,8 @@ static int switch_branches(struct checkout_opts *opts, return post_checkout_hook(old.commit, new->commit, 1); } -static int branch_track = 0; - static int git_checkout_config(const char *var, const char *value) { - if (!strcmp(var, "branch.autosetupmerge")) - branch_track = git_config_bool(var, value); - return git_default_config(var, value); } @@ -478,7 +473,8 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) OPT__QUIET(&opts.quiet), OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"), OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"), - OPT_BOOLEAN( 0 , "track", &opts.track, "track"), + OPT_SET_INT( 0 , "track", &opts.track, "track", + BRANCH_TRACK_EXPLICIT), OPT_BOOLEAN('f', NULL, &opts.force, "force"), OPT_BOOLEAN('m', NULL, &opts.merge, "merge"), OPT_END(), @@ -489,7 +485,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) git_config(git_checkout_config); - opts.track = branch_track; + opts.track = git_branch_track; argc = parse_options(argc, argv, options, checkout_usage, 0); if (argc) { @@ -518,7 +514,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) argc--; } - if (!opts.new_branch && (opts.track != branch_track)) + if (!opts.new_branch && (opts.track != git_branch_track)) die("git checkout: --track and --no-track require -b"); if (opts.force && opts.merge) diff --git a/cache.h b/cache.h index 888895a..0cd1368 100644 --- a/cache.h +++ b/cache.h @@ -373,6 +373,15 @@ extern size_t packed_git_limit; extern size_t delta_base_cache_limit; extern int auto_crlf; +enum branch_track { + BRANCH_TRACK_NEVER = 0, + BRANCH_TRACK_REMOTE, + BRANCH_TRACK_ALWAYS, + BRANCH_TRACK_EXPLICIT, +}; + +extern enum branch_track git_branch_track; + #define GIT_REPO_VERSION 0 extern int repository_format_version; extern int check_repository_format(void); diff --git a/config.c b/config.c index 526a3f4..97d7505 100644 --- a/config.c +++ b/config.c @@ -454,6 +454,14 @@ int git_default_config(const char *var, const char *value) whitespace_rule_cfg = parse_whitespace_rule(value); return 0; } + if (!strcmp(var, "branch.autosetupmerge")) { + if (value && !strcasecmp(value, "always")) { + git_branch_track = BRANCH_TRACK_ALWAYS; + return 0; + } + git_branch_track = git_config_bool(var, value); + return 0; + } /* Add other config variables here and to Documentation/config.txt. */ return 0; diff --git a/environment.c b/environment.c index 18a1c4e..1f74b4b 100644 --- a/environment.c +++ b/environment.c @@ -36,6 +36,7 @@ char *editor_program; char *excludes_file; int auto_crlf = 0; /* 1: both ways, -1: only when adding git objects */ unsigned whitespace_rule_cfg = WS_DEFAULT_RULE; +enum branch_track git_branch_track = BRANCH_TRACK_REMOTE; /* This is set by setup_git_dir_gently() and/or git_default_config() */ char *git_work_tree_cfg; diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh index ef1eeb7..900d814 100755 --- a/t/t3200-branch.sh +++ b/t/t3200-branch.sh @@ -15,6 +15,9 @@ test_expect_success \ 'echo Hello > A && git update-index --add A && git-commit -m "Initial commit." && + echo World >> A && + git update-index --add A && + git-commit -m "Second commit." && HEAD=$(git rev-parse --verify HEAD)' test_expect_failure \ @@ -169,7 +172,9 @@ test_expect_success 'test overriding tracking setup via --no-track' \ ! test "$(git config branch.my2.merge)" = refs/heads/master' test_expect_success 'no tracking without .fetch entries' \ - 'git branch --track my6 s && + 'git config branch.autosetupmerge true && + git branch my6 s && + git config branch.automsetupmerge false && test -z "$(git config branch.my6.remote)" && test -z "$(git config branch.my6.merge)"' @@ -190,6 +195,21 @@ test_expect_success 'test deleting branch without config' \ 'git branch my7 s && test "$(git branch -d my7 2>&1)" = "Deleted branch my7."' +test_expect_success 'test --track without .fetch entries' \ + 'git branch --track my8 && + test "$(git config branch.my8.remote)" && + test "$(git config branch.my8.merge)"' + +test_expect_success \ + 'branch from non-branch HEAD w/autosetupmerge=always' \ + 'git config branch.autosetupmerge always && + git branch my9 HEAD^ && + git config branch.autosetupmerge false' + +test_expect_success \ + 'branch from non-branch HEAD w/--track causes failure' \ + '!(git branch --track my10 HEAD^)' + # Keep this test last, as it changes the current branch cat >expect < 1117150200 +0000 branch: Created from master diff --git a/t/t7201-co.sh b/t/t7201-co.sh index 5492f21..17cff8d 100755 --- a/t/t7201-co.sh +++ b/t/t7201-co.sh @@ -263,4 +263,28 @@ test_expect_success 'checkout with ambiguous tag/branch names' ' ' +test_expect_success \ + 'checkout w/--track sets up tracking' ' + git config branch.autosetupmerge false && + git checkout master && + git checkout --track -b track1 && + test "$(git config branch.track1.remote)" && + test "$(git config branch.track1.merge)"' + +test_expect_success \ + 'checkout w/autosetupmerge=always sets up tracking' ' + git config branch.autosetupmerge always && + git checkout master && + git checkout -b track2 && + test "$(git config branch.track2.remote)" && + test "$(git config branch.track2.merge)" + git config branch.autosetupmerge false' + +test_expect_success \ + 'checkout w/--track from non-branch HEAD fails' ' + git checkout -b delete-me master && + rm .git/refs/heads/delete-me && + test refs/heads/delete-me = "$(git symbolic-ref HEAD)" && + !(git checkout --track -b track)' + test_done -- cgit v0.10.2-6-g49f6 From 572fc81d21b26d856dd3c2cc366b7452a4ed16e4 Mon Sep 17 00:00:00 2001 From: Jay Soffian Date: Tue, 19 Feb 2008 11:24:38 -0500 Subject: doc: documentation update for the branch track changes Documents the branch.autosetupmerge=always setting and usage of --track when branching from a local branch. Signed-off-by: Jay Soffian Signed-off-by: Junio C Hamano diff --git a/Documentation/config.txt b/Documentation/config.txt index 877eda9..f5994bd 100644 --- a/Documentation/config.txt +++ b/Documentation/config.txt @@ -330,10 +330,14 @@ apply.whitespace:: branch.autosetupmerge:: Tells `git-branch` and `git-checkout` to setup new branches - so that linkgit:git-pull[1] will appropriately merge from that - remote branch. Note that even if this option is not set, + so that linkgit:git-pull[1] will appropriately merge from the + starting point branch. Note that even if this option is not set, this behavior can be chosen per-branch using the `--track` - and `--no-track` options. This option defaults to false. + and `--no-track` options. The valid settings are: `false` -- no + automatic setup is done; `true` -- automatic setup is done when the + starting point is a remote branch; `always` -- automatic setup is + done when the starting point is either a local branch or remote + branch. This option defaults to true. branch..remote:: When in branch , it tells `git fetch` which remote to fetch. diff --git a/Documentation/git-branch.txt b/Documentation/git-branch.txt index f920c04..6f07a17 100644 --- a/Documentation/git-branch.txt +++ b/Documentation/git-branch.txt @@ -34,12 +34,11 @@ Note that this will create the new branch, but it will not switch the working tree to it; use "git checkout " to switch to the new branch. -When a local branch is started off a remote branch, git can setup the -branch so that linkgit:git-pull[1] will appropriately merge from that -remote branch. If this behavior is desired, it is possible to make it -the default using the global `branch.autosetupmerge` configuration -flag. Otherwise, it can be chosen per-branch using the `--track` -and `--no-track` options. +When a local branch is started off a remote branch, git sets up the +branch so that linkgit:git-pull[1] will appropriately merge from +the remote branch. This behavior may be changed via the global +`branch.autosetupmerge` configuration flag. That setting can be +overridden by using the `--track` and `--no-track` options. With a '-m' or '-M' option, will be renamed to . If had a corresponding reflog, it is renamed to match @@ -105,19 +104,19 @@ OPTIONS Display the full sha1s in output listing rather than abbreviating them. --track:: - Set up configuration so that git-pull will automatically - retrieve data from the remote branch. Use this if you always - pull from the same remote branch into the new branch, or if you - don't want to use "git pull " explicitly. Set the - branch.autosetupmerge configuration variable to true if you - want git-checkout and git-branch to always behave as if - '--track' were given. + When creating a new branch, set up configuration so that git-pull + will automatically retrieve data from the start point, which must be + a branch. Use this if you always pull from the same upstream branch + into the new branch, and if you don't want to use "git pull + " explicitly. This behavior is the default + when the start point is a remote branch. Set the + branch.autosetupmerge configuration variable to `false` if you want + git-checkout and git-branch to always behave as if '--no-track' were + given. Set it to `always` if you want this behavior when the + start-point is either a local or remote branch. --no-track:: - When a branch is created off a remote branch, - set up configuration so that git-pull will not retrieve data - from the remote branch, ignoring the branch.autosetupmerge - configuration variable. + Ignore the branch.autosetupmerge configuration variable. :: The name of the branch to create or delete. diff --git a/Documentation/git-checkout.txt b/Documentation/git-checkout.txt index 584359f..4014e72 100644 --- a/Documentation/git-checkout.txt +++ b/Documentation/git-checkout.txt @@ -48,20 +48,19 @@ OPTIONS may restrict the characters allowed in a branch name. --track:: - When -b is given and a branch is created off a remote branch, - set up configuration so that git-pull will automatically - retrieve data from the remote branch. Use this if you always - pull from the same remote branch into the new branch, or if you - don't want to use "git pull " explicitly. Set the - branch.autosetupmerge configuration variable to true if you - want git-checkout and git-branch to always behave as if - '--track' were given. + When creating a new branch, set up configuration so that git-pull + will automatically retrieve data from the start point, which must be + a branch. Use this if you always pull from the same upstream branch + into the new branch, and if you don't want to use "git pull + " explicitly. This behavior is the default + when the start point is a remote branch. Set the + branch.autosetupmerge configuration variable to `false` if you want + git-checkout and git-branch to always behave as if '--no-track' were + given. Set it to `always` if you want this behavior when the + start-point is either a local or remote branch. --no-track:: - When -b is given and a branch is created off a remote branch, - set up configuration so that git-pull will not retrieve data - from the remote branch, ignoring the branch.autosetupmerge - configuration variable. + Ignore the branch.autosetupmerge configuration variable. -l:: Create the new branch's reflog. This activates recording of -- cgit v0.10.2-6-g49f6 From a5a27c79b7e77e28462b6d089e827391b67d3e5f Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 18 Feb 2008 22:56:13 -0500 Subject: Add a --cover-letter option to format-patch If --cover-letter is provided, generate a cover letter message before the patches, numbered 0. Original patch thanks to Johannes Schindelin Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/Documentation/git-format-patch.txt b/Documentation/git-format-patch.txt index 651efe6..b27bb94 100644 --- a/Documentation/git-format-patch.txt +++ b/Documentation/git-format-patch.txt @@ -10,13 +10,14 @@ SYNOPSIS -------- [verse] 'git-format-patch' [-k] [-o | --stdout] [--thread] - [--attach[=] | --inline[=]] - [-s | --signoff] [] - [-n | --numbered | -N | --no-numbered] - [--start-number ] [--numbered-files] - [--in-reply-to=Message-Id] [--suffix=.] - [--ignore-if-in-upstream] - [--subject-prefix=Subject-Prefix] + [--attach[=] | --inline[=]] + [-s | --signoff] [] + [-n | --numbered | -N | --no-numbered] + [--start-number ] [--numbered-files] + [--in-reply-to=Message-Id] [--suffix=.] + [--ignore-if-in-upstream] + [--subject-prefix=Subject-Prefix] + [--cover-letter] [ | ] DESCRIPTION @@ -135,6 +136,11 @@ include::diff-options.txt[] allows for useful naming of a patch series, and can be combined with the --numbered option. +--cover-letter:: + Generate a cover letter template. You still have to fill in + a description, but the shortlog and the diffstat will be + generated for you. + --suffix=.:: Instead of using `.patch` as the suffix for generated filenames, use specified suffix. A common alternative is diff --git a/builtin-log.c b/builtin-log.c index 4f08ca4..3dc7650 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -14,6 +14,7 @@ #include "reflog-walk.h" #include "patch-ids.h" #include "refs.h" +#include "run-command.h" static int default_show_root = 1; static const char *fmt_patch_subject_prefix = "PATCH"; @@ -452,74 +453,81 @@ static int git_format_config(const char *var, const char *value) } +static const char *get_oneline_for_filename(struct commit *commit, + int keep_subject) +{ + static char filename[PATH_MAX]; + char *sol; + int len = 0; + int suffix_len = strlen(fmt_patch_suffix) + 1; + + sol = strstr(commit->buffer, "\n\n"); + if (!sol) + filename[0] = '\0'; + else { + int j, space = 0; + + sol += 2; + /* strip [PATCH] or [PATCH blabla] */ + if (!keep_subject && !prefixcmp(sol, "[PATCH")) { + char *eos = strchr(sol + 6, ']'); + if (eos) { + while (isspace(*eos)) + eos++; + sol = eos; + } + } + + for (j = 0; + j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 && + len < sizeof(filename) - suffix_len && + sol[j] && sol[j] != '\n'; + j++) { + if (istitlechar(sol[j])) { + if (space) { + filename[len++] = '-'; + space = 0; + } + filename[len++] = sol[j]; + if (sol[j] == '.') + while (sol[j + 1] == '.') + j++; + } else + space = 1; + } + while (filename[len - 1] == '.' + || filename[len - 1] == '-') + len--; + filename[len] = '\0'; + } + return filename; +} + static FILE *realstdout = NULL; static const char *output_directory = NULL; -static int reopen_stdout(struct commit *commit, int nr, int keep_subject, - int numbered_files) +static int reopen_stdout(const char *oneline, int nr, int total) { char filename[PATH_MAX]; - char *sol; int len = 0; int suffix_len = strlen(fmt_patch_suffix) + 1; if (output_directory) { - if (strlen(output_directory) >= + len = snprintf(filename, sizeof(filename), "%s", + output_directory); + if (len >= sizeof(filename) - FORMAT_PATCH_NAME_MAX - suffix_len) return error("name of output directory is too long"); - strlcpy(filename, output_directory, sizeof(filename) - suffix_len); - len = strlen(filename); if (filename[len - 1] != '/') filename[len++] = '/'; } - if (numbered_files) { - sprintf(filename + len, "%d", nr); - len = strlen(filename); - - } else { - sprintf(filename + len, "%04d", nr); - len = strlen(filename); - - sol = strstr(commit->buffer, "\n\n"); - if (sol) { - int j, space = 1; - - sol += 2; - /* strip [PATCH] or [PATCH blabla] */ - if (!keep_subject && !prefixcmp(sol, "[PATCH")) { - char *eos = strchr(sol + 6, ']'); - if (eos) { - while (isspace(*eos)) - eos++; - sol = eos; - } - } - - for (j = 0; - j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 && - len < sizeof(filename) - suffix_len && - sol[j] && sol[j] != '\n'; - j++) { - if (istitlechar(sol[j])) { - if (space) { - filename[len++] = '-'; - space = 0; - } - filename[len++] = sol[j]; - if (sol[j] == '.') - while (sol[j + 1] == '.') - j++; - } else - space = 1; - } - while (filename[len - 1] == '.' - || filename[len - 1] == '-') - len--; - filename[len] = 0; - } - if (len + suffix_len >= sizeof(filename)) - return error("Patch pathname too long"); + if (!oneline) + len += sprintf(filename + len, "%d", nr); + else { + len += sprintf(filename + len, "%04d-", nr); + len += snprintf(filename + len, sizeof(filename) - len - 1 + - suffix_len, "%s", oneline); strcpy(filename + len, fmt_patch_suffix); } @@ -590,6 +598,76 @@ static void gen_message_id(struct rev_info *info, char *base) info->message_id = strbuf_detach(&buf, NULL); } +static void make_cover_letter(struct rev_info *rev, + int use_stdout, int numbered, int numbered_files, + struct commit *origin, struct commit *head) +{ + const char *committer; + const char *origin_sha1, *head_sha1; + const char *argv[7]; + const char *subject_start = NULL; + const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n"; + const char *msg; + const char *extra_headers = rev->extra_headers; + struct strbuf sb; + const char *encoding = "utf-8"; + + if (rev->commit_format != CMIT_FMT_EMAIL) + die("Cover letter needs email format"); + + if (!use_stdout && reopen_stdout(numbered_files ? + NULL : "cover-letter", 0, rev->total)) + return; + + origin_sha1 = sha1_to_hex(origin ? origin->object.sha1 : null_sha1); + head_sha1 = sha1_to_hex(head->object.sha1); + + log_write_email_headers(rev, head_sha1, &subject_start, &extra_headers); + + committer = git_committer_info(0); + + msg = body; + strbuf_init(&sb, 0); + pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822, + encoding); + pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers, + encoding, 0); + pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0); + printf("%s\n", sb.buf); + + strbuf_release(&sb); + + /* + * We can only do diffstat with a unique reference point, and + * log is a bit tricky, so just skip it. + */ + if (!origin) + return; + + argv[0] = "shortlog"; + argv[1] = head_sha1; + argv[2] = "--not"; + argv[3] = origin_sha1; + argv[4] = "--"; + argv[5] = NULL; + fflush(stdout); + run_command_v_opt(argv, RUN_GIT_CMD); + + argv[0] = "diff"; + argv[1] = "--stat"; + argv[2] = "--summary"; + argv[3] = head_sha1; + argv[4] = "--not"; + argv[5] = origin_sha1; + argv[6] = "--"; + argv[7] = NULL; + fflush(stdout); + run_command_v_opt(argv, RUN_GIT_CMD); + + fflush(stdout); + printf("\n"); +} + static const char *clean_message_id(const char *msg_id) { char ch; @@ -625,6 +703,8 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) int subject_prefix = 0; int ignore_if_in_upstream = 0; int thread = 0; + int cover_letter = 0; + struct commit *origin = NULL, *head = NULL; const char *in_reply_to = NULL; struct patch_ids ids; char *add_signoff = NULL; @@ -724,6 +804,8 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) rev.subject_prefix = argv[i] + 17; } else if (!prefixcmp(argv[i], "--suffix=")) fmt_patch_suffix = argv[i] + 9; + else if (!strcmp(argv[i], "--cover-letter")) + cover_letter = 1; else argv[j++] = argv[i]; } @@ -775,6 +857,25 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) * get_revision() to do the usual traversal. */ } + if (cover_letter) { + /* remember the range */ + int negative_count = 0; + int i; + for (i = 0; i < rev.pending.nr; i++) { + struct object *o = rev.pending.objects[i].item; + if (o->flags & UNINTERESTING) { + origin = (struct commit *)o; + negative_count++; + } else + head = (struct commit *)o; + } + /* Multiple origins don't work for diffstat. */ + if (negative_count > 1) + origin = NULL; + /* We can't generate a cover letter without any patches */ + if (!head) + return 0; + } if (ignore_if_in_upstream) get_patch_ids(&rev, &ids, prefix); @@ -801,16 +902,31 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) numbered = 1; if (numbered) rev.total = total + start_number - 1; - rev.add_signoff = add_signoff; if (in_reply_to) rev.ref_message_id = clean_message_id(in_reply_to); + if (cover_letter) { + if (thread) + gen_message_id(&rev, "cover"); + make_cover_letter(&rev, use_stdout, numbered, numbered_files, + origin, head); + total++; + start_number--; + } + rev.add_signoff = add_signoff; while (0 <= --nr) { int shown; commit = list[nr]; rev.nr = total - nr + (start_number - 1); /* Make the second and subsequent mails replies to the first */ if (thread) { + /* Have we already had a message ID? */ if (rev.message_id) { + /* + * If we've got the ID to be a reply + * to, discard the current ID; + * otherwise, make everything a reply + * to that. + */ if (rev.ref_message_id) free(rev.message_id); else @@ -818,10 +934,10 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) } gen_message_id(&rev, sha1_to_hex(commit->object.sha1)); } - if (!use_stdout) - if (reopen_stdout(commit, rev.nr, keep_subject, - numbered_files)) - die("Failed to create output files"); + if (!use_stdout && reopen_stdout(numbered_files ? NULL : + get_oneline_for_filename(commit, keep_subject), + rev.nr, rev.total)) + die("Failed to create output files"); shown = log_tree_commit(&rev, commit); free(commit->buffer); commit->buffer = NULL; diff --git a/t/t4013-diff-various.sh b/t/t4013-diff-various.sh index 9eec754..6b4d1c5 100755 --- a/t/t4013-diff-various.sh +++ b/t/t4013-diff-various.sh @@ -245,6 +245,7 @@ format-patch --inline --stdout initial..master format-patch --inline --stdout --subject-prefix=TESTCASE initial..master config format.subjectprefix DIFFERENT_PREFIX format-patch --inline --stdout initial..master^^ +format-patch --stdout --cover-letter -n initial..master^ diff --abbrev initial..side diff -r initial..side diff --git a/t/t4013/diff.format-patch_--stdout_--cover-letter_-n_initial..master^ b/t/t4013/diff.format-patch_--stdout_--cover-letter_-n_initial..master^ new file mode 100644 index 0000000..0151453 --- /dev/null +++ b/t/t4013/diff.format-patch_--stdout_--cover-letter_-n_initial..master^ @@ -0,0 +1,100 @@ +$ git format-patch --stdout --cover-letter -n initial..master^ +From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 +From: C O Mitter +Date: Mon, 26 Jun 2006 00:05:00 +0000 +Subject: [DIFFERENT_PREFIX 0/2] *** SUBJECT HERE *** + +*** BLURB HERE *** + +A U Thor (2): + Second + Third + + dir/sub | 4 ++++ + file0 | 3 +++ + file1 | 3 +++ + file2 | 3 --- + 4 files changed, 10 insertions(+), 3 deletions(-) + create mode 100644 file1 + delete mode 100644 file2 + +From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 +From: A U Thor +Date: Mon, 26 Jun 2006 00:01:00 +0000 +Subject: [DIFFERENT_PREFIX 1/2] Second + +This is the second commit. +--- + dir/sub | 2 ++ + file0 | 3 +++ + file2 | 3 --- + 3 files changed, 5 insertions(+), 3 deletions(-) + delete mode 100644 file2 + +diff --git a/dir/sub b/dir/sub +index 35d242b..8422d40 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -1,2 +1,4 @@ + A + B ++C ++D +diff --git a/file0 b/file0 +index 01e79c3..b414108 100644 +--- a/file0 ++++ b/file0 +@@ -1,3 +1,6 @@ + 1 + 2 + 3 ++4 ++5 ++6 +diff --git a/file2 b/file2 +deleted file mode 100644 +index 01e79c3..0000000 +--- a/file2 ++++ /dev/null +@@ -1,3 +0,0 @@ +-1 +-2 +-3 +-- +g-i-t--v-e-r-s-i-o-n + + +From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 +From: A U Thor +Date: Mon, 26 Jun 2006 00:02:00 +0000 +Subject: [DIFFERENT_PREFIX 2/2] Third + +--- + dir/sub | 2 ++ + file1 | 3 +++ + 2 files changed, 5 insertions(+), 0 deletions(-) + create mode 100644 file1 + +diff --git a/dir/sub b/dir/sub +index 8422d40..cead32e 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -2,3 +2,5 @@ A + B + C + D ++E ++F +diff --git a/file1 b/file1 +new file mode 100644 +index 0000000..b1e6722 +--- /dev/null ++++ b/file1 +@@ -0,0 +1,3 @@ ++A ++B ++C +-- +g-i-t--v-e-r-s-i-o-n + +$ diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index 6e8b5f4..ac78752 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -122,6 +122,32 @@ test_expect_success 'thread in-reply-to' ' done ' +test_expect_success 'thread cover-letter' ' + + rm -rf patches/ && + git checkout side && + git format-patch --cover-letter --thread -o patches/ master && + FIRST_MID=$(grep "Message-Id:" patches/0000-* | sed "s/^[^<]*\(<[^>]*>\).*$/\1/") && + for i in patches/0001-* patches/0002-* patches/0003-* + do + grep "References: $FIRST_MID" $i && + grep "In-Reply-To: $FIRST_MID" $i + done +' + +test_expect_success 'thread cover-letter in-reply-to' ' + + rm -rf patches/ && + git checkout side && + git format-patch --cover-letter --in-reply-to="" --thread -o patches/ master && + FIRST_MID="" && + for i in patches/* + do + grep "References: $FIRST_MID" $i && + grep "In-Reply-To: $FIRST_MID" $i + done +' + test_expect_success 'excessive subject' ' rm -rf patches/ && -- cgit v0.10.2-6-g49f6 From a8d8173e6c7ff85627377389e40844ec71206f5e Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Tue, 19 Feb 2008 02:40:28 -0500 Subject: Add tests for extra headers in format-patch Presently, it works with each header ending with a newline, but not without the newlines. Also add a test to see that multiple "To:" headers get combined. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index ac78752..28ab7b9 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -88,6 +88,40 @@ test_expect_success 'replay did not screw up the log message' ' ' +test_expect_success 'extra headers' ' + + git config format.headers "To: R. E. Cipient +" && + git config --add format.headers "Cc: S. E. Cipient +" && + git format-patch --stdout master..side > patch2 && + sed -e "/^$/Q" patch2 > hdrs2 && + grep "^To: R. E. Cipient $" hdrs2 && + grep "^Cc: S. E. Cipient $" hdrs2 + +' + +test_expect_failure 'extra headers without newlines' ' + + git config --replace-all format.headers "To: R. E. Cipient " && + git config --add format.headers "Cc: S. E. Cipient " && + git format-patch --stdout master..side >patch3 && + sed -e "/^$/Q" patch3 > hdrs3 && + grep "^To: R. E. Cipient $" hdrs3 && + grep "^Cc: S. E. Cipient $" hdrs3 + +' + +test_expect_failure 'extra headers with multiple To:s' ' + + git config --replace-all format.headers "To: R. E. Cipient " && + git config --add format.headers "To: S. E. Cipient " && + git format-patch --stdout master..side > patch4 && + sed -e "/^$/Q" patch4 > hdrs4 && + grep "^To: R. E. Cipient ,$" hdrs4 && + grep "^ *S. E. Cipient $" hdrs4 +' + test_expect_success 'multiple files' ' rm -rf patches/ && -- cgit v0.10.2-6-g49f6 From 7d22708b254d4ec28cd865dc5489d175ee6d65c2 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Tue, 19 Feb 2008 02:40:31 -0500 Subject: Fix format.headers not ending with a newline Now each value of format.headers will always be treated as a single valid header, and newlines will be inserted between them as needed. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-log.c b/builtin-log.c index 3dc7650..fe1a2d7 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -425,10 +425,14 @@ static int git_format_config(const char *var, const char *value) if (!value) die("format.headers without value"); len = strlen(value); - extra_headers_size += len + 1; + while (value[len - 1] == '\n') + len--; + extra_headers_size += len + 2; extra_headers = xrealloc(extra_headers, extra_headers_size); - extra_headers[extra_headers_size - len - 1] = 0; + extra_headers[extra_headers_size - len - 2] = 0; strcat(extra_headers, value); + extra_headers[extra_headers_size - 2] = '\n'; + extra_headers[extra_headers_size - 1] = 0; return 0; } if (!strcmp(var, "format.suffix")) { diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index 28ab7b9..755fe6d 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -101,7 +101,7 @@ test_expect_success 'extra headers' ' ' -test_expect_failure 'extra headers without newlines' ' +test_expect_success 'extra headers without newlines' ' git config --replace-all format.headers "To: R. E. Cipient " && git config --add format.headers "Cc: S. E. Cipient " && -- cgit v0.10.2-6-g49f6 From 3ee79d9f59684778151804c02cc6ad155b30efde Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Tue, 19 Feb 2008 02:40:33 -0500 Subject: Combine To: and Cc: headers RFC 2822 only permits a single To: header and a single Cc: header, so we need to turn multiple values of each of these into a list. This will be particularly significant with a command-line option to add Cc: headers, where the user can't make sure to configure valid header sets in any easy way. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-log.c b/builtin-log.c index fe1a2d7..71ae55b 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -411,28 +411,47 @@ static int istitlechar(char c) (c >= '0' && c <= '9') || c == '.' || c == '_'; } -static char *extra_headers = NULL; -static int extra_headers_size = 0; static const char *fmt_patch_suffix = ".patch"; static int numbered = 0; static int auto_number = 0; +static char **extra_hdr; +static int extra_hdr_nr; +static int extra_hdr_alloc; + +static char **extra_to; +static int extra_to_nr; +static int extra_to_alloc; + +static char **extra_cc; +static int extra_cc_nr; +static int extra_cc_alloc; + +static void add_header(const char *value) +{ + int len = strlen(value); + while (value[len - 1] == '\n') + len--; + if (!strncasecmp(value, "to: ", 4)) { + ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc); + extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4); + return; + } + if (!strncasecmp(value, "cc: ", 4)) { + ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc); + extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4); + return; + } + ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc); + extra_hdr[extra_hdr_nr++] = xstrndup(value, len); +} + static int git_format_config(const char *var, const char *value) { if (!strcmp(var, "format.headers")) { - int len; - if (!value) die("format.headers without value"); - len = strlen(value); - while (value[len - 1] == '\n') - len--; - extra_headers_size += len + 2; - extra_headers = xrealloc(extra_headers, extra_headers_size); - extra_headers[extra_headers_size - len - 2] = 0; - strcat(extra_headers, value); - extra_headers[extra_headers_size - 2] = '\n'; - extra_headers[extra_headers_size - 1] = 0; + add_header(value); return 0; } if (!strcmp(var, "format.suffix")) { @@ -712,6 +731,7 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) const char *in_reply_to = NULL; struct patch_ids ids; char *add_signoff = NULL; + struct strbuf buf; git_config(git_format_config); init_revisions(&rev, prefix); @@ -724,7 +744,6 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) DIFF_OPT_SET(&rev.diffopt, RECURSIVE); rev.subject_prefix = fmt_patch_subject_prefix; - rev.extra_headers = extra_headers; /* * Parse the arguments before setup_revisions(), or something @@ -815,6 +834,37 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) } argc = j; + strbuf_init(&buf, 0); + + for (i = 0; i < extra_hdr_nr; i++) { + strbuf_addstr(&buf, extra_hdr[i]); + strbuf_addch(&buf, '\n'); + } + + if (extra_to_nr) + strbuf_addstr(&buf, "To: "); + for (i = 0; i < extra_to_nr; i++) { + if (i) + strbuf_addstr(&buf, " "); + strbuf_addstr(&buf, extra_to[i]); + if (i + 1 < extra_to_nr) + strbuf_addch(&buf, ','); + strbuf_addch(&buf, '\n'); + } + + if (extra_cc_nr) + strbuf_addstr(&buf, "Cc: "); + for (i = 0; i < extra_cc_nr; i++) { + if (i) + strbuf_addstr(&buf, " "); + strbuf_addstr(&buf, extra_cc[i]); + if (i + 1 < extra_cc_nr) + strbuf_addch(&buf, ','); + strbuf_addch(&buf, '\n'); + } + + rev.extra_headers = strbuf_detach(&buf, 0); + if (start_number < 0) start_number = 1; if (numbered && keep_subject) diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index 755fe6d..43d8841 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -112,7 +112,7 @@ test_expect_success 'extra headers without newlines' ' ' -test_expect_failure 'extra headers with multiple To:s' ' +test_expect_success 'extra headers with multiple To:s' ' git config --replace-all format.headers "To: R. E. Cipient " && git config --add format.headers "To: S. E. Cipient " && -- cgit v0.10.2-6-g49f6 From 736cc67dd7f4f8004215e24f876178e6f34c191d Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Tue, 19 Feb 2008 02:40:35 -0500 Subject: Support a --cc= option in format-patch When you have particular reviewers you want to sent particular series to, it's nice to be able to generate the whole series with them as additional recipients, without configuring them into your general headers or adding them by hand afterwards. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/Documentation/git-format-patch.txt b/Documentation/git-format-patch.txt index b27bb94..b5207b7 100644 --- a/Documentation/git-format-patch.txt +++ b/Documentation/git-format-patch.txt @@ -17,6 +17,7 @@ SYNOPSIS [--in-reply-to=Message-Id] [--suffix=.] [--ignore-if-in-upstream] [--subject-prefix=Subject-Prefix] + [--cc=] [--cover-letter] [ | ] @@ -136,6 +137,10 @@ include::diff-options.txt[] allows for useful naming of a patch series, and can be combined with the --numbered option. +--cc=:: + Add a "Cc:" header to the email headers. This is in addition + to any configured headers, and may be used multiple times. + --cover-letter:: Generate a cover letter template. You still have to fill in a description, but the shortlog and the diffstat will be diff --git a/builtin-log.c b/builtin-log.c index 71ae55b..0b348eb 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -771,6 +771,10 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) die("Need a number for --start-number"); start_number = strtol(argv[i], NULL, 10); } + else if (!prefixcmp(argv[i], "--cc=")) { + ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc); + extra_cc[extra_cc_nr++] = xstrdup(argv[i] + 5); + } else if (!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keep-subject")) { keep_subject = 1; diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index 43d8841..a39e786 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -122,6 +122,14 @@ test_expect_success 'extra headers with multiple To:s' ' grep "^ *S. E. Cipient $" hdrs4 ' +test_expect_success 'additional command line cc' ' + + git config --replace-all format.headers "Cc: R. E. Cipient " && + git format-patch --cc="S. E. Cipient " --stdout master..side | sed -e "/^$/Q" >patch5 && + grep "^Cc: R. E. Cipient ,$" patch5 && + grep "^ *S. E. Cipient $" patch5 +' + test_expect_success 'multiple files' ' rm -rf patches/ && -- cgit v0.10.2-6-g49f6 From 9f0ea7e8283da126c8e1d5e0c3b39c39200258ad Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Wed, 20 Feb 2008 12:54:05 -0500 Subject: Resolve value supplied for no-colon push refspecs When pushing a refspec like "HEAD", we used to treat it as "HEAD:HEAD", which didn't work without rewriting. Instead, we should resolve the ref. If it's a symref, further require it to point to a branch, to avoid doing anything especially unexpected. Also remove the rewriting previously added in builtin-push. Since the code for "HEAD" uses the regular refspec parsing, it automatically handles "+HEAD" without anything special. [jc: added a further test to make sure that "remote.*.push = HEAD" works] Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-push.c b/builtin-push.c index 9f727c0..b68c681 100644 --- a/builtin-push.c +++ b/builtin-push.c @@ -44,15 +44,6 @@ static void set_refspecs(const char **refs, int nr) strcat(tag, refs[i]); ref = tag; } - if (!strcmp("HEAD", ref)) { - unsigned char sha1_dummy[20]; - ref = resolve_ref(ref, sha1_dummy, 1, NULL); - if (!ref) - die("HEAD cannot be resolved."); - if (prefixcmp(ref, "refs/heads/")) - die("HEAD cannot be resolved to branch."); - ref = xstrdup(ref + 11); - } add_refspec(ref); } } diff --git a/remote.c b/remote.c index 6b56473..8ee2487 100644 --- a/remote.c +++ b/remote.c @@ -643,9 +643,17 @@ static int match_explicit(struct ref *src, struct ref *dst, errs = 1; if (!dst_value) { + unsigned char sha1[20]; + int flag; + if (!matched_src) return errs; - dst_value = matched_src->name; + dst_value = resolve_ref(matched_src->name, sha1, 1, &flag); + if (!dst_value || + ((flag & REF_ISSYMREF) && + prefixcmp(dst_value, "refs/heads/"))) + die("%s cannot be resolved to branch.", + matched_src->name); } switch (count_refspec_match(dst_value, dst, &matched_dst)) { diff --git a/t/t5516-fetch-push.sh b/t/t5516-fetch-push.sh index 9d2dc33..b0d97db 100755 --- a/t/t5516-fetch-push.sh +++ b/t/t5516-fetch-push.sh @@ -271,6 +271,49 @@ test_expect_success 'push with HEAD nonexisting at remote' ' check_push_result $the_commit heads/local ' +test_expect_success 'push with +HEAD' ' + + mk_test heads/master && + git checkout master && + git branch -D local && + git checkout -b local && + git push testrepo master local && + check_push_result $the_commit heads/master && + check_push_result $the_commit heads/local && + + # Without force rewinding should fail + git reset --hard HEAD^ && + ! git push testrepo HEAD && + check_push_result $the_commit heads/local && + + # With force rewinding should succeed + git push testrepo +HEAD && + check_push_result $the_first_commit heads/local + +' + +test_expect_success 'push with config remote.*.push = HEAD' ' + + mk_test heads/local && + git checkout master && + git branch -f local $the_commit && + ( + cd testrepo && + git checkout local && + git reset --hard $the_first_commit + ) && + git config remote.there.url testrepo && + git config remote.there.push HEAD && + git config branch.master.remote there && + git push && + check_push_result $the_commit heads/master && + check_push_result $the_first_commit heads/local +' + +# clean up the cruft left with the previous one +git config --remove-section remote.there +git config --remove-section branch.master + test_expect_success 'push with dry-run' ' mk_test heads/master && -- cgit v0.10.2-6-g49f6 From b0030db331141bedfaf02f34a83f18712c0ae011 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 20 Feb 2008 15:05:23 -0800 Subject: checkout: tone down the "forked status" diagnostic messages When checking out a branch that is behind or forked from a branch you are building on top of, we used to show full left-right log but if you already _know_ you have long history since you forked, it is a bit too much. This tones down the message quite a bit, by only showing the number of commits each side has since they diverged. Also the message is not shown at all under --quiet. Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 5291f72..1fc1e56 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -301,64 +301,88 @@ static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *op char *base; unsigned char sha1[20]; struct commit *ours, *theirs; - const char *msgfmt; char symmetric[84]; - int show_log; + struct rev_info revs; + const char *rev_argv[10]; + int rev_argc; + int num_ours, num_theirs; + const char *remote_msg; struct branch *branch = branch_get(NULL); + /* + * Nothing to report unless we are marked to build on top of + * somebody else. + */ if (!branch || !branch->merge) return; - base = branch->merge[0]->dst; - - ours = new->commit; - - sprintf(symmetric, "%s", sha1_to_hex(ours->object.sha1)); - /* - * Ok, it is tracking base; is it ahead of us? + * 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); - - sprintf(symmetric + 40, "...%s", sha1_to_hex(sha1)); + theirs = lookup_commit(sha1); + ours = new->commit; if (!hashcmp(sha1, ours->object.sha1)) return; /* we are the same */ - show_log = 1; - if (in_merge_bases(theirs, &ours, 1)) { - msgfmt = "You are ahead of the tracked branch '%s'\n"; - show_log = 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++; } - else if (in_merge_bases(ours, &theirs, 1)) - msgfmt = "Your branch can be fast-forwarded to the tracked branch '%s'\n"; - else - msgfmt = "Both your branch and the tracked branch '%s' have own changes, you would eventually need to merge\n"; - if (!prefixcmp(base, "refs/remotes/")) + if (!prefixcmp(base, "refs/remotes/")) { + remote_msg = " remote"; base += strlen("refs/remotes/"); - fprintf(stderr, msgfmt, base); - - if (show_log) { - const char *args[32]; - int ac; - - ac = 0; - args[ac++] = "log"; - args[ac++] = "--pretty=oneline"; - args[ac++] = "--abbrev-commit"; - args[ac++] = "--left-right"; - args[ac++] = "--boundary"; - args[ac++] = symmetric; - args[ac++] = "--"; - args[ac] = NULL; - - run_command_v_opt(args, RUN_GIT_CMD); + } 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 of 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); +} static void update_refs_for_switch(struct checkout_opts *opts, struct branch_info *old, @@ -402,7 +426,7 @@ static void update_refs_for_switch(struct checkout_opts *opts, } remove_branch_state(); strbuf_release(&msg); - if (new->path || !strcmp(new->name, "HEAD")) + if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD"))) adjust_to_tracking(new, opts); } -- cgit v0.10.2-6-g49f6 From 6010d2d957fb05838cd3ab887ac261752ff8ff87 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 20 Feb 2008 15:54:54 -0800 Subject: checkout: work from a subdirectory When switching branches from a subdirectory, checkout rewritten in C extracted the toplevel of the tree in there. This should fix it. Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 1fc1e56..f51b77a 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -237,7 +237,6 @@ static int merge_working_tree(struct checkout_opts *opts, topts.dir = xcalloc(1, sizeof(*topts.dir)); topts.dir->show_ignored = 1; topts.dir->exclude_per_dir = ".gitignore"; - topts.prefix = prefix; tree = parse_tree_indirect(old->commit->object.sha1); init_tree_desc(&trees[0], tree->buffer, tree->size); tree = parse_tree_indirect(new->commit->object.sha1); diff --git a/t/t7201-co.sh b/t/t7201-co.sh index 5492f21..0fa9467 100755 --- a/t/t7201-co.sh +++ b/t/t7201-co.sh @@ -263,4 +263,38 @@ test_expect_success 'checkout with ambiguous tag/branch names' ' ' +test_expect_success 'switch branches while in subdirectory' ' + + git reset --hard && + git checkout master && + + mkdir subs && + ( + cd subs && + git checkout side + ) && + ! test -f subs/one && + rm -fr subs + +' + +test_expect_success 'checkout specific path while in subdirectory' ' + + git reset --hard && + git checkout side && + mkdir subs && + >subs/bero && + git add subs/bero && + git commit -m "add subs/bero" && + + git checkout master && + mkdir -p subs && + ( + cd subs && + git checkout side -- bero + ) && + test -f subs/bero + +' + test_done -- cgit v0.10.2-6-g49f6 From aba15f7f592c302196401d17a42c772d744555b4 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Wed, 20 Feb 2008 23:37:07 -0500 Subject: git-gui: Ensure error dialogs always appear over all other windows If we are opening an error dialog we want it to appear above all of the other windows, even those that we may have opened with a grab to make the window modal. Failure to do so may allow an error dialog to open up (and grab focus!) under an existing toplevel, making the user think git-gui has frozen up and is unresponsive, as they cannot get to the dialog. Signed-off-by: Shawn O. Pearce diff --git a/lib/error.tcl b/lib/error.tcl index 0fdd753..45800d5 100644 --- a/lib/error.tcl +++ b/lib/error.tcl @@ -1,6 +1,10 @@ # git-gui branch (create/delete) support # Copyright (C) 2006, 2007 Shawn Pearce +proc _error_parent {} { + return [grab current .] +} + proc error_popup {msg} { set title [appname] if {[reponame] ne {}} { @@ -11,8 +15,8 @@ proc error_popup {msg} { -type ok \ -title [append "$title: " [mc "error"]] \ -message $msg] - if {[winfo ismapped .]} { - lappend cmd -parent . + if {[winfo ismapped [_error_parent]]} { + lappend cmd -parent [_error_parent] } eval $cmd } @@ -27,13 +31,13 @@ proc warn_popup {msg} { -type ok \ -title [append "$title: " [mc "warning"]] \ -message $msg] - if {[winfo ismapped .]} { - lappend cmd -parent . + if {[winfo ismapped [_error_parent]]} { + lappend cmd -parent [_error_parent] } eval $cmd } -proc info_popup {msg {parent .}} { +proc info_popup {msg} { set title [appname] if {[reponame] ne {}} { append title " ([reponame])" @@ -56,8 +60,8 @@ proc ask_popup {msg} { -type yesno \ -title $title \ -message $msg] - if {[winfo ismapped .]} { - lappend cmd -parent . + if {[winfo ismapped [_error_parent]]} { + lappend cmd -parent [_error_parent] } eval $cmd } -- cgit v0.10.2-6-g49f6 From 75ea38df66910dcb9d09f1320ae2787b5bc8211e Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 21 Feb 2008 10:50:42 -0500 Subject: builtin-checkout.c: Remove unused prefix arguments in switch_branches path This path doesn't actually care where in the tree you started out, since it must change the whole thing anyway. With the gratuitous bug removed, the argument is unused. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index f51b77a..e89b8f8 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -205,8 +205,7 @@ static void setup_branch_path(struct branch_info *branch) } static int merge_working_tree(struct checkout_opts *opts, - struct branch_info *old, struct branch_info *new, - const char *prefix) + struct branch_info *old, struct branch_info *new) { int ret; struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file)); @@ -429,8 +428,7 @@ static void update_refs_for_switch(struct checkout_opts *opts, adjust_to_tracking(new, opts); } -static int switch_branches(struct checkout_opts *opts, - struct branch_info *new, const char *prefix) +static int switch_branches(struct checkout_opts *opts, struct branch_info *new) { int ret = 0; struct branch_info old; @@ -471,7 +469,7 @@ static int switch_branches(struct checkout_opts *opts, opts->force = 1; } - ret = merge_working_tree(opts, &old, new, prefix); + ret = merge_working_tree(opts, &old, new); if (ret) return ret; @@ -569,5 +567,5 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) die("Cannot switch branch to a non-commit."); } - return switch_branches(&opts, &new, prefix); + return switch_branches(&opts, &new); } -- cgit v0.10.2-6-g49f6 From b56fca07d2bac20339d59218ab98de38a9363e77 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 20 Feb 2008 19:42:53 -0800 Subject: checkout: updates to tracking report Ask branch_get() for the new branch explicitly instead of letting it return a potentially stale information. Tighten the logic to find the tracking branch to deal better with misconfigured repositories (i.e. branch.*.merge can exist but it may not have a refspec that fetches to .it) Also fixes grammar in a message, as pointed out by Jeff King. The function is about reporting and not automatically fast-forwarding to the upstream, so stop calling it "adjust-to". Signed-off-by: Junio C Hamano Acked-by: Daniel Barkalow diff --git a/builtin-checkout.c b/builtin-checkout.c index e89b8f8..5f176c6 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -289,7 +289,7 @@ static int merge_working_tree(struct checkout_opts *opts, return 0; } -static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *opts) +static void report_tracking(struct branch_info *new, struct checkout_opts *opts) { /* * We have switched to a new branch; is it building on @@ -305,13 +305,13 @@ static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *op int rev_argc; int num_ours, num_theirs; const char *remote_msg; - struct branch *branch = branch_get(NULL); + 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) + if (!branch || !branch->merge || !branch->merge[0] || !branch->merge[0]->dst) return; /* @@ -369,7 +369,7 @@ static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *op remote_msg, base, num_ours, (num_ours == 1) ? "" : "s"); else if (!num_ours) - printf("Your branch is behind of the tracked%s branch '%s' " + printf("Your branch is behind the tracked%s branch '%s' " "by %d commit%s,\n" "and can be fast-forwarded.\n", remote_msg, base, @@ -425,7 +425,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"))) - adjust_to_tracking(new, opts); + report_tracking(new, opts); } static int switch_branches(struct checkout_opts *opts, struct branch_info *new) -- cgit v0.10.2-6-g49f6 From 85ec3e7778c09f5d4f52a29f57c5ecc64070ffd1 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Thu, 21 Feb 2008 12:22:08 -0500 Subject: git-gui: Paper bag fix error dialogs opening over the main window If the main window is the only toplevel we have open then we don't have a valid grab right now, so we need to assume the best toplevel to use for the parent is ".". Signed-off-by: Shawn O. Pearce diff --git a/lib/error.tcl b/lib/error.tcl index 45800d5..08a2462 100644 --- a/lib/error.tcl +++ b/lib/error.tcl @@ -2,7 +2,11 @@ # Copyright (C) 2006, 2007 Shawn Pearce proc _error_parent {} { - return [grab current .] + set p [grab current .] + if {$p eq {}} { + return . + } + return $p } proc error_popup {msg} { -- cgit v0.10.2-6-g49f6 From 651fbba2d36072b2491bc53628159ff4fb3085dc Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Thu, 21 Feb 2008 19:17:27 -0500 Subject: git-gui: Default TCL_PATH to same location as TCLTK_PATH Most users set TCLTK_PATH to tell git-gui where to find wish, but they fail to set TCL_PATH to the same Tcl installation. We use the non-GUI tclsh during builds so headless systems are still able to create an index file and create message files without GNU msgfmt. So it matters to us that we find a working TCL_PATH at build time. If TCL_PATH hasn't been set yet we can take a better guess about what tclsh executable to use by replacing 'wish' in the executable path with 'tclsh'. We only do this replacement on the filename part of the path, just in case the string "wish" appears in the directory paths. Most of the time the tclsh will be installed alongside wish so this replacement is a sensible and safe default. Signed-off-by: Shawn O. Pearce diff --git a/Makefile b/Makefile index 081d755..1ba0e78 100644 --- a/Makefile +++ b/Makefile @@ -92,8 +92,12 @@ ifndef V REMOVE_F1 = && echo ' ' REMOVE `basename "$$dst"` && $(RM_RF) "$$dst" endif -TCL_PATH ?= tclsh TCLTK_PATH ?= wish +ifeq (./,$(dir $(TCLTK_PATH))) + TCL_PATH ?= $(subst wish,tclsh,$(TCLTK_PATH)) +else + TCL_PATH ?= $(dir $(TCLTK_PATH))$(notdir $(subst wish,tclsh,$(TCLTK_PATH))) +endif ifeq ($(uname_S),Darwin) TKFRAMEWORK = /Library/Frameworks/Tk.framework/Resources/Wish.app -- cgit v0.10.2-6-g49f6 From df4ec4cf6f68d92d2fbf20e808722d242ab2b894 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Thu, 21 Feb 2008 19:27:46 -0500 Subject: git-gui: Avoid hardcoded Windows paths in Cygwin package files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When we are being built by the Cygwin package maintainers we need to embed the POSIX path to our library files and not the Windows path. Embedding the Windows path means all end-users who install our Cygwin package would be required to install Cygwin at the same Windows path as the package maintainer had Cygwin installed to. This requirement is simply not user-friendly and may be infeasible for a large number of our users. We now try to auto-detect if the Tcl/Tk binary we will use at runtime is capable of translating POSIX paths into Windows paths the same way that cygpath does the translations. If the Tcl/Tk binary gives us the same results then it understands the Cygwin path translation process and should be able to read our library files from a POSIX path name. If it does not give us the same answer as cygpath then the Tcl/Tk binary might actually be a native Win32 build (one that is not linked against Cygwin) and thus requires the native Windows path to our library files. We can assume this is not a Cygwin package as the Cygwin maintainers do not currently ship a pure Win32 build of Tcl/Tk. Reported on the git mailing list by Jurko Gospodnetić. Signed-off-by: Shawn O. Pearce diff --git a/Makefile b/Makefile index 1ba0e78..01e0a46 100644 --- a/Makefile +++ b/Makefile @@ -131,7 +131,17 @@ GITGUI_MACOSXAPP := ifeq ($(uname_O),Cygwin) GITGUI_SCRIPT := `cygpath --windows --absolute "$(GITGUI_SCRIPT)"` - gg_libdir_sed_in := $(shell cygpath --windows --absolute "$(gg_libdir)") + + # Is this a Cygwin Tcl/Tk binary? If so it knows how to do + # POSIX path translation just like cygpath does and we must + # keep libdir in POSIX format so Cygwin packages of git-gui + # work no matter where the user installs them. + # + ifeq ($(shell echo 'puts [file normalize /]' | '$(TCL_PATH_SQ)'),$(shell cygpath --mixed --absolute /)) + gg_libdir_sed_in := $(gg_libdir) + else + gg_libdir_sed_in := $(shell cygpath --windows --absolute "$(gg_libdir)") + endif else ifeq ($(exedir),$(gg_libdir)) GITGUI_RELATIVE := 1 -- cgit v0.10.2-6-g49f6 From 3baee1f3bf8e30f0fc67bbb1a49877bf0660fd29 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Mon, 11 Feb 2008 00:53:52 -0500 Subject: git-gui: Focus insertion point at end of strings in repository chooser When selecting a local working directory for a new repository or a location to clone an existing repository into we now set the insert point at the end of the selected path, allowing the user to type in any additional parts of the path if they so desire. Signed-off-by: Shawn O. Pearce diff --git a/lib/choose_repository.tcl b/lib/choose_repository.tcl index 86faf24..0adcf9d 100644 --- a/lib/choose_repository.tcl +++ b/lib/choose_repository.tcl @@ -11,6 +11,7 @@ field w_quit ; # Quit button field o_cons ; # Console object (if active) field w_types ; # List of type buttons in clone field w_recentlist ; # Listbox containing recent repositories +field w_localpath ; # Entry widget bound to local_path field done 0 ; # Finished picking the repository? field local_path {} ; # Where this repository is locally @@ -385,6 +386,7 @@ method _do_new {} { button $w_body.where.b \ -text [mc "Browse"] \ -command [cb _new_local_path] + set w_localpath $w_body.where.t pack $w_body.where.b -side right pack $w_body.where.l -side left @@ -416,6 +418,7 @@ method _new_local_path {} { return } set local_path $p + $w_localpath icursor end } method _do_new2 {} { @@ -481,6 +484,7 @@ method _do_clone {} { -text [mc "Browse"] \ -command [cb _new_local_path] grid $args.where_l $args.where_t $args.where_b -sticky ew + set w_localpath $args.where_t label $args.type_l -text [mc "Clone Type:"] frame $args.type_f -- cgit v0.10.2-6-g49f6 From 8a2f5e5b032ca73e19ad1425b75c63234eb166fa Mon Sep 17 00:00:00 2001 From: Gerrit Pape Date: Thu, 21 Feb 2008 10:06:47 +0000 Subject: hash-object: cleanup handling of command line options git hash-object used to process the --stdin command line argument before reading subsequent arguments. This caused 'git hash-object --stdin -w' to fail to actually write the object into the database, while '-w --stdin' properly did. Now git hash-object first reads all arguments, and then processes them. This regresses one insane use case. git hash-object used to allow multiple --stdin arguments on the command line: $ git hash-object --stdin --stdin foo ^D bar ^D Now git hash-object errors out if --stdin is given more than once. Reported by Josh Triplett through http://bugs.debian.org/464432 Signed-off-by: Gerrit Pape Signed-off-by: Junio C Hamano diff --git a/hash-object.c b/hash-object.c index 0a58f3f..61e7160 100644 --- a/hash-object.c +++ b/hash-object.c @@ -41,6 +41,7 @@ int main(int argc, char **argv) const char *prefix = NULL; int prefix_length = -1; int no_more_flags = 0; + int hashstdin = 0; git_config(git_default_config); @@ -65,13 +66,20 @@ int main(int argc, char **argv) else if (!strcmp(argv[i], "--help")) usage(hash_object_usage); else if (!strcmp(argv[i], "--stdin")) { - hash_stdin(type, write_object); + if (hashstdin) + die("Multiple --stdin arguments are not supported"); + hashstdin = 1; } else usage(hash_object_usage); } else { const char *arg = argv[i]; + + if (hashstdin) { + hash_stdin(type, write_object); + hashstdin = 0; + } if (0 <= prefix_length) arg = prefix_filename(prefix, prefix_length, arg); @@ -79,5 +87,7 @@ int main(int argc, char **argv) no_more_flags = 1; } } + if (hashstdin) + hash_stdin(type, write_object); return 0; } diff --git a/t/t5303-hash-object.sh b/t/t5303-hash-object.sh new file mode 100755 index 0000000..543c078 --- /dev/null +++ b/t/t5303-hash-object.sh @@ -0,0 +1,35 @@ +#!/bin/sh + +test_description=git-hash-object + +. ./test-lib.sh + +test_expect_success \ + 'git hash-object -w --stdin saves the object' \ + 'obname=$(echo foo | git hash-object -w --stdin) && + obpath=$(echo $obname | sed -e "s/\(..\)/\1\//") && + test -r .git/objects/"$obpath" && + rm -f .git/objects/"$obpath"' + +test_expect_success \ + 'git hash-object --stdin -w saves the object' \ + 'obname=$(echo foo | git hash-object --stdin -w) && + obpath=$(echo $obname | sed -e "s/\(..\)/\1\//") && + test -r .git/objects/"$obpath" && + rm -f .git/objects/"$obpath"' + +test_expect_success \ + 'git hash-object --stdin file1 file1 && + obname0=$(echo bar | git hash-object --stdin) && + obname1=$(git hash-object file1) && + obname0new=$(echo bar | git hash-object --stdin file1 | sed -n -e 1p) && + obname1new=$(echo bar | git hash-object --stdin file1 | sed -n -e 2p) && + test "$obname0" = "$obname0new" && + test "$obname1" = "$obname1new"' + +test_expect_success \ + 'git hash-object refuses multiple --stdin arguments' \ + '! git hash-object --stdin --stdin < file1' + +test_done -- cgit v0.10.2-6-g49f6 From 8e0f70033b2bd1679a6e5971978fdc3ee09bdb72 Mon Sep 17 00:00:00 2001 From: Jim Meyering Date: Thu, 31 Jan 2008 18:26:32 +0100 Subject: Avoid unnecessary "if-before-free" tests. This change removes all obvious useless if-before-free tests. E.g., it replaces code like this: if (some_expression) free (some_expression); with the now-equivalent: free (some_expression); It is equivalent not just because POSIX has required free(NULL) to work for a long time, but simply because it has worked for so long that no reasonable porting target fails the test. Here's some evidence from nearly 1.5 years ago: http://www.winehq.org/pipermail/wine-patches/2006-October/031544.html FYI, the change below was prepared by running the following: git ls-files -z | xargs -0 \ perl -0x3b -pi -e \ 's/\bif\s*\(\s*(\S+?)(?:\s*!=\s*NULL)?\s*\)\s+(free\s*\(\s*\1\s*\))/$2/s' Note however, that it doesn't handle brace-enclosed blocks like "if (x) { free (x); }". But that's ok, since there were none like that in git sources. Beware: if you do use the above snippet, note that it can produce syntactically invalid C code. That happens when the affected "if"-statement has a matching "else". E.g., it would transform this if (x) free (x); else foo (); into this: free (x); else foo (); There were none of those here, either. If you're interested in automating detection of the useless tests, you might like the useless-if-before-free script in gnulib: [it *does* detect brace-enclosed free statements, and has a --name=S option to make it detect free-like functions with different names] http://git.sv.gnu.org/gitweb/?p=gnulib.git;a=blob;f=build-aux/useless-if-before-free Addendum: Remove one more (in imap-send.c), spotted by Jean-Luc Herren . Signed-off-by: Jim Meyering Signed-off-by: Junio C Hamano diff --git a/builtin-blame.c b/builtin-blame.c index 59d7237..bfd562d 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -123,8 +123,7 @@ static inline struct origin *origin_incref(struct origin *o) static void origin_decref(struct origin *o) { if (o && --o->refcnt <= 0) { - if (o->file.ptr) - free(o->file.ptr); + free(o->file.ptr); free(o); } } diff --git a/builtin-branch.c b/builtin-branch.c index 9edf2eb..7917700 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -126,8 +126,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds) continue; } - if (name) - free(name); + free(name); name = xstrdup(mkpath(fmt, argv[i])); if (!resolve_ref(name, sha1, 1, NULL)) { @@ -172,8 +171,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds) } } - if (name) - free(name); + free(name); return(ret); } @@ -490,8 +488,7 @@ static void create_branch(const char *name, const char *start_name, if (write_ref_sha1(lock, sha1, msg) < 0) die("Failed to write ref: %s.", strerror(errno)); - if (real_ref) - free(real_ref); + free(real_ref); } static void rename_branch(const char *oldname, const char *newname, int force) diff --git a/builtin-fast-export.c b/builtin-fast-export.c index f741df5..49b54de 100755 --- a/builtin-fast-export.c +++ b/builtin-fast-export.c @@ -196,8 +196,7 @@ static void handle_commit(struct commit *commit, struct rev_info *rev) ? strlen(reencoded) : message ? strlen(message) : 0), reencoded ? reencoded : message ? message : ""); - if (reencoded) - free(reencoded); + free(reencoded); for (i = 0, p = commit->parents; p; p = p->next) { int mark = get_object_mark(&p->item->object); diff --git a/builtin-http-fetch.c b/builtin-http-fetch.c index 7f450c6..299093f 100644 --- a/builtin-http-fetch.c +++ b/builtin-http-fetch.c @@ -80,8 +80,7 @@ int cmd_http_fetch(int argc, const char **argv, const char *prefix) walker_free(walker); - if (rewritten_url) - free(rewritten_url); + free(rewritten_url); return rc; } diff --git a/builtin-pack-objects.c b/builtin-pack-objects.c index d2bb12e..7dff653 100644 --- a/builtin-pack-objects.c +++ b/builtin-pack-objects.c @@ -1428,8 +1428,7 @@ static int try_delta(struct unpacked *trg, struct unpacked *src, * accounting lock. Compiler will optimize the strangeness * away when THREADED_DELTA_SEARCH is not defined. */ - if (trg_entry->delta_data) - free(trg_entry->delta_data); + free(trg_entry->delta_data); cache_lock(); if (trg_entry->delta_data) { delta_cache_size -= trg_entry->delta_size; diff --git a/builtin-revert.c b/builtin-revert.c index e219859..b6dee6a 100644 --- a/builtin-revert.c +++ b/builtin-revert.c @@ -397,8 +397,7 @@ static int revert_or_cherry_pick(int argc, const char **argv) else return execl_git_cmd("commit", "-n", "-F", defmsg, NULL); } - if (reencoded_message) - free(reencoded_message); + free(reencoded_message); return 0; } diff --git a/connect.c b/connect.c index 5ac3572..d12b105 100644 --- a/connect.c +++ b/connect.c @@ -68,8 +68,7 @@ struct ref **get_remote_heads(int in, struct ref **list, name_len = strlen(name); if (len != name_len + 41) { - if (server_capabilities) - free(server_capabilities); + free(server_capabilities); server_capabilities = xstrdup(name + name_len + 1); } diff --git a/diff.c b/diff.c index 699b21f..f08e663 100644 --- a/diff.c +++ b/diff.c @@ -118,8 +118,7 @@ static int parse_funcname_pattern(const char *var, const char *ep, const char *v pp->next = funcname_pattern_list; funcname_pattern_list = pp; } - if (pp->pattern) - free(pp->pattern); + free(pp->pattern); pp->pattern = xstrdup(value); return 0; } @@ -492,10 +491,8 @@ static void free_diff_words_data(struct emit_callback *ecbdata) ecbdata->diff_words->plus.text.size) diff_words_show(ecbdata->diff_words); - if (ecbdata->diff_words->minus.text.ptr) - free (ecbdata->diff_words->minus.text.ptr); - if (ecbdata->diff_words->plus.text.ptr) - free (ecbdata->diff_words->plus.text.ptr); + free (ecbdata->diff_words->minus.text.ptr); + free (ecbdata->diff_words->plus.text.ptr); free(ecbdata->diff_words); ecbdata->diff_words = NULL; } diff --git a/dir.c b/dir.c index 1f507da..edc458e 100644 --- a/dir.c +++ b/dir.c @@ -704,8 +704,7 @@ static struct path_simplify *create_simplify(const char **pathspec) static void free_simplify(struct path_simplify *simplify) { - if (simplify) - free(simplify); + free(simplify); } int read_directory(struct dir_struct *dir, const char *path, const char *base, int baselen, const char **pathspec) diff --git a/http-push.c b/http-push.c index 0beb740..406270f 100644 --- a/http-push.c +++ b/http-push.c @@ -664,8 +664,7 @@ static void release_request(struct transfer_request *request) close(request->local_fileno); if (request->local_stream) fclose(request->local_stream); - if (request->url != NULL) - free(request->url); + free(request->url); free(request); } @@ -1283,10 +1282,8 @@ static struct remote_lock *lock_remote(const char *path, long timeout) strbuf_release(&in_buffer); if (lock->token == NULL || lock->timeout <= 0) { - if (lock->token != NULL) - free(lock->token); - if (lock->owner != NULL) - free(lock->owner); + free(lock->token); + free(lock->owner); free(url); free(lock); lock = NULL; @@ -1344,8 +1341,7 @@ static int unlock_remote(struct remote_lock *lock) prev->next = prev->next->next; } - if (lock->owner != NULL) - free(lock->owner); + free(lock->owner); free(lock->url); free(lock->token); free(lock); @@ -2035,8 +2031,7 @@ static void fetch_symref(const char *path, char **symref, unsigned char *sha1) } free(url); - if (*symref != NULL) - free(*symref); + free(*symref); *symref = NULL; hashclr(sha1); @@ -2435,8 +2430,7 @@ int main(int argc, char **argv) } cleanup: - if (rewritten_url) - free(rewritten_url); + free(rewritten_url); if (info_ref_lock) unlock_remote(info_ref_lock); free(remote); diff --git a/imap-send.c b/imap-send.c index 9025d9a..10cce15 100644 --- a/imap-send.c +++ b/imap-send.c @@ -472,7 +472,7 @@ v_issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb, if (socket_write( &imap->buf.sock, buf, bufl ) != bufl) { free( cmd->cmd ); free( cmd ); - if (cb && cb->data) + if (cb) free( cb->data ); return NULL; } @@ -858,8 +858,7 @@ get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd ) normal: if (cmdp->cb.done) cmdp->cb.done( ctx, cmdp, resp ); - if (cmdp->cb.data) - free( cmdp->cb.data ); + free( cmdp->cb.data ); free( cmdp->cmd ); free( cmdp ); if (!tcmd || tcmd == cmdp) diff --git a/interpolate.c b/interpolate.c index 6ef53f2..7f03bd9 100644 --- a/interpolate.c +++ b/interpolate.c @@ -11,8 +11,7 @@ void interp_set_entry(struct interp *table, int slot, const char *value) char *oldval = table[slot].value; char *newval = NULL; - if (oldval) - free(oldval); + free(oldval); if (value) newval = xstrdup(value); diff --git a/pretty.c b/pretty.c index 997f583..4bf3be2 100644 --- a/pretty.c +++ b/pretty.c @@ -30,8 +30,7 @@ enum cmit_fmt get_commit_format(const char *arg) if (*arg == '=') arg++; if (!prefixcmp(arg, "format:")) { - if (user_format) - free(user_format); + free(user_format); user_format = xstrdup(arg + 7); return CMIT_FMT_USERFORMAT; } diff --git a/remote.c b/remote.c index 6b56473..ae1ef57 100644 --- a/remote.c +++ b/remote.c @@ -506,8 +506,7 @@ void free_refs(struct ref *ref) struct ref *next; while (ref) { next = ref->next; - if (ref->peer_ref) - free(ref->peer_ref); + free(ref->peer_ref); free(ref); ref = next; } diff --git a/setup.c b/setup.c index dc247a8..89c81e5 100644 --- a/setup.c +++ b/setup.c @@ -448,8 +448,7 @@ int check_repository_format_version(const char *var, const char *value) } else if (strcmp(var, "core.worktree") == 0) { if (!value) return config_error_nonbool(var); - if (git_work_tree_cfg) - free(git_work_tree_cfg); + free(git_work_tree_cfg); git_work_tree_cfg = xstrdup(value); inside_work_tree = -1; } diff --git a/sha1_name.c b/sha1_name.c index c2805e7..9d088cc 100644 --- a/sha1_name.c +++ b/sha1_name.c @@ -625,8 +625,7 @@ static int get_sha1_oneline(const char *prefix, unsigned char *sha1) commit = pop_most_recent_commit(&list, ONELINE_SEEN); if (!parse_object(commit->object.sha1)) continue; - if (temp_commit_buffer) - free(temp_commit_buffer); + free(temp_commit_buffer); if (commit->buffer) p = commit->buffer; else { @@ -643,8 +642,7 @@ static int get_sha1_oneline(const char *prefix, unsigned char *sha1) break; } } - if (temp_commit_buffer) - free(temp_commit_buffer); + free(temp_commit_buffer); free_commit_list(list); for (l = backup; l; l = l->next) clear_commit_marks(l->item, ONELINE_SEEN); diff --git a/xdiff-interface.c b/xdiff-interface.c index 4b8e5cc..bba2364 100644 --- a/xdiff-interface.c +++ b/xdiff-interface.c @@ -233,8 +233,7 @@ void xdiff_set_find_func(xdemitconf_t *xecfg, const char *value) expression = value; if (regcomp(®->re, expression, 0)) die("Invalid regexp to look for hunk header: %s", expression); - if (buffer) - free(buffer); + free(buffer); value = ep + 1; } } -- cgit v0.10.2-6-g49f6 From a22c637124a2f591382d56546136a8e2bb2c2c66 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Fri, 22 Feb 2008 20:37:40 -0800 Subject: Fix name re-hashing semantics We handled the case of removing and re-inserting cache entries badly, which is something that merging commonly needs to do (removing the different stages, and then re-inserting one of them as the merged state). We even had a rather ugly special case for this failure case, where replace_index_entry() basically turned itself into a no-op if the new and the old entries were the same, exactly because the hash routines didn't handle it on their own. So what this patch does is to not just have the UNHASHED bit, but a HASHED bit too, and when you insert an entry into the name hash, that involves: - clear the UNHASHED bit, because now it's valid again for lookup (which is really all that UNHASHED meant) - if we're being lazy, we're done here (but we still want to clear the UNHASHED bit regardless of lazy mode, since we can become unlazy later, and so we need the UNHASHED bit to always be set correctly, even if we never actually insert the entry into the hash list) - if it was already hashed, we just leave it on the list - otherwise mark it HASHED and insert it into the list this all means that unhashing and rehashing a name all just works automatically. Obviously, you cannot change the name of an entry (that would be a serious bug), but nothing can validly do that anyway (you'd have to allocate a new struct cache_entry anyway since the name length could change), so that's not a new limitation. The code actually gets simpler in many ways, although the lazy hashing does mean that there are a few odd cases (ie something can be marked unhashed even though it was never on the hash in the first place, and isn't actually marked hashed!). Signed-off-by: Linus Torvalds Signed-off-by: Junio C Hamano diff --git a/cache.h b/cache.h index e1000bc..0b69c92 100644 --- a/cache.h +++ b/cache.h @@ -133,7 +133,9 @@ struct cache_entry { #define CE_UPDATE (0x10000) #define CE_REMOVE (0x20000) #define CE_UPTODATE (0x40000) -#define CE_UNHASHED (0x80000) + +#define CE_HASHED (0x100000) +#define CE_UNHASHED (0x200000) static inline unsigned create_ce_flags(size_t len, unsigned stage) { diff --git a/read-cache.c b/read-cache.c index e45f4b3..eb58b03 100644 --- a/read-cache.c +++ b/read-cache.c @@ -37,8 +37,13 @@ static unsigned int hash_name(const char *name, int namelen) static void hash_index_entry(struct index_state *istate, struct cache_entry *ce) { void **pos; - unsigned int hash = hash_name(ce->name, ce_namelen(ce)); + unsigned int hash; + if (ce->ce_flags & CE_HASHED) + return; + ce->ce_flags |= CE_HASHED; + ce->next = NULL; + hash = hash_name(ce->name, ce_namelen(ce)); pos = insert_hash(hash, ce, &istate->name_hash); if (pos) { ce->next = *pos; @@ -59,6 +64,7 @@ static void lazy_init_name_hash(struct index_state *istate) static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce) { + ce->ce_flags &= ~CE_UNHASHED; istate->cache[nr] = ce; if (istate->name_hash_initialized) hash_index_entry(istate, ce); @@ -82,10 +88,8 @@ static void replace_index_entry(struct index_state *istate, int nr, struct cache { struct cache_entry *old = istate->cache[nr]; - if (ce != old) { - remove_hash_entry(istate, old); - set_index_entry(istate, nr, ce); - } + remove_hash_entry(istate, old); + set_index_entry(istate, nr, ce); istate->cache_changed = 1; } -- cgit v0.10.2-6-g49f6 From d070e3a31bf94de1ef503b155a5e028545f7decc Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Fri, 22 Feb 2008 20:39:21 -0800 Subject: Name hash fixups: export (and rename) remove_hash_entry This makes the name hash removal function (which really just sets the bit that disables lookups of it) available to external routines, and makes read_cache_unmerged() use it when it drops an unmerged entry from the index. It's renamed to remove_index_entry(), and we drop the (unused) 'istate' argument. Signed-off-by: Linus Torvalds Signed-off-by: Junio C Hamano diff --git a/builtin-read-tree.c b/builtin-read-tree.c index 726fb0b..7bdc312 100644 --- a/builtin-read-tree.c +++ b/builtin-read-tree.c @@ -41,6 +41,7 @@ static int read_cache_unmerged(void) for (i = 0; i < active_nr; i++) { struct cache_entry *ce = active_cache[i]; if (ce_stage(ce)) { + remove_index_entry(ce); if (last && !strcmp(ce->name, last->name)) continue; cache_tree_invalidate_path(active_cache_tree, ce->name); diff --git a/cache.h b/cache.h index 0b69c92..88d3b92 100644 --- a/cache.h +++ b/cache.h @@ -137,6 +137,20 @@ struct cache_entry { #define CE_HASHED (0x100000) #define CE_UNHASHED (0x200000) +/* + * We don't actually *remove* it, we can just mark it invalid so that + * we won't find it in lookups. + * + * Not only would we have to search the lists (simple enough), but + * we'd also have to rehash other hash buckets in case this makes the + * hash bucket empty (common). So it's much better to just mark + * it. + */ +static inline void remove_index_entry(struct cache_entry *ce) +{ + ce->ce_flags |= CE_UNHASHED; +} + static inline unsigned create_ce_flags(size_t len, unsigned stage) { if (len >= CE_NAMEMASK) diff --git a/read-cache.c b/read-cache.c index eb58b03..fee0c80 100644 --- a/read-cache.c +++ b/read-cache.c @@ -70,25 +70,11 @@ static void set_index_entry(struct index_state *istate, int nr, struct cache_ent hash_index_entry(istate, ce); } -/* - * We don't actually *remove* it, we can just mark it invalid so that - * we won't find it in lookups. - * - * Not only would we have to search the lists (simple enough), but - * we'd also have to rehash other hash buckets in case this makes the - * hash bucket empty (common). So it's much better to just mark - * it. - */ -static void remove_hash_entry(struct index_state *istate, struct cache_entry *ce) -{ - ce->ce_flags |= CE_UNHASHED; -} - static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce) { struct cache_entry *old = istate->cache[nr]; - remove_hash_entry(istate, old); + remove_index_entry(old); set_index_entry(istate, nr, ce); istate->cache_changed = 1; } @@ -417,7 +403,7 @@ int remove_index_entry_at(struct index_state *istate, int pos) { struct cache_entry *ce = istate->cache[pos]; - remove_hash_entry(istate, ce); + remove_index_entry(ce); istate->cache_changed = 1; istate->cache_nr--; if (pos >= istate->cache_nr) -- cgit v0.10.2-6-g49f6 From eb7a2f1d50ca8620b087dd2751d0fe2505e7974f Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Fri, 22 Feb 2008 20:41:17 -0800 Subject: Use helper function for copying index entry information We used to just memcpy() the index entry when we copied the stat() and SHA1 hash information, which worked well enough back when the index entry was just an exact bit-for-bit representation of the information on disk. However, these days we actually have various management information in the cache entry too, and we should be careful to not overwrite it when we copy the stat information from another index entry. Signed-off-by: Linus Torvalds Signed-off-by: Junio C Hamano diff --git a/cache.h b/cache.h index 88d3b92..fa5a9e5 100644 --- a/cache.h +++ b/cache.h @@ -110,7 +110,6 @@ struct ondisk_cache_entry { }; struct cache_entry { - struct cache_entry *next; unsigned int ce_ctime; unsigned int ce_mtime; unsigned int ce_dev; @@ -121,6 +120,7 @@ struct cache_entry { unsigned int ce_size; unsigned int ce_flags; unsigned char sha1[20]; + struct cache_entry *next; char name[FLEX_ARRAY]; /* more */ }; @@ -138,6 +138,22 @@ struct cache_entry { #define CE_UNHASHED (0x200000) /* + * Copy the sha1 and stat state of a cache entry from one to + * another. But we never change the name, or the hash state! + */ +#define CE_STATE_MASK (CE_HASHED | CE_UNHASHED) +static inline void copy_cache_entry(struct cache_entry *dst, struct cache_entry *src) +{ + unsigned int state = dst->ce_flags & CE_STATE_MASK; + + /* Don't copy hash chain and name */ + memcpy(dst, src, offsetof(struct cache_entry, next)); + + /* Restore the hash state */ + dst->ce_flags = (dst->ce_flags & ~CE_STATE_MASK) | state; +} + +/* * We don't actually *remove* it, we can just mark it invalid so that * we won't find it in lookups. * diff --git a/unpack-trees.c b/unpack-trees.c index ec558f9..07c4c28 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -590,7 +590,7 @@ static int merged_entry(struct cache_entry *merge, struct cache_entry *old, * a match. */ if (same(old, merge)) { - memcpy(merge, old, offsetof(struct cache_entry, name)); + copy_cache_entry(merge, old); } else { verify_uptodate(old, o); invalidate_ce_path(old); -- cgit v0.10.2-6-g49f6 From 0d2dd191cdfa3f1795c4df60a5cfb0f7e58c097a Mon Sep 17 00:00:00 2001 From: Jay Soffian Date: Fri, 22 Feb 2008 19:52:29 -0500 Subject: pull: pass --strategy along to to rebase rebase supports --strategy, so pull should pass the option along to it. Signed-off-by: Jay Soffian Signed-off-by: Junio C Hamano diff --git a/git-pull.sh b/git-pull.sh index 46da0f4..3ce32b5 100755 --- a/git-pull.sh +++ b/git-pull.sh @@ -174,6 +174,7 @@ fi merge_name=$(git fmt-merge-msg <"$GIT_DIR/FETCH_HEAD") || exit test true = "$rebase" && - exec git-rebase --onto $merge_head ${oldremoteref:-$merge_head} + exec git-rebase $strategy_args --onto $merge_head \ + ${oldremoteref:-$merge_head} exec git-merge $no_summary $no_commit $squash $no_ff $strategy_args \ "$merge_name" HEAD $merge_head -- cgit v0.10.2-6-g49f6 From 1736855c9b59ac787af979a44840a58361cbaf66 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 23 Feb 2008 11:08:25 -0800 Subject: Add merge-subtree back An earlier commit e1b3a2c (Build-in merge-recursive) made the subtree merge strategy backend unavailable. This resurrects it. A new test t6029 currently only tests the strategy is available, but it should be enhanced to check the real "subtree" case. Signed-off-by: Junio C Hamano diff --git a/Makefile b/Makefile index 90c0dd8..40fa41b 100644 --- a/Makefile +++ b/Makefile @@ -261,17 +261,18 @@ PROGRAMS = \ # Empty... EXTRA_PROGRAMS = +# List built-in command $C whose implementation cmd_$C() is not in +# builtin-$C.o but is linked in as part of some other command. BUILT_INS = \ git-format-patch$X git-show$X git-whatchanged$X git-cherry$X \ git-get-tar-commit-id$X git-init$X git-repo-config$X \ git-fsck-objects$X git-cherry-pick$X git-peek-remote$X git-status$X \ + git-merge-subtree$X \ $(patsubst builtin-%.o,git-%$X,$(BUILTIN_OBJS)) # what 'all' will build and 'install' will install, in gitexecdir ALL_PROGRAMS = $(PROGRAMS) $(SCRIPTS) -ALL_PROGRAMS += git-merge-subtree$X - # what 'all' will build but not install in gitexecdir OTHER_PROGRAMS = git$X gitweb/gitweb.cgi @@ -807,9 +808,6 @@ help.o: help.c common-cmds.h GIT-CFLAGS '-DGIT_MAN_PATH="$(mandir_SQ)"' \ '-DGIT_INFO_PATH="$(infodir_SQ)"' $< -git-merge-subtree$X: git-merge-recursive$X - $(QUIET_BUILT_IN)$(RM) $@ && ln git-merge-recursive$X $@ - $(BUILT_INS): git$X $(QUIET_BUILT_IN)$(RM) $@ && ln git$X $@ diff --git a/git.c b/git.c index fc15686..bd424ea 100644 --- a/git.c +++ b/git.c @@ -332,6 +332,7 @@ static void handle_internal_command(int argc, const char **argv) { "merge-file", cmd_merge_file }, { "merge-ours", cmd_merge_ours, RUN_SETUP }, { "merge-recursive", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE }, + { "merge-subtree", cmd_merge_recursive, RUN_SETUP | NEED_WORK_TREE }, { "mv", cmd_mv, RUN_SETUP | NEED_WORK_TREE }, { "name-rev", cmd_name_rev, RUN_SETUP }, { "pack-objects", cmd_pack_objects, RUN_SETUP }, diff --git a/t/t6029-merge-subtree.sh b/t/t6029-merge-subtree.sh new file mode 100755 index 0000000..3900a05 --- /dev/null +++ b/t/t6029-merge-subtree.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +test_description='subtree merge strategy' + +. ./test-lib.sh + +test_expect_success setup ' + + s="1 2 3 4 5 6 7 8" + for i in $s; do echo $i; done >hello && + git add hello && + git commit -m initial && + git checkout -b side && + echo >>hello world && + git add hello && + git commit -m second && + git checkout master && + for i in mundo $s; do echo $i; done >hello && + git add hello && + git commit -m master + +' + +test_expect_success 'subtree available and works like recursive' ' + + git merge -s subtree side && + for i in mundo $s world; do echo $i; done >expect && + diff -u expect hello + +' + +test_done -- cgit v0.10.2-6-g49f6 From 31e0b2ca81ad985a8768c33c0aba547a51d05277 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 23 Feb 2008 11:31:04 -0800 Subject: GIT 1.5.4.3 Signed-off-by: Junio C Hamano diff --git a/Documentation/RelNotes-1.5.4.3.txt b/Documentation/RelNotes-1.5.4.3.txt new file mode 100644 index 0000000..b0fc67f --- /dev/null +++ b/Documentation/RelNotes-1.5.4.3.txt @@ -0,0 +1,27 @@ +GIT v1.5.4.3 Release Notes +========================== + +Fixes since v1.5.4.2 +-------------------- + + * RPM spec used to pull in everything with 'git'. This has been + changed so that 'git' package contains just the core parts, + and we now supply 'git-all' metapackage to slurp in everything. + This should match end user's expectation better. + + * When some refs failed to update, git-push reported "failure" + which was unclear if some other refs were updated or all of + them failed atomically (the answer is the former). Reworded + the message to clarify this. + + * "git clone" from a repository whose HEAD was misconfigured + did not set up the remote properly. Now it tries to do + better. + + * Updated git-push documentation to clarify what "matching" + means, in order to reduce user confusion. + + * Updated git-add documentation to clarify "add -u" operates in + the current subdirectory you are in, just like other commands. + + * git-gui updates to work on OSX and Windows better. diff --git a/GIT-VERSION-GEN b/GIT-VERSION-GEN index 03fb9d7..0d4c2f7 100755 --- a/GIT-VERSION-GEN +++ b/GIT-VERSION-GEN @@ -1,7 +1,7 @@ #!/bin/sh GVF=GIT-VERSION-FILE -DEF_VER=v1.5.4.2.GIT +DEF_VER=v1.5.4.3.GIT LF=' ' @@ -16,7 +16,8 @@ elif test -d .git && case "$VN" in *$LF*) (exit 1) ;; v[0-9]*) - git diff-index --quiet HEAD || VN="$VN-dirty" ;; + test -z "$(git diff-index --name-only HEAD)" || + VN="$VN-dirty" ;; esac then VN=$(echo "$VN" | sed -e 's/-/./g'); diff --git a/RelNotes b/RelNotes index 7ab3485..3084ce6 120000 --- a/RelNotes +++ b/RelNotes @@ -1 +1 @@ -Documentation/RelNotes-1.5.4.2.txt \ No newline at end of file +Documentation/RelNotes-1.5.4.3.txt \ No newline at end of file -- cgit v0.10.2-6-g49f6 From e72ae28895b22052b7ca2eef36c039ac62671f7d Mon Sep 17 00:00:00 2001 From: Johannes Sixt Date: Sat, 16 Feb 2008 18:36:38 +0100 Subject: start_command(), .in/.out/.err = -1: Callers must close the file descriptor By setting .in, .out, or .err members of struct child_process to -1, the callers of start_command() can request that a pipe is allocated that talks to the child process and one end is returned by replacing -1 with the file descriptor. Previously, a flag was set (for .in and .out, but not .err) to signal finish_command() to close the pipe end that start_command() had handed out, so it was optional for callers to close the pipe, and many already do so. Now we make it mandatory to close the pipe. Signed-off-by: Johannes Sixt Signed-off-by: Junio C Hamano diff --git a/builtin-fetch-pack.c b/builtin-fetch-pack.c index f401352..5ea48ca 100644 --- a/builtin-fetch-pack.c +++ b/builtin-fetch-pack.c @@ -538,8 +538,10 @@ static int get_pack(int xd[2], char **pack_lockfile) cmd.git_cmd = 1; if (start_command(&cmd)) die("fetch-pack: unable to fork off %s", argv[0]); - if (do_keep && pack_lockfile) + if (do_keep && pack_lockfile) { *pack_lockfile = index_pack_lockfile(cmd.out); + close(cmd.out); + } if (finish_command(&cmd)) die("%s failed", argv[0]); diff --git a/builtin-send-pack.c b/builtin-send-pack.c index 8afb1d0..ba9bc91 100644 --- a/builtin-send-pack.c +++ b/builtin-send-pack.c @@ -71,6 +71,7 @@ static int pack_objects(int fd, struct ref *refs) refs = refs->next; } + close(po.in); if (finish_command(&po)) return error("pack-objects died with strange error"); return 0; diff --git a/builtin-tag.c b/builtin-tag.c index 716b4ff..28c36fd 100644 --- a/builtin-tag.c +++ b/builtin-tag.c @@ -226,12 +226,13 @@ static int do_sign(struct strbuf *buffer) if (write_in_full(gpg.in, buffer->buf, buffer->len) != buffer->len) { close(gpg.in); + close(gpg.out); finish_command(&gpg); return error("gpg did not accept the tag data"); } close(gpg.in); - gpg.close_in = 0; len = strbuf_read(buffer, gpg.out, 1024); + close(gpg.out); if (finish_command(&gpg) || !len || len < 0) return error("gpg failed to sign the tag"); diff --git a/builtin-verify-tag.c b/builtin-verify-tag.c index cc4c55d..b3010f9 100644 --- a/builtin-verify-tag.c +++ b/builtin-verify-tag.c @@ -52,7 +52,6 @@ static int run_gpg_verify(const char *buf, unsigned long size, int verbose) write_in_full(gpg.in, buf, len); close(gpg.in); - gpg.close_in = 0; ret = finish_command(&gpg); unlink(path); diff --git a/bundle.c b/bundle.c index bd12ec8..4352ce8 100644 --- a/bundle.c +++ b/bundle.c @@ -333,6 +333,7 @@ int create_bundle(struct bundle_header *header, const char *path, write_or_die(rls.in, sha1_to_hex(object->sha1), 40); write_or_die(rls.in, "\n", 1); } + close(rls.in); if (finish_command(&rls)) return error ("pack-objects died"); diff --git a/receive-pack.c b/receive-pack.c index 3267495..a971433 100644 --- a/receive-pack.c +++ b/receive-pack.c @@ -132,6 +132,7 @@ static int run_hook(const char *hook_name) break; } } + close(proc.in); return hook_status(finish_command(&proc), hook_name); } @@ -414,6 +415,7 @@ static const char *unpack(void) if (start_command(&ip)) return "index-pack fork failed"; pack_lockfile = index_pack_lockfile(ip.out); + close(ip.out); status = finish_command(&ip); if (!status) { reprepare_packed_git(); diff --git a/run-command.c b/run-command.c index 476d00c..2919330 100644 --- a/run-command.c +++ b/run-command.c @@ -25,7 +25,6 @@ int start_command(struct child_process *cmd) if (pipe(fdin) < 0) return -ERR_RUN_COMMAND_PIPE; cmd->in = fdin[1]; - cmd->close_in = 1; } need_out = !cmd->no_stdout @@ -38,7 +37,6 @@ int start_command(struct child_process *cmd) return -ERR_RUN_COMMAND_PIPE; } cmd->out = fdout[0]; - cmd->close_out = 1; } need_err = !cmd->no_stderr && cmd->err < 0; @@ -157,10 +155,6 @@ static int wait_or_whine(pid_t pid) int finish_command(struct child_process *cmd) { - if (cmd->close_in) - close(cmd->in); - if (cmd->close_out) - close(cmd->out); return wait_or_whine(cmd->pid); } diff --git a/run-command.h b/run-command.h index 1fc781d..e9c84d0 100644 --- a/run-command.h +++ b/run-command.h @@ -19,8 +19,6 @@ struct child_process { int err; const char *dir; const char *const *env; - unsigned close_in:1; - unsigned close_out:1; unsigned no_stdin:1; unsigned no_stdout:1; unsigned no_stderr:1; -- cgit v0.10.2-6-g49f6 From c20181e3a3e39f2c8874567c219e9edddb84393a Mon Sep 17 00:00:00 2001 From: Johannes Sixt Date: Thu, 21 Feb 2008 23:42:56 +0100 Subject: start_command(), if .in/.out > 0, closes file descriptors, not the callers Callers of start_command() can set the members .in and .out of struct child_process to a value > 0 to specify that this descriptor is used as the stdin or stdout of the child process. Previously, if start_command() was successful, this descriptor was closed upon return. Here we now make sure that the descriptor is also closed in case of failures. All callers are updated not to close the file descriptor themselves after start_command() was called. Note that earlier run_gpg_verify() of git-verify-tag set .out = 1, which worked because start_command() treated this as a special case, but now this is incorrect because it closes the descriptor. The intent here is to inherit stdout to the child, which is achieved by .out = 0. Signed-off-by: Johannes Sixt Signed-off-by: Junio C Hamano diff --git a/builtin-send-pack.c b/builtin-send-pack.c index ba9bc91..b0cfae8 100644 --- a/builtin-send-pack.c +++ b/builtin-send-pack.c @@ -404,12 +404,15 @@ static int do_send_pack(int in, int out, struct remote *remote, const char *dest if (!remote_tail) remote_tail = &remote_refs; if (match_refs(local_refs, remote_refs, &remote_tail, - nr_refspec, refspec, flags)) + nr_refspec, refspec, flags)) { + close(out); return -1; + } if (!remote_refs) { fprintf(stderr, "No refs in common and none specified; doing nothing.\n" "Perhaps you should specify a branch such as 'master'.\n"); + close(out); return 0; } @@ -496,12 +499,11 @@ static int do_send_pack(int in, int out, struct remote *remote, const char *dest packet_flush(out); if (new_refs && !args.dry_run) { - if (pack_objects(out, remote_refs) < 0) { - close(out); + if (pack_objects(out, remote_refs) < 0) return -1; - } } - close(out); + else + close(out); if (expect_status_report) ret = receive_status(in, remote_refs); @@ -649,7 +651,7 @@ int send_pack(struct send_pack_args *my_args, conn = git_connect(fd, dest, args.receivepack, args.verbose ? CONNECT_VERBOSE : 0); ret = do_send_pack(fd[0], fd[1], remote, dest, nr_heads, heads); close(fd[0]); - close(fd[1]); + /* do_send_pack always closes fd[1] */ ret |= finish_connect(conn); return !!ret; } diff --git a/builtin-verify-tag.c b/builtin-verify-tag.c index b3010f9..f3ef11f 100644 --- a/builtin-verify-tag.c +++ b/builtin-verify-tag.c @@ -45,7 +45,6 @@ static int run_gpg_verify(const char *buf, unsigned long size, int verbose) memset(&gpg, 0, sizeof(gpg)); gpg.argv = args_gpg; gpg.in = -1; - gpg.out = 1; args_gpg[2] = path; if (start_command(&gpg)) return error("could not run gpg."); diff --git a/bundle.c b/bundle.c index 4352ce8..0ba5df1 100644 --- a/bundle.c +++ b/bundle.c @@ -336,8 +336,9 @@ int create_bundle(struct bundle_header *header, const char *path, close(rls.in); if (finish_command(&rls)) return error ("pack-objects died"); - - return bundle_to_stdout ? close(bundle_fd) : commit_lock_file(&lock); + if (!bundle_to_stdout) + commit_lock_file(&lock); + return 0; } int unbundle(struct bundle_header *header, int bundle_fd) diff --git a/run-command.c b/run-command.c index 2919330..743757c 100644 --- a/run-command.c +++ b/run-command.c @@ -20,10 +20,18 @@ int start_command(struct child_process *cmd) int need_in, need_out, need_err; int fdin[2], fdout[2], fderr[2]; + /* + * In case of errors we must keep the promise to close FDs + * that have been passed in via ->in and ->out. + */ + need_in = !cmd->no_stdin && cmd->in < 0; if (need_in) { - if (pipe(fdin) < 0) + if (pipe(fdin) < 0) { + if (cmd->out > 0) + close(cmd->out); return -ERR_RUN_COMMAND_PIPE; + } cmd->in = fdin[1]; } @@ -34,6 +42,8 @@ int start_command(struct child_process *cmd) if (pipe(fdout) < 0) { if (need_in) close_pair(fdin); + else if (cmd->in) + close(cmd->in); return -ERR_RUN_COMMAND_PIPE; } cmd->out = fdout[0]; @@ -44,8 +54,12 @@ int start_command(struct child_process *cmd) if (pipe(fderr) < 0) { if (need_in) close_pair(fdin); + else if (cmd->in) + close(cmd->in); if (need_out) close_pair(fdout); + else if (cmd->out) + close(cmd->out); return -ERR_RUN_COMMAND_PIPE; } cmd->err = fderr[0]; @@ -55,8 +69,12 @@ int start_command(struct child_process *cmd) if (cmd->pid < 0) { if (need_in) close_pair(fdin); + else if (cmd->in) + close(cmd->in); if (need_out) close_pair(fdout); + else if (cmd->out) + close(cmd->out); if (need_err) close_pair(fderr); return -ERR_RUN_COMMAND_FORK; @@ -118,7 +136,7 @@ int start_command(struct child_process *cmd) if (need_out) close(fdout[1]); - else if (cmd->out > 1) + else if (cmd->out) close(cmd->out); if (need_err) diff --git a/run-command.h b/run-command.h index e9c84d0..debe307 100644 --- a/run-command.h +++ b/run-command.h @@ -14,6 +14,24 @@ enum { struct child_process { const char **argv; pid_t pid; + /* + * Using .in, .out, .err: + * - Specify 0 for no redirections (child inherits stdin, stdout, + * stderr from parent). + * - Specify -1 to have a pipe allocated as follows: + * .in: returns the writable pipe end; parent writes to it, + * the readable pipe end becomes child's stdin + * .out, .err: returns the readable pipe end; parent reads from + * it, the writable pipe end becomes child's stdout/stderr + * The caller of start_command() must close the returned FDs + * after it has completed reading from/writing to it! + * - Specify > 0 to set a channel to a particular FD as follows: + * .in: a readable FD, becomes child's stdin + * .out: a writable FD, becomes child's stdout/stderr + * .err > 0 not supported + * The specified FD is closed by start_command(), even in case + * of errors! + */ int in; int out; int err; -- cgit v0.10.2-6-g49f6 From 833e3df17188e48b2d31db0966a4051dad5e03b9 Mon Sep 17 00:00:00 2001 From: Andreas Ericsson Date: Fri, 22 Feb 2008 20:11:56 -0600 Subject: pack-objects: Add runtime detection of online CPU's Packing objects can be done in parallell nowadays, but it's only done if the config option pack.threads is set to a value above 1. Because of that, the code-path used is often not the most optimal one. This patch adds a routine to detect the number of online CPU's at runtime (online_cpus()). When pack.threads (or --threads=) is given a value of 0, the number of threads is set to the number of online CPU's. This feature is also documented. As per Nicolas Pitre's recommendations, the default is still to run pack-objects single-threaded unless explicitly activated, either by configuration or by command line parameter. The routine online_cpus() is a rework of "numcpus.c", written by one Philip Willoughby . numcpus.c is in the public domain and can presently be downloaded from http://csgsoft.doc.ic.ac.uk/numcpus/ Signed-off-by: Andreas Ericsson Signed-off-by: Brandon Casey Signed-off-by: Junio C Hamano diff --git a/Documentation/config.txt b/Documentation/config.txt index 7b67671..62b697c 100644 --- a/Documentation/config.txt +++ b/Documentation/config.txt @@ -808,6 +808,8 @@ pack.threads:: warning. This is meant to reduce packing time on multiprocessor machines. The required amount of memory for the delta search window is however multiplied by the number of threads. + Specifying 0 will cause git to auto-detect the number of CPU's + and set the number of threads accordingly. pack.indexVersion:: Specify the default pack index version. Valid values are 1 for diff --git a/Documentation/git-pack-objects.txt b/Documentation/git-pack-objects.txt index 8353be1..5c1bd3b 100644 --- a/Documentation/git-pack-objects.txt +++ b/Documentation/git-pack-objects.txt @@ -177,6 +177,8 @@ base-name:: This is meant to reduce packing time on multiprocessor machines. The required amount of memory for the delta search window is however multiplied by the number of threads. + Specifying 0 will cause git to auto-detect the number of CPU's + and set the number of threads accordingly. --index-version=[,]:: This is intended to be used by the test suite only. It allows diff --git a/Makefile b/Makefile index d33a556..2dc8247 100644 --- a/Makefile +++ b/Makefile @@ -741,6 +741,7 @@ endif ifdef THREADED_DELTA_SEARCH BASIC_CFLAGS += -DTHREADED_DELTA_SEARCH EXTLIBS += -lpthread + LIB_OBJS += thread-utils.o endif ifeq ($(TCLTK_PATH),) diff --git a/builtin-pack-objects.c b/builtin-pack-objects.c index d2bb12e..586ae11 100644 --- a/builtin-pack-objects.c +++ b/builtin-pack-objects.c @@ -16,6 +16,7 @@ #include "progress.h" #ifdef THREADED_DELTA_SEARCH +#include "thread-utils.h" #include #endif @@ -1852,11 +1853,11 @@ static int git_pack_config(const char *k, const char *v) } if (!strcmp(k, "pack.threads")) { delta_search_threads = git_config_int(k, v); - if (delta_search_threads < 1) + if (delta_search_threads < 0) die("invalid number of threads specified (%d)", delta_search_threads); #ifndef THREADED_DELTA_SEARCH - if (delta_search_threads > 1) + if (delta_search_threads != 1) warning("no threads support, ignoring %s", k); #endif return 0; @@ -2122,10 +2123,10 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix) if (!prefixcmp(arg, "--threads=")) { char *end; delta_search_threads = strtoul(arg+10, &end, 0); - if (!arg[10] || *end || delta_search_threads < 1) + if (!arg[10] || *end || delta_search_threads < 0) usage(pack_usage); #ifndef THREADED_DELTA_SEARCH - if (delta_search_threads > 1) + if (delta_search_threads != 1) warning("no threads support, " "ignoring %s", arg); #endif @@ -2235,6 +2236,11 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix) if (!pack_to_stdout && thin) die("--thin cannot be used to build an indexable pack."); +#ifdef THREADED_DELTA_SEARCH + if (!delta_search_threads) /* --threads=0 means autodetect */ + delta_search_threads = online_cpus(); +#endif + prepare_packed_git(); if (progress) diff --git a/thread-utils.c b/thread-utils.c new file mode 100644 index 0000000..55e7e29 --- /dev/null +++ b/thread-utils.c @@ -0,0 +1,48 @@ +#include "cache.h" + +#ifdef _WIN32 +# define WIN32_LEAN_AND_MEAN +# include +#elif defined(hpux) || defined(__hpux) || defined(_hpux) +# include +#endif + +/* + * By doing this in two steps we can at least get + * the function to be somewhat coherent, even + * with this disgusting nest of #ifdefs. + */ +#ifndef _SC_NPROCESSORS_ONLN +# ifdef _SC_NPROC_ONLN +# define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN +# elif defined _SC_CRAY_NCPU +# define _SC_NPROCESSORS_ONLN _SC_CRAY_NCPU +# endif +#endif + +int online_cpus(void) +{ +#ifdef _SC_NPROCESSORS_ONLN + long ncpus; +#endif + +#ifdef _WIN32 + SYSTEM_INFO info; + GetSystemInfo(&info); + + if ((int)info.dwNumberOfProcessors > 0) + return (int)info.dwNumberOfProcessors; +#elif defined(hpux) || defined(__hpux) || defined(_hpux) + struct pst_dynamic psd; + + if (!pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0)) + return (int)psd.psd_proc_cnt; +#endif + +#ifdef _SC_NPROCESSORS_ONLN + if ((ncpus = (long)sysconf(_SC_NPROCESSORS_ONLN)) > 0) + return (int)ncpus; +#endif + + return 1; +} diff --git a/thread-utils.h b/thread-utils.h new file mode 100644 index 0000000..cce4b77 --- /dev/null +++ b/thread-utils.h @@ -0,0 +1,6 @@ +#ifndef THREAD_COMPAT_H +#define THREAD_COMPAT_H + +extern int online_cpus(void); + +#endif /* THREAD_COMPAT_H */ -- cgit v0.10.2-6-g49f6 From 6c723f5e6bc579e06a904874f1ceeb8ff2b5a17c Mon Sep 17 00:00:00 2001 From: Brandon Casey Date: Fri, 22 Feb 2008 20:12:58 -0600 Subject: pack-objects: Print a message describing the number of threads for packing Signed-off-by: Brandon Casey Signed-off-by: Junio C Hamano diff --git a/builtin-pack-objects.c b/builtin-pack-objects.c index 586ae11..5a22f49 100644 --- a/builtin-pack-objects.c +++ b/builtin-pack-objects.c @@ -2239,6 +2239,9 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix) #ifdef THREADED_DELTA_SEARCH if (!delta_search_threads) /* --threads=0 means autodetect */ delta_search_threads = online_cpus(); + if (progress) + fprintf(stderr, "Using %d pack threads.\n", + delta_search_threads); #endif prepare_packed_git(); -- cgit v0.10.2-6-g49f6 From 9d561ad324fc8942919981f2c80360e22896989c Mon Sep 17 00:00:00 2001 From: Jakub Narebski Date: Sat, 23 Feb 2008 22:37:08 +0100 Subject: gitweb: Fix bugs in git_search_grep_body: it's length(), not len() Use int(/2) to get integer value for a substring length. Signed-off-by: Jakub Narebski Signed-off-by: Junio C Hamano diff --git a/gitweb/gitweb.perl b/gitweb/gitweb.perl index 326e27c..e8226b1 100755 --- a/gitweb/gitweb.perl +++ b/gitweb/gitweb.perl @@ -3792,7 +3792,7 @@ sub git_search_grep_body { if ($line =~ m/^(.*)($search_regexp)(.*)$/i) { my ($lead, $match, $trail) = ($1, $2, $3); $match = chop_str($match, 70, 5); # in case match is very long - my $contextlen = (80 - len($match))/2; # is left for the remainder + my $contextlen = int((80 - length($match))/2); # for the remainder $contextlen = 30 if ($contextlen > 30); # but not too much $lead = chop_str($lead, $contextlen, 10); $trail = chop_str($trail, $contextlen, 10); -- cgit v0.10.2-6-g49f6 From 52229a29c78df2e48de23ed70ab1934667971d3c Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 23 Feb 2008 15:37:48 -0800 Subject: checkout: show progress when checkout takes long time while switching branches Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 5f176c6..283831e 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -232,6 +232,7 @@ static int merge_working_tree(struct checkout_opts *opts, topts.update = 1; topts.merge = 1; topts.gently = opts->merge; + topts.verbose_update = !opts->quiet; topts.fn = twoway_merge; topts.dir = xcalloc(1, sizeof(*topts.dir)); topts.dir->show_ignored = 1; -- cgit v0.10.2-6-g49f6 From fe3403c3205de44faa926a086b4b99f157fc63fe Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 23 Feb 2008 16:59:16 -0800 Subject: ws_fix_copy(): move the whitespace fixing function to ws.c This is used by git-apply but we can use it elsewhere by slightly generalizing it. Signed-off-by: Junio C Hamano diff --git a/builtin-apply.c b/builtin-apply.c index 5ed4e91..64471a2 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -1515,110 +1515,6 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf) } } -static int copy_wsfix(char *output, const char *patch, int plen, - unsigned ws_rule, int count_error) -{ - /* - * plen is number of bytes to be copied from patch, starting - * at patch. Typically patch[plen-1] is '\n', unless this is - * the incomplete last line. - */ - int i; - int add_nl_to_tail = 0; - int add_cr_to_tail = 0; - int fixed = 0; - int last_tab_in_indent = -1; - int last_space_in_indent = -1; - int need_fix_leading_space = 0; - char *buf; - - /* - * Strip trailing whitespace - */ - if ((ws_rule & WS_TRAILING_SPACE) && - (2 < plen && isspace(patch[plen-2]))) { - if (patch[plen - 1] == '\n') { - add_nl_to_tail = 1; - plen--; - if (1 < plen && patch[plen - 1] == '\r') { - add_cr_to_tail = !!(ws_rule & WS_CR_AT_EOL); - plen--; - } - } - if (0 < plen && isspace(patch[plen - 1])) { - while (0 < plen && isspace(patch[plen-1])) - plen--; - fixed = 1; - } - } - - /* - * Check leading whitespaces (indent) - */ - for (i = 0; i < plen; i++) { - char ch = patch[i]; - if (ch == '\t') { - last_tab_in_indent = i; - if ((ws_rule & WS_SPACE_BEFORE_TAB) && - 0 <= last_space_in_indent) - need_fix_leading_space = 1; - } else if (ch == ' ') { - last_space_in_indent = i; - if ((ws_rule & WS_INDENT_WITH_NON_TAB) && - 8 <= i - last_tab_in_indent) - need_fix_leading_space = 1; - } else - break; - } - - buf = output; - if (need_fix_leading_space) { - /* Process indent ourselves */ - int consecutive_spaces = 0; - int last = last_tab_in_indent + 1; - - if (ws_rule & WS_INDENT_WITH_NON_TAB) { - /* have "last" point at one past the indent */ - if (last_tab_in_indent < last_space_in_indent) - last = last_space_in_indent + 1; - else - last = last_tab_in_indent + 1; - } - - /* - * between patch[0..last-1], strip the funny spaces, - * updating them to tab as needed. - */ - for (i = 0; i < last; i++) { - char ch = patch[i]; - if (ch != ' ') { - consecutive_spaces = 0; - *output++ = ch; - } else { - consecutive_spaces++; - if (consecutive_spaces == 8) { - *output++ = '\t'; - consecutive_spaces = 0; - } - } - } - while (0 < consecutive_spaces--) - *output++ = ' '; - plen -= last; - patch += last; - fixed = 1; - } - - memcpy(output, patch, plen); - if (add_cr_to_tail) - output[plen++] = '\r'; - if (add_nl_to_tail) - output[plen++] = '\n'; - if (fixed && count_error) - applied_after_fixing_ws++; - return output + plen - buf; -} - static void update_pre_post_images(struct image *preimage, struct image *postimage, char *buf, @@ -1740,14 +1636,14 @@ static int match_fragment(struct image *img, int match; /* Try fixing the line in the preimage */ - fixlen = copy_wsfix(buf, orig, oldlen, ws_rule, 0); + fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL); /* Try fixing the line in the target */ if (sizeof(tgtfixbuf) < tgtlen) tgtfix = tgtfixbuf; else tgtfix = xmalloc(tgtlen); - tgtfixlen = copy_wsfix(tgtfix, target, tgtlen, ws_rule, 0); + tgtfixlen = ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL); /* * If they match, either the preimage was based on @@ -2006,8 +1902,7 @@ static int apply_one_fragment(struct image *img, struct fragment *frag, added = plen; } else { - added = copy_wsfix(new, patch + 1, plen, - ws_rule, 1); + added = ws_fix_copy(new, patch + 1, plen, ws_rule, &applied_after_fixing_ws); } add_line_info(&postimage, new, added, (first == '+' ? 0 : LINE_COMMON)); diff --git a/cache.h b/cache.h index ad11c90..3d4c6b0 100644 --- a/cache.h +++ b/cache.h @@ -661,6 +661,7 @@ extern unsigned check_and_emit_line(const char *line, int len, unsigned ws_rule, FILE *stream, const char *set, const char *reset, const char *ws); extern char *whitespace_error_string(unsigned ws); +extern int ws_fix_copy(char *, const char *, int, unsigned, int *); /* ls-files */ int pathspec_match(const char **spec, char *matched, const char *filename, int skiplen); diff --git a/ws.c b/ws.c index 5a9ac45..522f646 100644 --- a/ws.c +++ b/ws.c @@ -212,3 +212,107 @@ unsigned check_and_emit_line(const char *line, int len, unsigned ws_rule, } return result; } + +/* Copy the line to the buffer while fixing whitespaces */ +int ws_fix_copy(char *dst, const char *src, int len, unsigned ws_rule, int *error_count) +{ + /* + * len is number of bytes to be copied from src, starting + * at src. Typically src[len-1] is '\n', unless this is + * the incomplete last line. + */ + int i; + int add_nl_to_tail = 0; + int add_cr_to_tail = 0; + int fixed = 0; + int last_tab_in_indent = -1; + int last_space_in_indent = -1; + int need_fix_leading_space = 0; + char *buf; + + /* + * Strip trailing whitespace + */ + if ((ws_rule & WS_TRAILING_SPACE) && + (2 < len && isspace(src[len-2]))) { + if (src[len - 1] == '\n') { + add_nl_to_tail = 1; + len--; + if (1 < len && src[len - 1] == '\r') { + add_cr_to_tail = !!(ws_rule & WS_CR_AT_EOL); + len--; + } + } + if (0 < len && isspace(src[len - 1])) { + while (0 < len && isspace(src[len-1])) + len--; + fixed = 1; + } + } + + /* + * Check leading whitespaces (indent) + */ + for (i = 0; i < len; i++) { + char ch = src[i]; + if (ch == '\t') { + last_tab_in_indent = i; + if ((ws_rule & WS_SPACE_BEFORE_TAB) && + 0 <= last_space_in_indent) + need_fix_leading_space = 1; + } else if (ch == ' ') { + last_space_in_indent = i; + if ((ws_rule & WS_INDENT_WITH_NON_TAB) && + 8 <= i - last_tab_in_indent) + need_fix_leading_space = 1; + } else + break; + } + + buf = dst; + if (need_fix_leading_space) { + /* Process indent ourselves */ + int consecutive_spaces = 0; + int last = last_tab_in_indent + 1; + + if (ws_rule & WS_INDENT_WITH_NON_TAB) { + /* have "last" point at one past the indent */ + if (last_tab_in_indent < last_space_in_indent) + last = last_space_in_indent + 1; + else + last = last_tab_in_indent + 1; + } + + /* + * between src[0..last-1], strip the funny spaces, + * updating them to tab as needed. + */ + for (i = 0; i < last; i++) { + char ch = src[i]; + if (ch != ' ') { + consecutive_spaces = 0; + *dst++ = ch; + } else { + consecutive_spaces++; + if (consecutive_spaces == 8) { + *dst++ = '\t'; + consecutive_spaces = 0; + } + } + } + while (0 < consecutive_spaces--) + *dst++ = ' '; + len -= last; + src += last; + fixed = 1; + } + + memcpy(dst, src, len); + if (add_cr_to_tail) + dst[len++] = '\r'; + if (add_nl_to_tail) + dst[len++] = '\n'; + if (fixed && error_count) + (*error_count)++; + return dst + len - buf; +} -- cgit v0.10.2-6-g49f6 From 1ba0836307c463ce6de11868c85aa46c7396dae4 Mon Sep 17 00:00:00 2001 From: Steffen Prohaska Date: Sat, 23 Feb 2008 09:41:56 +0100 Subject: t4014: Replace sed's non-standard 'Q' by standard 'q' t4014 test used GNU extension 'Q' in its sed scripts, but the uses can safely be replaced with 'q'. Among other platforms, sed on Mac OS X 10.4 does not accept the former. Signed-off-by: Steffen Prohaska Signed-off-by: Junio C Hamano diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh index a39e786..16aa99d 100755 --- a/t/t4014-format-patch.sh +++ b/t/t4014-format-patch.sh @@ -95,7 +95,7 @@ test_expect_success 'extra headers' ' git config --add format.headers "Cc: S. E. Cipient " && git format-patch --stdout master..side > patch2 && - sed -e "/^$/Q" patch2 > hdrs2 && + sed -e "/^$/q" patch2 > hdrs2 && grep "^To: R. E. Cipient $" hdrs2 && grep "^Cc: S. E. Cipient $" hdrs2 @@ -106,7 +106,7 @@ test_expect_success 'extra headers without newlines' ' git config --replace-all format.headers "To: R. E. Cipient " && git config --add format.headers "Cc: S. E. Cipient " && git format-patch --stdout master..side >patch3 && - sed -e "/^$/Q" patch3 > hdrs3 && + sed -e "/^$/q" patch3 > hdrs3 && grep "^To: R. E. Cipient $" hdrs3 && grep "^Cc: S. E. Cipient $" hdrs3 @@ -117,7 +117,7 @@ test_expect_success 'extra headers with multiple To:s' ' git config --replace-all format.headers "To: R. E. Cipient " && git config --add format.headers "To: S. E. Cipient " && git format-patch --stdout master..side > patch4 && - sed -e "/^$/Q" patch4 > hdrs4 && + sed -e "/^$/q" patch4 > hdrs4 && grep "^To: R. E. Cipient ,$" hdrs4 && grep "^ *S. E. Cipient $" hdrs4 ' @@ -125,7 +125,7 @@ test_expect_success 'extra headers with multiple To:s' ' test_expect_success 'additional command line cc' ' git config --replace-all format.headers "Cc: R. E. Cipient " && - git format-patch --cc="S. E. Cipient " --stdout master..side | sed -e "/^$/Q" >patch5 && + git format-patch --cc="S. E. Cipient " --stdout master..side | sed -e "/^$/q" >patch5 && grep "^Cc: R. E. Cipient ,$" patch5 && grep "^ *S. E. Cipient $" patch5 ' -- cgit v0.10.2-6-g49f6 From 04c9e11f2cffaf84dd20602f811bf377f6033cb6 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sat, 23 Feb 2008 15:45:19 -0800 Subject: checkout: error out when index is unmerged even with -m Even when -m is given to allow fallilng back to 3-way merge while switching branches, we should refuse if the original index is unmerged. Signed-off-by: Junio C Hamano Acked-by: Daniel Barkalow diff --git a/builtin-checkout.c b/builtin-checkout.c index 283831e..d5f0930 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -226,24 +226,25 @@ static int merge_working_tree(struct checkout_opts *opts, refresh_cache(REFRESH_QUIET); if (unmerged_cache()) { - ret = opts->merge ? -1 : - error("you need to resolve your current index first"); - } else { - topts.update = 1; - topts.merge = 1; - topts.gently = opts->merge; - topts.verbose_update = !opts->quiet; - topts.fn = twoway_merge; - topts.dir = xcalloc(1, sizeof(*topts.dir)); - topts.dir->show_ignored = 1; - topts.dir->exclude_per_dir = ".gitignore"; - tree = parse_tree_indirect(old->commit->object.sha1); - init_tree_desc(&trees[0], tree->buffer, tree->size); - tree = parse_tree_indirect(new->commit->object.sha1); - init_tree_desc(&trees[1], tree->buffer, tree->size); - ret = unpack_trees(2, trees, &topts); + error("you need to resolve your current index first"); + return 1; } - if (ret) { + + /* 2-way merge to the new branch */ + topts.update = 1; + topts.merge = 1; + topts.gently = opts->merge; + topts.verbose_update = !opts->quiet; + topts.fn = twoway_merge; + topts.dir = xcalloc(1, sizeof(*topts.dir)); + topts.dir->show_ignored = 1; + topts.dir->exclude_per_dir = ".gitignore"; + tree = parse_tree_indirect(old->commit->object.sha1); + init_tree_desc(&trees[0], tree->buffer, tree->size); + tree = parse_tree_indirect(new->commit->object.sha1); + init_tree_desc(&trees[1], tree->buffer, tree->size); + + if (unpack_trees(2, trees, &topts)) { /* * Unpack couldn't do a trivial merge; either * give up or do a real merge, depending on -- cgit v0.10.2-6-g49f6 From 6c0f86943e9ebba5aa281772e01559773e0c1234 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 00:38:04 -0500 Subject: Ensure 'make dist' compiles git-archive.exe on Cygwin On Cygwin we have to use git-archive.exe as the target, otherwise running 'make dist' does not compile git-archive in the current directory. That may cause 'make dist' to fail on a clean source tree that has never been built before. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/Makefile b/Makefile index 92341c4..7a3c6d1 100644 --- a/Makefile +++ b/Makefile @@ -1087,7 +1087,7 @@ git.spec: git.spec.in mv $@+ $@ GIT_TARNAME=git-$(GIT_VERSION) -dist: git.spec git-archive configure +dist: git.spec git-archive$(X) configure ./git-archive --format=tar \ --prefix=$(GIT_TARNAME)/ HEAD^{tree} > $(GIT_TARNAME).tar @mkdir -p $(GIT_TARNAME) -- cgit v0.10.2-6-g49f6 From 8c87dc77ae45d7277001b1be2c88ea9062e11d72 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 03:07:19 -0500 Subject: Protect peel_ref fallback case from NULL parse_object result If the SHA-1 we are requesting the object for does not exist in the object database we get a NULL back. Accessing the type from that is not likely to succeed on any system. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/refs.c b/refs.c index 67d2a50..fb33da1 100644 --- a/refs.c +++ b/refs.c @@ -506,7 +506,7 @@ int peel_ref(const char *ref, unsigned char *sha1) /* fallback - callers should not call this for unpacked refs */ o = parse_object(base); - if (o->type == OBJ_TAG) { + if (o && o->type == OBJ_TAG) { o = deref_tag(o, ref, 0); if (o) { hashcpy(sha1, o->sha1); -- cgit v0.10.2-6-g49f6 From e85486450eb0407ad0449d0214b97506d452407f Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sat, 23 Feb 2008 13:36:08 -0800 Subject: Be more verbose when checkout takes a long time So I find it irritating when git thinks for a long time without telling me what's taking so long. And by "long time" I definitely mean less than two seconds, which is already way too long for me. This hits me when doing a large pull and the checkout takes a long time, or when just switching to another branch that is old and again checkout takes a while. Now, git read-tree already had support for the "-v" flag that does nice updates about what's going on, but it was delayed by two seconds, and if the thing had already done more than half by then it would be quiet even after that, so in practice it meant that we migth be quiet for up to four seconds. Much too long. So this patch changes the timeout to just one second, which makes it much more palatable to me. The other thing this patch does is that "git checkout" now doesn't disable the "-v" flag when doing its thing, and only disables the output when given the -q flag. When allowing "checkout -m" to fall back to a 3-way merge, the users will see the error message from straight "checkout", so we will tell them that we do fall back to make them look less scary. Signed-off-by: Junio C Hamano diff --git a/git-checkout.sh b/git-checkout.sh index bd74d70..1a7689a 100755 --- a/git-checkout.sh +++ b/git-checkout.sh @@ -210,11 +210,14 @@ then git read-tree $v --reset -u $new else git update-index --refresh >/dev/null - merge_error=$(git read-tree -m -u --exclude-per-directory=.gitignore $old $new 2>&1) || ( - case "$merge" in - '') - echo >&2 "$merge_error" + git read-tree $v -m -u --exclude-per-directory=.gitignore $old $new || ( + case "$merge,$v" in + ,*) exit 1 ;; + 1,) + ;; # quiet + *) + echo >&2 "Falling back to 3-way merge..." ;; esac # Match the index to the working tree, and do a three-way. diff --git a/unpack-trees.c b/unpack-trees.c index 07c4c28..56c1ffb 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -301,7 +301,7 @@ static void check_updates(struct cache_entry **src, int nr, } progress = start_progress_delay("Checking out files", - total, 50, 2); + total, 50, 1); cnt = 0; } -- cgit v0.10.2-6-g49f6 From 0ae91be0e1fac3ff31675f0ec2c7ebf2bb5c1be6 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 03:07:22 -0500 Subject: Optimize peel_ref for the current ref of a for_each_ref callback Currently the only caller of peel_ref is show-ref, which is using this function to show the peeled tag information if it is available from an existing packed-refs file. The call happens during the for_each_ref callback function, so we have the proper struct ref_list already on the call stack but it is not easily available to return the peeled information to the caller. We now save the current struct ref_list item before calling back into the callback function so that future calls to peel_ref from within the callback function can quickly access the current ref. Doing so will save us an lstat() per ref processed as we no longer have to check the filesystem to see if the ref exists as a loose file or is packed. This current ref caching also saves a linear scan of the cached packed refs list. As a micro-optimization we test the address of the passed ref name against the current_ref->name before we go into the much more costly strcmp(). Nearly any caller of peel_ref will be passing us the same string do_for_each_ref passed them, which is current_ref->name. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/refs.c b/refs.c index fb33da1..c979fb1 100644 --- a/refs.c +++ b/refs.c @@ -157,6 +157,7 @@ static struct cached_refs { struct ref_list *loose; struct ref_list *packed; } cached_refs; +static struct ref_list *current_ref; static void free_ref_list(struct ref_list *list) { @@ -476,6 +477,7 @@ static int do_one_ref(const char *base, each_ref_fn fn, int trim, error("%s does not point to a valid object!", entry->name); return 0; } + current_ref = entry; return fn(entry->name + trim, entry->sha1, entry->flag, cb_data); } @@ -485,6 +487,16 @@ int peel_ref(const char *ref, unsigned char *sha1) unsigned char base[20]; struct object *o; + if (current_ref && (current_ref->name == ref + || !strcmp(current_ref->name, ref))) { + if (current_ref->flag & REF_KNOWS_PEELED) { + hashcpy(sha1, current_ref->peeled); + return 0; + } + hashcpy(base, current_ref->sha1); + goto fallback; + } + if (!resolve_ref(ref, base, 1, &flag)) return -1; @@ -504,7 +516,7 @@ int peel_ref(const char *ref, unsigned char *sha1) } } - /* fallback - callers should not call this for unpacked refs */ +fallback: o = parse_object(base); if (o && o->type == OBJ_TAG) { o = deref_tag(o, ref, 0); @@ -519,7 +531,7 @@ int peel_ref(const char *ref, unsigned char *sha1) static int do_for_each_ref(const char *base, each_ref_fn fn, int trim, void *cb_data) { - int retval; + int retval = 0; struct ref_list *packed = get_packed_refs(); struct ref_list *loose = get_loose_refs(); @@ -539,15 +551,18 @@ static int do_for_each_ref(const char *base, each_ref_fn fn, int trim, } retval = do_one_ref(base, fn, trim, cb_data, entry); if (retval) - return retval; + goto end_each; } for (packed = packed ? packed : loose; packed; packed = packed->next) { retval = do_one_ref(base, fn, trim, cb_data, packed); if (retval) - return retval; + goto end_each; } - return 0; + +end_each: + current_ref = NULL; + return retval; } int head_ref(each_ref_fn fn, void *cb_data) -- cgit v0.10.2-6-g49f6 From feededd05b551a02a95fe2a736e9d5f688b86119 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 03:07:25 -0500 Subject: Teach git-describe to use peeled ref information when scanning tags By using the peeled ref information inside of the packed-refs file we can avoid opening tag objects to obtain the commits they reference. This speeds up git-describe when there are a large number of tags in the repository as we have less objects to parse before we can start commit matching. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/builtin-describe.c b/builtin-describe.c index 3428483..bfd25e2 100644 --- a/builtin-describe.c +++ b/builtin-describe.c @@ -46,19 +46,30 @@ static void add_to_known_names(const char *path, static int get_name(const char *path, const unsigned char *sha1, int flag, void *cb_data) { - struct commit *commit = lookup_commit_reference_gently(sha1, 1); + struct commit *commit; struct object *object; - int prio; + unsigned char peeled[20]; + int is_tag, prio; + + if (!peel_ref(path, peeled) && !is_null_sha1(peeled)) { + commit = lookup_commit_reference_gently(peeled, 1); + if (!commit) + return 0; + is_tag = !!hashcmp(sha1, commit->object.sha1); + } else { + commit = lookup_commit_reference_gently(sha1, 1); + object = parse_object(sha1); + if (!commit || !object) + return 0; + is_tag = object->type == OBJ_TAG; + } - if (!commit) - return 0; - object = parse_object(sha1); /* If --all, then any refs are used. * If --tags, then any tags are used. * Otherwise only annotated tags are used. */ if (!prefixcmp(path, "refs/tags/")) { - if (object->type == OBJ_TAG) { + if (is_tag) { prio = 2; if (pattern && fnmatch(pattern, path + 10, 0)) prio = 0; -- cgit v0.10.2-6-g49f6 From 8a5a1884e93564cb1f46a73184d083a5181d573b Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 03:07:28 -0500 Subject: Avoid accessing non-tag refs in git-describe unless --all is requested If we aren't going to use a ref there is no reason for us to open its object from the object database. This avoids opening any of the head commits reachable from refs/heads/ unless they are also reachable through the commit we have been asked to describe and we need to walk through it to find a tag. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/builtin-describe.c b/builtin-describe.c index bfd25e2..9c958bd 100644 --- a/builtin-describe.c +++ b/builtin-describe.c @@ -46,11 +46,15 @@ static void add_to_known_names(const char *path, static int get_name(const char *path, const unsigned char *sha1, int flag, void *cb_data) { + int might_be_tag = !prefixcmp(path, "refs/tags/"); struct commit *commit; struct object *object; unsigned char peeled[20]; int is_tag, prio; + if (!all && !might_be_tag) + return 0; + if (!peel_ref(path, peeled) && !is_null_sha1(peeled)) { commit = lookup_commit_reference_gently(peeled, 1); if (!commit) @@ -68,7 +72,7 @@ static int get_name(const char *path, const unsigned char *sha1, int flag, void * If --tags, then any tags are used. * Otherwise only annotated tags are used. */ - if (!prefixcmp(path, "refs/tags/")) { + if (might_be_tag) { if (is_tag) { prio = 2; if (pattern && fnmatch(pattern, path + 10, 0)) -- cgit v0.10.2-6-g49f6 From 2c33f7575452f53382dcf77fdc88a2ea5d46f09d Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 03:07:31 -0500 Subject: Teach git-describe --exact-match to avoid expensive tag searches Sometimes scripts want (or need) the annotated tag name that exactly matches a specific commit, or no tag at all. In such cases it can be difficult to determine if the output of `git describe $commit` is a real tag name or a tag+abbreviated commit. A common idiom is to run git-describe twice: if test $(git describe $commit) = $(git describe --abbrev=0 $commit) ... but this is a huge waste of time if the caller is just going to pick a different method to describe $commit or abort because it is not exactly an annotated tag. Setting the maximum number of candidates to 0 allows the caller to ask for only a tag that directly points at the supplied commit, or to have git-describe abort if no such item exists. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/Documentation/git-describe.txt b/Documentation/git-describe.txt index 1c3dfb4..fbb40a2 100644 --- a/Documentation/git-describe.txt +++ b/Documentation/git-describe.txt @@ -45,6 +45,11 @@ OPTIONS candidates to describe the input committish consider up to candidates. Increasing above 10 will take slightly longer but may produce a more accurate result. + An of 0 will cause only exact matches to be output. + +--exact-match:: + Only output exact matches (a tag directly references the + supplied commit). This is a synonym for --candidates=0. --debug:: Verbosely display information about the searching strategy diff --git a/builtin-describe.c b/builtin-describe.c index 9c958bd..05e309f 100644 --- a/builtin-describe.c +++ b/builtin-describe.c @@ -174,6 +174,8 @@ static void describe(const char *arg, int last_one) return; } + if (!max_candidates) + die("no tag exactly matches '%s'", sha1_to_hex(cmit->object.sha1)); if (debug) fprintf(stderr, "searching to describe %s\n", arg); @@ -270,6 +272,8 @@ int cmd_describe(int argc, const char **argv, const char *prefix) OPT_BOOLEAN(0, "all", &all, "use any ref in .git/refs"), OPT_BOOLEAN(0, "tags", &tags, "use any tag in .git/refs/tags"), OPT__ABBREV(&abbrev), + OPT_SET_INT(0, "exact-match", &max_candidates, + "only output exact matches", 0), OPT_INTEGER(0, "candidates", &max_candidates, "consider most recent tags (default: 10)"), OPT_STRING(0, "match", &pattern, "pattern", @@ -278,8 +282,8 @@ int cmd_describe(int argc, const char **argv, const char *prefix) }; argc = parse_options(argc, argv, options, describe_usage, 0); - if (max_candidates < 1) - max_candidates = 1; + if (max_candidates < 0) + max_candidates = 0; else if (max_candidates > MAX_TAGS) max_candidates = MAX_TAGS; -- cgit v0.10.2-6-g49f6 From 27c578885a0b8f56430c5a24f558e2b45cf04a38 Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 03:07:33 -0500 Subject: Use git-describe --exact-match in bash prompt on detached HEAD Most of the time when I am on a detached HEAD and I am not doing a rebase or bisect operation the working directory is sitting on a tagged release of the repository. Showing the tag name instead of the commit SHA-1 is much more descriptive and a much better reminder of the state of this working directory. Now that git-describe --exact-match is available as a cheap means of obtaining the exact annotated tag or nothing at all, we can favor the annotated tag name over the abbreviated commit SHA-1. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash index 4ea727b..8722a68 100755 --- a/contrib/completion/git-completion.bash +++ b/contrib/completion/git-completion.bash @@ -91,7 +91,10 @@ __git_ps1 () fi if ! b="$(git symbolic-ref HEAD 2>/dev/null)" then - b="$(cut -c1-7 $g/HEAD)..." + if ! b="$(git describe --exact-match HEAD 2>/dev/null)" + then + b="$(cut -c1-7 $g/HEAD)..." + fi fi fi -- cgit v0.10.2-6-g49f6 From 2b0b551d7662a4246ed55b6a7029ba3caa65cf98 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sun, 24 Feb 2008 17:37:15 -0800 Subject: diff --dirstat: saner handling of binary and unmerged files We do not account binary nor unmerged files when --shortstat is asked for (or the summary stat at the end of --stat). The new option --dirstat should work the same way as it is about summarizing the changes of multiple files by adding them up. Signed-off-by: Junio C Hamano diff --git a/diff.c b/diff.c index dd374d4..bcc323f 100644 --- a/diff.c +++ b/diff.c @@ -1016,7 +1016,10 @@ static long gather_dirstat(struct diffstat_dir *dir, unsigned long changed, cons this = gather_dirstat(dir, changed, f->name, newbaselen); sources++; } else { - this = f->added + f->deleted; + if (f->is_unmerged || f->is_binary) + this = 0; + else + this = f->added + f->deleted; dir->files++; dir->nr--; sources += 2; @@ -1053,6 +1056,8 @@ static void show_dirstat(struct diffstat_t *data, struct diff_options *options) /* Calculate total changes */ changed = 0; for (i = 0; i < data->nr; i++) { + if (data->files[i]->is_binary || data->files[i]->is_unmerged) + continue; changed += data->files[i]->added; changed += data->files[i]->deleted; } -- cgit v0.10.2-6-g49f6 From b577bb925e745845155c6f51eae841c339ce68f6 Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Sat, 23 Feb 2008 17:14:17 -0800 Subject: Eliminate confusing "won't bisect on seeked tree" failure This error message is very confusing---it doesn't tell the user anything about how to fix the situation. And the actual fix for the situation ("git bisect reset") does a checkout of a potentially random branch, (compared to what the user wants to be on for the bisect she is starting). The simplest way to eliminate the confusion is to just make "git bisect start" do the cleanup itself. There's no significant loss of safety here since we already have a general safety in the form of the reflog. Note: We preserve the warning for any cogito users. We do this by switching from .git/head-name to .git/BISECT_START for the extra state, (which is a more descriptive name anyway). Signed-off-by: Carl Worth Signed-off-by: Junio C Hamano diff --git a/git-bisect.sh b/git-bisect.sh index 74715ed..2c32d0b 100755 --- a/git-bisect.sh +++ b/git-bisect.sh @@ -67,16 +67,18 @@ bisect_start() { die "Bad HEAD - I need a HEAD" case "$head" in refs/heads/bisect) - if [ -s "$GIT_DIR/head-name" ]; then - branch=`cat "$GIT_DIR/head-name"` + if [ -s "$GIT_DIR/BISECT_START" ]; then + branch=`cat "$GIT_DIR/BISECT_START"` else branch=master fi git checkout $branch || exit ;; refs/heads/*|$_x40) + # This error message should only be triggered by cogito usage, + # and cogito users should understand it relates to cg-seek. [ -s "$GIT_DIR/head-name" ] && die "won't bisect on seeked tree" - echo "${head#refs/heads/}" >"$GIT_DIR/head-name" + echo "${head#refs/heads/}" >"$GIT_DIR/BISECT_START" ;; *) die "Bad HEAD - strange symbolic ref" @@ -353,8 +355,8 @@ bisect_reset() { return } case "$#" in - 0) if [ -s "$GIT_DIR/head-name" ]; then - branch=`cat "$GIT_DIR/head-name"` + 0) if [ -s "$GIT_DIR/BISECT_START" ]; then + branch=`cat "$GIT_DIR/BISECT_START"` else branch=master fi ;; @@ -365,7 +367,9 @@ bisect_reset() { usage ;; esac if git checkout "$branch"; then + # Cleanup head-name if it got left by an old version of git-bisect rm -f "$GIT_DIR/head-name" + rm -f "$GIT_DIR/BISECT_START" bisect_clean_state fi } diff --git a/t/t6030-bisect-porcelain.sh b/t/t6030-bisect-porcelain.sh index ec71123..4908e87 100755 --- a/t/t6030-bisect-porcelain.sh +++ b/t/t6030-bisect-porcelain.sh @@ -260,7 +260,7 @@ test_expect_success 'bisect starting with a detached HEAD' ' git checkout master^ && HEAD=$(git rev-parse --verify HEAD) && git bisect start && - test $HEAD = $(cat .git/head-name) && + test $HEAD = $(cat .git/BISECT_START) && git bisect reset && test $HEAD = $(git rev-parse --verify HEAD) -- cgit v0.10.2-6-g49f6 From 6d34a2bad11f241e56423511d4a0d62a1f378668 Mon Sep 17 00:00:00 2001 From: Jeff King Date: Sun, 24 Feb 2008 16:03:52 -0500 Subject: t9001: enhance fake sendmail test harness Previously, the fake.sendmail test harness would write its output to a hardcoded file, allowing only a single message to be tested. Instead, let's have it save the messages for all of its invocations so that we can see which messages were sent, and in which order. Signed-off-by: Jeff King Signed-off-by: Junio C Hamano diff --git a/t/t9001-send-email.sh b/t/t9001-send-email.sh index 2efaed4..4975048 100755 --- a/t/t9001-send-email.sh +++ b/t/t9001-send-email.sh @@ -15,16 +15,22 @@ test_expect_success \ 'Setup helper tool' \ '(echo "#!/bin/sh" echo shift + echo output=1 + echo "while test -f commandline\$output; do output=\$((\$output+1)); done" echo for a echo do echo " echo \"!\$a!\"" - echo "done >commandline" - echo "cat > msgtxt" + echo "done >commandline\$output" + echo "cat > msgtxt\$output" ) >fake.sendmail && chmod +x ./fake.sendmail && git add fake.sendmail && GIT_AUTHOR_NAME="A" git commit -a -m "Second."' +clean_fake_sendmail() { + rm -f commandline* msgtxt* +} + test_expect_success 'Extract patches' ' patches=`git format-patch -n HEAD^1` ' @@ -39,7 +45,7 @@ cat >expected <<\EOF EOF test_expect_success \ 'Verify commandline' \ - 'diff commandline expected' + 'diff commandline1 expected' cat >expected-show-all-headers <<\EOF 0001-Second.patch @@ -82,7 +88,7 @@ z8=zzzzzzzz z64=$z8$z8$z8$z8$z8$z8$z8$z8 z512=$z64$z64$z64$z64$z64$z64$z64$z64 test_expect_success 'reject long lines' ' - rm -f commandline && + clean_fake_sendmail && cp $patches longline.patch && echo $z512$z512 >>longline.patch && ! git send-email \ @@ -95,7 +101,7 @@ test_expect_success 'reject long lines' ' ' test_expect_success 'no patch was sent' ' - ! test -e commandline + ! test -e commandline1 ' test_expect_success 'allow long lines with --no-validate' ' @@ -109,6 +115,7 @@ test_expect_success 'allow long lines with --no-validate' ' ' test_expect_success 'Invalid In-Reply-To' ' + clean_fake_sendmail && git send-email \ --from="Example " \ --to=nobody@example.com \ @@ -116,17 +123,18 @@ test_expect_success 'Invalid In-Reply-To' ' --smtp-server="$(pwd)/fake.sendmail" \ $patches 2>errors - ! grep "^In-Reply-To: < *>" msgtxt + ! grep "^In-Reply-To: < *>" msgtxt1 ' test_expect_success 'Valid In-Reply-To when prompting' ' + clean_fake_sendmail && (echo "From Example " echo "To Example " echo "" ) | env GIT_SEND_EMAIL_NOTTY=1 git send-email \ --smtp-server="$(pwd)/fake.sendmail" \ $patches 2>errors && - ! grep "^In-Reply-To: < *>" msgtxt + ! grep "^In-Reply-To: < *>" msgtxt1 ' test_done -- cgit v0.10.2-6-g49f6 From 8a8bf4690e20a545561249a9b393c1ef3239c03d Mon Sep 17 00:00:00 2001 From: Jeff King Date: Sun, 24 Feb 2008 16:04:14 -0500 Subject: send-email: test compose functionality This is just a basic sanity check that --compose works at all. Signed-off-by: Jeff King Signed-off-by: Junio C Hamano diff --git a/t/t9001-send-email.sh b/t/t9001-send-email.sh index 4975048..cbbfa9c 100755 --- a/t/t9001-send-email.sh +++ b/t/t9001-send-email.sh @@ -137,4 +137,33 @@ test_expect_success 'Valid In-Reply-To when prompting' ' ! grep "^In-Reply-To: < *>" msgtxt1 ' +test_expect_success 'setup fake editor' ' + (echo "#!/bin/sh" && + echo "echo fake edit >>\$1" + ) >fake-editor && + chmod +x fake-editor +' + +test_expect_success '--compose works' ' + clean_fake_sendmail && + echo y | \ + GIT_EDITOR=$(pwd)/fake-editor \ + GIT_SEND_EMAIL_NOTTY=1 \ + git send-email \ + --compose --subject foo \ + --from="Example " \ + --to=nobody@example.com \ + --smtp-server="$(pwd)/fake.sendmail" \ + $patches \ + 2>errors +' + +test_expect_success 'first message is compose text' ' + grep "^fake edit" msgtxt1 +' + +test_expect_success 'second message is patch' ' + grep "Subject:.*Second" msgtxt2 +' + test_done -- cgit v0.10.2-6-g49f6 From 41eb33bd0cbecf1b441ada91ab186ee49fb086cc Mon Sep 17 00:00:00 2001 From: Jeff King Date: Sun, 24 Feb 2008 17:16:55 -0500 Subject: help: use parseopt This patch converts cmd_help to use parseopt, along with a few style cleanups, including: - enum constants are now ALL_CAPS - parse_help_format returns an enum value rather than setting a global as a side effect Signed-off-by: Jeff King Signed-off-by: Junio C Hamano diff --git a/help.c b/help.c index 8143dcd..5feb849 100644 --- a/help.c +++ b/help.c @@ -7,40 +7,49 @@ #include "builtin.h" #include "exec_cmd.h" #include "common-cmds.h" - -static const char *help_default_format; - -static enum help_format { - man_format, - info_format, - web_format, -} help_format = man_format; - -static void parse_help_format(const char *format) +#include "parse-options.h" + +enum help_format { + HELP_FORMAT_MAN, + HELP_FORMAT_INFO, + HELP_FORMAT_WEB, +}; + +static int show_all = 0; +static enum help_format help_format = HELP_FORMAT_MAN; +static struct option builtin_help_options[] = { + OPT_BOOLEAN('a', "all", &show_all, "print all available commands"), + OPT_SET_INT('m', "man", &help_format, "show man page", HELP_FORMAT_MAN), + OPT_SET_INT('w', "web", &help_format, "show manual in web browser", + HELP_FORMAT_WEB), + OPT_SET_INT('i', "info", &help_format, "show info page", + HELP_FORMAT_INFO), +}; + +static const char * const builtin_help_usage[] = { + "git-help [--all] [--man|--web|--info] [command]", + NULL +}; + +static enum help_format parse_help_format(const char *format) { - if (!format) { - help_format = man_format; - return; - } - if (!strcmp(format, "man")) { - help_format = man_format; - return; - } - if (!strcmp(format, "info")) { - help_format = info_format; - return; - } - if (!strcmp(format, "web") || !strcmp(format, "html")) { - help_format = web_format; - return; - } + if (!strcmp(format, "man")) + return HELP_FORMAT_MAN; + if (!strcmp(format, "info")) + return HELP_FORMAT_INFO; + if (!strcmp(format, "web") || !strcmp(format, "html")) + return HELP_FORMAT_WEB; die("unrecognized help format '%s'", format); } static int git_help_config(const char *var, const char *value) { - if (!strcmp(var, "help.format")) - return git_config_string(&help_default_format, var, value); + if (!strcmp(var, "help.format")) { + if (!value) + return config_error_nonbool(var); + help_format = parse_help_format(value); + return 0; + } return git_default_config(var, value); } @@ -362,50 +371,36 @@ int cmd_version(int argc, const char **argv, const char *prefix) int cmd_help(int argc, const char **argv, const char *prefix) { - const char *help_cmd = argv[1]; + int nongit; - if (argc < 2) { - printf("usage: %s\n\n", git_usage_string); - list_common_cmds_help(); - exit(0); - } + setup_git_directory_gently(&nongit); + git_config(git_help_config); - if (!strcmp(help_cmd, "--all") || !strcmp(help_cmd, "-a")) { + argc = parse_options(argc, argv, builtin_help_options, + builtin_help_usage, 0); + + if (show_all) { printf("usage: %s\n\n", git_usage_string); list_commands(); + return 0; } - else if (!strcmp(help_cmd, "--web") || !strcmp(help_cmd, "-w")) { - show_html_page(argc > 2 ? argv[2] : NULL); - } - - else if (!strcmp(help_cmd, "--info") || !strcmp(help_cmd, "-i")) { - show_info_page(argc > 2 ? argv[2] : NULL); - } - - else if (!strcmp(help_cmd, "--man") || !strcmp(help_cmd, "-m")) { - show_man_page(argc > 2 ? argv[2] : NULL); + if (!argv[0]) { + printf("usage: %s\n\n", git_usage_string); + list_common_cmds_help(); + return 0; } - else { - int nongit; - - setup_git_directory_gently(&nongit); - git_config(git_help_config); - if (help_default_format) - parse_help_format(help_default_format); - - switch (help_format) { - case man_format: - show_man_page(help_cmd); - break; - case info_format: - show_info_page(help_cmd); - break; - case web_format: - show_html_page(help_cmd); - break; - } + switch (help_format) { + case HELP_FORMAT_MAN: + show_man_page(argv[0]); + break; + case HELP_FORMAT_INFO: + show_info_page(argv[0]); + break; + case HELP_FORMAT_WEB: + show_html_page(argv[0]); + break; } return 0; -- cgit v0.10.2-6-g49f6 From 94351118c0a820002b093598e7fac5bdf3c0291f Mon Sep 17 00:00:00 2001 From: Jeff King Date: Sun, 24 Feb 2008 17:17:14 -0500 Subject: make alias lookup a public, procedural function This converts git_config_alias to the public alias_lookup function. Because of the nature of our config parser, we still have to rely on setting static data. However, that interface is wrapped so that you can just say value = alias_lookup(key); Signed-off-by: Jeff King Signed-off-by: Junio C Hamano diff --git a/Makefile b/Makefile index d33a556..b460bb2 100644 --- a/Makefile +++ b/Makefile @@ -327,7 +327,8 @@ LIB_OBJS = \ alloc.o merge-file.o path-list.o help.o unpack-trees.o $(DIFF_OBJS) \ color.o wt-status.o archive-zip.o archive-tar.o shallow.o utf8.o \ convert.o attr.o decorate.o progress.o mailmap.o symlinks.o remote.o \ - transport.o bundle.o walker.o parse-options.o ws.o archive.o + transport.o bundle.o walker.o parse-options.o ws.o archive.o \ + alias.o BUILTIN_OBJS = \ builtin-add.o \ diff --git a/alias.c b/alias.c new file mode 100644 index 0000000..116cac8 --- /dev/null +++ b/alias.c @@ -0,0 +1,22 @@ +#include "cache.h" + +static const char *alias_key; +static char *alias_val; +static int alias_lookup_cb(const char *k, const char *v) +{ + if (!prefixcmp(k, "alias.") && !strcmp(k+6, alias_key)) { + if (!v) + return config_error_nonbool(k); + alias_val = xstrdup(v); + return 0; + } + return 0; +} + +char *alias_lookup(const char *alias) +{ + alias_key = alias; + alias_val = NULL; + git_config(alias_lookup_cb); + return alias_val; +} diff --git a/cache.h b/cache.h index fa5a9e5..1e9c937 100644 --- a/cache.h +++ b/cache.h @@ -765,4 +765,6 @@ int pathspec_match(const char **spec, char *matched, const char *filename, int s int report_path_error(const char *ps_matched, const char **pathspec, int prefix_offset); void overlay_tree_on_cache(const char *tree_name, const char *prefix); +char *alias_lookup(const char *alias); + #endif /* CACHE_H */ diff --git a/git.c b/git.c index 0cb8688..8f08b12 100644 --- a/git.c +++ b/git.c @@ -87,19 +87,6 @@ static int handle_options(const char*** argv, int* argc, int* envchanged) return handled; } -static const char *alias_command; -static char *alias_string; - -static int git_alias_config(const char *var, const char *value) -{ - if (!prefixcmp(var, "alias.") && !strcmp(var + 6, alias_command)) { - if (!value) - return config_error_nonbool(var); - alias_string = xstrdup(value); - } - return 0; -} - static int split_cmdline(char *cmdline, const char ***argv) { int src, dst, count = 0, size = 16; @@ -159,11 +146,13 @@ static int handle_alias(int *argcp, const char ***argv) const char *subdir; int count, option_count; const char** new_argv; + const char *alias_command; + char *alias_string; subdir = setup_git_directory_gently(&nongit); alias_command = (*argv)[0]; - git_config(git_alias_config); + alias_string = alias_lookup(alias_command); if (alias_string) { if (alias_string[0] == '!') { if (*argcp > 1) { -- cgit v0.10.2-6-g49f6 From 2156435ff22437909cda825f1901dceb198fef19 Mon Sep 17 00:00:00 2001 From: Jeff King Date: Sun, 24 Feb 2008 17:17:37 -0500 Subject: help: respect aliases If we have an alias "foo" defined, then the help text for "foo" (via "git help foo" or "git foo --help") now shows the definition of the alias. Before showing an alias definition, we make sure that there is no git command which would override the alias (so that even though you may have a "log" alias, even though it will not work, we don't want to it supersede "git help log"). Signed-off-by: Jeff King Signed-off-by: Junio C Hamano diff --git a/help.c b/help.c index 5feb849..e57a50e 100644 --- a/help.c +++ b/help.c @@ -210,7 +210,7 @@ static unsigned int list_commands_in_dir(struct cmdnames *cmds, return longest; } -static void list_commands(void) +static unsigned int load_command_list(void) { unsigned int longest = 0; unsigned int len; @@ -250,6 +250,14 @@ static void list_commands(void) uniq(&other_cmds); exclude_cmds(&other_cmds, &main_cmds); + return longest; +} + +static void list_commands(void) +{ + unsigned int longest = load_command_list(); + const char *exec_path = git_exec_path(); + if (main_cmds.cnt) { printf("available git commands in '%s'\n", exec_path); printf("----------------------------"); @@ -284,6 +292,22 @@ void list_common_cmds_help(void) } } +static int is_in_cmdlist(struct cmdnames *c, const char *s) +{ + int i; + for (i = 0; i < c->cnt; i++) + if (!strcmp(s, c->names[i]->name)) + return 1; + return 0; +} + +static int is_git_command(const char *s) +{ + load_command_list(); + return is_in_cmdlist(&main_cmds, s) || + is_in_cmdlist(&other_cmds, s); +} + static const char *cmd_to_page(const char *git_cmd) { if (!git_cmd) @@ -372,6 +396,7 @@ int cmd_version(int argc, const char **argv, const char *prefix) int cmd_help(int argc, const char **argv, const char *prefix) { int nongit; + const char *alias; setup_git_directory_gently(&nongit); git_config(git_help_config); @@ -391,6 +416,12 @@ int cmd_help(int argc, const char **argv, const char *prefix) return 0; } + alias = alias_lookup(argv[0]); + if (alias && !is_git_command(argv[0])) { + printf("`git %s' is aliased to `%s'\n", argv[0], alias); + return 0; + } + switch (help_format) { case HELP_FORMAT_MAN: show_man_page(argv[0]); -- cgit v0.10.2-6-g49f6 From 8e0fbe671f6a63b885702917bf4e7d7a85c59ab4 Mon Sep 17 00:00:00 2001 From: Michele Ballabio Date: Mon, 25 Feb 2008 00:16:04 +0100 Subject: builtin-for-each-ref.c: fix typo in error message Signed-off-by: Michele Ballabio Signed-off-by: Junio C Hamano diff --git a/builtin-for-each-ref.c b/builtin-for-each-ref.c index f36a43c..07d9c57 100644 --- a/builtin-for-each-ref.c +++ b/builtin-for-each-ref.c @@ -165,7 +165,7 @@ static int verify_format(const char *format) for (cp = format; *cp && (sp = find_next(cp)); ) { const char *ep = strchr(sp, ')'); if (!ep) - return error("malformatted format string %s", sp); + return error("malformed format string %s", sp); /* sp points at "%(" and ep points at the closing ")" */ parse_atom(sp + 2, ep); cp = ep + 1; -- cgit v0.10.2-6-g49f6 From 99d8ea2c5ce6fc0b06fe8a43e7c0c108ddad853b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Santi=20B=C3=A9jar?= Date: Sun, 24 Feb 2008 14:42:40 +0100 Subject: git-bundle.txt: Add different strategies to create the bundle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Santi Béjar Signed-off-by: Junio C Hamano diff --git a/Documentation/git-bundle.txt b/Documentation/git-bundle.txt index 72f080a..505ac05 100644 --- a/Documentation/git-bundle.txt +++ b/Documentation/git-bundle.txt @@ -99,36 +99,62 @@ Assume two repositories exist as R1 on machine A, and R2 on machine B. For whatever reason, direct connection between A and B is not allowed, but we can move data from A to B via some mechanism (CD, email, etc). We want to update R2 with developments made on branch master in R1. + +To create the bundle you have to specify the basis. You have some options: + +- Without basis. ++ +This is useful when sending the whole history. + +------------ +$ git bundle create mybundle master +------------ + +- Using temporally tags. ++ We set a tag in R1 (lastR2bundle) after the previous such transport, and move it afterwards to help build the bundle. -in R1 on A: - ------------ $ git-bundle create mybundle master ^lastR2bundle $ git tag -f lastR2bundle master ------------ -(move mybundle from A to B by some mechanism) +- Using a tag present in both repositories + +------------ +$ git bundle create mybundle master ^v1.0.0 +------------ + +- A basis based on time. + +------------ +$ git bundle create mybundle master --since=10.days.ago +------------ -in R2 on B: +- With a limit on the number of commits ------------ -$ git-bundle verify mybundle -$ git-fetch mybundle refspec +$ git bundle create mybundle master -n 10 ------------ -where refspec is refInBundle:localRef +Then you move mybundle from A to B, and in R2 on B: +------------ +$ git-bundle verify mybundle +$ git-fetch mybundle master:localRef +------------ -Also, with something like this in your config: +With something like this in the config in R2: +------------------------ [remote "bundle"] url = /home/me/tmp/file.bdl fetch = refs/heads/*:refs/remotes/origin/* +------------------------ You can first sneakernet the bundle file to ~/tmp/file.bdl and -then these commands: +then these commands on machine B: ------------ $ git ls-remote bundle -- cgit v0.10.2-6-g49f6 From 55029ae4dac07942437c0c715ea7c8ac60dd3576 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Wed, 20 Feb 2008 13:43:53 -0500 Subject: Add support for url aliases in config files This allows users with different preferences for access methods to the same remote repositories to rewrite each other's URLs by pattern matching across a large set of similiarly set up repositories to each get the desired access. For example, if you don't have a kernel.org account, you might want settings like: [url "git://git.kernel.org/pub/"] insteadOf = master.kernel.org:/pub Then, if you give git a URL like: master.kernel.org:/pub/scm/linux/kernel/git/linville/wireless-2.6.git it will act like you gave it: git://git.kernel.org/pub/scm/linux/kernel/git/linville/wireless-2.6.git and you can cut-and-paste pull requests in email without fixing them by hand, for example. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/Documentation/config.txt b/Documentation/config.txt index f2f6a77..2981389 100644 --- a/Documentation/config.txt +++ b/Documentation/config.txt @@ -886,6 +886,18 @@ tar.umask:: archiving user's umask will be used instead. See umask(2) and linkgit:git-archive[1]. +url..insteadOf:: + Any URL that starts with this value will be rewritten to + start, instead, with . In cases where some site serves a + large number of repositories, and serves them with multiple + access methods, and some users need to use different access + methods, this feature allows people to specify any of the + equivalent URLs and have git automatically rewrite the URL to + the best alternative for the particular user, even for a + never-before-seen repository on the site. The effect of + having multiple `insteadOf` values from different + `` match to an URL is undefined. + user.email:: Your email address to be recorded in any newly created commits. Can be overridden by the 'GIT_AUTHOR_EMAIL', 'GIT_COMMITTER_EMAIL', and diff --git a/Documentation/urls.txt b/Documentation/urls.txt index 81ac17f..fa34c67 100644 --- a/Documentation/urls.txt +++ b/Documentation/urls.txt @@ -44,3 +44,26 @@ endif::git-clone[] ifdef::git-clone[] They are equivalent, except the former implies --local option. endif::git-clone[] + + +If there are a large number of similarly-named remote repositories and +you want to use a different format for them (such that the URLs you +use will be rewritten into URLs that work), you can create a +configuration section of the form: + +------------ + [url ""] + insteadOf = +------------ + +For example, with this: + +------------ + [url "git://git.host.xz/"] + insteadOf = host.xz:/path/to/ + insteadOf = work: +------------ + +a URL like "work:repo.git" or like "host.xz:/path/to/repo.git" will be +rewritten in any context that takes a URL to be "git://git.host.xz/repo.git". + diff --git a/remote.c b/remote.c index 457d8a4..0012954 100644 --- a/remote.c +++ b/remote.c @@ -2,6 +2,13 @@ #include "remote.h" #include "refs.h" +struct rewrite { + const char *base; + const char **instead_of; + int instead_of_nr; + int instead_of_alloc; +}; + static struct remote **remotes; static int remotes_alloc; static int remotes_nr; @@ -13,9 +20,33 @@ static int branches_nr; static struct branch *current_branch; static const char *default_remote_name; +static struct rewrite **rewrite; +static int rewrite_alloc; +static int rewrite_nr; + #define BUF_SIZE (2048) static char buffer[BUF_SIZE]; +static const char *alias_url(const char *url) +{ + int i, j; + for (i = 0; i < rewrite_nr; i++) { + if (!rewrite[i]) + continue; + for (j = 0; j < rewrite[i]->instead_of_nr; j++) { + if (!prefixcmp(url, rewrite[i]->instead_of[j])) { + char *ret = malloc(strlen(rewrite[i]->base) - + strlen(rewrite[i]->instead_of[j]) + + strlen(url) + 1); + strcpy(ret, rewrite[i]->base); + strcat(ret, url + strlen(rewrite[i]->instead_of[j])); + return ret; + } + } + } + return url; +} + static void add_push_refspec(struct remote *remote, const char *ref) { ALLOC_GROW(remote->push_refspec, @@ -38,6 +69,11 @@ static void add_url(struct remote *remote, const char *url) remote->url[remote->url_nr++] = url; } +static void add_url_alias(struct remote *remote, const char *url) +{ + add_url(remote, alias_url(url)); +} + static struct remote *make_remote(const char *name, int len) { struct remote *ret; @@ -95,6 +131,35 @@ static struct branch *make_branch(const char *name, int len) return ret; } +static struct rewrite *make_rewrite(const char *base, int len) +{ + struct rewrite *ret; + int i; + + for (i = 0; i < rewrite_nr; i++) { + if (len ? (!strncmp(base, rewrite[i]->base, len) && + !rewrite[i]->base[len]) : + !strcmp(base, rewrite[i]->base)) + return rewrite[i]; + } + + ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc); + ret = xcalloc(1, sizeof(struct rewrite)); + rewrite[rewrite_nr++] = ret; + if (len) + ret->base = xstrndup(base, len); + else + ret->base = xstrdup(base); + + return ret; +} + +static void add_instead_of(struct rewrite *rewrite, const char *instead_of) +{ + ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc); + rewrite->instead_of[rewrite->instead_of_nr++] = instead_of; +} + static void read_remotes_file(struct remote *remote) { FILE *f = fopen(git_path("remotes/%s", remote->name), "r"); @@ -128,7 +193,7 @@ static void read_remotes_file(struct remote *remote) switch (value_list) { case 0: - add_url(remote, xstrdup(s)); + add_url_alias(remote, xstrdup(s)); break; case 1: add_push_refspec(remote, xstrdup(s)); @@ -180,7 +245,7 @@ static void read_branches_file(struct remote *remote) } else { branch = "refs/heads/master"; } - add_url(remote, p); + add_url_alias(remote, p); add_fetch_refspec(remote, branch); remote->fetch_tags = 1; /* always auto-follow */ } @@ -210,6 +275,19 @@ static int handle_config(const char *key, const char *value) } return 0; } + if (!prefixcmp(key, "url.")) { + struct rewrite *rewrite; + name = key + 5; + subkey = strrchr(name, '.'); + if (!subkey) + return 0; + rewrite = make_rewrite(name, subkey - name); + if (!strcmp(subkey, ".insteadof")) { + if (!value) + return config_error_nonbool(key); + add_instead_of(rewrite, xstrdup(value)); + } + } if (prefixcmp(key, "remote.")) return 0; name = key + 7; @@ -261,6 +339,18 @@ static int handle_config(const char *key, const char *value) return 0; } +static void alias_all_urls(void) +{ + int i, j; + for (i = 0; i < remotes_nr; i++) { + if (!remotes[i]) + continue; + for (j = 0; j < remotes[i]->url_nr; j++) { + remotes[i]->url[j] = alias_url(remotes[i]->url[j]); + } + } +} + static void read_config(void) { unsigned char sha1[20]; @@ -277,6 +367,7 @@ static void read_config(void) make_branch(head_ref + strlen("refs/heads/"), 0); } git_config(handle_config); + alias_all_urls(); } struct refspec *parse_ref_spec(int nr_refspec, const char **refspec) @@ -342,7 +433,7 @@ struct remote *remote_get(const char *name) read_branches_file(ret); } if (!ret->url) - add_url(ret, name); + add_url_alias(ret, name); if (!ret->url) return NULL; ret->fetch = parse_ref_spec(ret->fetch_refspec_nr, ret->fetch_refspec); diff --git a/t/t5516-fetch-push.sh b/t/t5516-fetch-push.sh index 9d2dc33..9023ba0 100755 --- a/t/t5516-fetch-push.sh +++ b/t/t5516-fetch-push.sh @@ -100,6 +100,23 @@ test_expect_success 'fetch with wildcard' ' ) ' +test_expect_success 'fetch with insteadOf' ' + mk_empty && + ( + TRASH=$(pwd) && + cd testrepo && + git config url./$TRASH/.insteadOf trash/ + git config remote.up.url trash/. && + git config remote.up.fetch "refs/heads/*:refs/remotes/origin/*" && + git fetch up && + + r=$(git show-ref -s --verify refs/remotes/origin/master) && + test "z$r" = "z$the_commit" && + + test 1 = $(git for-each-ref refs/remotes/origin | wc -l) + ) +' + test_expect_success 'push without wildcard' ' mk_empty && @@ -126,6 +143,20 @@ test_expect_success 'push with wildcard' ' ) ' +test_expect_success 'push with insteadOf' ' + mk_empty && + TRASH=$(pwd) && + git config url./$TRASH/.insteadOf trash/ && + git push trash/testrepo refs/heads/master:refs/remotes/origin/master && + ( + cd testrepo && + r=$(git show-ref -s --verify refs/remotes/origin/master) && + test "z$r" = "z$the_commit" && + + test 1 = $(git for-each-ref refs/remotes/origin | wc -l) + ) +' + test_expect_success 'push with matching heads' ' mk_test heads/master && -- cgit v0.10.2-6-g49f6 From ce4a7bff41c6bb4dc2d578264a429b5e13e89bdc Mon Sep 17 00:00:00 2001 From: "Shawn O. Pearce" Date: Sun, 24 Feb 2008 22:57:29 -0500 Subject: Correct fast-export file mode strings to match fast-import standard The fast-import file format does not expect leading '0' in front of a file mode; that is we want '100644' and '0100644'. Thanks to Ian Clatworthy of the Bazaar project for noticing the difference in output/input. Signed-off-by: Shawn O. Pearce Signed-off-by: Junio C Hamano diff --git a/builtin-fast-export.c b/builtin-fast-export.c index ef27eee..724cff3 100755 --- a/builtin-fast-export.c +++ b/builtin-fast-export.c @@ -123,7 +123,7 @@ static void show_filemodify(struct diff_queue_struct *q, printf("D %s\n", spec->path); else { struct object *object = lookup_object(spec->sha1); - printf("M 0%06o :%d %s\n", spec->mode, + printf("M %06o :%d %s\n", spec->mode, get_object_mark(object), spec->path); } } -- cgit v0.10.2-6-g49f6 From 844112cac07d6413b9bb42d38527d2f7ca7c7801 Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Sun, 24 Feb 2008 22:25:04 -0800 Subject: url rewriting: take longest and first match Earlier we had a cop-out in the documentation to make the behaviour "undefined" if configuration had more than one insteadOf that would match the target URL, like this: [url "git://git.or.cz/"] insteadOf = "git.or.cz:" ; (1) insteadOf = "repo.or.cz:" ; (2) [url "/local/mirror/"] insteadOf = "git.or.cz:myrepo" ; (3) insteadOf = "repo.or.cz:" ; (4) It would be most natural to take the longest and first match, i.e. - rewrite "git.or.cz:frotz" to "git://git.or.cz/frotz" by using (1), - rewrite "git.or.cz:myrepo/xyzzy" to "/local/mirror/xyzzy" by favoring (3) over (1), and - rewrite "repo.or.cz:frotz" to "git://git.or.cz/frotz" by favoring (2) over (4). Signed-off-by: Junio C Hamano diff --git a/Documentation/config.txt b/Documentation/config.txt index 2981389..57b9b99 100644 --- a/Documentation/config.txt +++ b/Documentation/config.txt @@ -894,9 +894,8 @@ url..insteadOf:: methods, this feature allows people to specify any of the equivalent URLs and have git automatically rewrite the URL to the best alternative for the particular user, even for a - never-before-seen repository on the site. The effect of - having multiple `insteadOf` values from different - `` match to an URL is undefined. + never-before-seen repository on the site. When more than one + insteadOf strings match a given URL, the longest match is used. user.email:: Your email address to be recorded in any newly created commits. diff --git a/remote.c b/remote.c index 0012954..1f83696 100644 --- a/remote.c +++ b/remote.c @@ -2,9 +2,14 @@ #include "remote.h" #include "refs.h" +struct counted_string { + size_t len; + const char *s; +}; struct rewrite { const char *base; - const char **instead_of; + size_t baselen; + struct counted_string *instead_of; int instead_of_nr; int instead_of_alloc; }; @@ -30,21 +35,32 @@ static char buffer[BUF_SIZE]; static const char *alias_url(const char *url) { int i, j; + char *ret; + struct counted_string *longest; + int longest_i; + + longest = NULL; + longest_i = -1; for (i = 0; i < rewrite_nr; i++) { if (!rewrite[i]) continue; for (j = 0; j < rewrite[i]->instead_of_nr; j++) { - if (!prefixcmp(url, rewrite[i]->instead_of[j])) { - char *ret = malloc(strlen(rewrite[i]->base) - - strlen(rewrite[i]->instead_of[j]) + - strlen(url) + 1); - strcpy(ret, rewrite[i]->base); - strcat(ret, url + strlen(rewrite[i]->instead_of[j])); - return ret; + if (!prefixcmp(url, rewrite[i]->instead_of[j].s) && + (!longest || + longest->len < rewrite[i]->instead_of[j].len)) { + longest = &(rewrite[i]->instead_of[j]); + longest_i = i; } } } - return url; + if (!longest) + return url; + + ret = malloc(rewrite[longest_i]->baselen + + (strlen(url) - longest->len) + 1); + strcpy(ret, rewrite[longest_i]->base); + strcpy(ret + rewrite[longest_i]->baselen, url + longest->len); + return ret; } static void add_push_refspec(struct remote *remote, const char *ref) @@ -137,27 +153,33 @@ static struct rewrite *make_rewrite(const char *base, int len) int i; for (i = 0; i < rewrite_nr; i++) { - if (len ? (!strncmp(base, rewrite[i]->base, len) && - !rewrite[i]->base[len]) : - !strcmp(base, rewrite[i]->base)) + if (len + ? (len == rewrite[i]->baselen && + !strncmp(base, rewrite[i]->base, len)) + : !strcmp(base, rewrite[i]->base)) return rewrite[i]; } ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc); ret = xcalloc(1, sizeof(struct rewrite)); rewrite[rewrite_nr++] = ret; - if (len) + if (len) { ret->base = xstrndup(base, len); - else + ret->baselen = len; + } + else { ret->base = xstrdup(base); - + ret->baselen = strlen(base); + } return ret; } static void add_instead_of(struct rewrite *rewrite, const char *instead_of) { ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc); - rewrite->instead_of[rewrite->instead_of_nr++] = instead_of; + rewrite->instead_of[rewrite->instead_of_nr].s = instead_of; + rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of); + rewrite->instead_of_nr++; } static void read_remotes_file(struct remote *remote) -- cgit v0.10.2-6-g49f6 From ed10d9aa3f771ad343df5aa50d9004945f7a4e56 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Mon, 25 Feb 2008 15:43:53 +0100 Subject: Documentation/git-filter-branch: add a new msg-filter example There were no example on how to edit commit messages, so add an msg-filter example. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano diff --git a/Documentation/git-filter-branch.txt b/Documentation/git-filter-branch.txt index e22dfa5..1948f6f 100644 --- a/Documentation/git-filter-branch.txt +++ b/Documentation/git-filter-branch.txt @@ -240,6 +240,15 @@ committed a merge between P1 and P2, it will be propagated properly and all children of the merge will become merge commits with P1,P2 as their parents instead of the merge commit. +You can rewrite the commit log messages using `--message-filter`. For +example, `git-svn-id` strings in a repository created by `git-svn` can +be removed this way: + +------------------------------------------------------- +git filter-branch --message-filter ' + sed -e "/^git-svn-id:/d" +' +------------------------------------------------------- To restrict rewriting to only part of the history, specify a revision range in addition to the new branch name. The new branch name will -- cgit v0.10.2-6-g49f6 From 1468bd47833c6ec3c85620d6af1d910e9378f714 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 25 Feb 2008 14:24:48 -0500 Subject: Use a single implementation and API for copy_file() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Originally by Kristian Hï¿œgsberg; I fixed the conversion of rerere, which had a different API. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/builtin-init-db.c b/builtin-init-db.c index e1393b8..ff6e877 100644 --- a/builtin-init-db.c +++ b/builtin-init-db.c @@ -29,27 +29,6 @@ static void safe_create_dir(const char *dir, int share) die("Could not make %s writable by group\n", dir); } -static int copy_file(const char *dst, const char *src, int mode) -{ - int fdi, fdo, status; - - mode = (mode & 0111) ? 0777 : 0666; - if ((fdi = open(src, O_RDONLY)) < 0) - return fdi; - if ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) { - close(fdi); - return fdo; - } - status = copy_fd(fdi, fdo); - if (close(fdo) != 0) - return error("%s: write error: %s", dst, strerror(errno)); - - if (!status && adjust_shared_perm(dst)) - return -1; - - return status; -} - static void copy_templates_1(char *path, int baselen, char *template, int template_baselen, DIR *dir) diff --git a/builtin-rerere.c b/builtin-rerere.c index a9e3ebc..b2971f3 100644 --- a/builtin-rerere.c +++ b/builtin-rerere.c @@ -267,23 +267,6 @@ static int diff_two(const char *file1, const char *label1, return 0; } -static int copy_file(const char *src, const char *dest) -{ - FILE *in, *out; - char buffer[32768]; - int count; - - if (!(in = fopen(src, "r"))) - return error("Could not open %s", src); - if (!(out = fopen(dest, "w"))) - return error("Could not open %s", dest); - while ((count = fread(buffer, 1, sizeof(buffer), in))) - fwrite(buffer, 1, count, out); - fclose(in); - fclose(out); - return 0; -} - static int do_plain_rerere(struct path_list *rr, int fd) { struct path_list conflict = { NULL, 0, 0, 1 }; @@ -343,7 +326,7 @@ static int do_plain_rerere(struct path_list *rr, int fd) continue; fprintf(stderr, "Recorded resolution for '%s'.\n", path); - copy_file(path, rr_path(name, "postimage")); + copy_file(rr_path(name, "postimage"), path, 0666); tail_optimization: if (i < rr->nr - 1) memmove(rr->items + i, diff --git a/cache.h b/cache.h index 43ba6a3..98cfed6 100644 --- a/cache.h +++ b/cache.h @@ -602,6 +602,7 @@ extern const char *git_log_output_encoding; /* IO helper functions */ extern void maybe_flush_or_die(FILE *, const char *); extern int copy_fd(int ifd, int ofd); +extern int copy_file(const char *dst, const char *src, int mode); extern int read_in_full(int fd, void *buf, size_t count); extern int write_in_full(int fd, const void *buf, size_t count); extern void write_or_die(int fd, const void *buf, size_t count); diff --git a/copy.c b/copy.c index c225d1b..afc4fbf 100644 --- a/copy.c +++ b/copy.c @@ -34,3 +34,24 @@ int copy_fd(int ifd, int ofd) close(ifd); return 0; } + +int copy_file(const char *dst, const char *src, int mode) +{ + int fdi, fdo, status; + + mode = (mode & 0111) ? 0777 : 0666; + if ((fdi = open(src, O_RDONLY)) < 0) + return fdi; + if ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) { + close(fdi); + return fdo; + } + status = copy_fd(fdi, fdo); + if (close(fdo) != 0) + return error("%s: write error: %s", dst, strerror(errno)); + + if (!status && adjust_shared_perm(dst)) + return -1; + + return status; +} diff --git a/diff.c b/diff.c index 39f6e21..76ba5f4 100644 --- a/diff.c +++ b/diff.c @@ -272,8 +272,8 @@ static void print_line_count(int count) } } -static void copy_file(int prefix, const char *data, int size, - const char *set, const char *reset) +static void copy_file_with_prefix(int prefix, const char *data, int size, + const char *set, const char *reset) { int ch, nl_just_seen = 1; while (0 < size--) { @@ -331,9 +331,9 @@ static void emit_rewrite_diff(const char *name_a, print_line_count(lc_b); printf(" @@%s\n", reset); if (lc_a) - copy_file('-', one->data, one->size, old, reset); + copy_file_with_prefix('-', one->data, one->size, old, reset); if (lc_b) - copy_file('+', two->data, two->size, new, reset); + copy_file_with_prefix('+', two->data, two->size, new, reset); } static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one) -- cgit v0.10.2-6-g49f6 From b560707a1da841d2430d5d1eaeca0f63ddf4aae7 Mon Sep 17 00:00:00 2001 From: Steffen Prohaska Date: Sun, 24 Feb 2008 18:19:09 +0100 Subject: Add tests for filesystem challenges (case and unicode normalization) Git has difficulties on file systems that do not properly distinguish case or modify filenames in unexpected ways. The two major examples are Windows and Mac OS X. Both systems preserve case of file names but do not distinguish between filenames that differ only by case. Simple operations such as "git mv" or "git merge" can fail unexpectedly. In addition, Mac OS X normalizes unicode, which make git's life even harder. This commit adds tests that currently fail but should pass if file system as decribed above are fully supported. The test need to be run on Windows and Mac X as they already pass on Linux. Mitch Tishmack is the original author of the tests for unicode normalization. [jc: fixed-up so that it will use test_expect_success to test on sanely behaving filesystems.] Signed-off-by: Steffen Prohaska Signed-off-by: Junio C Hamano diff --git a/t/t0050-filesystem.sh b/t/t0050-filesystem.sh new file mode 100755 index 0000000..cd088b3 --- /dev/null +++ b/t/t0050-filesystem.sh @@ -0,0 +1,93 @@ +#!/bin/sh + +test_description='Various filesystem issues' + +. ./test-lib.sh + +auml=`perl -CO -e 'print pack("U",0x00E4)'` +aumlcdiar=`perl -CO -e 'print pack("U",0x0061).pack("U",0x0308)'` + +test_expect_success 'see if we expect ' ' + + test_case=test_expect_success + test_unicode=test_expect_success + mkdir junk && + echo good >junk/CamelCase && + echo bad >junk/camelcase && + if test "$(cat junk/CamelCase)" != good + then + test_case=test_expect_failure + say "will test on a case insensitive filesystem" + fi && + rm -fr junk && + mkdir junk && + >junk/"$auml" && + case "$(cd junk && echo *)" in + "$aumlcdiar") + test_unicode=test_expect_failure + say "will test on a unicode corrupting filesystem" + ;; + *) ;; + esac && + rm -fr junk +' + +test_expect_success "setup case tests" ' + + touch camelcase && + git add camelcase && + git commit -m "initial" && + git tag initial && + git checkout -b topic && + git mv camelcase tmp && + git mv tmp CamelCase && + git commit -m "rename" && + git checkout -f master + +' + +$test_case 'rename (case change)' ' + + git mv camelcase CamelCase && + git commit -m "rename" + +' + +$test_case 'merge (case change)' ' + + git reset --hard initial && + git merge topic + +' + +test_expect_success "setup unicode normalization tests" ' + + test_create_repo unicode && + cd unicode && + touch "$aumlcdiar" && + git add "$aumlcdiar" && + git commit -m initial + git tag initial && + git checkout -b topic && + git mv $aumlcdiar tmp && + git mv tmp "$auml" && + git commit -m rename && + git checkout -f master + +' + +$test_unicode 'rename (silent unicode normalization)' ' + + git mv "$aumlcdiar" "$auml" && + git commit -m rename + +' + +$test_unicode 'merge (silent unicode normalization)' ' + + git reset --hard initial && + git merge topic + +' + +test_done -- cgit v0.10.2-6-g49f6 From 552bcac3f9f34833cf546f8c197da4c1985a0b84 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 25 Feb 2008 18:24:14 -0500 Subject: Add API access to shortlog Shortlog is gives a pretty simple API for cases where you're already identifying all of the individual commits. Make this available to other code instead of requiring them to use the revision API and command line. Signed-off-by: Daniel Barkalow diff --git a/builtin-shortlog.c b/builtin-shortlog.c index fa8bc7d..af31aba 100644 --- a/builtin-shortlog.c +++ b/builtin-shortlog.c @@ -6,13 +6,11 @@ #include "revision.h" #include "utf8.h" #include "mailmap.h" +#include "shortlog.h" static const char shortlog_usage[] = "git-shortlog [-n] [-s] [-e] [... ]"; -static char *common_repo_prefix; -static int email; - static int compare_by_number(const void *a1, const void *a2) { const struct path_list_item *i1 = a1, *i2 = a2; @@ -26,13 +24,11 @@ static int compare_by_number(const void *a1, const void *a2) return -1; } -static struct path_list mailmap = {NULL, 0, 0, 0}; - -static void insert_one_record(struct path_list *list, +static void insert_one_record(struct shortlog *log, const char *author, const char *oneline) { - const char *dot3 = common_repo_prefix; + const char *dot3 = log->common_repo_prefix; char *buffer, *p; struct path_list_item *item; struct path_list *onelines; @@ -47,7 +43,7 @@ static void insert_one_record(struct path_list *list, eoemail = strchr(boemail, '>'); if (!eoemail) return; - if (!map_email(&mailmap, boemail+1, namebuf, sizeof(namebuf))) { + if (!map_email(&log->mailmap, boemail+1, namebuf, sizeof(namebuf))) { while (author < boemail && isspace(*author)) author++; for (len = 0; @@ -61,14 +57,14 @@ static void insert_one_record(struct path_list *list, else len = strlen(namebuf); - if (email) { + if (log->email) { size_t room = sizeof(namebuf) - len - 1; int maillen = eoemail - boemail + 1; snprintf(namebuf + len, room, " %.*s", maillen, boemail); } buffer = xstrdup(namebuf); - item = path_list_insert(buffer, list); + item = path_list_insert(buffer, &log->list); if (item->util == NULL) item->util = xcalloc(1, sizeof(struct path_list)); else @@ -114,7 +110,7 @@ static void insert_one_record(struct path_list *list, onelines->items[onelines->nr++].path = buffer; } -static void read_from_stdin(struct path_list *list) +static void read_from_stdin(struct shortlog *log) { char author[1024], oneline[1024]; @@ -128,38 +124,43 @@ static void read_from_stdin(struct path_list *list) while (fgets(oneline, sizeof(oneline), stdin) && oneline[0] == '\n') ; /* discard blanks */ - insert_one_record(list, author + 8, oneline); + insert_one_record(log, author + 8, oneline); } } -static void get_from_rev(struct rev_info *rev, struct path_list *list) +void shortlog_add_commit(struct shortlog *log, struct commit *commit) { - struct commit *commit; - - prepare_revision_walk(rev); - while ((commit = get_revision(rev)) != NULL) { - const char *author = NULL, *buffer; + const char *author = NULL, *buffer; - buffer = commit->buffer; - while (*buffer && *buffer != '\n') { - const char *eol = strchr(buffer, '\n'); + buffer = commit->buffer; + while (*buffer && *buffer != '\n') { + const char *eol = strchr(buffer, '\n'); - if (eol == NULL) - eol = buffer + strlen(buffer); - else - eol++; + if (eol == NULL) + eol = buffer + strlen(buffer); + else + eol++; - if (!prefixcmp(buffer, "author ")) - author = buffer + 7; - buffer = eol; - } - if (!author) - die("Missing author: %s", - sha1_to_hex(commit->object.sha1)); - if (*buffer) - buffer++; - insert_one_record(list, author, !*buffer ? "" : buffer); + if (!prefixcmp(buffer, "author ")) + author = buffer + 7; + buffer = eol; } + if (!author) + die("Missing author: %s", + sha1_to_hex(commit->object.sha1)); + if (*buffer) + buffer++; + insert_one_record(log, author, !*buffer ? "" : buffer); +} + +static void get_from_rev(struct rev_info *rev, struct shortlog *log) +{ + struct commit *commit; + + if (prepare_revision_walk(rev)) + die("revision walk setup failed"); + while ((commit = get_revision(rev)) != NULL) + shortlog_add_commit(log, commit); } static int parse_uint(char const **arg, int comma) @@ -211,29 +212,38 @@ static void parse_wrap_args(const char *arg, int *in1, int *in2, int *wrap) die(wrap_arg_usage); } +void shortlog_init(struct shortlog *log) +{ + memset(log, 0, sizeof(*log)); + + read_mailmap(&log->mailmap, ".mailmap", &log->common_repo_prefix); + + log->list.strdup_paths = 1; + log->wrap = DEFAULT_WRAPLEN; + log->in1 = DEFAULT_INDENT1; + log->in2 = DEFAULT_INDENT2; +} + int cmd_shortlog(int argc, const char **argv, const char *prefix) { + struct shortlog log; struct rev_info rev; - struct path_list list = { NULL, 0, 0, 1 }; - int i, j, sort_by_number = 0, summary = 0; - int wrap_lines = 0; - int wrap = DEFAULT_WRAPLEN; - int in1 = DEFAULT_INDENT1; - int in2 = DEFAULT_INDENT2; + + 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")) - sort_by_number = 1; + log.sort_by_number = 1; else if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--summary")) - summary = 1; + log.summary = 1; else if (!strcmp(argv[1], "-e") || !strcmp(argv[1], "--email")) - email = 1; + log.email = 1; else if (!prefixcmp(argv[1], "-w")) { - wrap_lines = 1; - parse_wrap_args(argv[1], &in1, &in2, &wrap); + 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); @@ -247,34 +257,38 @@ int cmd_shortlog(int argc, const char **argv, const char *prefix) if (argc > 1) die ("unrecognized argument: %s", argv[1]); - read_mailmap(&mailmap, ".mailmap", &common_repo_prefix); - /* assume HEAD if from a tty */ if (!rev.pending.nr && isatty(0)) add_head_to_pending(&rev); if (rev.pending.nr == 0) { - read_from_stdin(&list); + read_from_stdin(&log); } else - get_from_rev(&rev, &list); + get_from_rev(&rev, &log); - if (sort_by_number) - qsort(list.items, list.nr, sizeof(struct path_list_item), - compare_by_number); + shortlog_output(&log); + return 0; +} - for (i = 0; i < list.nr; i++) { - struct path_list *onelines = list.items[i].util; +void shortlog_output(struct shortlog *log) +{ + int i, j; + if (log->sort_by_number) + qsort(log->list.items, log->list.nr, sizeof(struct path_list_item), + compare_by_number); + for (i = 0; i < log->list.nr; i++) { + struct path_list *onelines = log->list.items[i].util; - if (summary) { - printf("%6d\t%s\n", onelines->nr, list.items[i].path); + if (log->summary) { + printf("%6d\t%s\n", onelines->nr, log->list.items[i].path); } else { - printf("%s (%d):\n", list.items[i].path, onelines->nr); + printf("%s (%d):\n", log->list.items[i].path, onelines->nr); for (j = onelines->nr - 1; j >= 0; j--) { const char *msg = onelines->items[j].path; - if (wrap_lines) { - int col = print_wrapped_text(msg, in1, in2, wrap); - if (col != wrap) + if (log->wrap_lines) { + int col = print_wrapped_text(msg, log->in1, log->in2, log->wrap); + if (col != log->wrap) putchar('\n'); } else @@ -286,13 +300,11 @@ int cmd_shortlog(int argc, const char **argv, const char *prefix) onelines->strdup_paths = 1; path_list_clear(onelines, 1); free(onelines); - list.items[i].util = NULL; + log->list.items[i].util = NULL; } - list.strdup_paths = 1; - path_list_clear(&list, 1); - mailmap.strdup_paths = 1; - path_list_clear(&mailmap, 1); - - return 0; + log->list.strdup_paths = 1; + path_list_clear(&log->list, 1); + log->mailmap.strdup_paths = 1; + path_list_clear(&log->mailmap, 1); } diff --git a/shortlog.h b/shortlog.h new file mode 100644 index 0000000..31ff491 --- /dev/null +++ b/shortlog.h @@ -0,0 +1,26 @@ +#ifndef SHORTLOG_H +#define SHORTLOG_H + +#include "path-list.h" + +struct shortlog { + struct path_list list; + int summary; + int wrap_lines; + int sort_by_number; + int wrap; + int in1; + int in2; + + char *common_repo_prefix; + int email; + struct path_list mailmap; +}; + +void shortlog_init(struct shortlog *log); + +void shortlog_add_commit(struct shortlog *log, struct commit *commit); + +void shortlog_output(struct shortlog *log); + +#endif -- cgit v0.10.2-6-g49f6 From 2bda2cf4f966ae50d08a32a3839f930c1daac907 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Mon, 25 Feb 2008 18:24:17 -0500 Subject: Improve collection of information for format-patch --cover-letter Use the "boundary" feature to find the origin (or find that there are multiple origins), and use the actual list of commits to pass to shortlog. This makes all cover letter include shortlogs, and all cover letters for series with a single boundary commit include diffstats (if there are multiple boundary commits it's unclear what would be meaningful as a diffstat). Note that the single boundary test is empirical, not theoretical; even a -2 limiting condition will give a diffstat if there's only one boundary commit in this particular case. Signed-off-by: Daniel Barkalow diff --git a/builtin-log.c b/builtin-log.c index 0b348eb..3112d96 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -15,6 +15,7 @@ #include "patch-ids.h" #include "refs.h" #include "run-command.h" +#include "shortlog.h" static int default_show_root = 1; static const char *fmt_patch_subject_prefix = "PATCH"; @@ -621,9 +622,10 @@ static void gen_message_id(struct rev_info *info, char *base) info->message_id = strbuf_detach(&buf, NULL); } -static void make_cover_letter(struct rev_info *rev, - int use_stdout, int numbered, int numbered_files, - struct commit *origin, struct commit *head) +static void make_cover_letter(struct rev_info *rev, int use_stdout, + int numbered, int numbered_files, + struct commit *origin, + int nr, struct commit **list, struct commit *head) { const char *committer; const char *origin_sha1, *head_sha1; @@ -632,7 +634,9 @@ static void make_cover_letter(struct rev_info *rev, const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n"; const char *msg; const char *extra_headers = rev->extra_headers; + struct shortlog log; struct strbuf sb; + int i; const char *encoding = "utf-8"; if (rev->commit_format != CMIT_FMT_EMAIL) @@ -642,7 +646,6 @@ static void make_cover_letter(struct rev_info *rev, NULL : "cover-letter", 0, rev->total)) return; - origin_sha1 = sha1_to_hex(origin ? origin->object.sha1 : null_sha1); head_sha1 = sha1_to_hex(head->object.sha1); log_write_email_headers(rev, head_sha1, &subject_start, &extra_headers); @@ -660,21 +663,19 @@ static void make_cover_letter(struct rev_info *rev, strbuf_release(&sb); + shortlog_init(&log); + for (i = 0; i < nr; i++) + shortlog_add_commit(&log, list[i]); + + shortlog_output(&log); + /* - * We can only do diffstat with a unique reference point, and - * log is a bit tricky, so just skip it. + * We can only do diffstat with a unique reference point */ if (!origin) return; - argv[0] = "shortlog"; - argv[1] = head_sha1; - argv[2] = "--not"; - argv[3] = origin_sha1; - argv[4] = "--"; - argv[5] = NULL; - fflush(stdout); - run_command_v_opt(argv, RUN_GIT_CMD); + origin_sha1 = sha1_to_hex(origin->object.sha1); argv[0] = "diff"; argv[1] = "--stat"; @@ -727,6 +728,7 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) int ignore_if_in_upstream = 0; int thread = 0; int cover_letter = 0; + int boundary_count = 0; struct commit *origin = NULL, *head = NULL; const char *in_reply_to = NULL; struct patch_ids ids; @@ -917,19 +919,12 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) } if (cover_letter) { /* remember the range */ - int negative_count = 0; int i; for (i = 0; i < rev.pending.nr; i++) { struct object *o = rev.pending.objects[i].item; - if (o->flags & UNINTERESTING) { - origin = (struct commit *)o; - negative_count++; - } else + if (!(o->flags & UNINTERESTING)) head = (struct commit *)o; } - /* Multiple origins don't work for diffstat. */ - if (negative_count > 1) - origin = NULL; /* We can't generate a cover letter without any patches */ if (!head) return 0; @@ -941,8 +936,17 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) if (!use_stdout) realstdout = xfdopen(xdup(1), "w"); - prepare_revision_walk(&rev); + if (prepare_revision_walk(&rev)) + die("revision walk setup failed"); + rev.boundary = 1; while ((commit = get_revision(&rev)) != NULL) { + if (commit->object.flags & BOUNDARY) { + fprintf(stderr, "Boundary %s\n", sha1_to_hex(commit->object.sha1)); + boundary_count++; + origin = (boundary_count == 1) ? commit : NULL; + continue; + } + /* ignore merges */ if (commit->parents && commit->parents->next) continue; @@ -966,7 +970,7 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) if (thread) gen_message_id(&rev, "cover"); make_cover_letter(&rev, use_stdout, numbered, numbered_files, - origin, head); + origin, nr, list, head); total++; start_number--; } -- cgit v0.10.2-6-g49f6 From e103343644188ddddb3678f0568d150ca56f59e3 Mon Sep 17 00:00:00 2001 From: Jay Soffian Date: Mon, 25 Feb 2008 23:07:39 -0500 Subject: rev-parse: fix potential bus error with --parseopt option spec handling A non-empty line containing no spaces should be treated by --parseopt as an option group header, but was causing a bus error. Also added a test script for rev-parse --parseopt. Signed-off-by: Jay Soffian Signed-off-by: Junio C Hamano diff --git a/builtin-rev-parse.c b/builtin-rev-parse.c index b9af1a5..90dbb9d 100644 --- a/builtin-rev-parse.c +++ b/builtin-rev-parse.c @@ -315,7 +315,7 @@ static int cmd_parseopt(int argc, const char **argv, const char *prefix) s = strchr(sb.buf, ' '); if (!s || *sb.buf == ' ') { o->type = OPTION_GROUP; - o->help = xstrdup(skipspaces(s)); + o->help = xstrdup(skipspaces(sb.buf)); continue; } diff --git a/t/t1502-rev-parse-parseopt.sh b/t/t1502-rev-parse-parseopt.sh new file mode 100755 index 0000000..762af5f --- /dev/null +++ b/t/t1502-rev-parse-parseopt.sh @@ -0,0 +1,43 @@ +#!/bin/sh + +test_description='test git rev-parse --parseopt' +. ./test-lib.sh + +cat > expect.err <... + + some-command does foo and bar! + + -h, --help show the help + --foo some nifty option --foo + --bar ... some cool option --bar with an argument + +An option group Header + -C [...] option C with an optional argument + +Extras + --extra1 line above used to cause a segfault but no longer does + +EOF + +test_expect_success 'test --parseopt help output' ' + git rev-parse --parseopt -- -h 2> output.err <... + +some-command does foo and bar! +-- +h,help show the help + +foo some nifty option --foo +bar= some cool option --bar with an argument + + An option group Header +C? option C with an optional argument + +Extras +extra1 line above used to cause a segfault but no longer does +EOF + git diff expect.err output.err +' + +test_done -- cgit v0.10.2-6-g49f6 From 41e86a377496231709a5fb78df730df7be80b6c9 Mon Sep 17 00:00:00 2001 From: Caio Marcelo de Oliveira Filho Date: Mon, 25 Feb 2008 23:14:31 -0300 Subject: filter-branch documentation: non-zero exit status in command abort the filter Since commit 8c1ce0f46b85d40f215084eed7313896300082df filter-branch fails when a has a non-zero exit status. This commit makes it clear in the documentation and also fixes the parent-filter example, that was incorrectly returning non-zero when the commit being tested wasn't the one to be rewritten. Signed-off-by: Caio Marcelo de Oliveira Filho Signed-off-by: Junio C Hamano diff --git a/Documentation/git-filter-branch.txt b/Documentation/git-filter-branch.txt index 1948f6f..543a1cf 100644 --- a/Documentation/git-filter-branch.txt +++ b/Documentation/git-filter-branch.txt @@ -56,7 +56,9 @@ notable exception of the commit filter, for technical reasons). Prior to that, the $GIT_COMMIT environment variable will be set to contain the id of the commit being rewritten. Also, GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, GIT_AUTHOR_DATE, GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL, -and GIT_COMMITTER_DATE are set according to the current commit. +and GIT_COMMITTER_DATE are set according to the current commit. If any +evaluation of returns a non-zero exit status, the whole operation +will be aborted. A 'map' function is available that takes an "original sha1 id" argument and outputs a "rewritten sha1 id" if the commit has been already @@ -197,7 +199,7 @@ happened). If this is not the case, use: -------------------------------------------------------------------------- git filter-branch --parent-filter \ - 'cat; test $GIT_COMMIT = && echo "-p "' HEAD + 'test $GIT_COMMIT = && echo "-p " || cat' HEAD -------------------------------------------------------------------------- or even simpler: -- cgit v0.10.2-6-g49f6 From 695ed47228021f7408f58e6174168ea583c448d0 Mon Sep 17 00:00:00 2001 From: Steven Drake Date: Tue, 26 Feb 2008 13:45:53 +1300 Subject: timezone_names[]: fixed the tz offset for New Zealand. Signed-off-by: Junio C Hamano diff --git a/date.c b/date.c index 8f70500..a74ed86 100644 --- a/date.c +++ b/date.c @@ -213,9 +213,9 @@ static const struct { { "EAST", +10, 0, }, /* Eastern Australian Standard */ { "EADT", +10, 1, }, /* Eastern Australian Daylight */ { "GST", +10, 0, }, /* Guam Standard, USSR Zone 9 */ - { "NZT", +11, 0, }, /* New Zealand */ - { "NZST", +11, 0, }, /* New Zealand Standard */ - { "NZDT", +11, 1, }, /* New Zealand Daylight */ + { "NZT", +12, 0, }, /* New Zealand */ + { "NZST", +12, 0, }, /* New Zealand Standard */ + { "NZDT", +12, 1, }, /* New Zealand Daylight */ { "IDLE", +12, 0, }, /* International Date Line East */ }; -- cgit v0.10.2-6-g49f6 From 81fa145917c40b68a5e2cca6afc6a10cdfdbd25b Mon Sep 17 00:00:00 2001 From: Bryan Donlan Date: Mon, 25 Feb 2008 17:40:19 -0500 Subject: Documentation/git-am.txt: Pass -r in the example invocation of rm -f .dotest Signed-off-by: Bryan Donlan Signed-off-by: Junio C Hamano diff --git a/Documentation/git-am.txt b/Documentation/git-am.txt index 2ffba21..e640fc7 100644 --- a/Documentation/git-am.txt +++ b/Documentation/git-am.txt @@ -138,7 +138,7 @@ aborts in the middle,. You can recover from this in one of two ways: The command refuses to process new mailboxes while `.dotest` directory exists, so if you decide to start over from scratch, -run `rm -f .dotest` before running the command with mailbox +run `rm -f -r .dotest` before running the command with mailbox names. -- cgit v0.10.2-6-g49f6 From b8d97d07fd5025232cae74cfc9a555abd9ac390e Mon Sep 17 00:00:00 2001 From: Jakub Narebski Date: Mon, 25 Feb 2008 21:07:57 +0100 Subject: gitweb: Better cutting matched string and its context Improve look of commit search output ('search' view) by better cutting of matched string and its context in match info, as suggested by Junio. For example, if you are looking for "very long search string" in the following line: Could somebody test this with very long search string, and see how you would now see: ...this with <>, and see... instead of: Could som... <>, and see... (where <> denotes emphasized / colored fragment; matched fragment to be more exact). For this feature, support for fourth [optional] parameter to chop_str subroutine was added. This fourth parameter is used to denote where to cut string to make it shorter. chop_str can now cut at the beginning (from the _left_ side of the string), in the middle (_center_ of the string), or at the end (from the _right_ side of the string); cutting from right is the default: chop_str(somestring, len, slop, 'left') -> ' ...string' chop_str(somestring, len, slop, 'center') -> 'som ... ing' chop_str(somestring, len, slop, 'right') -> 'somestr... ' If you want to use default slop (default additional length), use undef as value for third parameter to chop_str. While at it, return from chop_str early if given string is so short that chop_str couldn't shorten it. Simplify also regexp used by chop_str. Make ellipsis (dots) stick to shortened fragment for cutting at ends, to better see which part got shortened. Simplify passing all arguments to chop_str in chop_and_escape_str subroutine. This was needed to pass additional options to chop_str. Signed-off-by: Jakub Narebski Signed-off-by: Junio C Hamano diff --git a/gitweb/gitweb.perl b/gitweb/gitweb.perl index e8226b1..fc95e2c 100755 --- a/gitweb/gitweb.perl +++ b/gitweb/gitweb.perl @@ -848,32 +848,73 @@ sub project_in_list { ## ---------------------------------------------------------------------- ## HTML aware string manipulation +# Try to chop given string on a word boundary between position +# $len and $len+$add_len. If there is no word boundary there, +# chop at $len+$add_len. Do not chop if chopped part plus ellipsis +# (marking chopped part) would be longer than given string. sub chop_str { my $str = shift; my $len = shift; my $add_len = shift || 10; + my $where = shift || 'right'; # 'left' | 'center' | 'right' # allow only $len chars, but don't cut a word if it would fit in $add_len # if it doesn't fit, cut it if it's still longer than the dots we would add - $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/; - my $body = $1; - my $tail = $2; - if (length($tail) > 4) { - $tail = " ..."; - $body =~ s/&[^;]*$//; # remove chopped character entities + # remove chopped character entities entirely + + # when chopping in the middle, distribute $len into left and right part + # return early if chopping wouldn't make string shorter + if ($where eq 'center') { + return $str if ($len + 5 >= length($str)); # filler is length 5 + $len = int($len/2); + } else { + return $str if ($len + 4 >= length($str)); # filler is length 4 + } + + # regexps: ending and beginning with word part up to $add_len + my $endre = qr/.{$len}\w{0,$add_len}/; + my $begre = qr/\w{0,$add_len}.{$len}/; + + if ($where eq 'left') { + $str =~ m/^(.*?)($begre)$/; + my ($lead, $body) = ($1, $2); + if (length($lead) > 4) { + $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/); + $lead = " ..."; + } + return "$lead$body"; + + } elsif ($where eq 'center') { + $str =~ m/^($endre)(.*)$/; + my ($left, $str) = ($1, $2); + $str =~ m/^(.*?)($begre)$/; + my ($mid, $right) = ($1, $2); + if (length($mid) > 5) { + $left =~ s/&[^;]*$//; + $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/); + $mid = " ... "; + } + return "$left$mid$right"; + + } else { + $str =~ m/^($endre)(.*)$/; + my $body = $1; + my $tail = $2; + if (length($tail) > 4) { + $body =~ s/&[^;]*$//; + $tail = "... "; + } + return "$body$tail"; } - return "$body$tail"; } # takes the same arguments as chop_str, but also wraps a around the # result with a title attribute if it does get chopped. Additionally, the # string is HTML-escaped. sub chop_and_escape_str { - my $str = shift; - my $len = shift; - my $add_len = shift || 10; + my ($str) = @_; - my $chopped = chop_str($str, $len, $add_len); + my $chopped = chop_str(@_); if ($chopped eq $str) { return esc_html($chopped); } else { @@ -3791,11 +3832,11 @@ sub git_search_grep_body { foreach my $line (@$comment) { if ($line =~ m/^(.*)($search_regexp)(.*)$/i) { my ($lead, $match, $trail) = ($1, $2, $3); - $match = chop_str($match, 70, 5); # in case match is very long - my $contextlen = int((80 - length($match))/2); # for the remainder - $contextlen = 30 if ($contextlen > 30); # but not too much - $lead = chop_str($lead, $contextlen, 10); - $trail = chop_str($trail, $contextlen, 10); + $match = chop_str($match, 70, 5, 'center'); + my $contextlen = int((80 - length($match))/2); + $contextlen = 30 if ($contextlen > 30); + $lead = chop_str($lead, $contextlen, 10, 'left'); + $trail = chop_str($trail, $contextlen, 10, 'right'); $lead = esc_html($lead); $match = esc_html($match); -- cgit v0.10.2-6-g49f6 From c6fabfafbcebca13cee0047b337b7c7a87e3515e Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 26 Feb 2008 12:24:40 -0800 Subject: git-apply --whitespace=fix: fix off by one thinko When a patch adds a whitespace followed by end-of-line, the trailing whitespace error was detected correctly but was not fixed, due to misconversion in 42ab241 (builtin-apply.c: do not feed copy_wsfix() leading '+'). Signed-off-by: Junio C Hamano diff --git a/ws.c b/ws.c index 522f646..ba7e834 100644 --- a/ws.c +++ b/ws.c @@ -234,7 +234,7 @@ int ws_fix_copy(char *dst, const char *src, int len, unsigned ws_rule, int *erro * Strip trailing whitespace */ if ((ws_rule & WS_TRAILING_SPACE) && - (2 < len && isspace(src[len-2]))) { + (2 <= len && isspace(src[len-2]))) { if (src[len - 1] == '\n') { add_nl_to_tail = 1; len--; -- cgit v0.10.2-6-g49f6 From 392b78ca42b6b1a68a77966acab38554c6edab3e Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Tue, 26 Feb 2008 23:27:31 -0800 Subject: Revert "pack-objects: Print a message describing the number of threads for packing" This reverts commit 6c723f5e6bc579e06a904874f1ceeb8ff2b5a17c. The additional message may be interesting for git developers, but not useful for the end users, and clutters the output. diff --git a/builtin-pack-objects.c b/builtin-pack-objects.c index 5a22f49..586ae11 100644 --- a/builtin-pack-objects.c +++ b/builtin-pack-objects.c @@ -2239,9 +2239,6 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix) #ifdef THREADED_DELTA_SEARCH if (!delta_search_threads) /* --threads=0 means autodetect */ delta_search_threads = online_cpus(); - if (progress) - fprintf(stderr, "Using %d pack threads.\n", - delta_search_threads); #endif prepare_packed_git(); -- cgit v0.10.2-6-g49f6 From dc1c0fffd3723ceebff51053938db5baf26a47f5 Mon Sep 17 00:00:00 2001 From: Jakub Narebski Date: Tue, 26 Feb 2008 13:22:05 +0100 Subject: Add '--fixed-strings' option to "git log --grep" and friends Add support for -F | --fixed-strings option to "git log --grep" and friends: "git log --author", "git log --committer=". Code is based on implementation of this option in "git grep". Signed-off-by: Jakub Narebski Signed-off-by: Junio C Hamano diff --git a/Documentation/git-rev-list.txt b/Documentation/git-rev-list.txt index 5b96eab..a8d489f 100644 --- a/Documentation/git-rev-list.txt +++ b/Documentation/git-rev-list.txt @@ -31,6 +31,7 @@ SYNOPSIS [ \--(author|committer|grep)= ] [ \--regexp-ignore-case | \-i ] [ \--extended-regexp | \-E ] + [ \--fixed-strings | \-F ] [ \--date={local|relative|default|iso|rfc|short} ] [ [\--objects | \--objects-edge] [ \--unpacked ] ] [ \--pretty | \--header ] diff --git a/Documentation/rev-list-options.txt b/Documentation/rev-list-options.txt index a8138e2..259072c 100644 --- a/Documentation/rev-list-options.txt +++ b/Documentation/rev-list-options.txt @@ -153,6 +153,11 @@ limiting may be applied. Consider the limiting patterns to be extended regular expressions instead of the default basic regular expressions. +-F, --fixed-strings:: + + Consider the limiting patterns to be fixed strings (don't interpret + pattern as a regular expression). + --remove-empty:: Stop when a given path disappears from the tree. diff --git a/revision.c b/revision.c index d3e8658..5df7961 100644 --- a/revision.c +++ b/revision.c @@ -942,6 +942,7 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch int left = 1; int all_match = 0; int regflags = 0; + int fixed = 0; /* First, search for "--" */ seen_dashdash = 0; @@ -1238,6 +1239,11 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch regflags |= REG_ICASE; continue; } + if (!strcmp(arg, "--fixed-strings") || + !strcmp(arg, "-F")) { + fixed = 1; + continue; + } if (!strcmp(arg, "--all-match")) { all_match = 1; continue; @@ -1293,8 +1299,10 @@ int setup_revisions(int argc, const char **argv, struct rev_info *revs, const ch } } - if (revs->grep_filter) + if (revs->grep_filter) { revs->grep_filter->regflags |= regflags; + revs->grep_filter->fixed = fixed; + } if (show_merge) prepare_show_merge(revs); -- cgit v0.10.2-6-g49f6 From 2ac8af1619feba08ec2285c0e305489a5cf815c9 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Tue, 26 Feb 2008 17:15:31 -0500 Subject: Don't use GIT_CONFIG in t5505-remote For some reason, t5505-remote was setting GIT_CONFIG to .git/config and exporting it. This should have been no-op, as test framework did the same for a long time anyway. Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/t/t5505-remote.sh b/t/t5505-remote.sh index 636aec2..4fc62f5 100755 --- a/t/t5505-remote.sh +++ b/t/t5505-remote.sh @@ -4,9 +4,6 @@ test_description='git remote porcelain-ish' . ./test-lib.sh -GIT_CONFIG=.git/config -export GIT_CONFIG - setup_repository () { mkdir "$1" && ( cd "$1" && -- cgit v0.10.2-6-g49f6 From 354081d5a0392a015731a637f026dc885a4ddb0f Mon Sep 17 00:00:00 2001 From: Tommy Thorn Date: Sun, 3 Feb 2008 10:38:51 -0800 Subject: git-p4: support exclude paths Teach git-p4 about the -/ option which adds depot paths to the exclude list, used when cloning. The option is chosen such that the natural Perforce syntax works, eg: git p4 clone //branch/path/... -//branch/path/{large,old}/... Trailing ... on exclude paths are optional. This is a generalization of a change by Dmitry Kakurin (thanks). Signed-off-by: Tommy Thorn Signed-off-by: Simon Hausmann diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4 index 781a0cb..e423853 100755 --- a/contrib/fast-import/git-p4 +++ b/contrib/fast-import/git-p4 @@ -843,18 +843,25 @@ class P4Sync(Command): self.keepRepoPath = False self.depotPaths = None self.p4BranchesInGit = [] + self.cloneExclude = [] if gitConfig("git-p4.syncFromOrigin") == "false": self.syncWithOrigin = False def extractFilesFromCommit(self, commit): + self.cloneExclude = [re.sub(r"\.\.\.$", "", path) + for path in self.cloneExclude] files = [] fnum = 0 while commit.has_key("depotFile%s" % fnum): path = commit["depotFile%s" % fnum] - found = [p for p in self.depotPaths - if path.startswith (p)] + if [p for p in self.cloneExclude + if path.startswith (p)]: + found = False + else: + found = [p for p in self.depotPaths + if path.startswith (p)] if not found: fnum = fnum + 1 continue @@ -1634,13 +1641,23 @@ class P4Clone(P4Sync): P4Sync.__init__(self) self.description = "Creates a new git repository and imports from Perforce into it" self.usage = "usage: %prog [options] //depot/path[@revRange]" - self.options.append( + self.options += [ optparse.make_option("--destination", dest="cloneDestination", action='store', default=None, - help="where to leave result of the clone")) + help="where to leave result of the clone"), + optparse.make_option("-/", dest="cloneExclude", + action="append", type="string", + help="exclude depot path") + ] self.cloneDestination = None self.needsGit = False + # This is required for the "append" cloneExclude action + def ensure_value(self, attr, value): + if not hasattr(self, attr) or getattr(self, attr) is None: + setattr(self, attr, value) + return getattr(self, attr) + def defaultDestination(self, args): ## TODO: use common prefix of args? depotPath = args[0] @@ -1664,6 +1681,7 @@ class P4Clone(P4Sync): self.cloneDestination = depotPaths[-1] depotPaths = depotPaths[:-1] + self.cloneExclude = ["/"+p for p in self.cloneExclude] for p in depotPaths: if not p.startswith("//"): return False -- cgit v0.10.2-6-g49f6 From 4b61b5c963ad1fd59e858c2bc21b1b48836f04f8 Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Tue, 19 Feb 2008 09:12:29 +0100 Subject: git-p4: Remove --log-substitutions feature. This turns out to be rarely useful and is already covered by git's commit.template configuration variable. Signed-off-by: Simon Hausmann diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4 index e423853..f2a6059 100755 --- a/contrib/fast-import/git-p4 +++ b/contrib/fast-import/git-p4 @@ -468,7 +468,6 @@ class P4Submit(Command): optparse.make_option("--verbose", dest="verbose", action="store_true"), optparse.make_option("--origin", dest="origin"), optparse.make_option("--reset", action="store_true", dest="reset"), - optparse.make_option("--log-substitutions", dest="substFile"), optparse.make_option("--direct", dest="directSubmit", action="store_true"), optparse.make_option("-M", dest="detectRename", action="store_true"), ] @@ -477,7 +476,6 @@ class P4Submit(Command): self.firstTime = True self.reset = False self.interactive = True - self.substFile = "" self.firstTime = True self.origin = "" self.directSubmit = False @@ -759,11 +757,6 @@ class P4Submit(Command): if self.reset: self.firstTime = True - if len(self.substFile) > 0: - for line in open(self.substFile, "r").readlines(): - tokens = line.strip().split("=") - self.logSubstitutions[tokens[0]] = tokens[1] - self.check() self.configFile = self.gitdir + "/p4-git-sync.cfg" self.config = shelve.open(self.configFile, writeback=True) -- cgit v0.10.2-6-g49f6 From edae1e2f407d0e9c6c92333047bc31b27bfdd58f Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Tue, 19 Feb 2008 09:29:06 +0100 Subject: git-p4: Clean up git-p4 submit's log message handling. Instead of trying to substitute fields in the p4 submit template we now simply replace the description of the submit with the log message of the git commit. Signed-off-by: Simon Hausmann diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4 index f2a6059..e55a41b 100755 --- a/contrib/fast-import/git-p4 +++ b/contrib/fast-import/git-p4 @@ -483,10 +483,6 @@ class P4Submit(Command): self.verbose = False self.isWindows = (platform.system() == "Windows") - self.logSubstitutions = {} - self.logSubstitutions[""] = "%log%" - self.logSubstitutions["\tDetails:"] = "\tDetails: %log%" - def check(self): if len(p4CmdList("opened ...")) > 0: die("You have files opened with perforce! Close them before starting the sync.") @@ -507,26 +503,31 @@ class P4Submit(Command): self.config["commits"] = commits + # replaces everything between 'Description:' and the next P4 submit template field with the + # commit message def prepareLogMessage(self, template, message): result = "" + inDescriptionSection = False + for line in template.split("\n"): if line.startswith("#"): result += line + "\n" continue - substituted = False - for key in self.logSubstitutions.keys(): - if line.find(key) != -1: - value = self.logSubstitutions[key] - value = value.replace("%log%", message) - if value != "@remove@": - result += line.replace(key, value) + "\n" - substituted = True - break + if inDescriptionSection: + if line.startswith("Files:"): + inDescriptionSection = False + else: + continue + else: + if line.startswith("Description:"): + inDescriptionSection = True + line += "\n" + for messageLine in message.split("\n"): + line += "\t" + messageLine + "\n" - if not substituted: - result += line + "\n" + result += line + "\n" return result @@ -650,7 +651,6 @@ class P4Submit(Command): logMessage = "" if not self.directSubmit: logMessage = extractLogMessageFromGitCommit(id) - logMessage = logMessage.replace("\n", "\n\t") if self.isWindows: logMessage = logMessage.replace("\n", "\r\n") logMessage = logMessage.strip() -- cgit v0.10.2-6-g49f6 From 0e36f2d726d4ce50c3f128bcc168d59ad03e804f Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Tue, 19 Feb 2008 09:33:08 +0100 Subject: git-p4: Removed git-p4 submit --direct. This feature was originally meant to allow for quicker direct submits into perforce, but it turns out that it is not actually quicker than doing a git commit and then running git-p4 submit. Signed-off-by: Simon Hausmann diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4 index e55a41b..087f422 100755 --- a/contrib/fast-import/git-p4 +++ b/contrib/fast-import/git-p4 @@ -468,7 +468,6 @@ class P4Submit(Command): optparse.make_option("--verbose", dest="verbose", action="store_true"), optparse.make_option("--origin", dest="origin"), optparse.make_option("--reset", action="store_true", dest="reset"), - optparse.make_option("--direct", dest="directSubmit", action="store_true"), optparse.make_option("-M", dest="detectRename", action="store_true"), ] self.description = "Submit changes from git to the perforce depot." @@ -478,7 +477,6 @@ class P4Submit(Command): self.interactive = True self.firstTime = True self.origin = "" - self.directSubmit = False self.detectRename = False self.verbose = False self.isWindows = (platform.system() == "Windows") @@ -494,12 +492,9 @@ class P4Submit(Command): "maybe you want to call git-p4 submit --reset" % self.configFile) commits = [] - if self.directSubmit: - commits.append("0") - else: - for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)): - commits.append(line.strip()) - commits.reverse() + for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)): + commits.append(line.strip()) + commits.reverse() self.config["commits"] = commits @@ -556,13 +551,9 @@ class P4Submit(Command): return template def applyCommit(self, id): - if self.directSubmit: - print "Applying local change in working directory/index" - diff = self.diffStatus - else: - print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id)) - diffOpts = ("", "-M")[self.detectRename] - diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (diffOpts, id, id)) + print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id)) + diffOpts = ("", "-M")[self.detectRename] + diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (diffOpts, id, id)) filesToAdd = set() filesToDelete = set() editedFiles = set() @@ -597,10 +588,7 @@ class P4Submit(Command): else: die("unknown modifier %s for %s" % (modifier, path)) - if self.directSubmit: - diffcmd = "cat \"%s\"" % self.diffFile - else: - diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id) + diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id) patchcmd = diffcmd + " | git apply " tryPatchCmd = patchcmd + "--check -" applyPatchCmd = patchcmd + "--check --apply -" @@ -648,12 +636,10 @@ class P4Submit(Command): mode = filesToChangeExecBit[f] setP4ExecBit(f, mode) - logMessage = "" - if not self.directSubmit: - logMessage = extractLogMessageFromGitCommit(id) - if self.isWindows: - logMessage = logMessage.replace("\n", "\r\n") - logMessage = logMessage.strip() + logMessage = extractLogMessageFromGitCommit(id) + if self.isWindows: + logMessage = logMessage.replace("\n", "\r\n") + logMessage = logMessage.strip() template = self.prepareSubmitTemplate() @@ -692,12 +678,6 @@ class P4Submit(Command): if self.isWindows: submitTemplate = submitTemplate.replace("\r\n", "\n") - if self.directSubmit: - print "Submitting to git first" - os.chdir(self.oldWorkingDirectory) - write_pipe("git commit -a -F -", submitTemplate) - os.chdir(self.clientPath) - write_pipe("p4 submit -i", submitTemplate) else: fileName = "submit.txt" @@ -739,17 +719,6 @@ class P4Submit(Command): print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath) self.oldWorkingDirectory = os.getcwd() - if self.directSubmit: - self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD") - if len(self.diffStatus) == 0: - print "No changes in working directory to submit." - return True - patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD") - self.diffFile = self.gitdir + "/p4-git-diff" - f = open(self.diffFile, "wb") - f.write(patch) - f.close(); - os.chdir(self.clientPath) print "Syncronizing p4 checkout..." system("p4 sync ...") @@ -777,9 +746,6 @@ class P4Submit(Command): self.config.close() - if self.directSubmit: - os.remove(self.diffFile) - if len(commits) == 0: if self.firstTime: print "No changes found to apply between %s and current HEAD" % self.origin -- cgit v0.10.2-6-g49f6 From 4c750c0d8bfd7e75b86d660def012bff17d2bf8e Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Tue, 19 Feb 2008 09:37:16 +0100 Subject: git-p4: git-p4 submit cleanups. Removed storing the list of commits in a configuration file. We only need the list of commits at run-time. Signed-off-by: Simon Hausmann diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4 index 087f422..d59ed94 100755 --- a/contrib/fast-import/git-p4 +++ b/contrib/fast-import/git-p4 @@ -464,18 +464,13 @@ class P4Submit(Command): def __init__(self): Command.__init__(self) self.options = [ - optparse.make_option("--continue", action="store_false", dest="firstTime"), optparse.make_option("--verbose", dest="verbose", action="store_true"), optparse.make_option("--origin", dest="origin"), - optparse.make_option("--reset", action="store_true", dest="reset"), optparse.make_option("-M", dest="detectRename", action="store_true"), ] self.description = "Submit changes from git to the perforce depot." self.usage += " [name of git branch to submit into perforce depot]" - self.firstTime = True - self.reset = False self.interactive = True - self.firstTime = True self.origin = "" self.detectRename = False self.verbose = False @@ -485,19 +480,6 @@ class P4Submit(Command): if len(p4CmdList("opened ...")) > 0: die("You have files opened with perforce! Close them before starting the sync.") - def start(self): - if len(self.config) > 0 and not self.reset: - die("Cannot start sync. Previous sync config found at %s\n" - "If you want to start submitting again from scratch " - "maybe you want to call git-p4 submit --reset" % self.configFile) - - commits = [] - for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)): - commits.append(line.strip()) - commits.reverse() - - self.config["commits"] = commits - # replaces everything between 'Description:' and the next P4 submit template field with the # commit message def prepareLogMessage(self, template, message): @@ -723,42 +705,29 @@ class P4Submit(Command): print "Syncronizing p4 checkout..." system("p4 sync ...") - if self.reset: - self.firstTime = True - self.check() - self.configFile = self.gitdir + "/p4-git-sync.cfg" - self.config = shelve.open(self.configFile, writeback=True) - if self.firstTime: - self.start() - - commits = self.config.get("commits", []) + commits = [] + for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)): + commits.append(line.strip()) + commits.reverse() while len(commits) > 0: - self.firstTime = False commit = commits[0] commits = commits[1:] - self.config["commits"] = commits self.applyCommit(commit) if not self.interactive: break - self.config.close() - if len(commits) == 0: - if self.firstTime: - print "No changes found to apply between %s and current HEAD" % self.origin - else: - print "All changes applied!" - os.chdir(self.oldWorkingDirectory) + print "All changes applied!" + os.chdir(self.oldWorkingDirectory) - sync = P4Sync() - sync.run([]) + sync = P4Sync() + sync.run([]) - rebase = P4Rebase() - rebase.rebase() - os.remove(self.configFile) + rebase = P4Rebase() + rebase.rebase() return True -- cgit v0.10.2-6-g49f6 From 3a70cdfa42199e16d2d047c286431c4274d65b1a Mon Sep 17 00:00:00 2001 From: Tor Arvid Lund Date: Mon, 18 Feb 2008 15:22:08 +0100 Subject: git-p4: Support usage of perforce client spec When syncing, git-p4 will only download files that are included in the active perforce client spec. This does not change the default behaviour - it requires that the user either supplies the command line argument --use-client-spec, or sets the git config option p4.useclientspec to "true". Signed-off-by: Tor Arvid Lund Signed-off-by: Simon Hausmann diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4 index d59ed94..be96600 100755 --- a/contrib/fast-import/git-p4 +++ b/contrib/fast-import/git-p4 @@ -745,7 +745,9 @@ class P4Sync(Command): help="Import into refs/heads/ , not refs/remotes"), optparse.make_option("--max-changes", dest="maxChanges"), optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true', - help="Keep entire BRANCH/DIR/SUBDIR prefix during import") + help="Keep entire BRANCH/DIR/SUBDIR prefix during import"), + optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true', + help="Only sync files that are included in the Perforce Client Spec") ] self.description = """Imports from Perforce into a git repository.\n example: @@ -772,6 +774,8 @@ class P4Sync(Command): self.depotPaths = None self.p4BranchesInGit = [] self.cloneExclude = [] + self.useClientSpec = False + self.clientSpecDirs = [] if gitConfig("git-p4.syncFromOrigin") == "false": self.syncWithOrigin = False @@ -846,11 +850,21 @@ class P4Sync(Command): ## Should move this out, doesn't use SELF. def readP4Files(self, files): + for f in files: + for val in self.clientSpecDirs: + if f['path'].startswith(val[0]): + if val[1] > 0: + f['include'] = True + else: + f['include'] = False + break + files = [f for f in files - if f['action'] != 'delete'] + if f['action'] != 'delete' and + (f.has_key('include') == False or f['include'] == True)] if not files: - return + return [] filedata = p4CmdList('-x - print', stdin='\n'.join(['%s#%s' % (f['path'], f['rev']) @@ -885,6 +899,7 @@ class P4Sync(Command): for f in files: assert not f.has_key('data') f['data'] = contents[f['path']] + return files def commit(self, details, files, branch, branchPrefixes, parent = ""): epoch = details["time"] @@ -901,11 +916,7 @@ class P4Sync(Command): new_files.append (f) else: sys.stderr.write("Ignoring file outside of prefix: %s\n" % path) - files = new_files - self.readP4Files(files) - - - + files = self.readP4Files(new_files) self.gitStream.write("commit %s\n" % branch) # gitStream.write("mark :%s\n" % details["change"]) @@ -1320,6 +1331,26 @@ class P4Sync(Command): print self.gitError.read() + def getClientSpec(self): + specList = p4CmdList( "client -o" ) + temp = {} + for entry in specList: + for k,v in entry.iteritems(): + if k.startswith("View"): + if v.startswith('"'): + start = 1 + else: + start = 0 + index = v.find("...") + v = v[start:index] + if v.startswith("-"): + v = v[1:] + temp[v] = -len(v) + else: + temp[v] = len(v) + self.clientSpecDirs = temp.items() + self.clientSpecDirs.sort( lambda x, y: abs( y[1] ) - abs( x[1] ) ) + def run(self, args): self.depotPaths = [] self.changeRange = "" @@ -1352,6 +1383,9 @@ class P4Sync(Command): if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch): system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch)) + if self.useClientSpec or gitConfig("p4.useclientspec") == "true": + self.getClientSpec() + # TODO: should always look at previous commits, # merge with previous imports, if possible. if args == []: -- cgit v0.10.2-6-g49f6 From a50a5c8fa66bf7077c986bcc39b3fdad17931e37 Mon Sep 17 00:00:00 2001 From: Miklos Vajna Date: Wed, 27 Feb 2008 14:13:00 +0100 Subject: Documentation/git svn log: add a note about timezones. git svn log mimics the timezone converting behaviour of svn log, but this was undocumented. Signed-off-by: Miklos Vajna Signed-off-by: Junio C Hamano diff --git a/Documentation/git-svn.txt b/Documentation/git-svn.txt index b1d527f..115b8be 100644 --- a/Documentation/git-svn.txt +++ b/Documentation/git-svn.txt @@ -159,6 +159,10 @@ New features: our version of --pretty=oneline -- + +NOTE: SVN itself only stores times in UTC and nothing else. The regular svn +client converts the UTC time to the local time (or based on the TZ= +environment). This command has the same behaviour. ++ Any other arguments are passed directly to `git log' -- -- cgit v0.10.2-6-g49f6 From 0460fb449b18cd95805c1bf97013957ee9b8ff9b Mon Sep 17 00:00:00 2001 From: Jonathan del Strother Date: Wed, 27 Feb 2008 12:50:22 +0000 Subject: Prompt to continue when editing during rebase --interactive On hitting an edit point in an interactive rebase, git should prompt the user to run "git rebase --continue" Signed-off-by: Jonathan del Strother Signed-off-by: Junio C Hamano diff --git a/git-rebase--interactive.sh b/git-rebase--interactive.sh index fb12b03..c2bedd6 100755 --- a/git-rebase--interactive.sh +++ b/git-rebase--interactive.sh @@ -268,6 +268,10 @@ do_next () { warn warn " git commit --amend" warn + warn "Once you are satisfied with your changes, run" + warn + warn " git rebase --continue" + warn exit 0 ;; squash|s) -- cgit v0.10.2-6-g49f6 From 9057f0a62c8681bcff8460fec80747a6aa5b43c8 Mon Sep 17 00:00:00 2001 From: Johan Herland Date: Wed, 13 Feb 2008 04:11:22 +0100 Subject: Add testcase for 'git cvsexportcommit -w $cvsdir ...' with relative $GIT_DIR The testcase verifies that 'git cvsexportcommit' functions correctly when the '-w' option is used, and GIT_DIR is set to a relative path (e.g. '.'). Signed-off-by: Johan Herland Signed-off-by: Junio C Hamano diff --git a/t/t9200-git-cvsexportcommit.sh b/t/t9200-git-cvsexportcommit.sh index a15222c..7e25a39 100755 --- a/t/t9200-git-cvsexportcommit.sh +++ b/t/t9200-git-cvsexportcommit.sh @@ -2,7 +2,7 @@ # # Copyright (c) Robin Rosenberg # -test_description='CVS export comit. ' +test_description='Test export of commits to CVS' . ./test-lib.sh @@ -246,4 +246,20 @@ test_expect_success \ ;; esac +test_expect_failure '-w option should work with relative GIT_DIR' ' + mkdir W && + echo foobar >W/file1.txt && + echo bazzle >W/file2.txt && + git add W/file1.txt && + git add W/file2.txt && + git commit -m "More updates" && + id=$(git rev-list --max-count=1 HEAD) && + (cd "$GIT_DIR" && + GIT_DIR=. git cvsexportcommit -w "$CVSWORK" -c $id && + check_entries "$CVSWORK/W" "file1.txt/1.1/|file2.txt/1.1/" && + diff -u "$CVSWORK/W/file1.txt" ../W/file1.txt && + diff -u "$CVSWORK/W/file2.txt" ../W/file2.txt + ) +' + test_done -- cgit v0.10.2-6-g49f6 From 12f0a5ea7dc999bfe06973bf61261fc809c2b2fb Mon Sep 17 00:00:00 2001 From: Johan Herland Date: Tue, 12 Feb 2008 00:43:41 +0100 Subject: Fix 'git cvsexportcommit -w $cvsdir ...' when used with relative $GIT_DIR When using the '-w $cvsdir' option to cvsexportcommit, it will chdir into $cvsdir before executing several other git commands. If $GIT_DIR is set to a relative path (e.g. '.'), the git commands executed by cvsexportcommit will naturally fail. Therefore, ensure that $GIT_DIR is absolute before the chdir to $cvsdir. Signed-off-by: Johan Herland Signed-off-by: Junio C Hamano diff --git a/git-cvsexportcommit.perl b/git-cvsexportcommit.perl index d2e50c3..2a8ad1e 100755 --- a/git-cvsexportcommit.perl +++ b/git-cvsexportcommit.perl @@ -5,6 +5,7 @@ use Getopt::Std; use File::Temp qw(tempdir); use Data::Dumper; use File::Basename qw(basename dirname); +use File::Spec; our ($opt_h, $opt_P, $opt_p, $opt_v, $opt_c, $opt_f, $opt_a, $opt_m, $opt_d, $opt_u, $opt_w); @@ -15,17 +16,15 @@ $opt_h && usage(); die "Need at least one commit identifier!" unless @ARGV; if ($opt_w) { + # Remember where GIT_DIR is before changing to CVS checkout unless ($ENV{GIT_DIR}) { - # Remember where our GIT_DIR is before changing to CVS checkout + # No GIT_DIR set. Figure it out for ourselves my $gd =`git-rev-parse --git-dir`; chomp($gd); - if ($gd eq '.git') { - my $wd = `pwd`; - chomp($wd); - $gd = $wd."/.git" ; - } $ENV{GIT_DIR} = $gd; } + # Make sure GIT_DIR is absolute + $ENV{GIT_DIR} = File::Spec->rel2abs($ENV{GIT_DIR}); if (! -d $opt_w."/CVS" ) { die "$opt_w is not a CVS checkout"; diff --git a/t/t9200-git-cvsexportcommit.sh b/t/t9200-git-cvsexportcommit.sh index 7e25a39..49d57a8 100755 --- a/t/t9200-git-cvsexportcommit.sh +++ b/t/t9200-git-cvsexportcommit.sh @@ -246,7 +246,7 @@ test_expect_success \ ;; esac -test_expect_failure '-w option should work with relative GIT_DIR' ' +test_expect_success '-w option should work with relative GIT_DIR' ' mkdir W && echo foobar >W/file1.txt && echo bazzle >W/file2.txt && -- cgit v0.10.2-6-g49f6 From 21a2d69b2a14f1b42b18cfd18ff0477bb97eb11f Mon Sep 17 00:00:00 2001 From: Alexandre Julliard Date: Fri, 22 Feb 2008 16:48:53 +0100 Subject: git.el: Do not display empty directories. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Alexandre Julliard Tested-by: Karl Hasselström Signed-off-by: Junio C Hamano diff --git a/contrib/emacs/git.el b/contrib/emacs/git.el index f69b697..cc21e9c 100644 --- a/contrib/emacs/git.el +++ b/contrib/emacs/git.el @@ -728,7 +728,7 @@ Return the list of files that haven't been handled." (defun git-run-ls-files-with-excludes (status files default-state &rest options) "Run git-ls-files on FILES with appropriate --exclude-from options." (let ((exclude-files (git-get-exclude-files))) - (apply #'git-run-ls-files status files default-state "--directory" + (apply #'git-run-ls-files status files default-state "--directory" "--no-empty-directory" (concat "--exclude-per-directory=" git-per-dir-ignore-file) (append options (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files))))) -- cgit v0.10.2-6-g49f6 From 77266e96d38bf922a3d8add5bd3dda924aadea05 Mon Sep 17 00:00:00 2001 From: Sebastian Noack Date: Mon, 25 Feb 2008 15:56:28 +0100 Subject: git-svn: Don't prompt for client cert password everytime. Acked-by: Eric Wong Signed-off-by: Junio C Hamano diff --git a/git-svn.perl b/git-svn.perl index 05fb358..9e2faf9 100755 --- a/git-svn.perl +++ b/git-svn.perl @@ -3643,6 +3643,7 @@ sub _auth_providers () { SVN::Client::get_ssl_client_cert_file_provider(), SVN::Client::get_ssl_client_cert_prompt_provider( \&Git::SVN::Prompt::ssl_client_cert, 2), + SVN::Client::get_ssl_client_cert_pw_file_provider(), SVN::Client::get_ssl_client_cert_pw_prompt_provider( \&Git::SVN::Prompt::ssl_client_cert_pw, 2), SVN::Client::get_username_provider(), -- cgit v0.10.2-6-g49f6 From 6ecbc851fb30f540e1a25761f221aab963cfe619 Mon Sep 17 00:00:00 2001 From: Jay Soffian Date: Thu, 21 Feb 2008 19:16:04 -0500 Subject: send-email: fix In-Reply-To regression Fix a regression introduced by 1ca3d6e (send-email: squelch warning due to comparing undefined $_ to "") where if the user was prompted for an initial In-Reply-To and didn't provide one, messages would be sent out with an invalid In-Reply-To of "<>" Also add test cases for the regression and the fix. A small modification was needed to allow send-email to take its replies from stdin if the environment variable GIT_SEND_EMAIL_NOTTY is set. Signed-off-by: Jay Soffian Signed-off-by: Junio C Hamano diff --git a/git-send-email.perl b/git-send-email.perl index 8e6f3b2..e5d67f1 100755 --- a/git-send-email.perl +++ b/git-send-email.perl @@ -166,7 +166,9 @@ my $envelope_sender; my $repo = Git->repository(); my $term = eval { - new Term::ReadLine 'git-send-email'; + $ENV{"GIT_SEND_EMAIL_NOTTY"} + ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT + : new Term::ReadLine 'git-send-email'; }; if ($@) { $term = new FakeTerm "$@: going non-interactive"; @@ -407,8 +409,9 @@ if ($thread && !defined $initial_reply_to && $prompting) { $initial_reply_to = $_; } if (defined $initial_reply_to) { - $initial_reply_to =~ s/^\s*?\s*$/>/; + $initial_reply_to =~ s/^\s*?\s*$//; + $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne ''; } if (!defined $smtp_server) { diff --git a/t/t9001-send-email.sh b/t/t9001-send-email.sh index 08f7c3d..2efaed4 100755 --- a/t/t9001-send-email.sh +++ b/t/t9001-send-email.sh @@ -108,4 +108,25 @@ test_expect_success 'allow long lines with --no-validate' ' 2>errors ' +test_expect_success 'Invalid In-Reply-To' ' + git send-email \ + --from="Example " \ + --to=nobody@example.com \ + --in-reply-to=" " \ + --smtp-server="$(pwd)/fake.sendmail" \ + $patches + 2>errors + ! grep "^In-Reply-To: < *>" msgtxt +' + +test_expect_success 'Valid In-Reply-To when prompting' ' + (echo "From Example " + echo "To Example " + echo "" + ) | env GIT_SEND_EMAIL_NOTTY=1 git send-email \ + --smtp-server="$(pwd)/fake.sendmail" \ + $patches 2>errors && + ! grep "^In-Reply-To: < *>" msgtxt +' + test_done -- cgit v0.10.2-6-g49f6 From 7a0a34ca6f31c6bb5d24ccc0cdab606736d7a322 Mon Sep 17 00:00:00 2001 From: Brandon Casey Date: Fri, 22 Feb 2008 12:47:08 -0600 Subject: builtin-reflog.c: don't install new reflog on write failure When expiring reflog entries, a new temporary log is written which contains only the entries to retain. After it is written, it is renamed to replace the existing reflog. Currently, we check that writing of the new log is successful and print a message on failure, but the original reflog is still replaced with the new reflog even on failure. This patch causes the original reflog to be retained if we fail when writing the new reflog. Signed-off-by: Brandon Casey Signed-off-by: Junio C Hamano diff --git a/builtin-reflog.c b/builtin-reflog.c index 4836ec9..ab53c8c 100644 --- a/builtin-reflog.c +++ b/builtin-reflog.c @@ -276,10 +276,11 @@ static int expire_reflog(const char *ref, const unsigned char *sha1, int unused, for_each_reflog_ent(ref, expire_reflog_ent, &cb); finish: if (cb.newlog) { - if (fclose(cb.newlog)) + if (fclose(cb.newlog)) { status |= error("%s: %s", strerror(errno), newlog_path); - if (rename(newlog_path, log_file)) { + unlink(newlog_path); + } else if (rename(newlog_path, log_file)) { status |= error("cannot rename %s to %s", newlog_path, log_file); unlink(newlog_path); -- cgit v0.10.2-6-g49f6 From 0f497e75f05cdf0c0c1278eaba898cda6f118d71 Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Sat, 23 Feb 2008 17:14:17 -0800 Subject: Eliminate confusing "won't bisect on seeked tree" failure This error message is very confusing---it doesn't tell the user anything about how to fix the situation. And the actual fix for the situation ("git bisect reset") does a checkout of a potentially random branch, (compared to what the user wants to be on for the bisect she is starting). The simplest way to eliminate the confusion is to just make "git bisect start" do the cleanup itself. There's no significant loss of safety here since we already have a general safety in the form of the reflog. Note: We preserve the warning for any cogito users. We do this by switching from .git/head-name to .git/BISECT_START for the extra state, (which is a more descriptive name anyway). Signed-off-by: Carl Worth Signed-off-by: Junio C Hamano diff --git a/git-bisect.sh b/git-bisect.sh index 6594a62..f885774 100755 --- a/git-bisect.sh +++ b/git-bisect.sh @@ -67,16 +67,18 @@ bisect_start() { die "Bad HEAD - I need a HEAD" case "$head" in refs/heads/bisect) - if [ -s "$GIT_DIR/head-name" ]; then - branch=`cat "$GIT_DIR/head-name"` + if [ -s "$GIT_DIR/BISECT_START" ]; then + branch=`cat "$GIT_DIR/BISECT_START"` else branch=master fi git checkout $branch || exit ;; refs/heads/*|$_x40) + # This error message should only be triggered by cogito usage, + # and cogito users should understand it relates to cg-seek. [ -s "$GIT_DIR/head-name" ] && die "won't bisect on seeked tree" - echo "${head#refs/heads/}" >"$GIT_DIR/head-name" + echo "${head#refs/heads/}" >"$GIT_DIR/BISECT_START" ;; *) die "Bad HEAD - strange symbolic ref" @@ -353,8 +355,8 @@ bisect_reset() { return } case "$#" in - 0) if [ -s "$GIT_DIR/head-name" ]; then - branch=`cat "$GIT_DIR/head-name"` + 0) if [ -s "$GIT_DIR/BISECT_START" ]; then + branch=`cat "$GIT_DIR/BISECT_START"` else branch=master fi ;; @@ -365,7 +367,9 @@ bisect_reset() { usage ;; esac if git checkout "$branch"; then + # Cleanup head-name if it got left by an old version of git-bisect rm -f "$GIT_DIR/head-name" + rm -f "$GIT_DIR/BISECT_START" bisect_clean_state fi } diff --git a/t/t6030-bisect-porcelain.sh b/t/t6030-bisect-porcelain.sh index ec71123..4908e87 100755 --- a/t/t6030-bisect-porcelain.sh +++ b/t/t6030-bisect-porcelain.sh @@ -260,7 +260,7 @@ test_expect_success 'bisect starting with a detached HEAD' ' git checkout master^ && HEAD=$(git rev-parse --verify HEAD) && git bisect start && - test $HEAD = $(cat .git/head-name) && + test $HEAD = $(cat .git/BISECT_START) && git bisect reset && test $HEAD = $(git rev-parse --verify HEAD) -- cgit v0.10.2-6-g49f6 From be5f5bf02706357794cdf093ebe603aa82ae52eb Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Thu, 21 Feb 2008 16:21:49 +0000 Subject: completion: support format-patch's --cover-letter option Signed-off-by: Johannes Schindelin Signed-off-by: Junio C Hamano diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash index 8722a68..8f70e1e 100755 --- a/contrib/completion/git-completion.bash +++ b/contrib/completion/git-completion.bash @@ -648,6 +648,7 @@ _git_format_patch () --in-reply-to= --full-index --binary --not --all + --cover-letter " return ;; -- cgit v0.10.2-6-g49f6 From 42be5cc61202014d4f1df61f9791067191f9393d Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 27 Feb 2008 22:08:57 -0800 Subject: format-patch: remove a leftover debugging message Signed-off-by: Junio C Hamano diff --git a/builtin-log.c b/builtin-log.c index 3209ea5..836b61e 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -960,7 +960,6 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) rev.boundary = 1; while ((commit = get_revision(&rev)) != NULL) { if (commit->object.flags & BOUNDARY) { - fprintf(stderr, "Boundary %s\n", sha1_to_hex(commit->object.sha1)); boundary_count++; origin = (boundary_count == 1) ? commit : NULL; continue; -- cgit v0.10.2-6-g49f6 From b75bb1d695b0958d77b7894fa4a7dbc76167b65a Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Wed, 27 Feb 2008 23:37:39 -0800 Subject: Start preparing for 1.5.4.4 Signed-off-by: Junio C Hamano diff --git a/Documentation/RelNotes-1.5.4.4.txt b/Documentation/RelNotes-1.5.4.4.txt new file mode 100644 index 0000000..5bfdb35 --- /dev/null +++ b/Documentation/RelNotes-1.5.4.4.txt @@ -0,0 +1,26 @@ +GIT v1.5.4.4 Release Notes +========================== + +Fixes since v1.5.4.3 +-------------------- + + * "git cvsexportcommit -w $cvsdir" misbehaved when GIT_DIR is set to a + relative directory. + + * "git http-push" had an invalid memory access that could lead it to + segfault. + + * When "git rebase -i" gave control back to the user for a commit that is + marked to be edited, it just said "modify it with commit --amend", + without saying what to do to continue after modifying it. Give an + explicit instruction to run "rebase --continue" to be more helpful. + + * "git send-email" in 1.5.4.3 issued a bogus empty In-Reply-To: header. + +Also included are a handful documentation updates. + +--- +exec >/var/tmp/1 +echo O=$(git describe maint) +O=v1.5.4.3 +git shortlog --no-merges $O..maint diff --git a/RelNotes b/RelNotes index 3084ce6..f84c4c7 120000 --- a/RelNotes +++ b/RelNotes @@ -1 +1 @@ -Documentation/RelNotes-1.5.4.3.txt \ No newline at end of file +Documentation/RelNotes-1.5.4.4.txt \ No newline at end of file -- cgit v0.10.2-6-g49f6 From a6f13ccf2460a7905e223cd40ff06631294a4189 Mon Sep 17 00:00:00 2001 From: Daniel Barkalow Date: Thu, 28 Feb 2008 12:24:42 -0500 Subject: Correct name of diff_flush() in API documentation Signed-off-by: Daniel Barkalow Signed-off-by: Junio C Hamano diff --git a/Documentation/technical/api-diff.txt b/Documentation/technical/api-diff.txt index 83b007e..20b0241 100644 --- a/Documentation/technical/api-diff.txt +++ b/Documentation/technical/api-diff.txt @@ -39,7 +39,7 @@ Calling sequence * Once you finish feeding the pairs of files, call `diffcore_std()`. This will tell the diffcore library to go ahead and do its work. -* Calling `diffcore_flush()` will produce the output. +* Calling `diff_flush()` will produce the output. Data structures -- cgit v0.10.2-6-g49f6 From 9907721501e19758e64bcce6d3b140316c9307b9 Mon Sep 17 00:00:00 2001 From: Gerrit Pape Date: Thu, 28 Feb 2008 18:44:42 +0000 Subject: templates/Makefile: don't depend on local umask setting Don't take the local umask setting into account when installing the templates/* files and directories, running 'make install' with umask set to 077 resulted in template/* installed with permissions 700 and 600. The problem was discovered by Florian Zumbiehl, reported through http://bugs.debian.org/467518 Signed-off-by: Gerrit Pape Signed-off-by: Junio C Hamano diff --git a/templates/Makefile b/templates/Makefile index ebd3a62..bda9d13 100644 --- a/templates/Makefile +++ b/templates/Makefile @@ -29,10 +29,10 @@ boilerplates.made : $(bpsrc) case "$$boilerplate" in *~) continue ;; esac && \ dst=`echo "$$boilerplate" | sed -e 's|^this|.|;s|--|/|g'` && \ dir=`expr "$$dst" : '\(.*\)/'` && \ - mkdir -p blt/$$dir && \ + $(INSTALL) -d -m 755 blt/$$dir && \ case "$$boilerplate" in \ *--) ;; \ - *) cp $$boilerplate blt/$$dst ;; \ + *) cp -p $$boilerplate blt/$$dst ;; \ esac || exit; \ done && \ date >$@ @@ -48,4 +48,4 @@ clean: install: all $(INSTALL) -d -m 755 '$(DESTDIR_SQ)$(template_dir_SQ)' (cd blt && $(TAR) cf - .) | \ - (cd '$(DESTDIR_SQ)$(template_dir_SQ)' && $(TAR) xf -) + (cd '$(DESTDIR_SQ)$(template_dir_SQ)' && umask 022 && $(TAR) xf -) -- cgit v0.10.2-6-g49f6 From 301e42edc3fa277059be97b3be5b97d86ddc9d9f Mon Sep 17 00:00:00 2001 From: Alex Riesen Date: Thu, 28 Feb 2008 17:30:47 +0100 Subject: Fix builtin checkout crashing when given an invalid path Signed-off-by: Alex Riesen Signed-off-by: Junio C Hamano diff --git a/builtin-checkout.c b/builtin-checkout.c index 4a4bb8b..9579ff4 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -545,6 +545,10 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) if (argc) { const char **pathspec = get_pathspec(prefix, argv); + + if (!pathspec) + die("invalid path specification"); + /* Checkout paths */ if (opts.new_branch || opts.force || opts.merge) { if (argc == 1) { -- cgit v0.10.2-6-g49f6 From 7435982102093179474a128648179a44042d8a1c Mon Sep 17 00:00:00 2001 From: Junio C Hamano Date: Thu, 28 Feb 2008 13:09:30 -0800 Subject: tests: introduce test_must_fail When we expect a git command to notice and signal errors, we carelessly wrote in our tests: test_expect_success 'reject bogus request' ' do something && do something else && ! git command ' but a non-zero exit could come from the "git command" segfaulting. A new helper function "tset_must_fail" is introduced and it is meant to be used to make sure the command gracefully fails (iow, dying and exiting with non zero status is counted as a failure to "gracefully fail"). The above example should be written as: test_expect_success 'reject bogus request' ' do something && do something else && test_must_fail git command ' Signed-off-by: Junio C Hamano diff --git a/t/t2008-checkout-subdir.sh b/t/t2008-checkout-subdir.sh index 4a723dc..3e098ab 100755 --- a/t/t2008-checkout-subdir.sh +++ b/t/t2008-checkout-subdir.sh @@ -68,15 +68,15 @@ test_expect_success 'checkout with simple prefix' ' ' test_expect_success 'relative path outside tree should fail' \ - '! git checkout HEAD -- ../../Makefile' + 'test_must_fail git checkout HEAD -- ../../Makefile' test_expect_success 'incorrect relative path to file should fail (1)' \ - '! git checkout HEAD -- ../file0' + 'test_must_fail git checkout HEAD -- ../file0' test_expect_success 'incorrect relative path should fail (2)' \ - '( cd dir1 && ! git checkout HEAD -- ./file0 )' + '( cd dir1 && test_must_fail git checkout HEAD -- ./file0 )' test_expect_success 'incorrect relative path should fail (3)' \ - '( cd dir1 && ! git checkout HEAD -- ../../file0 )' + '( cd dir1 && test_must_fail git checkout HEAD -- ../../file0 )' test_done diff --git a/t/test-lib.sh b/t/test-lib.sh index 83889c4..90df619 100644 --- a/t/test-lib.sh +++ b/t/test-lib.sh @@ -270,6 +270,23 @@ test_expect_code () { echo >&3 "" } +# This is not among top-level (test_expect_success | test_expect_failure) +# but is a prefix that can be used in the test script, like: +# +# test_expect_success 'complain and die' ' +# do something && +# do something else && +# test_must_fail git checkout ../outerspace +# ' +# +# Writing this as "! git checkout ../outerspace" is wrong, because +# the failure could be due to a segv. We want a controlled failure. + +test_must_fail () { + "$@" + test $? -gt 0 -a $? -le 128 +} + # Most tests can use the created repository, but some may need to create more. # Usage: test_create_repo test_create_repo () { -- cgit v0.10.2-6-g49f6