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"
17 #include "object-store.h"
18 #include "repository.h"
21 static const char * const git_replace_usage[] = {
22 N_("git replace [-f] <object> <replacement>"),
23 N_("git replace [-f] --edit <object>"),
24 N_("git replace [-f] --graft <commit> [<parent>...]"),
25 N_("git replace [-f] --convert-graft-file"),
26 N_("git replace -d <object>..."),
27 N_("git replace [--format=<format>] [-l [<pattern>]]"),
33 REPLACE_FORMAT_MEDIUM,
39 enum replace_format format;
42 static int show_reference(const char *refname, const struct object_id *oid,
43 int flag, void *cb_data)
45 struct show_data *data = cb_data;
47 if (!wildmatch(data->pattern, refname, 0)) {
48 if (data->format == REPLACE_FORMAT_SHORT)
49 printf("%s\n", refname);
50 else if (data->format == REPLACE_FORMAT_MEDIUM)
51 printf("%s -> %s\n", refname, oid_to_hex(oid));
52 else { /* data->format == REPLACE_FORMAT_LONG */
53 struct object_id object;
54 enum object_type obj_type, repl_type;
56 if (get_oid(refname, &object))
57 return error("Failed to resolve '%s' as a valid ref.", refname);
59 obj_type = oid_object_info(the_repository, &object,
61 repl_type = oid_object_info(the_repository, oid, NULL);
63 printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
64 oid_to_hex(oid), type_name(repl_type));
71 static int list_replace_refs(const char *pattern, const char *format)
73 struct show_data data;
77 data.pattern = pattern;
79 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
80 data.format = REPLACE_FORMAT_SHORT;
81 else if (!strcmp(format, "medium"))
82 data.format = REPLACE_FORMAT_MEDIUM;
83 else if (!strcmp(format, "long"))
84 data.format = REPLACE_FORMAT_LONG;
86 return error("invalid replace format '%s'\n"
87 "valid formats are 'short', 'medium' and 'long'\n",
90 for_each_replace_ref(the_repository, show_reference, (void *)&data);
95 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
96 const struct object_id *oid);
98 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
100 const char **p, *full_hex;
101 struct strbuf ref = STRBUF_INIT;
104 struct object_id oid;
106 strbuf_addstr(&ref, git_replace_ref_base);
109 for (p = argv; *p; p++) {
110 if (get_oid(*p, &oid)) {
111 error("Failed to resolve '%s' as a valid ref.", *p);
116 strbuf_setlen(&ref, base_len);
117 strbuf_addstr(&ref, oid_to_hex(&oid));
118 full_hex = ref.buf + base_len;
120 if (read_ref(ref.buf, &oid)) {
121 error("replace ref '%s' not found.", full_hex);
125 if (fn(full_hex, ref.buf, &oid))
128 strbuf_release(&ref);
132 static int delete_replace_ref(const char *name, const char *ref,
133 const struct object_id *oid)
135 if (delete_ref(NULL, ref, oid, 0))
137 printf("Deleted replace ref '%s'\n", name);
141 static int check_ref_valid(struct object_id *object,
142 struct object_id *prev,
147 strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
148 if (check_refname_format(ref->buf, 0))
149 return error("'%s' is not a valid ref name.", ref->buf);
151 if (read_ref(ref->buf, prev))
154 return error("replace ref '%s' already exists", ref->buf);
158 static int replace_object_oid(const char *object_ref,
159 struct object_id *object,
160 const char *replace_ref,
161 struct object_id *repl,
164 struct object_id prev;
165 enum object_type obj_type, repl_type;
166 struct strbuf ref = STRBUF_INIT;
167 struct ref_transaction *transaction;
168 struct strbuf err = STRBUF_INIT;
171 obj_type = oid_object_info(the_repository, object, NULL);
172 repl_type = oid_object_info(the_repository, repl, NULL);
173 if (!force && obj_type != repl_type)
174 return error("Objects must be of the same type.\n"
175 "'%s' points to a replaced object of type '%s'\n"
176 "while '%s' points to a replacement object of "
178 object_ref, type_name(obj_type),
179 replace_ref, type_name(repl_type));
181 if (check_ref_valid(object, &prev, &ref, force)) {
182 strbuf_release(&ref);
186 transaction = ref_transaction_begin(&err);
188 ref_transaction_update(transaction, ref.buf, repl, &prev,
190 ref_transaction_commit(transaction, &err))
191 res = error("%s", err.buf);
193 ref_transaction_free(transaction);
194 strbuf_release(&ref);
198 static int replace_object(const char *object_ref, const char *replace_ref, int force)
200 struct object_id object, repl;
202 if (get_oid(object_ref, &object))
203 return error("Failed to resolve '%s' as a valid ref.",
205 if (get_oid(replace_ref, &repl))
206 return error("Failed to resolve '%s' as a valid ref.",
209 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
213 * Write the contents of the object named by "sha1" to the file "filename".
214 * If "raw" is true, then the object's raw contents are printed according to
215 * "type". Otherwise, we pretty-print the contents for human editing.
217 static int export_object(const struct object_id *oid, enum object_type type,
218 int raw, const char *filename)
220 struct child_process cmd = CHILD_PROCESS_INIT;
223 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
225 return error_errno("unable to open %s for writing", filename);
227 argv_array_push(&cmd.args, "--no-replace-objects");
228 argv_array_push(&cmd.args, "cat-file");
230 argv_array_push(&cmd.args, type_name(type));
232 argv_array_push(&cmd.args, "-p");
233 argv_array_push(&cmd.args, oid_to_hex(oid));
237 if (run_command(&cmd))
238 return error("cat-file reported failure");
243 * Read a previously-exported (and possibly edited) object back from "filename",
244 * interpreting it as "type", and writing the result to the object database.
245 * The sha1 of the written object is returned via sha1.
247 static int import_object(struct object_id *oid, enum object_type type,
248 int raw, const char *filename)
252 fd = open(filename, O_RDONLY);
254 return error_errno("unable to open %s for reading", filename);
256 if (!raw && type == OBJ_TREE) {
257 const char *argv[] = { "mktree", NULL };
258 struct child_process cmd = CHILD_PROCESS_INIT;
259 struct strbuf result = STRBUF_INIT;
266 if (start_command(&cmd)) {
268 return error("unable to spawn mktree");
271 if (strbuf_read(&result, cmd.out, 41) < 0) {
272 error_errno("unable to read from mktree");
279 if (finish_command(&cmd)) {
280 strbuf_release(&result);
281 return error("mktree reported failure");
283 if (get_oid_hex(result.buf, oid) < 0) {
284 strbuf_release(&result);
285 return error("mktree did not return an object name");
288 strbuf_release(&result);
291 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
293 if (fstat(fd, &st) < 0) {
294 error_errno("unable to fstat %s", filename);
298 if (index_fd(oid, fd, &st, type, NULL, flags) < 0)
299 return error("unable to write object to database");
300 /* index_fd close()s fd for us */
304 * No need to close(fd) here; both run-command and index-fd
305 * will have done it for us.
310 static int edit_and_replace(const char *object_ref, int force, int raw)
313 enum object_type type;
314 struct object_id old_oid, new_oid, prev;
315 struct strbuf ref = STRBUF_INIT;
317 if (get_oid(object_ref, &old_oid) < 0)
318 return error("Not a valid object name: '%s'", object_ref);
320 type = oid_object_info(the_repository, &old_oid, NULL);
322 return error("unable to get object type for %s",
323 oid_to_hex(&old_oid));
325 if (check_ref_valid(&old_oid, &prev, &ref, force)) {
326 strbuf_release(&ref);
329 strbuf_release(&ref);
331 tmpfile = git_pathdup("REPLACE_EDITOBJ");
332 if (export_object(&old_oid, type, raw, tmpfile)) {
336 if (launch_editor(tmpfile, NULL, NULL) < 0) {
338 return error("editing object file failed");
340 if (import_object(&new_oid, type, raw, tmpfile)) {
346 if (!oidcmp(&old_oid, &new_oid))
347 return error("new object is the same as the old one: '%s'", oid_to_hex(&old_oid));
349 return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
352 static int replace_parents(struct strbuf *buf, int argc, const char **argv)
354 struct strbuf new_parents = STRBUF_INIT;
355 const char *parent_start, *parent_end;
358 /* find existing parents */
359 parent_start = buf->buf;
360 parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
361 parent_end = parent_start;
363 while (starts_with(parent_end, "parent "))
364 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
366 /* prepare new parents */
367 for (i = 0; i < argc; i++) {
368 struct object_id oid;
369 if (get_oid(argv[i], &oid) < 0) {
370 strbuf_release(&new_parents);
371 return error(_("Not a valid object name: '%s'"),
374 if (!lookup_commit_reference(the_repository, &oid)) {
375 strbuf_release(&new_parents);
376 return error(_("could not parse %s"), argv[i]);
378 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
381 /* replace existing parents with new ones */
382 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
383 new_parents.buf, new_parents.len);
385 strbuf_release(&new_parents);
389 struct check_mergetag_data {
394 static int check_one_mergetag(struct commit *commit,
395 struct commit_extra_header *extra,
398 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
399 const char *ref = mergetag_data->argv[0];
400 struct object_id tag_oid;
404 hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
405 tag = lookup_tag(the_repository, &tag_oid);
407 return error(_("bad mergetag in commit '%s'"), ref);
408 if (parse_tag_buffer(the_repository, tag, extra->value, extra->len))
409 return error(_("malformed mergetag in commit '%s'"), ref);
411 /* iterate over new parents */
412 for (i = 1; i < mergetag_data->argc; i++) {
413 struct object_id oid;
414 if (get_oid(mergetag_data->argv[i], &oid) < 0)
415 return error(_("Not a valid object name: '%s'"),
416 mergetag_data->argv[i]);
417 if (!oidcmp(&tag->tagged->oid, &oid))
418 return 0; /* found */
421 return error(_("original commit '%s' contains mergetag '%s' that is "
422 "discarded; use --edit instead of --graft"), ref,
423 oid_to_hex(&tag_oid));
426 static int check_mergetags(struct commit *commit, int argc, const char **argv)
428 struct check_mergetag_data mergetag_data;
430 mergetag_data.argc = argc;
431 mergetag_data.argv = argv;
432 return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
435 static int create_graft(int argc, const char **argv, int force, int gentle)
437 struct object_id old_oid, new_oid;
438 const char *old_ref = argv[0];
439 struct commit *commit;
440 struct strbuf buf = STRBUF_INIT;
444 if (get_oid(old_ref, &old_oid) < 0)
445 return error(_("Not a valid object name: '%s'"), old_ref);
446 commit = lookup_commit_reference(the_repository, &old_oid);
448 return error(_("could not parse %s"), old_ref);
450 buffer = get_commit_buffer(commit, &size);
451 strbuf_add(&buf, buffer, size);
452 unuse_commit_buffer(commit, buffer);
454 if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
455 strbuf_release(&buf);
459 if (remove_signature(&buf)) {
460 warning(_("the original commit '%s' has a gpg signature."), old_ref);
461 warning(_("the signature will be removed in the replacement commit!"));
464 if (check_mergetags(commit, argc, argv)) {
465 strbuf_release(&buf);
469 if (write_object_file(buf.buf, buf.len, commit_type, &new_oid)) {
470 strbuf_release(&buf);
471 return error(_("could not write replacement commit for: '%s'"),
475 strbuf_release(&buf);
477 if (!oidcmp(&old_oid, &new_oid)) {
479 warning("graft for '%s' unnecessary", oid_to_hex(&old_oid));
482 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old_oid));
485 return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
488 static int convert_graft_file(int force)
490 const char *graft_file = get_graft_file(the_repository);
491 FILE *fp = fopen_or_warn(graft_file, "r");
492 struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
493 struct argv_array args = ARGV_ARRAY_INIT;
498 while (strbuf_getline(&buf, fp) != EOF) {
502 argv_array_split(&args, buf.buf);
503 if (args.argc && create_graft(args.argc, args.argv, force, 1))
504 strbuf_addf(&err, "\n\t%s", buf.buf);
505 argv_array_clear(&args);
509 strbuf_release(&buf);
512 return unlink_or_warn(graft_file);
514 warning(_("could not convert the following graft(s):\n%s"), err.buf);
515 strbuf_release(&err);
520 int cmd_replace(int argc, const char **argv, const char *prefix)
524 const char *format = NULL;
526 MODE_UNSPECIFIED = 0,
531 MODE_CONVERT_GRAFT_FILE,
533 } cmdmode = MODE_UNSPECIFIED;
534 struct option options[] = {
535 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
536 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
537 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
538 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
539 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
540 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
541 PARSE_OPT_NOCOMPLETE),
542 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
543 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
547 check_replace_refs = 0;
548 git_config(git_default_config, NULL);
550 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
553 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
555 if (format && cmdmode != MODE_LIST)
556 usage_msg_opt("--format cannot be used when not listing",
557 git_replace_usage, options);
560 cmdmode != MODE_REPLACE &&
561 cmdmode != MODE_EDIT &&
562 cmdmode != MODE_GRAFT &&
563 cmdmode != MODE_CONVERT_GRAFT_FILE)
564 usage_msg_opt("-f only makes sense when writing a replacement",
565 git_replace_usage, options);
567 if (raw && cmdmode != MODE_EDIT)
568 usage_msg_opt("--raw only makes sense with --edit",
569 git_replace_usage, options);
574 usage_msg_opt("-d needs at least one argument",
575 git_replace_usage, options);
576 return for_each_replace_name(argv, delete_replace_ref);
580 usage_msg_opt("bad number of arguments",
581 git_replace_usage, options);
582 return replace_object(argv[0], argv[1], force);
586 usage_msg_opt("-e needs exactly one argument",
587 git_replace_usage, options);
588 return edit_and_replace(argv[0], force, raw);
592 usage_msg_opt("-g needs at least one argument",
593 git_replace_usage, options);
594 return create_graft(argc, argv, force, 0);
596 case MODE_CONVERT_GRAFT_FILE:
598 usage_msg_opt("--convert-graft-file takes no argument",
599 git_replace_usage, options);
600 return !!convert_graft_file(force);
604 usage_msg_opt("only one pattern can be given with -l",
605 git_replace_usage, options);
606 return list_replace_refs(argv[0], format);
609 BUG("invalid cmdmode %d", (int)cmdmode);