2 * Builtin "git replace"
4 * Copyright (c) 2008 Christian Couder <chriscool@tuxfamily.org>
6 * Based on builtin/tag.c by Kristian Høgsberg <krh@redhat.com>
7 * and Carlos Rica <jasampler@gmail.com> that was itself based on
8 * git-tag.sh and mktag.c by Linus Torvalds.
15 #include "parse-options.h"
16 #include "run-command.h"
19 static const char * const git_replace_usage[] = {
20 N_("git replace [-f] <object> <replacement>"),
21 N_("git replace [-f] --edit <object>"),
22 N_("git replace [-f] --graft <commit> [<parent>...]"),
23 N_("git replace -d <object>..."),
24 N_("git replace [--format=<format>] [-l [<pattern>]]"),
30 REPLACE_FORMAT_MEDIUM,
36 enum replace_format format;
39 static int show_reference(const char *refname, const struct object_id *oid,
40 int flag, void *cb_data)
42 struct show_data *data = cb_data;
44 if (!wildmatch(data->pattern, refname, 0)) {
45 if (data->format == REPLACE_FORMAT_SHORT)
46 printf("%s\n", refname);
47 else if (data->format == REPLACE_FORMAT_MEDIUM)
48 printf("%s -> %s\n", refname, oid_to_hex(oid));
49 else { /* data->format == REPLACE_FORMAT_LONG */
50 struct object_id object;
51 enum object_type obj_type, repl_type;
53 if (get_oid(refname, &object))
54 return error("Failed to resolve '%s' as a valid ref.", refname);
56 obj_type = oid_object_info(&object, NULL);
57 repl_type = oid_object_info(oid, NULL);
59 printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
60 oid_to_hex(oid), type_name(repl_type));
67 static int list_replace_refs(const char *pattern, const char *format)
69 struct show_data data;
73 data.pattern = pattern;
75 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
76 data.format = REPLACE_FORMAT_SHORT;
77 else if (!strcmp(format, "medium"))
78 data.format = REPLACE_FORMAT_MEDIUM;
79 else if (!strcmp(format, "long"))
80 data.format = REPLACE_FORMAT_LONG;
82 return error("invalid replace format '%s'\n"
83 "valid formats are 'short', 'medium' and 'long'\n",
86 for_each_replace_ref(show_reference, (void *)&data);
91 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
92 const struct object_id *oid);
94 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
96 const char **p, *full_hex;
97 struct strbuf ref = STRBUF_INIT;
100 struct object_id oid;
102 strbuf_addstr(&ref, git_replace_ref_base);
105 for (p = argv; *p; p++) {
106 if (get_oid(*p, &oid)) {
107 error("Failed to resolve '%s' as a valid ref.", *p);
112 strbuf_setlen(&ref, base_len);
113 strbuf_addstr(&ref, oid_to_hex(&oid));
114 full_hex = ref.buf + base_len;
116 if (read_ref(ref.buf, &oid)) {
117 error("replace ref '%s' not found.", full_hex);
121 if (fn(full_hex, ref.buf, &oid))
124 strbuf_release(&ref);
128 static int delete_replace_ref(const char *name, const char *ref,
129 const struct object_id *oid)
131 if (delete_ref(NULL, ref, oid, 0))
133 printf("Deleted replace ref '%s'\n", name);
137 static int check_ref_valid(struct object_id *object,
138 struct object_id *prev,
143 strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
144 if (check_refname_format(ref->buf, 0))
145 return error("'%s' is not a valid ref name.", ref->buf);
147 if (read_ref(ref->buf, prev))
150 return error("replace ref '%s' already exists", ref->buf);
154 static int replace_object_oid(const char *object_ref,
155 struct object_id *object,
156 const char *replace_ref,
157 struct object_id *repl,
160 struct object_id prev;
161 enum object_type obj_type, repl_type;
162 struct strbuf ref = STRBUF_INIT;
163 struct ref_transaction *transaction;
164 struct strbuf err = STRBUF_INIT;
167 obj_type = oid_object_info(object, NULL);
168 repl_type = oid_object_info(repl, NULL);
169 if (!force && obj_type != repl_type)
170 return error("Objects must be of the same type.\n"
171 "'%s' points to a replaced object of type '%s'\n"
172 "while '%s' points to a replacement object of "
174 object_ref, type_name(obj_type),
175 replace_ref, type_name(repl_type));
177 if (check_ref_valid(object, &prev, &ref, force)) {
178 strbuf_release(&ref);
182 transaction = ref_transaction_begin(&err);
184 ref_transaction_update(transaction, ref.buf, repl, &prev,
186 ref_transaction_commit(transaction, &err))
187 res = error("%s", err.buf);
189 ref_transaction_free(transaction);
190 strbuf_release(&ref);
194 static int replace_object(const char *object_ref, const char *replace_ref, int force)
196 struct object_id object, repl;
198 if (get_oid(object_ref, &object))
199 return error("Failed to resolve '%s' as a valid ref.",
201 if (get_oid(replace_ref, &repl))
202 return error("Failed to resolve '%s' as a valid ref.",
205 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
209 * Write the contents of the object named by "sha1" to the file "filename".
210 * If "raw" is true, then the object's raw contents are printed according to
211 * "type". Otherwise, we pretty-print the contents for human editing.
213 static int export_object(const struct object_id *oid, enum object_type type,
214 int raw, const char *filename)
216 struct child_process cmd = CHILD_PROCESS_INIT;
219 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
221 return error_errno("unable to open %s for writing", filename);
223 argv_array_push(&cmd.args, "--no-replace-objects");
224 argv_array_push(&cmd.args, "cat-file");
226 argv_array_push(&cmd.args, type_name(type));
228 argv_array_push(&cmd.args, "-p");
229 argv_array_push(&cmd.args, oid_to_hex(oid));
233 if (run_command(&cmd))
234 return error("cat-file reported failure");
239 * Read a previously-exported (and possibly edited) object back from "filename",
240 * interpreting it as "type", and writing the result to the object database.
241 * The sha1 of the written object is returned via sha1.
243 static int import_object(struct object_id *oid, enum object_type type,
244 int raw, const char *filename)
248 fd = open(filename, O_RDONLY);
250 return error_errno("unable to open %s for reading", filename);
252 if (!raw && type == OBJ_TREE) {
253 const char *argv[] = { "mktree", NULL };
254 struct child_process cmd = CHILD_PROCESS_INIT;
255 struct strbuf result = STRBUF_INIT;
262 if (start_command(&cmd)) {
264 return error("unable to spawn mktree");
267 if (strbuf_read(&result, cmd.out, 41) < 0) {
268 error_errno("unable to read from mktree");
275 if (finish_command(&cmd)) {
276 strbuf_release(&result);
277 return error("mktree reported failure");
279 if (get_oid_hex(result.buf, oid) < 0) {
280 strbuf_release(&result);
281 return error("mktree did not return an object name");
284 strbuf_release(&result);
287 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
289 if (fstat(fd, &st) < 0) {
290 error_errno("unable to fstat %s", filename);
294 if (index_fd(oid, fd, &st, type, NULL, flags) < 0)
295 return error("unable to write object to database");
296 /* index_fd close()s fd for us */
300 * No need to close(fd) here; both run-command and index-fd
301 * will have done it for us.
306 static int edit_and_replace(const char *object_ref, int force, int raw)
309 enum object_type type;
310 struct object_id old_oid, new_oid, prev;
311 struct strbuf ref = STRBUF_INIT;
313 if (get_oid(object_ref, &old_oid) < 0)
314 return error("Not a valid object name: '%s'", object_ref);
316 type = oid_object_info(&old_oid, NULL);
318 return error("unable to get object type for %s",
319 oid_to_hex(&old_oid));
321 if (check_ref_valid(&old_oid, &prev, &ref, force)) {
322 strbuf_release(&ref);
325 strbuf_release(&ref);
327 tmpfile = git_pathdup("REPLACE_EDITOBJ");
328 if (export_object(&old_oid, type, raw, tmpfile)) {
332 if (launch_editor(tmpfile, NULL, NULL) < 0) {
334 return error("editing object file failed");
336 if (import_object(&new_oid, type, raw, tmpfile)) {
342 if (!oidcmp(&old_oid, &new_oid))
343 return error("new object is the same as the old one: '%s'", oid_to_hex(&old_oid));
345 return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
348 static int replace_parents(struct strbuf *buf, int argc, const char **argv)
350 struct strbuf new_parents = STRBUF_INIT;
351 const char *parent_start, *parent_end;
354 /* find existing parents */
355 parent_start = buf->buf;
356 parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
357 parent_end = parent_start;
359 while (starts_with(parent_end, "parent "))
360 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
362 /* prepare new parents */
363 for (i = 0; i < argc; i++) {
364 struct object_id oid;
365 if (get_oid(argv[i], &oid) < 0) {
366 strbuf_release(&new_parents);
367 return error(_("Not a valid object name: '%s'"),
370 if (!lookup_commit_reference(&oid)) {
371 strbuf_release(&new_parents);
372 return error(_("could not parse %s"), argv[i]);
374 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
377 /* replace existing parents with new ones */
378 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
379 new_parents.buf, new_parents.len);
381 strbuf_release(&new_parents);
385 struct check_mergetag_data {
390 static int check_one_mergetag(struct commit *commit,
391 struct commit_extra_header *extra,
394 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
395 const char *ref = mergetag_data->argv[0];
396 struct object_id tag_oid;
400 hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
401 tag = lookup_tag(&tag_oid);
403 return error(_("bad mergetag in commit '%s'"), ref);
404 if (parse_tag_buffer(tag, extra->value, extra->len))
405 return error(_("malformed mergetag in commit '%s'"), ref);
407 /* iterate over new parents */
408 for (i = 1; i < mergetag_data->argc; i++) {
409 struct object_id oid;
410 if (get_oid(mergetag_data->argv[i], &oid) < 0)
411 return error(_("Not a valid object name: '%s'"),
412 mergetag_data->argv[i]);
413 if (!oidcmp(&tag->tagged->oid, &oid))
414 return 0; /* found */
417 return error(_("original commit '%s' contains mergetag '%s' that is "
418 "discarded; use --edit instead of --graft"), ref,
419 oid_to_hex(&tag_oid));
422 static int check_mergetags(struct commit *commit, int argc, const char **argv)
424 struct check_mergetag_data mergetag_data;
426 mergetag_data.argc = argc;
427 mergetag_data.argv = argv;
428 return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
431 static int create_graft(int argc, const char **argv, int force)
433 struct object_id old_oid, new_oid;
434 const char *old_ref = argv[0];
435 struct commit *commit;
436 struct strbuf buf = STRBUF_INIT;
440 if (get_oid(old_ref, &old_oid) < 0)
441 return error(_("Not a valid object name: '%s'"), old_ref);
442 commit = lookup_commit_reference(&old_oid);
444 return error(_("could not parse %s"), old_ref);
446 buffer = get_commit_buffer(commit, &size);
447 strbuf_add(&buf, buffer, size);
448 unuse_commit_buffer(commit, buffer);
450 if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
451 strbuf_release(&buf);
455 if (remove_signature(&buf)) {
456 warning(_("the original commit '%s' has a gpg signature."), old_ref);
457 warning(_("the signature will be removed in the replacement commit!"));
460 if (check_mergetags(commit, argc, argv)) {
461 strbuf_release(&buf);
465 if (write_object_file(buf.buf, buf.len, commit_type, &new_oid)) {
466 strbuf_release(&buf);
467 return error(_("could not write replacement commit for: '%s'"),
471 strbuf_release(&buf);
473 if (!oidcmp(&old_oid, &new_oid))
474 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old_oid));
476 return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
479 int cmd_replace(int argc, const char **argv, const char *prefix)
483 const char *format = NULL;
485 MODE_UNSPECIFIED = 0,
491 } cmdmode = MODE_UNSPECIFIED;
492 struct option options[] = {
493 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
494 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
495 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
496 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
497 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
498 PARSE_OPT_NOCOMPLETE),
499 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
500 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
504 check_replace_refs = 0;
505 git_config(git_default_config, NULL);
507 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
510 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
512 if (format && cmdmode != MODE_LIST)
513 usage_msg_opt("--format cannot be used when not listing",
514 git_replace_usage, options);
517 cmdmode != MODE_REPLACE &&
518 cmdmode != MODE_EDIT &&
519 cmdmode != MODE_GRAFT)
520 usage_msg_opt("-f only makes sense when writing a replacement",
521 git_replace_usage, options);
523 if (raw && cmdmode != MODE_EDIT)
524 usage_msg_opt("--raw only makes sense with --edit",
525 git_replace_usage, options);
530 usage_msg_opt("-d needs at least one argument",
531 git_replace_usage, options);
532 return for_each_replace_name(argv, delete_replace_ref);
536 usage_msg_opt("bad number of arguments",
537 git_replace_usage, options);
538 return replace_object(argv[0], argv[1], force);
542 usage_msg_opt("-e needs exactly one argument",
543 git_replace_usage, options);
544 return edit_and_replace(argv[0], force, raw);
548 usage_msg_opt("-g needs at least one argument",
549 git_replace_usage, options);
550 return create_graft(argc, argv, force);
554 usage_msg_opt("only one pattern can be given with -l",
555 git_replace_usage, options);
556 return list_replace_refs(argv[0], format);
559 BUG("invalid cmdmode %d", (int)cmdmode);