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 [-f] --convert-graft-file"),
24 N_("git replace -d <object>..."),
25 N_("git replace [--format=<format>] [-l [<pattern>]]"),
31 REPLACE_FORMAT_MEDIUM,
37 enum replace_format format;
40 static int show_reference(const char *refname, const struct object_id *oid,
41 int flag, void *cb_data)
43 struct show_data *data = cb_data;
45 if (!wildmatch(data->pattern, refname, 0)) {
46 if (data->format == REPLACE_FORMAT_SHORT)
47 printf("%s\n", refname);
48 else if (data->format == REPLACE_FORMAT_MEDIUM)
49 printf("%s -> %s\n", refname, oid_to_hex(oid));
50 else { /* data->format == REPLACE_FORMAT_LONG */
51 struct object_id object;
52 enum object_type obj_type, repl_type;
54 if (get_oid(refname, &object))
55 return error("Failed to resolve '%s' as a valid ref.", refname);
57 obj_type = oid_object_info(&object, NULL);
58 repl_type = oid_object_info(oid, NULL);
60 printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
61 oid_to_hex(oid), type_name(repl_type));
68 static int list_replace_refs(const char *pattern, const char *format)
70 struct show_data data;
74 data.pattern = pattern;
76 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
77 data.format = REPLACE_FORMAT_SHORT;
78 else if (!strcmp(format, "medium"))
79 data.format = REPLACE_FORMAT_MEDIUM;
80 else if (!strcmp(format, "long"))
81 data.format = REPLACE_FORMAT_LONG;
83 return error("invalid replace format '%s'\n"
84 "valid formats are 'short', 'medium' and 'long'\n",
87 for_each_replace_ref(show_reference, (void *)&data);
92 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
93 const struct object_id *oid);
95 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
97 const char **p, *full_hex;
98 struct strbuf ref = STRBUF_INIT;
101 struct object_id oid;
103 strbuf_addstr(&ref, git_replace_ref_base);
106 for (p = argv; *p; p++) {
107 if (get_oid(*p, &oid)) {
108 error("Failed to resolve '%s' as a valid ref.", *p);
113 strbuf_setlen(&ref, base_len);
114 strbuf_addstr(&ref, oid_to_hex(&oid));
115 full_hex = ref.buf + base_len;
117 if (read_ref(ref.buf, &oid)) {
118 error("replace ref '%s' not found.", full_hex);
122 if (fn(full_hex, ref.buf, &oid))
125 strbuf_release(&ref);
129 static int delete_replace_ref(const char *name, const char *ref,
130 const struct object_id *oid)
132 if (delete_ref(NULL, ref, oid, 0))
134 printf("Deleted replace ref '%s'\n", name);
138 static int check_ref_valid(struct object_id *object,
139 struct object_id *prev,
144 strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
145 if (check_refname_format(ref->buf, 0))
146 return error("'%s' is not a valid ref name.", ref->buf);
148 if (read_ref(ref->buf, prev))
151 return error("replace ref '%s' already exists", ref->buf);
155 static int replace_object_oid(const char *object_ref,
156 struct object_id *object,
157 const char *replace_ref,
158 struct object_id *repl,
161 struct object_id prev;
162 enum object_type obj_type, repl_type;
163 struct strbuf ref = STRBUF_INIT;
164 struct ref_transaction *transaction;
165 struct strbuf err = STRBUF_INIT;
168 obj_type = oid_object_info(object, NULL);
169 repl_type = oid_object_info(repl, NULL);
170 if (!force && obj_type != repl_type)
171 return error("Objects must be of the same type.\n"
172 "'%s' points to a replaced object of type '%s'\n"
173 "while '%s' points to a replacement object of "
175 object_ref, type_name(obj_type),
176 replace_ref, type_name(repl_type));
178 if (check_ref_valid(object, &prev, &ref, force)) {
179 strbuf_release(&ref);
183 transaction = ref_transaction_begin(&err);
185 ref_transaction_update(transaction, ref.buf, repl, &prev,
187 ref_transaction_commit(transaction, &err))
188 res = error("%s", err.buf);
190 ref_transaction_free(transaction);
191 strbuf_release(&ref);
195 static int replace_object(const char *object_ref, const char *replace_ref, int force)
197 struct object_id object, repl;
199 if (get_oid(object_ref, &object))
200 return error("Failed to resolve '%s' as a valid ref.",
202 if (get_oid(replace_ref, &repl))
203 return error("Failed to resolve '%s' as a valid ref.",
206 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
210 * Write the contents of the object named by "sha1" to the file "filename".
211 * If "raw" is true, then the object's raw contents are printed according to
212 * "type". Otherwise, we pretty-print the contents for human editing.
214 static int export_object(const struct object_id *oid, enum object_type type,
215 int raw, const char *filename)
217 struct child_process cmd = CHILD_PROCESS_INIT;
220 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
222 return error_errno("unable to open %s for writing", filename);
224 argv_array_push(&cmd.args, "--no-replace-objects");
225 argv_array_push(&cmd.args, "cat-file");
227 argv_array_push(&cmd.args, type_name(type));
229 argv_array_push(&cmd.args, "-p");
230 argv_array_push(&cmd.args, oid_to_hex(oid));
234 if (run_command(&cmd))
235 return error("cat-file reported failure");
240 * Read a previously-exported (and possibly edited) object back from "filename",
241 * interpreting it as "type", and writing the result to the object database.
242 * The sha1 of the written object is returned via sha1.
244 static int import_object(struct object_id *oid, enum object_type type,
245 int raw, const char *filename)
249 fd = open(filename, O_RDONLY);
251 return error_errno("unable to open %s for reading", filename);
253 if (!raw && type == OBJ_TREE) {
254 const char *argv[] = { "mktree", NULL };
255 struct child_process cmd = CHILD_PROCESS_INIT;
256 struct strbuf result = STRBUF_INIT;
263 if (start_command(&cmd)) {
265 return error("unable to spawn mktree");
268 if (strbuf_read(&result, cmd.out, 41) < 0) {
269 error_errno("unable to read from mktree");
276 if (finish_command(&cmd)) {
277 strbuf_release(&result);
278 return error("mktree reported failure");
280 if (get_oid_hex(result.buf, oid) < 0) {
281 strbuf_release(&result);
282 return error("mktree did not return an object name");
285 strbuf_release(&result);
288 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
290 if (fstat(fd, &st) < 0) {
291 error_errno("unable to fstat %s", filename);
295 if (index_fd(oid, fd, &st, type, NULL, flags) < 0)
296 return error("unable to write object to database");
297 /* index_fd close()s fd for us */
301 * No need to close(fd) here; both run-command and index-fd
302 * will have done it for us.
307 static int edit_and_replace(const char *object_ref, int force, int raw)
310 enum object_type type;
311 struct object_id old_oid, new_oid, prev;
312 struct strbuf ref = STRBUF_INIT;
314 if (get_oid(object_ref, &old_oid) < 0)
315 return error("Not a valid object name: '%s'", object_ref);
317 type = oid_object_info(&old_oid, NULL);
319 return error("unable to get object type for %s",
320 oid_to_hex(&old_oid));
322 if (check_ref_valid(&old_oid, &prev, &ref, force)) {
323 strbuf_release(&ref);
326 strbuf_release(&ref);
328 tmpfile = git_pathdup("REPLACE_EDITOBJ");
329 if (export_object(&old_oid, type, raw, tmpfile)) {
333 if (launch_editor(tmpfile, NULL, NULL) < 0) {
335 return error("editing object file failed");
337 if (import_object(&new_oid, type, raw, tmpfile)) {
343 if (!oidcmp(&old_oid, &new_oid))
344 return error("new object is the same as the old one: '%s'", oid_to_hex(&old_oid));
346 return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
349 static int replace_parents(struct strbuf *buf, int argc, const char **argv)
351 struct strbuf new_parents = STRBUF_INIT;
352 const char *parent_start, *parent_end;
355 /* find existing parents */
356 parent_start = buf->buf;
357 parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
358 parent_end = parent_start;
360 while (starts_with(parent_end, "parent "))
361 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
363 /* prepare new parents */
364 for (i = 0; i < argc; i++) {
365 struct object_id oid;
366 if (get_oid(argv[i], &oid) < 0) {
367 strbuf_release(&new_parents);
368 return error(_("Not a valid object name: '%s'"),
371 if (!lookup_commit_reference(&oid)) {
372 strbuf_release(&new_parents);
373 return error(_("could not parse %s"), argv[i]);
375 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
378 /* replace existing parents with new ones */
379 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
380 new_parents.buf, new_parents.len);
382 strbuf_release(&new_parents);
386 struct check_mergetag_data {
391 static int check_one_mergetag(struct commit *commit,
392 struct commit_extra_header *extra,
395 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
396 const char *ref = mergetag_data->argv[0];
397 struct object_id tag_oid;
401 hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
402 tag = lookup_tag(&tag_oid);
404 return error(_("bad mergetag in commit '%s'"), ref);
405 if (parse_tag_buffer(tag, extra->value, extra->len))
406 return error(_("malformed mergetag in commit '%s'"), ref);
408 /* iterate over new parents */
409 for (i = 1; i < mergetag_data->argc; i++) {
410 struct object_id oid;
411 if (get_oid(mergetag_data->argv[i], &oid) < 0)
412 return error(_("Not a valid object name: '%s'"),
413 mergetag_data->argv[i]);
414 if (!oidcmp(&tag->tagged->oid, &oid))
415 return 0; /* found */
418 return error(_("original commit '%s' contains mergetag '%s' that is "
419 "discarded; use --edit instead of --graft"), ref,
420 oid_to_hex(&tag_oid));
423 static int check_mergetags(struct commit *commit, int argc, const char **argv)
425 struct check_mergetag_data mergetag_data;
427 mergetag_data.argc = argc;
428 mergetag_data.argv = argv;
429 return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
432 static int create_graft(int argc, const char **argv, int force, int gentle)
434 struct object_id old_oid, new_oid;
435 const char *old_ref = argv[0];
436 struct commit *commit;
437 struct strbuf buf = STRBUF_INIT;
441 if (get_oid(old_ref, &old_oid) < 0)
442 return error(_("Not a valid object name: '%s'"), old_ref);
443 commit = lookup_commit_reference(&old_oid);
445 return error(_("could not parse %s"), old_ref);
447 buffer = get_commit_buffer(commit, &size);
448 strbuf_add(&buf, buffer, size);
449 unuse_commit_buffer(commit, buffer);
451 if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
452 strbuf_release(&buf);
456 if (remove_signature(&buf)) {
457 warning(_("the original commit '%s' has a gpg signature."), old_ref);
458 warning(_("the signature will be removed in the replacement commit!"));
461 if (check_mergetags(commit, argc, argv)) {
462 strbuf_release(&buf);
466 if (write_object_file(buf.buf, buf.len, commit_type, &new_oid)) {
467 strbuf_release(&buf);
468 return error(_("could not write replacement commit for: '%s'"),
472 strbuf_release(&buf);
474 if (!oidcmp(&old_oid, &new_oid)) {
476 warning("graft for '%s' unnecessary", oid_to_hex(&old_oid));
479 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old_oid));
482 return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
485 static int convert_graft_file(int force)
487 const char *graft_file = get_graft_file();
488 FILE *fp = fopen_or_warn(graft_file, "r");
489 struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
490 struct argv_array args = ARGV_ARRAY_INIT;
495 while (strbuf_getline(&buf, fp) != EOF) {
499 argv_array_split(&args, buf.buf);
500 if (args.argc && create_graft(args.argc, args.argv, force, 1))
501 strbuf_addf(&err, "\n\t%s", buf.buf);
502 argv_array_clear(&args);
506 strbuf_release(&buf);
509 return unlink_or_warn(graft_file);
511 warning(_("could not convert the following graft(s):\n%s"), err.buf);
512 strbuf_release(&err);
517 int cmd_replace(int argc, const char **argv, const char *prefix)
521 const char *format = NULL;
523 MODE_UNSPECIFIED = 0,
528 MODE_CONVERT_GRAFT_FILE,
530 } cmdmode = MODE_UNSPECIFIED;
531 struct option options[] = {
532 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
533 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
534 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
535 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
536 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
537 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
538 PARSE_OPT_NOCOMPLETE),
539 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
540 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
544 check_replace_refs = 0;
545 git_config(git_default_config, NULL);
547 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
550 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
552 if (format && cmdmode != MODE_LIST)
553 usage_msg_opt("--format cannot be used when not listing",
554 git_replace_usage, options);
557 cmdmode != MODE_REPLACE &&
558 cmdmode != MODE_EDIT &&
559 cmdmode != MODE_GRAFT &&
560 cmdmode != MODE_CONVERT_GRAFT_FILE)
561 usage_msg_opt("-f only makes sense when writing a replacement",
562 git_replace_usage, options);
564 if (raw && cmdmode != MODE_EDIT)
565 usage_msg_opt("--raw only makes sense with --edit",
566 git_replace_usage, options);
571 usage_msg_opt("-d needs at least one argument",
572 git_replace_usage, options);
573 return for_each_replace_name(argv, delete_replace_ref);
577 usage_msg_opt("bad number of arguments",
578 git_replace_usage, options);
579 return replace_object(argv[0], argv[1], force);
583 usage_msg_opt("-e needs exactly one argument",
584 git_replace_usage, options);
585 return edit_and_replace(argv[0], force, raw);
589 usage_msg_opt("-g needs at least one argument",
590 git_replace_usage, options);
591 return create_graft(argc, argv, force, 0);
593 case MODE_CONVERT_GRAFT_FILE:
595 usage_msg_opt("--convert-graft-file takes no argument",
596 git_replace_usage, options);
597 return !!convert_graft_file(force);
601 usage_msg_opt("only one pattern can be given with -l",
602 git_replace_usage, options);
603 return list_replace_refs(argv[0], format);
606 BUG("invalid cmdmode %d", (int)cmdmode);