static void graph_output_collapsing_line(struct git_graph *graph, struct strbuf *sb) { int i; int *tmp_mapping; short used_horizontal = 0; int horizontal_edge = -1; int horizontal_edge_target = -1; /* * Clear out the new_mapping array */ for (i = 0; i < graph->mapping_size; i++) graph->new_mapping[i] = -1; for (i = 0; i < graph->mapping_size; i++) { int target = graph->mapping[i]; if (target < 0) continue; /* * Since update_columns() always inserts the leftmost * column first, each branch's target location should * always be either its current location or to the left of * its current location. * * We never have to move branches to the right. This makes * the graph much more legible, since whenever branches * cross, only one is moving directions. */ assert(target * 2 <= i); if (target * 2 == i) { /* * This column is already in the * correct place */ assert(graph->new_mapping[i] == -1); graph->new_mapping[i] = target; } else if (graph->new_mapping[i - 1] < 0) { /* * Nothing is to the left. * Move to the left by one */ graph->new_mapping[i - 1] = target; /* * If there isn't already an edge moving horizontally * select this one. */ if (horizontal_edge == -1) { int j; horizontal_edge = i; horizontal_edge_target = target; /* * The variable target is the index of the graph * column, and therefore target*2+3 is the * actual screen column of the first horizontal * line. */ for (j = (target * 2)+3; j < (i - 2); j += 2) graph->new_mapping[j] = target; } } else if (graph->new_mapping[i - 1] == target) { /* * There is a branch line to our left * already, and it is our target. We * combine with this line, since we share * the same parent commit. * * We don't have to add anything to the * output or new_mapping, since the * existing branch line has already taken * care of it. */ } else { /* * There is a branch line to our left, * but it isn't our target. We need to * cross over it. * * The space just to the left of this * branch should always be empty. * * The branch to the left of that space * should be our eventual target. */ assert(graph->new_mapping[i - 1] > target); assert(graph->new_mapping[i - 2] < 0); assert(graph->new_mapping[i - 3] == target); graph->new_mapping[i - 2] = target; /* * Mark this branch as the horizontal edge to * prevent any other edges from moving * horizontally. */ if (horizontal_edge == -1) horizontal_edge = i; } } /* * The new mapping may be 1 smaller than the old mapping */ if (graph->new_mapping[graph->mapping_size - 1] < 0) graph->mapping_size--; /* * Output out a line based on the new mapping info */ for (i = 0; i < graph->mapping_size; i++) { int target = graph->new_mapping[i]; if (target < 0) strbuf_addch(sb, ' '); else if (target * 2 == i) strbuf_write_column(sb, &graph->new_columns[target], '|'); else if (target == horizontal_edge_target && i != horizontal_edge - 1) { /* * Set the mappings for all but the * first segment to -1 so that they * won't continue into the next line. */ if (i != (target * 2)+3) graph->new_mapping[i] = -1; used_horizontal = 1; strbuf_write_column(sb, &graph->new_columns[target], '_'); } else { if (used_horizontal && i < horizontal_edge) graph->new_mapping[i] = -1; strbuf_write_column(sb, &graph->new_columns[target], '/'); } } graph_pad_horizontally(graph, sb, graph->mapping_size); /* * Swap mapping and new_mapping */ tmp_mapping = graph->mapping; graph->mapping = graph->new_mapping; graph->new_mapping = tmp_mapping; /* * If graph->mapping indicates that all of the branch lines * are already in the correct positions, we are done. * Otherwise, we need to collapse some branch lines together. */ if (graph_is_mapping_correct(graph)) graph_update_state(graph, GRAPH_PADDING); }
static void process_tree(struct rev_info *revs, struct tree *tree, show_object_fn show, struct strbuf *base, const char *name, void *cb_data) { struct object *obj = &tree->object; struct tree_desc desc; struct name_entry entry; enum interesting match = revs->diffopt.pathspec.nr == 0 ? all_entries_interesting: entry_not_interesting; int baselen = base->len; if (!revs->tree_objects) return; if (!obj) die("bad tree object"); if (obj->flags & (UNINTERESTING | SEEN)) return; if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) { if (revs->ignore_missing_links) return; die("bad tree object %s", oid_to_hex(&obj->oid)); } obj->flags |= SEEN; strbuf_addstr(base, name); show(obj, base->buf, cb_data); if (base->len) strbuf_addch(base, '/'); init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { if (match != all_entries_interesting) { match = tree_entry_interesting(&entry, base, 0, &revs->diffopt.pathspec); if (match == all_entries_not_interesting) break; if (match == entry_not_interesting) continue; } if (S_ISDIR(entry.mode)) process_tree(revs, lookup_tree(entry.sha1), show, base, entry.path, cb_data); else if (S_ISGITLINK(entry.mode)) process_gitlink(revs, entry.sha1, show, base, entry.path, cb_data); else process_blob(revs, lookup_blob(entry.sha1), show, base, entry.path, cb_data); } strbuf_setlen(base, baselen); free_tree_buffer(tree); }
int cmd_format_patch(int argc, const char **argv, const char *prefix) { struct commit *commit; struct commit **list = NULL; struct rev_info rev; int nr = 0, total, i, j; int use_stdout = 0; int start_number = -1; int keep_subject = 0; int numbered_files = 0; /* _just_ numbers */ int subject_prefix = 0; int ignore_if_in_upstream = 0; int thread = 0; int cover_letter = 0; int boundary_count = 0; int no_binary_diff = 0; struct commit *origin = NULL, *head = NULL; const char *in_reply_to = NULL; struct patch_ids ids; char *add_signoff = NULL; struct strbuf buf = STRBUF_INIT; git_config(git_format_config, NULL); init_revisions(&rev, prefix); rev.commit_format = CMIT_FMT_EMAIL; rev.verbose_header = 1; rev.diff = 1; rev.combine_merges = 0; rev.ignore_merges = 1; DIFF_OPT_SET(&rev.diffopt, RECURSIVE); rev.subject_prefix = fmt_patch_subject_prefix; /* * Parse the arguments before setup_revisions(), or something * like "git format-patch -o a123 HEAD^.." may fail; a123 is * possibly a valid SHA1. */ for (i = 1, j = 1; i < argc; i++) { if (!strcmp(argv[i], "--stdout")) use_stdout = 1; else if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--numbered")) numbered = 1; else if (!strcmp(argv[i], "-N") || !strcmp(argv[i], "--no-numbered")) { numbered = 0; auto_number = 0; } else if (!prefixcmp(argv[i], "--start-number=")) start_number = strtol(argv[i] + 15, NULL, 10); else if (!strcmp(argv[i], "--numbered-files")) numbered_files = 1; else if (!strcmp(argv[i], "--start-number")) { i++; if (i == argc) 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; rev.total = -1; } else if (!strcmp(argv[i], "--output-directory") || !strcmp(argv[i], "-o")) { i++; if (argc <= i) die("Which directory?"); if (output_directory) die("Two output directories?"); output_directory = argv[i]; } else if (!strcmp(argv[i], "--signoff") || !strcmp(argv[i], "-s")) { const char *committer; const char *endpos; committer = git_committer_info(IDENT_ERROR_ON_NO_NAME); endpos = strchr(committer, '>'); if (!endpos) die("bogus committer info %s\n", committer); add_signoff = xmemdupz(committer, endpos - committer + 1); } else if (!strcmp(argv[i], "--attach")) { rev.mime_boundary = git_version_string; rev.no_inline = 1; } else if (!prefixcmp(argv[i], "--attach=")) { rev.mime_boundary = argv[i] + 9; rev.no_inline = 1; } else if (!strcmp(argv[i], "--inline")) { rev.mime_boundary = git_version_string; rev.no_inline = 0; } else if (!prefixcmp(argv[i], "--inline=")) { rev.mime_boundary = argv[i] + 9; rev.no_inline = 0; } else if (!strcmp(argv[i], "--ignore-if-in-upstream")) ignore_if_in_upstream = 1; else if (!strcmp(argv[i], "--thread")) thread = 1; else if (!prefixcmp(argv[i], "--in-reply-to=")) in_reply_to = argv[i] + 14; else if (!strcmp(argv[i], "--in-reply-to")) { i++; if (i == argc) die("Need a Message-Id for --in-reply-to"); in_reply_to = argv[i]; } else if (!prefixcmp(argv[i], "--subject-prefix=")) { subject_prefix = 1; 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 if (!strcmp(argv[i], "--no-binary")) no_binary_diff = 1; else argv[j++] = argv[i]; } argc = j; 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) die ("-n and -k are mutually exclusive."); if (keep_subject && subject_prefix) die ("--subject-prefix and -k are mutually exclusive."); if (numbered_files && use_stdout) die ("--numbered-files and --stdout are mutually exclusive."); argc = setup_revisions(argc, argv, &rev, "HEAD"); if (argc > 1) die ("unrecognized argument: %s", argv[1]); if (!rev.diffopt.output_format || rev.diffopt.output_format == DIFF_FORMAT_PATCH) rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH; if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff) DIFF_OPT_SET(&rev.diffopt, BINARY); if (!output_directory && !use_stdout) output_directory = prefix; if (output_directory) { if (use_stdout) die("standard output, or directory, which one?"); if (mkdir(output_directory, 0777) < 0 && errno != EEXIST) die("Could not create directory %s", output_directory); } if (rev.pending.nr == 1) { if (rev.max_count < 0 && !rev.show_root_diff) { /* * This is traditional behaviour of "git format-patch * origin" that prepares what the origin side still * does not have. */ rev.pending.objects[0].item->flags |= UNINTERESTING; add_head_to_pending(&rev); } /* * Otherwise, it is "format-patch -22 HEAD", and/or * "format-patch --root HEAD". The user wants * get_revision() to do the usual traversal. */ } if (cover_letter) { /* remember the range */ int i; for (i = 0; i < rev.pending.nr; i++) { struct object *o = rev.pending.objects[i].item; if (!(o->flags & UNINTERESTING)) head = (struct commit *)o; } /* 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); if (!use_stdout) realstdout = xfdopen(xdup(1), "w"); if (prepare_revision_walk(&rev)) die("revision walk setup failed"); rev.boundary = 1; while ((commit = get_revision(&rev)) != NULL) { if (commit->object.flags & BOUNDARY) { boundary_count++; origin = (boundary_count == 1) ? commit : NULL; continue; } /* ignore merges */ if (commit->parents && commit->parents->next) continue; if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids)) continue; nr++; list = xrealloc(list, nr * sizeof(list[0])); list[nr - 1] = commit; } total = nr; if (!keep_subject && auto_number && total > 1) numbered = 1; if (numbered) rev.total = total + start_number - 1; 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, nr, list, 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 rev.ref_message_id = rev.message_id; } gen_message_id(&rev, sha1_to_hex(commit->object.sha1)); } 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; /* We put one extra blank line between formatted * patches and this flag is used by log-tree code * to see if it needs to emit a LF before showing * the log; when using one file per patch, we do * not want the extra blank line. */ if (!use_stdout) rev.shown_one = 0; if (shown) { if (rev.mime_boundary) printf("\n--%s%s--\n\n\n", mime_boundary_leader, rev.mime_boundary); else printf("-- \n%s\n\n", git_version_string); } if (!use_stdout) fclose(stdout); } free(list); if (ignore_if_in_upstream) free_patch_ids(&ids); return 0; }
void pretty_print_commit(struct pretty_print_context *pp, const struct commit *commit, struct strbuf *sb) { unsigned long beginning_of_body; int indent = 4; const char *msg; const char *reencoded; const char *encoding; int need_8bit_cte = pp->need_8bit_cte; if (pp->fmt == CMIT_FMT_USERFORMAT) { format_commit_message(commit, user_format, sb, pp); return; } encoding = get_log_output_encoding(); msg = reencoded = logmsg_reencode(commit, NULL, encoding); if (pp->fmt == CMIT_FMT_ONELINE || pp->fmt == CMIT_FMT_EMAIL) indent = 0; /* * We need to check and emit Content-type: to mark it * as 8-bit if we haven't done so. */ if (pp->fmt == CMIT_FMT_EMAIL && need_8bit_cte == 0) { int i, ch, in_body; for (in_body = i = 0; (ch = msg[i]); i++) { if (!in_body) { /* author could be non 7-bit ASCII but * the log may be so; skip over the * header part first. */ if (ch == '\n' && msg[i+1] == '\n') in_body = 1; } else if (non_ascii(ch)) { need_8bit_cte = 1; break; } } } pp_header(pp, encoding, commit, &msg, sb); if (pp->fmt != CMIT_FMT_ONELINE && !pp->subject) { strbuf_addch(sb, '\n'); } /* Skip excess blank lines at the beginning of body, if any... */ msg = skip_empty_lines(msg); /* These formats treat the title line specially. */ if (pp->fmt == CMIT_FMT_ONELINE || pp->fmt == CMIT_FMT_EMAIL) pp_title_line(pp, &msg, sb, encoding, need_8bit_cte); beginning_of_body = sb->len; if (pp->fmt != CMIT_FMT_ONELINE) pp_remainder(pp, &msg, sb, indent); strbuf_rtrim(sb); /* Make sure there is an EOLN for the non-oneline case */ if (pp->fmt != CMIT_FMT_ONELINE) strbuf_addch(sb, '\n'); /* * The caller may append additional body text in e-mail * format. Make sure we did not strip the blank line * between the header and the body. */ if (pp->fmt == CMIT_FMT_EMAIL && sb->len <= beginning_of_body) strbuf_addch(sb, '\n'); unuse_commit_buffer(commit, reencoded); }
/* * Traverse the index, find every entry that matches according to * o->el. Do "ce_flags &= ~clear_mask" on those entries. Return the * number of traversed entries. * * If select_mask is non-zero, only entries whose ce_flags has on of * those bits enabled are traversed. * * cache : pointer to an index entry * prefix_len : an offset to its path * * The current path ("prefix") including the trailing '/' is * cache[0]->name[0..(prefix_len-1)] * Top level path has prefix_len zero. */ static int clear_ce_flags_1(struct cache_entry **cache, int nr, struct strbuf *prefix, int select_mask, int clear_mask, struct exclude_list *el, int defval) { struct cache_entry **cache_end = cache + nr; /* * Process all entries that have the given prefix and meet * select_mask condition */ while(cache != cache_end) { struct cache_entry *ce = *cache; const char *name, *slash; int len, dtype, ret; if (select_mask && !(ce->ce_flags & select_mask)) { cache++; continue; } if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len)) break; name = ce->name + prefix->len; slash = strchr(name, '/'); /* If it's a directory, try whole directory match first */ if (slash) { int processed; len = slash - name; strbuf_add(prefix, name, len); processed = clear_ce_flags_dir(cache, cache_end - cache, prefix, prefix->buf + prefix->len - len, select_mask, clear_mask, el, defval); /* clear_c_f_dir eats a whole dir already? */ if (processed) { cache += processed; strbuf_setlen(prefix, prefix->len - len); continue; } strbuf_addch(prefix, '/'); cache += clear_ce_flags_1(cache, cache_end - cache, prefix, select_mask, clear_mask, el, defval); strbuf_setlen(prefix, prefix->len - len - 1); continue; } /* Non-directory */ dtype = ce_to_dtype(ce); ret = is_excluded_from_list(ce->name, ce_namelen(ce), name, &dtype, el); if (ret < 0) ret = defval; if (ret > 0) ce->ce_flags &= ~clear_mask; cache++; } return nr - (cache_end - cache); }
static int xml_parse_internal(XMLState *s, const char *buf_start, int buf_len, EditBuffer *b, int offset_start) { int ch, offset, offset0, text_offset_start, ret, offset_end; const char *buf_end, *buf; buf = buf_start; buf_end = buf + buf_len; offset = offset_start; offset_end = offset_start + buf_len; offset0 = 0; /* not used */ text_offset_start = 0; /* not used */ for (;;) { if (buf) { if (buf >= buf_end) break; ch = charset_decode(&s->charset_state, &buf); } else { if (offset >= offset_end) break; offset0 = offset; ch = eb_nextc(b, offset, &offset); } /* increment line number to signal errors */ if (ch == '\n') { /* well, should add counter, but we test abort here */ if (s->abort_func(s->abort_opaque)) return -1; s->line_num++; } switch (s->state) { case XML_STATE_TAG: if (ch == '>') { strbuf_addch(&s->str, '\0'); ret = parse_tag(s, (char *)s->str.buf); switch (ret) { default: case XML_STATE_TEXT: xml_text: strbuf_reset(&s->str); s->state = XML_STATE_TEXT; text_offset_start = offset; break; case XML_STATE_PRETAG: strbuf_reset(&s->str); s->state = XML_STATE_PRETAG; text_offset_start = offset; break; } } else { strbuf_addch(&s->str, ch); /* test comment */ if (s->str.size == 3 && s->str.buf[0] == '!' && s->str.buf[1] == '-' && s->str.buf[2] == '-') { s->state = XML_STATE_COMMENT; } } break; case XML_STATE_TEXT: if (ch == '<') { /* XXX: not strictly correct with comments : should not flush if comment */ if (buf) { strbuf_addch(&s->str, '\0'); flush_text(s, (char *)s->str.buf); strbuf_reset(&s->str); } else { flush_text_buffer(s, text_offset_start, offset0); } s->state = XML_STATE_TAG; } else { if (buf) { /* evaluate entities */ if (ch == '&') { buf--; ch = parse_entity(&buf); } strbuf_addch(&s->str, ch); } } break; case XML_STATE_COMMENT: if (ch == '-') s->state = XML_STATE_COMMENT1; break; case XML_STATE_COMMENT1: if (ch == '-') s->state = XML_STATE_COMMENT2; else s->state = XML_STATE_COMMENT; break; case XML_STATE_COMMENT2: if (ch == '>') { goto xml_text; } else if (ch != '-') { s->state = XML_STATE_COMMENT; } break; case XML_STATE_PRETAG: { int len, taglen; strbuf_addch(&s->str, ch); taglen = s->pretaglen + 2; len = s->str.size - taglen; if (len >= 0 && s->str.buf[len] == '<' && s->str.buf[len + 1] == '/' && !xml_tagcmp((char *)s->str.buf + len + 2, s->pretag)) { s->str.buf[len] = '\0'; if (!xml_tagcmp(s->pretag, "style")) { if (s->style_sheet) { CSSParseState b1, *b = &b1; b->ptr = (char *)s->str.buf; b->line_num = s->line_num; /* XXX: incorrect */ b->filename = s->filename; b->ignore_case = s->ignore_case; css_parse_style_sheet(s->style_sheet, b); } } else if (!xml_tagcmp(s->pretag, "script")) { /* XXX: handle script */ } else { /* just add the content */ if (buf) { flush_text(s, (char *)s->str.buf); } else { /* XXX: would be incorrect if non ascii chars */ flush_text_buffer(s, text_offset_start, offset - taglen); } strbuf_reset(&s->str); if (s->box) s->box = s->box->parent; } s->state = XML_STATE_WAIT_EOT; } } break; case XML_STATE_WAIT_EOT: /* wait end of tag */ if (ch == '>') goto xml_text; break; } } return buf - buf_start; }
static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */ const char *placeholder, void *context) { struct format_commit_context *c = context; const struct commit *commit = c->commit; const char *msg = c->message; struct commit_list *p; int h1, h2; /* these are independent of the commit */ switch (placeholder[0]) { case 'C': if (starts_with(placeholder + 1, "(auto)")) { c->auto_color = 1; return 7; /* consumed 7 bytes, "C(auto)" */ } else { int ret = parse_color(sb, placeholder, c); if (ret) c->auto_color = 0; /* * Otherwise, we decided to treat %C<unknown> * as a literal string, and the previous * %C(auto) is still valid. */ return ret; } case 'n': /* newline */ strbuf_addch(sb, '\n'); return 1; case 'x': /* %x00 == NUL, %x0a == LF, etc. */ if (0 <= (h1 = hexval_table[0xff & placeholder[1]]) && h1 <= 16 && 0 <= (h2 = hexval_table[0xff & placeholder[2]]) && h2 <= 16) { strbuf_addch(sb, (h1<<4)|h2); return 3; } else return 0; case 'w': if (placeholder[1] == '(') { unsigned long width = 0, indent1 = 0, indent2 = 0; char *next; const char *start = placeholder + 2; const char *end = strchr(start, ')'); if (!end) return 0; if (end > start) { width = strtoul(start, &next, 10); if (*next == ',') { indent1 = strtoul(next + 1, &next, 10); if (*next == ',') { indent2 = strtoul(next + 1, &next, 10); } } if (*next != ')') return 0; } rewrap_message_tail(sb, c, width, indent1, indent2); return end - placeholder + 1; } else return 0; case '<': case '>': return parse_padding_placeholder(sb, placeholder, c); } /* these depend on the commit */ if (!commit->object.parsed) parse_object(commit->object.sha1); switch (placeholder[0]) { case 'H': /* commit hash */ strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT)); strbuf_addstr(sb, sha1_to_hex(commit->object.sha1)); strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET)); return 1; case 'h': /* abbreviated commit hash */ strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT)); if (add_again(sb, &c->abbrev_commit_hash)) { strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET)); return 1; } strbuf_addstr(sb, find_unique_abbrev(commit->object.sha1, c->pretty_ctx->abbrev)); strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET)); c->abbrev_commit_hash.len = sb->len - c->abbrev_commit_hash.off; return 1; case 'T': /* tree hash */ strbuf_addstr(sb, sha1_to_hex(commit->tree->object.sha1)); return 1; case 't': /* abbreviated tree hash */ if (add_again(sb, &c->abbrev_tree_hash)) return 1; strbuf_addstr(sb, find_unique_abbrev(commit->tree->object.sha1, c->pretty_ctx->abbrev)); c->abbrev_tree_hash.len = sb->len - c->abbrev_tree_hash.off; return 1; case 'P': /* parent hashes */ for (p = commit->parents; p; p = p->next) { if (p != commit->parents) strbuf_addch(sb, ' '); strbuf_addstr(sb, sha1_to_hex(p->item->object.sha1)); } return 1; case 'p': /* abbreviated parent hashes */ if (add_again(sb, &c->abbrev_parent_hashes)) return 1; for (p = commit->parents; p; p = p->next) { if (p != commit->parents) strbuf_addch(sb, ' '); strbuf_addstr(sb, find_unique_abbrev( p->item->object.sha1, c->pretty_ctx->abbrev)); } c->abbrev_parent_hashes.len = sb->len - c->abbrev_parent_hashes.off; return 1; case 'm': /* left/right/bottom */ strbuf_addstr(sb, get_revision_mark(NULL, commit)); return 1; case 'd': load_ref_decorations(DECORATE_SHORT_REFS); format_decorations(sb, commit, c->auto_color); return 1; case 'g': /* reflog info */ switch(placeholder[1]) { case 'd': /* reflog selector */ case 'D': if (c->pretty_ctx->reflog_info) get_reflog_selector(sb, c->pretty_ctx->reflog_info, c->pretty_ctx->date_mode, c->pretty_ctx->date_mode_explicit, (placeholder[1] == 'd')); return 2; case 's': /* reflog message */ if (c->pretty_ctx->reflog_info) get_reflog_message(sb, c->pretty_ctx->reflog_info); return 2; case 'n': case 'N': case 'e': case 'E': return format_reflog_person(sb, placeholder[1], c->pretty_ctx->reflog_info, c->pretty_ctx->date_mode); } return 0; /* unknown %g placeholder */ case 'N': if (c->pretty_ctx->notes_message) { strbuf_addstr(sb, c->pretty_ctx->notes_message); return 1; } return 0; } if (placeholder[0] == 'G') { if (!c->signature_check.result) check_commit_signature(c->commit, &(c->signature_check)); switch (placeholder[1]) { case 'G': if (c->signature_check.gpg_output) strbuf_addstr(sb, c->signature_check.gpg_output); break; case '?': switch (c->signature_check.result) { case 'G': case 'B': case 'U': case 'N': strbuf_addch(sb, c->signature_check.result); } break; case 'S': if (c->signature_check.signer) strbuf_addstr(sb, c->signature_check.signer); break; case 'K': if (c->signature_check.key) strbuf_addstr(sb, c->signature_check.key); break; default: return 0; } return 2; } /* For the rest we have to parse the commit header. */ if (!c->commit_header_parsed) parse_commit_header(c); switch (placeholder[0]) { case 'a': /* author ... */ return format_person_part(sb, placeholder[1], msg + c->author.off, c->author.len, c->pretty_ctx->date_mode); case 'c': /* committer ... */ return format_person_part(sb, placeholder[1], msg + c->committer.off, c->committer.len, c->pretty_ctx->date_mode); case 'e': /* encoding */ if (c->commit_encoding) strbuf_addstr(sb, c->commit_encoding); return 1; case 'B': /* raw body */ /* message_off is always left at the initial newline */ strbuf_addstr(sb, msg + c->message_off + 1); return 1; } /* Now we need to parse the commit message. */ if (!c->commit_message_parsed) parse_commit_message(c); switch (placeholder[0]) { case 's': /* subject */ format_subject(sb, msg + c->subject_off, " "); return 1; case 'f': /* sanitized subject */ format_sanitized_subject(sb, msg + c->subject_off); return 1; case 'b': /* body */ strbuf_addstr(sb, msg + c->body_off); return 1; } return 0; /* unknown placeholder */ }
static void print_line(struct strbuf *buf) { strbuf_addch(buf, '\n'); write_or_die(credential_lock.fd, buf->buf, buf->len); }
const char *fmt_ident(const char *name, const char *email, const char *date_str, int flag) { static struct strbuf ident = STRBUF_INIT; int strict = (flag & IDENT_STRICT); int want_date = !(flag & IDENT_NO_DATE); int want_name = !(flag & IDENT_NO_NAME); if (want_name) { int using_default = 0; if (!name) { if (strict && ident_use_config_only && !(ident_config_given & IDENT_NAME_GIVEN)) { fputs(env_hint, stderr); die("no name was given and auto-detection is disabled"); } name = ident_default_name(); using_default = 1; if (strict && default_name_is_bogus) { fputs(env_hint, stderr); die("unable to auto-detect name (got '%s')", name); } } if (!*name) { struct passwd *pw; if (strict) { if (using_default) fputs(env_hint, stderr); die("empty ident name (for <%s>) not allowed", email); } pw = xgetpwuid_self(NULL); name = pw->pw_name; } } if (!email) { if (strict && ident_use_config_only && !(ident_config_given & IDENT_MAIL_GIVEN)) { fputs(env_hint, stderr); die("no email was given and auto-detection is disabled"); } email = ident_default_email(); if (strict && default_email_is_bogus) { fputs(env_hint, stderr); die("unable to auto-detect email address (got '%s')", email); } } strbuf_reset(&ident); if (want_name) { strbuf_addstr_without_crud(&ident, name); strbuf_addstr(&ident, " <"); } strbuf_addstr_without_crud(&ident, email); if (want_name) strbuf_addch(&ident, '>'); if (want_date) { strbuf_addch(&ident, ' '); if (date_str && date_str[0]) { if (parse_date(date_str, &ident) < 0) die("invalid date format: %s", date_str); } else strbuf_addstr(&ident, ident_default_date()); } return ident.buf; }
int dir_iterator_advance(struct dir_iterator *dir_iterator) { struct dir_iterator_int *iter = (struct dir_iterator_int *)dir_iterator; while (1) { struct dir_iterator_level *level = &iter->levels[iter->levels_nr - 1]; struct dirent *de; if (!level->initialized) { /* * Note: dir_iterator_begin() ensures that * path is not the empty string. */ if (!is_dir_sep(iter->base.path.buf[iter->base.path.len - 1])) strbuf_addch(&iter->base.path, '/'); level->prefix_len = iter->base.path.len; level->dir = opendir(iter->base.path.buf); if (!level->dir && errno != ENOENT) { warning("error opening directory %s: %s", iter->base.path.buf, strerror(errno)); /* Popping the level is handled below */ } level->initialized = 1; } else if (S_ISDIR(iter->base.st.st_mode)) { if (level->dir_state == DIR_STATE_ITER) { /* * The directory was just iterated * over; now prepare to iterate into * it. */ level->dir_state = DIR_STATE_RECURSE; ALLOC_GROW(iter->levels, iter->levels_nr + 1, iter->levels_alloc); level = &iter->levels[iter->levels_nr++]; level->initialized = 0; continue; } else { /* * The directory has already been * iterated over and iterated into; * we're done with it. */ } } if (!level->dir) { /* * This level is exhausted (or wasn't opened * successfully); pop up a level. */ if (--iter->levels_nr == 0) return dir_iterator_abort(dir_iterator); continue; } /* * Loop until we find an entry that we can give back * to the caller: */ while (1) { strbuf_setlen(&iter->base.path, level->prefix_len); errno = 0; de = readdir(level->dir); if (!de) { /* This level is exhausted; pop up a level. */ if (errno) { warning("error reading directory %s: %s", iter->base.path.buf, strerror(errno)); } else if (closedir(level->dir)) warning("error closing directory %s: %s", iter->base.path.buf, strerror(errno)); level->dir = NULL; if (--iter->levels_nr == 0) return dir_iterator_abort(dir_iterator); break; } if (is_dot_or_dotdot(de->d_name)) continue; strbuf_addstr(&iter->base.path, de->d_name); if (lstat(iter->base.path.buf, &iter->base.st) < 0) { if (errno != ENOENT) warning("error reading path '%s': %s", iter->base.path.buf, strerror(errno)); continue; } /* * We have to set these each time because * the path strbuf might have been realloc()ed. */ iter->base.relative_path = iter->base.path.buf + iter->levels[0].prefix_len; iter->base.basename = iter->base.path.buf + level->prefix_len; level->dir_state = DIR_STATE_ITER; return ITER_OK; } } }
int cmd_merge(int argc, const char **argv, const char *prefix) { unsigned char result_tree[20]; struct strbuf buf = STRBUF_INIT; const char *head_arg; int flag, head_invalid = 0, i; int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0; struct commit_list *common = NULL; const char *best_strategy = NULL, *wt_strategy = NULL; struct commit_list **remotes = &remoteheads; if (file_exists(git_path("MERGE_HEAD"))) die("You have not concluded your merge. (MERGE_HEAD exists)"); if (read_cache_unmerged()) die("You are in the middle of a conflicted merge." " (index unmerged)"); /* * Check if we are _not_ on a detached HEAD, i.e. if there is a * current branch. */ branch = resolve_ref("HEAD", head, 0, &flag); if (branch && !prefixcmp(branch, "refs/heads/")) branch += 11; if (is_null_sha1(head)) head_invalid = 1; git_config(git_merge_config, NULL); /* for color.ui */ if (diff_use_color_default == -1) diff_use_color_default = git_use_color_default; argc = parse_options(argc, argv, prefix, builtin_merge_options, builtin_merge_usage, 0); if (verbosity < 0) show_diffstat = 0; if (squash) { if (!allow_fast_forward) die("You cannot combine --squash with --no-ff."); option_commit = 0; } if (!allow_fast_forward && fast_forward_only) die("You cannot combine --no-ff with --ff-only."); if (!argc) usage_with_options(builtin_merge_usage, builtin_merge_options); /* * This could be traditional "merge <msg> HEAD <commit>..." and * the way we can tell it is to see if the second token is HEAD, * but some people might have misused the interface and used a * committish that is the same as HEAD there instead. * Traditional format never would have "-m" so it is an * additional safety measure to check for it. */ if (!have_message && is_old_style_invocation(argc, argv)) { strbuf_addstr(&merge_msg, argv[0]); head_arg = argv[1]; argv += 2; argc -= 2; } else if (head_invalid) { struct object *remote_head; /* * If the merged head is a valid one there is no reason * to forbid "git merge" into a branch yet to be born. * We do the same for "git pull". */ if (argc != 1) die("Can merge only exactly one commit into " "empty head"); if (squash) die("Squash commit into empty head not supported yet"); if (!allow_fast_forward) die("Non-fast-forward commit does not make sense into " "an empty head"); remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT); if (!remote_head) die("%s - not something we can merge", argv[0]); update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0, DIE_ON_ERR); reset_hard(remote_head->sha1, 0); return 0; } else { struct strbuf msg = STRBUF_INIT; /* We are invoked directly as the first-class UI. */ head_arg = "HEAD"; /* * All the rest are the commits being merged; * prepare the standard merge summary message to * be appended to the given message. If remote * is invalid we will die later in the common * codepath so we discard the error in this * loop. */ if (!have_message) { for (i = 0; i < argc; i++) merge_name(argv[i], &msg); fmt_merge_msg(option_log, &msg, &merge_msg); if (merge_msg.len) strbuf_setlen(&merge_msg, merge_msg.len-1); } } if (head_invalid || !argc) usage_with_options(builtin_merge_usage, builtin_merge_options); strbuf_addstr(&buf, "merge"); for (i = 0; i < argc; i++) strbuf_addf(&buf, " %s", argv[i]); setenv("GIT_REFLOG_ACTION", buf.buf, 0); strbuf_reset(&buf); for (i = 0; i < argc; i++) { struct object *o; struct commit *commit; o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT); if (!o) die("%s - not something we can merge", argv[i]); commit = lookup_commit(o->sha1); commit->util = (void *)argv[i]; remotes = &commit_list_insert(commit, remotes)->next; strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1)); setenv(buf.buf, argv[i], 1); strbuf_reset(&buf); } if (!use_strategies) { if (!remoteheads->next) add_strategies(pull_twohead, DEFAULT_TWOHEAD); else add_strategies(pull_octopus, DEFAULT_OCTOPUS); } for (i = 0; i < use_strategies_nr; i++) { if (use_strategies[i]->attr & NO_FAST_FORWARD) allow_fast_forward = 0; if (use_strategies[i]->attr & NO_TRIVIAL) allow_trivial = 0; } if (!remoteheads->next) common = get_merge_bases(lookup_commit(head), remoteheads->item, 1); else { struct commit_list *list = remoteheads; commit_list_insert(lookup_commit(head), &list); common = get_octopus_merge_bases(list); free(list); } update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0, DIE_ON_ERR); if (!common) ; /* No common ancestors found. We need a real merge. */ else if (!remoteheads->next && !common->next && common->item == remoteheads->item) { /* * If head can reach all the merge then we are up to date. * but first the most common case of merging one remote. */ finish_up_to_date("Already up-to-date."); return 0; } else if (allow_fast_forward && !remoteheads->next && !common->next && !hashcmp(common->item->object.sha1, head)) { /* Again the most common case of merging one remote. */ struct strbuf msg = STRBUF_INIT; struct object *o; char hex[41]; strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV)); if (verbosity >= 0) printf("Updating %s..%s\n", hex, find_unique_abbrev(remoteheads->item->object.sha1, DEFAULT_ABBREV)); strbuf_addstr(&msg, "Fast-forward"); if (have_message) strbuf_addstr(&msg, " (no commit created; -m option ignored)"); o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1), 0, NULL, OBJ_COMMIT); if (!o) return 1; if (checkout_fast_forward(head, remoteheads->item->object.sha1)) return 1; finish(o->sha1, msg.buf); drop_save(); return 0; } else if (!remoteheads->next && common->next) ; /* * We are not doing octopus and not fast-forward. Need * a real merge. */ else if (!remoteheads->next && !common->next && option_commit) { /* * We are not doing octopus, not fast-forward, and have * only one common. */ refresh_cache(REFRESH_QUIET); if (allow_trivial && !fast_forward_only) { /* See if it is really trivial. */ git_committer_info(IDENT_ERROR_ON_NO_NAME); printf("Trying really trivial in-index merge...\n"); if (!read_tree_trivial(common->item->object.sha1, head, remoteheads->item->object.sha1)) return merge_trivial(); printf("Nope.\n"); } } else { /* * An octopus. If we can reach all the remote we are up * to date. */ int up_to_date = 1; struct commit_list *j; for (j = remoteheads; j; j = j->next) { struct commit_list *common_one; /* * Here we *have* to calculate the individual * merge_bases again, otherwise "git merge HEAD^ * HEAD^^" would be missed. */ common_one = get_merge_bases(lookup_commit(head), j->item, 1); if (hashcmp(common_one->item->object.sha1, j->item->object.sha1)) { up_to_date = 0; break; } } if (up_to_date) { finish_up_to_date("Already up-to-date. Yeeah!"); return 0; } } if (fast_forward_only) die("Not possible to fast-forward, aborting."); /* We are going to make a new commit. */ git_committer_info(IDENT_ERROR_ON_NO_NAME); /* * At this point, we need a real merge. No matter what strategy * we use, it would operate on the index, possibly affecting the * working tree, and when resolved cleanly, have the desired * tree in the index -- this means that the index must be in * sync with the head commit. The strategies are responsible * to ensure this. */ if (use_strategies_nr != 1) { /* * Stash away the local changes so that we can try more * than one. */ save_state(); } else { memcpy(stash, null_sha1, 20); } for (i = 0; i < use_strategies_nr; i++) { int ret; if (i) { printf("Rewinding the tree to pristine...\n"); restore_state(); } if (use_strategies_nr != 1) printf("Trying merge strategy %s...\n", use_strategies[i]->name); /* * Remember which strategy left the state in the working * tree. */ wt_strategy = use_strategies[i]->name; ret = try_merge_strategy(use_strategies[i]->name, common, head_arg); if (!option_commit && !ret) { merge_was_ok = 1; /* * This is necessary here just to avoid writing * the tree, but later we will *not* exit with * status code 1 because merge_was_ok is set. */ ret = 1; } if (ret) { /* * The backend exits with 1 when conflicts are * left to be resolved, with 2 when it does not * handle the given merge at all. */ if (ret == 1) { int cnt = evaluate_result(); if (best_cnt <= 0 || cnt <= best_cnt) { best_strategy = use_strategies[i]->name; best_cnt = cnt; } } if (merge_was_ok) break; else continue; } /* Automerge succeeded. */ write_tree_trivial(result_tree); automerge_was_ok = 1; break; } /* * If we have a resulting tree, that means the strategy module * auto resolved the merge cleanly. */ if (automerge_was_ok) return finish_automerge(common, result_tree, wt_strategy); /* * Pick the result from the best strategy and have the user fix * it up. */ if (!best_strategy) { restore_state(); if (use_strategies_nr > 1) fprintf(stderr, "No merge strategy handled the merge.\n"); else fprintf(stderr, "Merge with strategy %s failed.\n", use_strategies[0]->name); return 2; } else if (best_strategy == wt_strategy) ; /* We already have its result in the working tree. */ else { printf("Rewinding the tree to pristine...\n"); restore_state(); printf("Using the %s to prepare resolving by hand.\n", best_strategy); try_merge_strategy(best_strategy, common, head_arg); } if (squash) finish(NULL, NULL); else { int fd; struct commit_list *j; for (j = remoteheads; j; j = j->next) strbuf_addf(&buf, "%s\n", sha1_to_hex(j->item->object.sha1)); fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666); if (fd < 0) die_errno("Could not open '%s' for writing", git_path("MERGE_HEAD")); if (write_in_full(fd, buf.buf, buf.len) != buf.len) die_errno("Could not write to '%s'", git_path("MERGE_HEAD")); close(fd); strbuf_addch(&merge_msg, '\n'); fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666); if (fd < 0) die_errno("Could not open '%s' for writing", git_path("MERGE_MSG")); if (write_in_full(fd, merge_msg.buf, merge_msg.len) != merge_msg.len) die_errno("Could not write to '%s'", git_path("MERGE_MSG")); close(fd); fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) die_errno("Could not open '%s' for writing", git_path("MERGE_MODE")); strbuf_reset(&buf); if (!allow_fast_forward) strbuf_addf(&buf, "no-ff"); if (write_in_full(fd, buf.buf, buf.len) != buf.len) die_errno("Could not write to '%s'", git_path("MERGE_MODE")); close(fd); } if (merge_was_ok) { fprintf(stderr, "Automatic merge went well; " "stopped before committing as requested\n"); return 0; } else return suggest_conflicts(); }
static void fill_tracking_info(struct strbuf *stat, const char *branch_name, int show_upstream_ref) { int ours, theirs; char *ref = NULL; struct branch *branch = branch_get(branch_name); struct strbuf fancy = STRBUF_INIT; int upstream_is_gone = 0; int added_decoration = 1; switch (stat_tracking_info(branch, &ours, &theirs)) { case 0: /* no base */ return; case -1: /* with "gone" base */ upstream_is_gone = 1; break; default: /* with base */ break; } if (show_upstream_ref) { ref = shorten_unambiguous_ref(branch->merge[0]->dst, 0); if (want_color(branch_use_color)) strbuf_addf(&fancy, "%s%s%s", branch_get_color(BRANCH_COLOR_UPSTREAM), ref, branch_get_color(BRANCH_COLOR_RESET)); else strbuf_addstr(&fancy, ref); } if (upstream_is_gone) { if (show_upstream_ref) strbuf_addf(stat, _("[%s: gone]"), fancy.buf); else added_decoration = 0; } else if (!ours && !theirs) { if (show_upstream_ref) strbuf_addf(stat, _("[%s]"), fancy.buf); else added_decoration = 0; } else if (!ours) { if (show_upstream_ref) strbuf_addf(stat, _("[%s: behind %d]"), fancy.buf, theirs); else strbuf_addf(stat, _("[behind %d]"), theirs); } else if (!theirs) { if (show_upstream_ref) strbuf_addf(stat, _("[%s: ahead %d]"), fancy.buf, ours); else strbuf_addf(stat, _("[ahead %d]"), ours); } else { if (show_upstream_ref) strbuf_addf(stat, _("[%s: ahead %d, behind %d]"), fancy.buf, ours, theirs); else strbuf_addf(stat, _("[ahead %d, behind %d]"), ours, theirs); } strbuf_release(&fancy); if (added_decoration) strbuf_addch(stat, ' '); free(ref); }
static void copy_templates_1(struct strbuf *path, struct strbuf *template_path, DIR *dir) { size_t path_baselen = path->len; size_t template_baselen = template_path->len; struct dirent *de; /* Note: if ".git/hooks" file exists in the repository being * re-initialized, /etc/core-git/templates/hooks/update would * cause "git init" to fail here. I think this is sane but * it means that the set of templates we ship by default, along * with the way the namespace under .git/ is organized, should * be really carefully chosen. */ safe_create_dir(path->buf, 1); while ((de = readdir(dir)) != NULL) { struct stat st_git, st_template; int exists = 0; strbuf_setlen(path, path_baselen); strbuf_setlen(template_path, template_baselen); if (de->d_name[0] == '.') continue; strbuf_addstr(path, de->d_name); strbuf_addstr(template_path, de->d_name); if (lstat(path->buf, &st_git)) { if (errno != ENOENT) die_errno(_("cannot stat '%s'"), path->buf); } else exists = 1; if (lstat(template_path->buf, &st_template)) die_errno(_("cannot stat template '%s'"), template_path->buf); if (S_ISDIR(st_template.st_mode)) { DIR *subdir = opendir(template_path->buf); if (!subdir) die_errno(_("cannot opendir '%s'"), template_path->buf); strbuf_addch(path, '/'); strbuf_addch(template_path, '/'); copy_templates_1(path, template_path, subdir); closedir(subdir); } else if (exists) continue; else if (S_ISLNK(st_template.st_mode)) { struct strbuf lnk = STRBUF_INIT; if (strbuf_readlink(&lnk, template_path->buf, st_template.st_size) < 0) die_errno(_("cannot readlink '%s'"), template_path->buf); if (create_symlink(NULL, lnk.buf, path->buf)) die_errno(_("cannot symlink '%s' '%s'"), lnk.buf, path->buf); strbuf_release(&lnk); } else if (S_ISREG(st_template.st_mode)) { if (copy_file(path->buf, template_path->buf, st_template.st_mode)) die_errno(_("cannot copy '%s' to '%s'"), template_path->buf, path->buf); } else error(_("ignoring template %s"), template_path->buf); } }
int notes_merge_commit(struct notes_merge_options *o, struct notes_tree *partial_tree, struct commit *partial_commit, struct object_id *result_oid) { /* * Iterate through files in .git/NOTES_MERGE_WORKTREE and add all * found notes to 'partial_tree'. Write the updated notes tree to * the DB, and commit the resulting tree object while reusing the * commit message and parents from 'partial_commit'. * Finally store the new commit object OID into 'result_oid'. */ DIR *dir; struct dirent *e; struct strbuf path = STRBUF_INIT; const char *buffer = get_commit_buffer(partial_commit, NULL); const char *msg = strstr(buffer, "\n\n"); int baselen; git_path_buf(&path, NOTES_MERGE_WORKTREE); if (o->verbosity >= 3) printf("Committing notes in notes merge worktree at %s\n", path.buf); if (!msg || msg[2] == '\0') die("partial notes commit has empty message"); msg += 2; dir = opendir(path.buf); if (!dir) die_errno("could not open %s", path.buf); strbuf_addch(&path, '/'); baselen = path.len; while ((e = readdir(dir)) != NULL) { struct stat st; struct object_id obj_oid, blob_oid; if (is_dot_or_dotdot(e->d_name)) continue; if (get_oid_hex(e->d_name, &obj_oid)) { if (o->verbosity >= 3) printf("Skipping non-SHA1 entry '%s%s'\n", path.buf, e->d_name); continue; } strbuf_addstr(&path, e->d_name); /* write file as blob, and add to partial_tree */ if (stat(path.buf, &st)) die_errno("Failed to stat '%s'", path.buf); if (index_path(&blob_oid, path.buf, &st, HASH_WRITE_OBJECT)) die("Failed to write blob object from '%s'", path.buf); if (add_note(partial_tree, &obj_oid, &blob_oid, NULL)) die("Failed to add resolved note '%s' to notes tree", path.buf); if (o->verbosity >= 4) printf("Added resolved note for object %s: %s\n", oid_to_hex(&obj_oid), oid_to_hex(&blob_oid)); strbuf_setlen(&path, baselen); } create_notes_commit(partial_tree, partial_commit->parents, msg, strlen(msg), result_oid->hash); unuse_commit_buffer(partial_commit, buffer); if (o->verbosity >= 4) printf("Finalized notes merge commit: %s\n", oid_to_hex(result_oid)); strbuf_release(&path); closedir(dir); return 0; }
static int queue_diff(struct diff_options *o, const char *name1, const char *name2) { int mode1 = 0, mode2 = 0; if (get_mode(name1, &mode1) || get_mode(name2, &mode2)) return -1; if (mode1 && mode2 && S_ISDIR(mode1) != S_ISDIR(mode2)) return error("file/directory conflict: %s, %s", name1, name2); if (S_ISDIR(mode1) || S_ISDIR(mode2)) { struct strbuf buffer1 = STRBUF_INIT; struct strbuf buffer2 = STRBUF_INIT; struct string_list p1 = STRING_LIST_INIT_DUP; struct string_list p2 = STRING_LIST_INIT_DUP; int i1, i2, ret = 0; size_t len1 = 0, len2 = 0; if (name1 && read_directory_contents(name1, &p1)) return -1; if (name2 && read_directory_contents(name2, &p2)) { string_list_clear(&p1, 0); return -1; } if (name1) { strbuf_addstr(&buffer1, name1); if (buffer1.len && buffer1.buf[buffer1.len - 1] != '/') strbuf_addch(&buffer1, '/'); len1 = buffer1.len; } if (name2) { strbuf_addstr(&buffer2, name2); if (buffer2.len && buffer2.buf[buffer2.len - 1] != '/') strbuf_addch(&buffer2, '/'); len2 = buffer2.len; } for (i1 = i2 = 0; !ret && (i1 < p1.nr || i2 < p2.nr); ) { const char *n1, *n2; int comp; strbuf_setlen(&buffer1, len1); strbuf_setlen(&buffer2, len2); if (i1 == p1.nr) comp = 1; else if (i2 == p2.nr) comp = -1; else comp = strcmp(p1.items[i1].string, p2.items[i2].string); if (comp > 0) n1 = NULL; else { strbuf_addstr(&buffer1, p1.items[i1++].string); n1 = buffer1.buf; } if (comp < 0) n2 = NULL; else { strbuf_addstr(&buffer2, p2.items[i2++].string); n2 = buffer2.buf; } ret = queue_diff(o, n1, n2); } string_list_clear(&p1, 0); string_list_clear(&p2, 0); strbuf_release(&buffer1); strbuf_release(&buffer2); return ret; } else { struct diff_filespec *d1, *d2; if (DIFF_OPT_TST(o, REVERSE_DIFF)) { unsigned tmp; const char *tmp_c; tmp = mode1; mode1 = mode2; mode2 = tmp; tmp_c = name1; name1 = name2; name2 = tmp_c; } d1 = noindex_filespec(name1, mode1); d2 = noindex_filespec(name2, mode2); diff_queue(&diff_queued_diff, d1, d2); return 0; } }
int cmd_format_patch(int argc, const char **argv, const char *prefix) { struct commit *commit; struct commit **list = NULL; struct rev_info rev; struct setup_revision_opt s_r_opt; int nr = 0, total, i; int use_stdout = 0; int start_number = -1; int numbered_files = 0; /* _just_ numbers */ int ignore_if_in_upstream = 0; int cover_letter = 0; int boundary_count = 0; int no_binary_diff = 0; struct commit *origin = NULL, *head = NULL; const char *in_reply_to = NULL; struct patch_ids ids; char *add_signoff = NULL; struct strbuf buf = STRBUF_INIT; int use_patch_format = 0; int quiet = 0; char *branch_name = NULL; const struct option builtin_format_patch_options[] = { { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL, N_("use [PATCH n/m] even with a single patch"), PARSE_OPT_NOARG, numbered_callback }, { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL, N_("use [PATCH] even with multiple patches"), PARSE_OPT_NOARG, no_numbered_callback }, OPT_BOOLEAN('s', "signoff", &do_signoff, N_("add Signed-off-by:")), OPT_BOOLEAN(0, "stdout", &use_stdout, N_("print patches to standard out")), OPT_BOOLEAN(0, "cover-letter", &cover_letter, N_("generate a cover letter")), OPT_BOOLEAN(0, "numbered-files", &numbered_files, N_("use simple number sequence for output file names")), OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"), N_("use <sfx> instead of '.patch'")), OPT_INTEGER(0, "start-number", &start_number, N_("start numbering patches at <n> instead of 1")), { OPTION_CALLBACK, 0, "subject-prefix", &rev, N_("prefix"), N_("Use [<prefix>] instead of [PATCH]"), PARSE_OPT_NONEG, subject_prefix_callback }, { OPTION_CALLBACK, 'o', "output-directory", &output_directory, N_("dir"), N_("store resulting files in <dir>"), PARSE_OPT_NONEG, output_directory_callback }, { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL, N_("don't strip/add [PATCH]"), PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback }, OPT_BOOLEAN(0, "no-binary", &no_binary_diff, N_("don't output binary diffs")), OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream, N_("don't include a patch matching a commit upstream")), { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL, N_("show patch format instead of default (patch + stat)"), PARSE_OPT_NONEG | PARSE_OPT_NOARG }, OPT_GROUP(N_("Messaging")), { OPTION_CALLBACK, 0, "add-header", NULL, N_("header"), N_("add email header"), 0, header_callback }, { OPTION_CALLBACK, 0, "to", NULL, N_("email"), N_("add To: header"), 0, to_callback }, { OPTION_CALLBACK, 0, "cc", NULL, N_("email"), N_("add Cc: header"), 0, cc_callback }, OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"), N_("make first mail a reply to <message-id>")), { OPTION_CALLBACK, 0, "attach", &rev, N_("boundary"), N_("attach the patch"), PARSE_OPT_OPTARG, attach_callback }, { OPTION_CALLBACK, 0, "inline", &rev, N_("boundary"), N_("inline the patch"), PARSE_OPT_OPTARG | PARSE_OPT_NONEG, inline_callback }, { OPTION_CALLBACK, 0, "thread", &thread, N_("style"), N_("enable message threading, styles: shallow, deep"), PARSE_OPT_OPTARG, thread_callback }, OPT_STRING(0, "signature", &signature, N_("signature"), N_("add a signature")), OPT_BOOLEAN(0, "quiet", &quiet, N_("don't print the patch filenames")), OPT_END() }; extra_hdr.strdup_strings = 1; extra_to.strdup_strings = 1; extra_cc.strdup_strings = 1; init_grep_defaults(); git_config(git_format_config, NULL); init_revisions(&rev, prefix); rev.commit_format = CMIT_FMT_EMAIL; rev.verbose_header = 1; rev.diff = 1; rev.max_parents = 1; DIFF_OPT_SET(&rev.diffopt, RECURSIVE); rev.subject_prefix = fmt_patch_subject_prefix; memset(&s_r_opt, 0, sizeof(s_r_opt)); s_r_opt.def = "HEAD"; s_r_opt.revarg_opt = REVARG_COMMITTISH; if (default_attach) { rev.mime_boundary = default_attach; rev.no_inline = 1; } /* * Parse the arguments before setup_revisions(), or something * like "git format-patch -o a123 HEAD^.." may fail; a123 is * possibly a valid SHA1. */ argc = parse_options(argc, argv, prefix, builtin_format_patch_options, builtin_format_patch_usage, PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH); if (do_signoff) { const char *committer; const char *endpos; committer = git_committer_info(IDENT_STRICT); endpos = strchr(committer, '>'); if (!endpos) die(_("bogus committer info %s"), committer); add_signoff = xmemdupz(committer, endpos - committer + 1); } for (i = 0; i < extra_hdr.nr; i++) { strbuf_addstr(&buf, extra_hdr.items[i].string); 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.items[i].string); 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.items[i].string); if (i + 1 < extra_cc.nr) strbuf_addch(&buf, ','); strbuf_addch(&buf, '\n'); } rev.extra_headers = strbuf_detach(&buf, NULL); if (start_number < 0) start_number = 1; /* * If numbered is set solely due to format.numbered in config, * and it would conflict with --keep-subject (-k) from the * command line, reset "numbered". */ if (numbered && keep_subject && !numbered_cmdline_opt) numbered = 0; if (numbered && keep_subject) die (_("-n and -k are mutually exclusive.")); if (keep_subject && subject_prefix) die (_("--subject-prefix and -k are mutually exclusive.")); rev.preserve_subject = keep_subject; argc = setup_revisions(argc, argv, &rev, &s_r_opt); if (argc > 1) die (_("unrecognized argument: %s"), argv[1]); if (rev.diffopt.output_format & DIFF_FORMAT_NAME) die(_("--name-only does not make sense")); if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS) die(_("--name-status does not make sense")); if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF) die(_("--check does not make sense")); if (!use_patch_format && (!rev.diffopt.output_format || rev.diffopt.output_format == DIFF_FORMAT_PATCH)) rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY; /* Always generate a patch */ rev.diffopt.output_format |= DIFF_FORMAT_PATCH; if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff) DIFF_OPT_SET(&rev.diffopt, BINARY); if (rev.show_notes) init_display_notes(&rev.notes_opt); if (!use_stdout) output_directory = set_outdir(prefix, output_directory); else setup_pager(); if (output_directory) { if (use_stdout) die(_("standard output, or directory, which one?")); if (mkdir(output_directory, 0777) < 0 && errno != EEXIST) die_errno(_("Could not create directory '%s'"), output_directory); } if (rev.pending.nr == 1) { if (rev.max_count < 0 && !rev.show_root_diff) { /* * This is traditional behaviour of "git format-patch * origin" that prepares what the origin side still * does not have. */ unsigned char sha1[20]; const char *ref; rev.pending.objects[0].item->flags |= UNINTERESTING; add_head_to_pending(&rev); ref = resolve_ref_unsafe("HEAD", sha1, 1, NULL); if (ref && !prefixcmp(ref, "refs/heads/")) branch_name = xstrdup(ref + strlen("refs/heads/")); else branch_name = xstrdup(""); /* no branch */ } /* * Otherwise, it is "format-patch -22 HEAD", and/or * "format-patch --root HEAD". The user wants * get_revision() to do the usual traversal. */ } /* * We cannot move this anywhere earlier because we do want to * know if --root was given explicitly from the command line. */ rev.show_root_diff = 1; if (cover_letter) { /* * NEEDSWORK:randomly pick one positive commit to show * diffstat; this is often the tip and the command * happens to do the right thing in most cases, but a * complex command like "--cover-letter a b c ^bottom" * picks "c" and shows diffstat between bottom..c * which may not match what the series represents at * all and totally broken. */ int i; for (i = 0; i < rev.pending.nr; i++) { struct object *o = rev.pending.objects[i].item; if (!(o->flags & UNINTERESTING)) head = (struct commit *)o; } /* There is nothing to show; it is not an error, though. */ if (!head) return 0; if (!branch_name) branch_name = find_branch_name(&rev); } if (ignore_if_in_upstream) { /* Don't say anything if head and upstream are the same. */ if (rev.pending.nr == 2) { struct object_array_entry *o = rev.pending.objects; if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0) return 0; } get_patch_ids(&rev, &ids); } if (!use_stdout) realstdout = xfdopen(xdup(1), "w"); if (prepare_revision_walk(&rev)) die(_("revision walk setup failed")); rev.boundary = 1; while ((commit = get_revision(&rev)) != NULL) { if (commit->object.flags & BOUNDARY) { boundary_count++; origin = (boundary_count == 1) ? commit : NULL; continue; } if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids)) continue; nr++; list = xrealloc(list, nr * sizeof(list[0])); list[nr - 1] = commit; } total = nr; if (!keep_subject && auto_number && total > 1) numbered = 1; if (numbered) rev.total = total + start_number - 1; if (in_reply_to || thread || cover_letter) rev.ref_message_ids = xcalloc(1, sizeof(struct string_list)); if (in_reply_to) { const char *msgid = clean_message_id(in_reply_to); string_list_append(rev.ref_message_ids, msgid); } rev.numbered_files = numbered_files; rev.patch_suffix = fmt_patch_suffix; if (cover_letter) { if (thread) gen_message_id(&rev, "cover"); make_cover_letter(&rev, use_stdout, numbered, numbered_files, origin, nr, list, head, branch_name, quiet); 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) { /* * For deep threading: make every mail * a reply to the previous one, no * matter what other options are set. * * For shallow threading: * * Without --cover-letter and * --in-reply-to, make every mail a * reply to the one before. * * With --in-reply-to but no * --cover-letter, make every mail a * reply to the <reply-to>. * * With --cover-letter, make every * mail but the cover letter a reply * to the cover letter. The cover * letter is a reply to the * --in-reply-to, if specified. */ if (thread == THREAD_SHALLOW && rev.ref_message_ids->nr > 0 && (!cover_letter || rev.nr > 1)) free(rev.message_id); else string_list_append(rev.ref_message_ids, rev.message_id); } gen_message_id(&rev, sha1_to_hex(commit->object.sha1)); } if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit, NULL, &rev, quiet)) die(_("Failed to create output files")); shown = log_tree_commit(&rev, commit); free(commit->buffer); commit->buffer = NULL; /* We put one extra blank line between formatted * patches and this flag is used by log-tree code * to see if it needs to emit a LF before showing * the log; when using one file per patch, we do * not want the extra blank line. */ if (!use_stdout) rev.shown_one = 0; if (shown) { if (rev.mime_boundary) printf("\n--%s%s--\n\n\n", mime_boundary_leader, rev.mime_boundary); else print_signature(); } if (!use_stdout) fclose(stdout); } free(list); free(branch_name); string_list_clear(&extra_to, 0); string_list_clear(&extra_cc, 0); string_list_clear(&extra_hdr, 0); if (ignore_if_in_upstream) free_patch_ids(&ids); return 0; }
static int rsync_transport_push(struct transport *transport, int refspec_nr, const char **refspec, int flags) { struct strbuf buf = STRBUF_INIT, temp_dir = STRBUF_INIT; int result = 0, i; struct child_process rsync; const char *args[10]; if (flags & TRANSPORT_PUSH_MIRROR) return error("rsync transport does not support mirror mode"); /* first push the objects */ strbuf_addstr(&buf, rsync_url(transport->url)); strbuf_addch(&buf, '/'); memset(&rsync, 0, sizeof(rsync)); rsync.argv = args; rsync.stdout_to_stderr = 1; i = 0; args[i++] = "rsync"; args[i++] = "-a"; if (flags & TRANSPORT_PUSH_DRY_RUN) args[i++] = "--dry-run"; if (transport->verbose > 1) args[i++] = "-v"; args[i++] = "--ignore-existing"; args[i++] = "--exclude"; args[i++] = "info"; args[i++] = get_object_directory(); args[i++] = buf.buf; args[i++] = NULL; if (run_command(&rsync)) return error("Could not push objects to %s", rsync_url(transport->url)); /* copy the refs to the temporary directory; they could be packed. */ strbuf_addstr(&temp_dir, git_path("rsync-refs-XXXXXX")); if (!mkdtemp(temp_dir.buf)) die_errno ("Could not make temporary directory"); strbuf_addch(&temp_dir, '/'); if (flags & TRANSPORT_PUSH_ALL) { if (for_each_ref(write_one_ref, &temp_dir)) return -1; } else if (write_refs_to_temp_dir(&temp_dir, refspec_nr, refspec)) return -1; i = 2; if (flags & TRANSPORT_PUSH_DRY_RUN) args[i++] = "--dry-run"; if (!(flags & TRANSPORT_PUSH_FORCE)) args[i++] = "--ignore-existing"; args[i++] = temp_dir.buf; args[i++] = rsync_url(transport->url); args[i++] = NULL; if (run_command(&rsync)) result = error("Could not push to %s", rsync_url(transport->url)); if (remove_dir_recursively(&temp_dir, 0)) warning ("Could not remove temporary directory %s.", temp_dir.buf); strbuf_release(&buf); strbuf_release(&temp_dir); return result; }
static int grep_submodule(struct grep_opt *opt, struct repository *superproject, const struct pathspec *pathspec, const struct object_id *oid, const char *filename, const char *path) { struct repository submodule; int hit; if (!is_submodule_active(superproject, path)) return 0; if (repo_submodule_init(&submodule, superproject, path)) return 0; repo_read_gitmodules(&submodule); /* * NEEDSWORK: This adds the submodule's object directory to the list of * alternates for the single in-memory object store. This has some bad * consequences for memory (processed objects will never be freed) and * performance (this increases the number of pack files git has to pay * attention to, to the sum of the number of pack files in all the * repositories processed so far). This can be removed once the object * store is no longer global and instead is a member of the repository * object. */ grep_read_lock(); add_to_alternates_memory(submodule.objectdir); grep_read_unlock(); if (oid) { struct object *object; struct tree_desc tree; void *data; unsigned long size; struct strbuf base = STRBUF_INIT; object = parse_object_or_die(oid, oid_to_hex(oid)); grep_read_lock(); data = read_object_with_reference(object->oid.hash, tree_type, &size, NULL); grep_read_unlock(); if (!data) die(_("unable to read tree (%s)"), oid_to_hex(&object->oid)); strbuf_addstr(&base, filename); strbuf_addch(&base, '/'); init_tree_desc(&tree, data, size); hit = grep_tree(opt, pathspec, &tree, &base, base.len, object->type == OBJ_COMMIT, &submodule); strbuf_release(&base); free(data); } else { hit = grep_cache(opt, &submodule, pathspec, 1); } repo_clear(&submodule); return hit; }
static void add_wrapped_shortlog_msg(struct strbuf *sb, const char *s, const struct shortlog *log) { strbuf_add_wrapped_text(sb, s, log->in1, log->in2, log->wrap); strbuf_addch(sb, '\n'); }
static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec, struct tree_desc *tree, struct strbuf *base, int tn_len, int check_attr, struct repository *repo) { int hit = 0; enum interesting match = entry_not_interesting; struct name_entry entry; int old_baselen = base->len; struct strbuf name = STRBUF_INIT; int name_base_len = 0; if (repo->submodule_prefix) { strbuf_addstr(&name, repo->submodule_prefix); name_base_len = name.len; } while (tree_entry(tree, &entry)) { int te_len = tree_entry_len(&entry); if (match != all_entries_interesting) { strbuf_addstr(&name, base->buf + tn_len); match = tree_entry_interesting(&entry, &name, 0, pathspec); strbuf_setlen(&name, name_base_len); if (match == all_entries_not_interesting) break; if (match == entry_not_interesting) continue; } strbuf_add(base, entry.path, te_len); if (S_ISREG(entry.mode)) { hit |= grep_oid(opt, entry.oid, base->buf, tn_len, check_attr ? base->buf + tn_len : NULL); } else if (S_ISDIR(entry.mode)) { enum object_type type; struct tree_desc sub; void *data; unsigned long size; data = lock_and_read_oid_file(entry.oid, &type, &size); if (!data) die(_("unable to read tree (%s)"), oid_to_hex(entry.oid)); strbuf_addch(base, '/'); init_tree_desc(&sub, data, size); hit |= grep_tree(opt, pathspec, &sub, base, tn_len, check_attr, repo); free(data); } else if (recurse_submodules && S_ISGITLINK(entry.mode)) { hit |= grep_submodule(opt, repo, pathspec, entry.oid, base->buf, base->buf + tn_len); } strbuf_setlen(base, old_baselen); if (hit && opt->status_only) break; } strbuf_release(&name); return hit; }
void pp_title_line(struct pretty_print_context *pp, const char **msg_p, struct strbuf *sb, const char *encoding, int need_8bit_cte) { static const int max_length = 78; /* per rfc2047 */ struct strbuf title; strbuf_init(&title, 80); *msg_p = format_subject(&title, *msg_p, pp->preserve_subject ? "\n" : " "); strbuf_grow(sb, title.len + 1024); if (pp->subject) { strbuf_addstr(sb, pp->subject); if (needs_rfc2047_encoding(title.buf, title.len, RFC2047_SUBJECT)) add_rfc2047(sb, title.buf, title.len, encoding, RFC2047_SUBJECT); else strbuf_add_wrapped_bytes(sb, title.buf, title.len, -last_line_length(sb), 1, max_length); } else { strbuf_addbuf(sb, &title); } strbuf_addch(sb, '\n'); if (need_8bit_cte == 0) { int i; for (i = 0; i < pp->in_body_headers.nr; i++) { if (has_non_ascii(pp->in_body_headers.items[i].string)) { need_8bit_cte = 1; break; } } } if (need_8bit_cte > 0) { const char *header_fmt = "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=%s\n" "Content-Transfer-Encoding: 8bit\n"; strbuf_addf(sb, header_fmt, encoding); } if (pp->after_subject) { strbuf_addstr(sb, pp->after_subject); } if (pp->fmt == CMIT_FMT_EMAIL) { strbuf_addch(sb, '\n'); } if (pp->in_body_headers.nr) { int i; for (i = 0; i < pp->in_body_headers.nr; i++) { strbuf_addstr(sb, pp->in_body_headers.items[i].string); free(pp->in_body_headers.items[i].string); } string_list_clear(&pp->in_body_headers, 0); strbuf_addch(sb, '\n'); } strbuf_release(&title); }
static int read_tree_1(struct tree *tree, struct strbuf *base, int stage, const struct pathspec *pathspec, read_tree_fn_t fn, void *context) { struct tree_desc desc; struct name_entry entry; unsigned char sha1[20]; int len, oldlen = base->len; enum interesting retval = entry_not_interesting; if (parse_tree(tree)) return -1; init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { if (retval != all_entries_interesting) { retval = tree_entry_interesting(&entry, base, 0, pathspec); if (retval == all_entries_not_interesting) break; if (retval == entry_not_interesting) continue; } switch (fn(entry.sha1, base, entry.path, entry.mode, stage, context)) { case 0: continue; case READ_TREE_RECURSIVE: break; default: return -1; } if (S_ISDIR(entry.mode)) hashcpy(sha1, entry.sha1); else if (S_ISGITLINK(entry.mode)) { struct commit *commit; commit = lookup_commit(entry.sha1); if (!commit) die("Commit %s in submodule path %s%s not found", sha1_to_hex(entry.sha1), base->buf, entry.path); if (parse_commit(commit)) die("Invalid commit %s in submodule path %s%s", sha1_to_hex(entry.sha1), base->buf, entry.path); hashcpy(sha1, commit->tree->object.sha1); } else continue; len = tree_entry_len(&entry); strbuf_add(base, entry.path, len); strbuf_addch(base, '/'); retval = read_tree_1(lookup_tree(sha1), base, stage, pathspec, fn, context); strbuf_setlen(base, oldlen); if (retval) return -1; } return 0; }
void pp_user_info(struct pretty_print_context *pp, const char *what, struct strbuf *sb, const char *line, const char *encoding) { struct ident_split ident; char *line_end; const char *mailbuf, *namebuf; size_t namelen, maillen; int max_length = 78; /* per rfc2822 */ if (pp->fmt == CMIT_FMT_ONELINE) return; line_end = strchrnul(line, '\n'); if (split_ident_line(&ident, line, line_end - line)) return; mailbuf = ident.mail_begin; maillen = ident.mail_end - ident.mail_begin; namebuf = ident.name_begin; namelen = ident.name_end - ident.name_begin; if (pp->mailmap) map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen); if (pp->fmt == CMIT_FMT_EMAIL) { if (pp->from_ident && ident_cmp(pp->from_ident, &ident)) { struct strbuf buf = STRBUF_INIT; strbuf_addstr(&buf, "From: "); strbuf_add(&buf, namebuf, namelen); strbuf_addstr(&buf, " <"); strbuf_add(&buf, mailbuf, maillen); strbuf_addstr(&buf, ">\n"); string_list_append(&pp->in_body_headers, strbuf_detach(&buf, NULL)); mailbuf = pp->from_ident->mail_begin; maillen = pp->from_ident->mail_end - mailbuf; namebuf = pp->from_ident->name_begin; namelen = pp->from_ident->name_end - namebuf; } strbuf_addstr(sb, "From: "); if (needs_rfc2047_encoding(namebuf, namelen, RFC2047_ADDRESS)) { add_rfc2047(sb, namebuf, namelen, encoding, RFC2047_ADDRESS); max_length = 76; /* per rfc2047 */ } else if (needs_rfc822_quoting(namebuf, namelen)) { struct strbuf quoted = STRBUF_INIT; add_rfc822_quoted("ed, namebuf, namelen); strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len, -6, 1, max_length); strbuf_release("ed); } else { strbuf_add_wrapped_bytes(sb, namebuf, namelen, -6, 1, max_length); } if (max_length < last_line_length(sb) + strlen(" <") + maillen + strlen(">")) strbuf_addch(sb, '\n'); strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf); } else { strbuf_addf(sb, "%s: %.*s%.*s <%.*s>\n", what, (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0, " ", (int)namelen, namebuf, (int)maillen, mailbuf); } switch (pp->fmt) { case CMIT_FMT_MEDIUM: strbuf_addf(sb, "Date: %s\n", show_ident_date(&ident, pp->date_mode)); break; case CMIT_FMT_EMAIL: strbuf_addf(sb, "Date: %s\n", show_ident_date(&ident, DATE_RFC2822)); break; case CMIT_FMT_FULLER: strbuf_addf(sb, "%sDate: %s\n", what, show_ident_date(&ident, pp->date_mode)); break; default: /* notin' */ break; } }
/* * Wrap the text, if necessary. The variable indent is the indent for the * first line, indent2 is the indent for all other lines. * If indent is negative, assume that already -indent columns have been * consumed (and no extra indent is necessary for the first line). */ int strbuf_add_wrapped_text(struct strbuf *buf, const char *text, int indent1, int indent2, int width) { int indent, w, assume_utf8 = 1; const char *bol, *space, *start = text; size_t orig_len = buf->len; if (width <= 0) { strbuf_add_indented_text(buf, text, indent1, indent2); return 1; } retry: bol = text; w = indent = indent1; space = NULL; if (indent < 0) { w = -indent; space = text; } for (;;) { char c; size_t skip; while ((skip = display_mode_esc_sequence_len(text))) text += skip; c = *text; if (!c || isspace(c)) { if (w < width || !space) { const char *start = bol; if (!c && text == start) return w; if (space) start = space; else strbuf_addchars(buf, ' ', indent); strbuf_add(buf, start, text - start); if (!c) return w; space = text; if (c == '\t') w |= 0x07; else if (c == '\n') { space++; if (*space == '\n') { strbuf_addch(buf, '\n'); goto new_line; } else if (!isalnum(*space)) goto new_line; else strbuf_addch(buf, ' '); } w++; text++; } else { new_line: strbuf_addch(buf, '\n'); text = bol = space + isspace(*space); space = NULL; w = indent = indent2; } continue; } if (assume_utf8) { w += utf8_width(&text, NULL); if (!text) { assume_utf8 = 0; text = start; strbuf_setlen(buf, orig_len); goto retry; } } else { w++; text++; } } }
static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest, const char *src_repo, int src_baselen) { struct dirent *de; struct stat buf; int src_len, dest_len; DIR *dir; dir = opendir(src->buf); if (!dir) die_errno(_("failed to open '%s'"), src->buf); if (mkdir(dest->buf, 0777)) { if (errno != EEXIST) die_errno(_("failed to create directory '%s'"), dest->buf); else if (stat(dest->buf, &buf)) die_errno(_("failed to stat '%s'"), dest->buf); else if (!S_ISDIR(buf.st_mode)) die(_("%s exists and is not a directory"), dest->buf); } strbuf_addch(src, '/'); src_len = src->len; strbuf_addch(dest, '/'); dest_len = dest->len; while ((de = readdir(dir)) != NULL) { strbuf_setlen(src, src_len); strbuf_addstr(src, de->d_name); strbuf_setlen(dest, dest_len); strbuf_addstr(dest, de->d_name); if (stat(src->buf, &buf)) { warning (_("failed to stat %s\n"), src->buf); continue; } if (S_ISDIR(buf.st_mode)) { if (de->d_name[0] != '.') copy_or_link_directory(src, dest, src_repo, src_baselen); continue; } /* Files that cannot be copied bit-for-bit... */ if (!strcmp(src->buf + src_baselen, "/info/alternates")) { copy_alternates(src, dest, src_repo); continue; } if (unlink(dest->buf) && errno != ENOENT) die_errno(_("failed to unlink '%s'"), dest->buf); if (!option_no_hardlinks) { if (!link(src->buf, dest->buf)) continue; if (option_local > 0) die_errno(_("failed to create link '%s'"), dest->buf); option_no_hardlinks = 1; } if (copy_file_with_time(dest->buf, src->buf, 0666)) die_errno(_("failed to copy file to '%s'"), dest->buf); } closedir(dir); }
static void print_line(struct strbuf *buf) { strbuf_addch(buf, '\n'); write_or_die(get_lock_file_fd(&credential_lock), buf->buf, buf->len); }
static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up) { DIR *dir; struct dirent *e; int ret = 0, original_len = path->len, len, kept_down = 0; int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY); int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL); unsigned char submodule_head[20]; if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) && !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) { /* Do not descend and nuke a nested git work tree. */ if (kept_up) *kept_up = 1; return 0; } flag &= ~REMOVE_DIR_KEEP_TOPLEVEL; dir = opendir(path->buf); if (!dir) { if (errno == ENOENT) return keep_toplevel ? -1 : 0; else if (errno == EACCES && !keep_toplevel) /* * An empty dir could be removable even if it * is unreadable: */ return rmdir(path->buf); else return -1; } if (path->buf[original_len - 1] != '/') strbuf_addch(path, '/'); len = path->len; while ((e = readdir(dir)) != NULL) { struct stat st; if (is_dot_or_dotdot(e->d_name)) continue; strbuf_setlen(path, len); strbuf_addstr(path, e->d_name); if (lstat(path->buf, &st)) { if (errno == ENOENT) /* * file disappeared, which is what we * wanted anyway */ continue; /* fall thru */ } else if (S_ISDIR(st.st_mode)) { if (!remove_dir_recurse(path, flag, &kept_down)) continue; /* happy */ } else if (!only_empty && (!unlink(path->buf) || errno == ENOENT)) { continue; /* happy, too */ } /* path too long, stat fails, or non-directory still exists */ ret = -1; break; } closedir(dir); strbuf_setlen(path, original_len); if (!ret && !keep_toplevel && !kept_down) ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1; else if (kept_up) /* * report the uplevel that it is not an error that we * did not rmdir() our directory. */ *kept_up = !ret; return ret; }
static int parse_commit(struct strbuf* input, struct string_list* files, struct strbuf* message) { int err; int pos; struct strbuf line; int lineno = 0; enum { BEGIN, FILES, MESSAGE } state = BEGIN; enum { OK, FAILED } result = OK; // if there is no data, just return if (input->len == 0) { return 0; } strbuf_init(&line, 0); pos = 0; while (result == OK) { err = get_strbuf_line(input, &pos, &line); lineno++; if (err != 0) { break; } if (is_comment(&line)) { continue; } switch (state) { case BEGIN: strbuf_trim(&line); if (line.len != 0) { if (0 == strcmp(line.buf, "Files:")) { state = FILES; } else { result = FAILED; } } break; case FILES: strbuf_trim(&line); if (line.len != 0) { if (0 == strcmp(line.buf, "Commit Message:")) { state = MESSAGE; } else if (0 == strip_file_info(&line)) { string_list_insert(line.buf, files); } else { result = FAILED; } } break; case MESSAGE: strbuf_rtrim(&line); strbuf_addbuf(message, &line); strbuf_addch(message, '\n'); break; } } strbuf_trim(message); return result == OK ? 0 : 1; }
void strbuf_ensure_end(struct strbuf *sb, char c) { if (!sb->len || sb->buf[sb->len - 1] != c) strbuf_addch(sb, c); }
static void graph_output_post_merge_line(struct git_graph *graph, struct strbuf *sb) { int seen_this = 0; int i, j, chars_written; /* * Output the post-merge row */ chars_written = 0; for (i = 0; i <= graph->num_columns; i++) { struct column *col = &graph->columns[i]; struct commit *col_commit; if (i == graph->num_columns) { if (seen_this) break; col_commit = graph->commit; } else { col_commit = col->commit; } if (col_commit == graph->commit) { /* * Since the current commit is a merge find * the columns for the parent commits in * new_columns and use those to format the * edges. */ struct commit_list *parents = NULL; struct column *par_column; seen_this = 1; parents = first_interesting_parent(graph); assert(parents); par_column = find_new_column_by_commit(graph, parents->item); assert(par_column); strbuf_write_column(sb, par_column, '|'); chars_written++; for (j = 0; j < graph->num_parents - 1; j++) { parents = next_interesting_parent(graph, parents); assert(parents); par_column = find_new_column_by_commit(graph, parents->item); assert(par_column); strbuf_write_column(sb, par_column, '\\'); strbuf_addch(sb, ' '); } chars_written += j * 2; } else if (seen_this) { strbuf_write_column(sb, col, '\\'); strbuf_addch(sb, ' '); chars_written += 2; } else { strbuf_write_column(sb, col, '|'); strbuf_addch(sb, ' '); chars_written += 2; } } graph_pad_horizontally(graph, sb, chars_written); /* * Update graph->state */ if (graph_is_mapping_correct(graph)) graph_update_state(graph, GRAPH_PADDING); else graph_update_state(graph, GRAPH_COLLAPSING); }