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 = sha1_object_info(object.hash, NULL);
57 repl_type = sha1_object_info(oid->hash, NULL);
59 printf("%s (%s) -> %s (%s)\n", refname, typename(obj_type),
60 oid_to_hex(oid), typename(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 die("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 void 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 die("'%s' is not a valid ref name.", ref->buf);
147 if (read_ref(ref->buf, prev))
150 die("replace ref '%s' already exists", ref->buf);
153 static int replace_object_oid(const char *object_ref,
154 struct object_id *object,
155 const char *replace_ref,
156 struct object_id *repl,
159 struct object_id prev;
160 enum object_type obj_type, repl_type;
161 struct strbuf ref = STRBUF_INIT;
162 struct ref_transaction *transaction;
163 struct strbuf err = STRBUF_INIT;
165 obj_type = sha1_object_info(object->hash, NULL);
166 repl_type = sha1_object_info(repl->hash, NULL);
167 if (!force && obj_type != repl_type)
168 die("Objects must be of the same type.\n"
169 "'%s' points to a replaced object of type '%s'\n"
170 "while '%s' points to a replacement object of type '%s'.",
171 object_ref, typename(obj_type),
172 replace_ref, typename(repl_type));
174 check_ref_valid(object, &prev, &ref, force);
176 transaction = ref_transaction_begin(&err);
178 ref_transaction_update(transaction, ref.buf, repl, &prev,
180 ref_transaction_commit(transaction, &err))
183 ref_transaction_free(transaction);
184 strbuf_release(&ref);
188 static int replace_object(const char *object_ref, const char *replace_ref, int force)
190 struct object_id object, repl;
192 if (get_oid(object_ref, &object))
193 die("Failed to resolve '%s' as a valid ref.", object_ref);
194 if (get_oid(replace_ref, &repl))
195 die("Failed to resolve '%s' as a valid ref.", replace_ref);
197 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
201 * Write the contents of the object named by "sha1" to the file "filename".
202 * If "raw" is true, then the object's raw contents are printed according to
203 * "type". Otherwise, we pretty-print the contents for human editing.
205 static void export_object(const struct object_id *oid, enum object_type type,
206 int raw, const char *filename)
208 struct child_process cmd = CHILD_PROCESS_INIT;
211 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
213 die_errno("unable to open %s for writing", filename);
215 argv_array_push(&cmd.args, "--no-replace-objects");
216 argv_array_push(&cmd.args, "cat-file");
218 argv_array_push(&cmd.args, typename(type));
220 argv_array_push(&cmd.args, "-p");
221 argv_array_push(&cmd.args, oid_to_hex(oid));
225 if (run_command(&cmd))
226 die("cat-file reported failure");
230 * Read a previously-exported (and possibly edited) object back from "filename",
231 * interpreting it as "type", and writing the result to the object database.
232 * The sha1 of the written object is returned via sha1.
234 static void import_object(struct object_id *oid, enum object_type type,
235 int raw, const char *filename)
239 fd = open(filename, O_RDONLY);
241 die_errno("unable to open %s for reading", filename);
243 if (!raw && type == OBJ_TREE) {
244 const char *argv[] = { "mktree", NULL };
245 struct child_process cmd = CHILD_PROCESS_INIT;
246 struct strbuf result = STRBUF_INIT;
253 if (start_command(&cmd))
254 die("unable to spawn mktree");
256 if (strbuf_read(&result, cmd.out, 41) < 0)
257 die_errno("unable to read from mktree");
260 if (finish_command(&cmd))
261 die("mktree reported failure");
262 if (get_oid_hex(result.buf, oid) < 0)
263 die("mktree did not return an object name");
265 strbuf_release(&result);
268 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
270 if (fstat(fd, &st) < 0)
271 die_errno("unable to fstat %s", filename);
272 if (index_fd(oid, fd, &st, type, NULL, flags) < 0)
273 die("unable to write object to database");
274 /* index_fd close()s fd for us */
278 * No need to close(fd) here; both run-command and index-fd
279 * will have done it for us.
283 static int edit_and_replace(const char *object_ref, int force, int raw)
285 char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
286 enum object_type type;
287 struct object_id old, new, prev;
288 struct strbuf ref = STRBUF_INIT;
290 if (get_oid(object_ref, &old) < 0)
291 die("Not a valid object name: '%s'", object_ref);
293 type = sha1_object_info(old.hash, NULL);
295 die("unable to get object type for %s", oid_to_hex(&old));
297 check_ref_valid(&old, &prev, &ref, force);
298 strbuf_release(&ref);
300 export_object(&old, type, raw, tmpfile);
301 if (launch_editor(tmpfile, NULL, NULL) < 0)
302 die("editing object file failed");
303 import_object(&new, type, raw, tmpfile);
307 if (!oidcmp(&old, &new))
308 return error("new object is the same as the old one: '%s'", oid_to_hex(&old));
310 return replace_object_oid(object_ref, &old, "replacement", &new, force);
313 static void replace_parents(struct strbuf *buf, int argc, const char **argv)
315 struct strbuf new_parents = STRBUF_INIT;
316 const char *parent_start, *parent_end;
319 /* find existing parents */
320 parent_start = buf->buf;
321 parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
322 parent_end = parent_start;
324 while (starts_with(parent_end, "parent "))
325 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
327 /* prepare new parents */
328 for (i = 0; i < argc; i++) {
329 struct object_id oid;
330 if (get_oid(argv[i], &oid) < 0)
331 die(_("Not a valid object name: '%s'"), argv[i]);
332 lookup_commit_or_die(&oid, argv[i]);
333 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
336 /* replace existing parents with new ones */
337 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
338 new_parents.buf, new_parents.len);
340 strbuf_release(&new_parents);
343 struct check_mergetag_data {
348 static void check_one_mergetag(struct commit *commit,
349 struct commit_extra_header *extra,
352 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
353 const char *ref = mergetag_data->argv[0];
354 struct object_id tag_oid;
358 hash_sha1_file(extra->value, extra->len, typename(OBJ_TAG), tag_oid.hash);
359 tag = lookup_tag(&tag_oid);
361 die(_("bad mergetag in commit '%s'"), ref);
362 if (parse_tag_buffer(tag, extra->value, extra->len))
363 die(_("malformed mergetag in commit '%s'"), ref);
365 /* iterate over new parents */
366 for (i = 1; i < mergetag_data->argc; i++) {
367 struct object_id oid;
368 if (get_oid(mergetag_data->argv[i], &oid) < 0)
369 die(_("Not a valid object name: '%s'"), mergetag_data->argv[i]);
370 if (!oidcmp(&tag->tagged->oid, &oid))
374 die(_("original commit '%s' contains mergetag '%s' that is discarded; "
375 "use --edit instead of --graft"), ref, oid_to_hex(&tag_oid));
378 static void check_mergetags(struct commit *commit, int argc, const char **argv)
380 struct check_mergetag_data mergetag_data;
382 mergetag_data.argc = argc;
383 mergetag_data.argv = argv;
384 for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
387 static int create_graft(int argc, const char **argv, int force)
389 struct object_id old, new;
390 const char *old_ref = argv[0];
391 struct commit *commit;
392 struct strbuf buf = STRBUF_INIT;
396 if (get_oid(old_ref, &old) < 0)
397 die(_("Not a valid object name: '%s'"), old_ref);
398 commit = lookup_commit_or_die(&old, old_ref);
400 buffer = get_commit_buffer(commit, &size);
401 strbuf_add(&buf, buffer, size);
402 unuse_commit_buffer(commit, buffer);
404 replace_parents(&buf, argc - 1, &argv[1]);
406 if (remove_signature(&buf)) {
407 warning(_("the original commit '%s' has a gpg signature."), old_ref);
408 warning(_("the signature will be removed in the replacement commit!"));
411 check_mergetags(commit, argc, argv);
413 if (write_sha1_file(buf.buf, buf.len, commit_type, new.hash))
414 die(_("could not write replacement commit for: '%s'"), old_ref);
416 strbuf_release(&buf);
418 if (!oidcmp(&old, &new))
419 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old));
421 return replace_object_oid(old_ref, &old, "replacement", &new, force);
424 int cmd_replace(int argc, const char **argv, const char *prefix)
428 const char *format = NULL;
430 MODE_UNSPECIFIED = 0,
436 } cmdmode = MODE_UNSPECIFIED;
437 struct option options[] = {
438 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
439 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
440 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
441 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
442 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
443 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
444 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
448 check_replace_refs = 0;
449 git_config(git_default_config, NULL);
451 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
454 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
456 if (format && cmdmode != MODE_LIST)
457 usage_msg_opt("--format cannot be used when not listing",
458 git_replace_usage, options);
461 cmdmode != MODE_REPLACE &&
462 cmdmode != MODE_EDIT &&
463 cmdmode != MODE_GRAFT)
464 usage_msg_opt("-f only makes sense when writing a replacement",
465 git_replace_usage, options);
467 if (raw && cmdmode != MODE_EDIT)
468 usage_msg_opt("--raw only makes sense with --edit",
469 git_replace_usage, options);
474 usage_msg_opt("-d needs at least one argument",
475 git_replace_usage, options);
476 return for_each_replace_name(argv, delete_replace_ref);
480 usage_msg_opt("bad number of arguments",
481 git_replace_usage, options);
482 return replace_object(argv[0], argv[1], force);
486 usage_msg_opt("-e needs exactly one argument",
487 git_replace_usage, options);
488 return edit_and_replace(argv[0], force, raw);
492 usage_msg_opt("-g needs at least one argument",
493 git_replace_usage, options);
494 return create_graft(argc, argv, force);
498 usage_msg_opt("only one pattern can be given with -l",
499 git_replace_usage, options);
500 return list_replace_refs(argv[0], format);
503 die("BUG: invalid cmdmode %d", (int)cmdmode);