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.
14 #include "parse-options.h"
15 #include "run-command.h"
18 static const char * const git_replace_usage[] = {
19 N_("git replace [-f] <object> <replacement>"),
20 N_("git replace [-f] --edit <object>"),
21 N_("git replace [-f] --graft <commit> [<parent>...]"),
22 N_("git replace -d <object>..."),
23 N_("git replace [--format=<format>] [-l [<pattern>]]"),
29 REPLACE_FORMAT_MEDIUM,
35 enum replace_format format;
38 static int show_reference(const char *refname, const struct object_id *oid,
39 int flag, void *cb_data)
41 struct show_data *data = cb_data;
43 if (!wildmatch(data->pattern, refname, 0, NULL)) {
44 if (data->format == REPLACE_FORMAT_SHORT)
45 printf("%s\n", refname);
46 else if (data->format == REPLACE_FORMAT_MEDIUM)
47 printf("%s -> %s\n", refname, oid_to_hex(oid));
48 else { /* data->format == REPLACE_FORMAT_LONG */
49 struct object_id object;
50 enum object_type obj_type, repl_type;
52 if (get_sha1(refname, object.hash))
53 return error("Failed to resolve '%s' as a valid ref.", refname);
55 obj_type = sha1_object_info(object.hash, NULL);
56 repl_type = sha1_object_info(oid->hash, NULL);
58 printf("%s (%s) -> %s (%s)\n", refname, typename(obj_type),
59 oid_to_hex(oid), typename(repl_type));
66 static int list_replace_refs(const char *pattern, const char *format)
68 struct show_data data;
72 data.pattern = pattern;
74 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
75 data.format = REPLACE_FORMAT_SHORT;
76 else if (!strcmp(format, "medium"))
77 data.format = REPLACE_FORMAT_MEDIUM;
78 else if (!strcmp(format, "long"))
79 data.format = REPLACE_FORMAT_LONG;
81 die("invalid replace format '%s'\n"
82 "valid formats are 'short', 'medium' and 'long'\n",
85 for_each_replace_ref(show_reference, (void *)&data);
90 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
91 const struct object_id *oid);
93 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
95 const char **p, *full_hex;
96 struct strbuf ref = STRBUF_INIT;
101 strbuf_addstr(&ref, git_replace_ref_base);
104 for (p = argv; *p; p++) {
105 if (get_oid(*p, &oid)) {
106 error("Failed to resolve '%s' as a valid ref.", *p);
111 strbuf_setlen(&ref, base_len);
112 strbuf_addstr(&ref, oid_to_hex(&oid));
113 full_hex = ref.buf + base_len;
115 if (read_ref(ref.buf, oid.hash)) {
116 error("replace ref '%s' not found.", full_hex);
120 if (fn(full_hex, ref.buf, &oid))
123 strbuf_release(&ref);
127 static int delete_replace_ref(const char *name, const char *ref,
128 const struct object_id *oid)
130 if (delete_ref(NULL, ref, oid->hash, 0))
132 printf("Deleted replace ref '%s'\n", name);
136 static void check_ref_valid(struct object_id *object,
137 struct object_id *prev,
142 strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
143 if (check_refname_format(ref->buf, 0))
144 die("'%s' is not a valid ref name.", ref->buf);
146 if (read_ref(ref->buf, prev->hash))
149 die("replace ref '%s' already exists", ref->buf);
152 static int replace_object_oid(const char *object_ref,
153 struct object_id *object,
154 const char *replace_ref,
155 struct object_id *repl,
158 struct object_id prev;
159 enum object_type obj_type, repl_type;
160 struct strbuf ref = STRBUF_INIT;
161 struct ref_transaction *transaction;
162 struct strbuf err = STRBUF_INIT;
164 obj_type = sha1_object_info(object->hash, NULL);
165 repl_type = sha1_object_info(repl->hash, NULL);
166 if (!force && obj_type != repl_type)
167 die("Objects must be of the same type.\n"
168 "'%s' points to a replaced object of type '%s'\n"
169 "while '%s' points to a replacement object of type '%s'.",
170 object_ref, typename(obj_type),
171 replace_ref, typename(repl_type));
173 check_ref_valid(object, &prev, &ref, force);
175 transaction = ref_transaction_begin(&err);
177 ref_transaction_update(transaction, ref.buf, repl->hash, prev.hash,
179 ref_transaction_commit(transaction, &err))
182 ref_transaction_free(transaction);
183 strbuf_release(&ref);
187 static int replace_object(const char *object_ref, const char *replace_ref, int force)
189 struct object_id object, repl;
191 if (get_oid(object_ref, &object))
192 die("Failed to resolve '%s' as a valid ref.", object_ref);
193 if (get_oid(replace_ref, &repl))
194 die("Failed to resolve '%s' as a valid ref.", replace_ref);
196 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
200 * Write the contents of the object named by "sha1" to the file "filename".
201 * If "raw" is true, then the object's raw contents are printed according to
202 * "type". Otherwise, we pretty-print the contents for human editing.
204 static void export_object(const struct object_id *oid, enum object_type type,
205 int raw, const char *filename)
207 struct child_process cmd = CHILD_PROCESS_INIT;
210 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
212 die_errno("unable to open %s for writing", filename);
214 argv_array_push(&cmd.args, "--no-replace-objects");
215 argv_array_push(&cmd.args, "cat-file");
217 argv_array_push(&cmd.args, typename(type));
219 argv_array_push(&cmd.args, "-p");
220 argv_array_push(&cmd.args, oid_to_hex(oid));
224 if (run_command(&cmd))
225 die("cat-file reported failure");
229 * Read a previously-exported (and possibly edited) object back from "filename",
230 * interpreting it as "type", and writing the result to the object database.
231 * The sha1 of the written object is returned via sha1.
233 static void import_object(struct object_id *oid, enum object_type type,
234 int raw, const char *filename)
238 fd = open(filename, O_RDONLY);
240 die_errno("unable to open %s for reading", filename);
242 if (!raw && type == OBJ_TREE) {
243 const char *argv[] = { "mktree", NULL };
244 struct child_process cmd = CHILD_PROCESS_INIT;
245 struct strbuf result = STRBUF_INIT;
252 if (start_command(&cmd))
253 die("unable to spawn mktree");
255 if (strbuf_read(&result, cmd.out, 41) < 0)
256 die_errno("unable to read from mktree");
259 if (finish_command(&cmd))
260 die("mktree reported failure");
261 if (get_oid_hex(result.buf, oid) < 0)
262 die("mktree did not return an object name");
264 strbuf_release(&result);
267 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
269 if (fstat(fd, &st) < 0)
270 die_errno("unable to fstat %s", filename);
271 if (index_fd(oid->hash, fd, &st, type, NULL, flags) < 0)
272 die("unable to write object to database");
273 /* index_fd close()s fd for us */
277 * No need to close(fd) here; both run-command and index-fd
278 * will have done it for us.
282 static int edit_and_replace(const char *object_ref, int force, int raw)
284 char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
285 enum object_type type;
286 struct object_id old, new, prev;
287 struct strbuf ref = STRBUF_INIT;
289 if (get_oid(object_ref, &old) < 0)
290 die("Not a valid object name: '%s'", object_ref);
292 type = sha1_object_info(old.hash, NULL);
294 die("unable to get object type for %s", oid_to_hex(&old));
296 check_ref_valid(&old, &prev, &ref, force);
297 strbuf_release(&ref);
299 export_object(&old, type, raw, tmpfile);
300 if (launch_editor(tmpfile, NULL, NULL) < 0)
301 die("editing object file failed");
302 import_object(&new, type, raw, tmpfile);
306 if (!oidcmp(&old, &new))
307 return error("new object is the same as the old one: '%s'", oid_to_hex(&old));
309 return replace_object_oid(object_ref, &old, "replacement", &new, force);
312 static void replace_parents(struct strbuf *buf, int argc, const char **argv)
314 struct strbuf new_parents = STRBUF_INIT;
315 const char *parent_start, *parent_end;
318 /* find existing parents */
319 parent_start = buf->buf;
320 parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
321 parent_end = parent_start;
323 while (starts_with(parent_end, "parent "))
324 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
326 /* prepare new parents */
327 for (i = 0; i < argc; i++) {
328 struct object_id oid;
329 if (get_oid(argv[i], &oid) < 0)
330 die(_("Not a valid object name: '%s'"), argv[i]);
331 lookup_commit_or_die(oid.hash, argv[i]);
332 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
335 /* replace existing parents with new ones */
336 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
337 new_parents.buf, new_parents.len);
339 strbuf_release(&new_parents);
342 struct check_mergetag_data {
347 static void check_one_mergetag(struct commit *commit,
348 struct commit_extra_header *extra,
351 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
352 const char *ref = mergetag_data->argv[0];
353 struct object_id tag_oid;
357 hash_sha1_file(extra->value, extra->len, typename(OBJ_TAG), tag_oid.hash);
358 tag = lookup_tag(tag_oid.hash);
360 die(_("bad mergetag in commit '%s'"), ref);
361 if (parse_tag_buffer(tag, extra->value, extra->len))
362 die(_("malformed mergetag in commit '%s'"), ref);
364 /* iterate over new parents */
365 for (i = 1; i < mergetag_data->argc; i++) {
366 struct object_id oid;
367 if (get_sha1(mergetag_data->argv[i], oid.hash) < 0)
368 die(_("Not a valid object name: '%s'"), mergetag_data->argv[i]);
369 if (!oidcmp(&tag->tagged->oid, &oid))
373 die(_("original commit '%s' contains mergetag '%s' that is discarded; "
374 "use --edit instead of --graft"), ref, oid_to_hex(&tag_oid));
377 static void check_mergetags(struct commit *commit, int argc, const char **argv)
379 struct check_mergetag_data mergetag_data;
381 mergetag_data.argc = argc;
382 mergetag_data.argv = argv;
383 for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
386 static int create_graft(int argc, const char **argv, int force)
388 struct object_id old, new;
389 const char *old_ref = argv[0];
390 struct commit *commit;
391 struct strbuf buf = STRBUF_INIT;
395 if (get_oid(old_ref, &old) < 0)
396 die(_("Not a valid object name: '%s'"), old_ref);
397 commit = lookup_commit_or_die(old.hash, old_ref);
399 buffer = get_commit_buffer(commit, &size);
400 strbuf_add(&buf, buffer, size);
401 unuse_commit_buffer(commit, buffer);
403 replace_parents(&buf, argc - 1, &argv[1]);
405 if (remove_signature(&buf)) {
406 warning(_("the original commit '%s' has a gpg signature."), old_ref);
407 warning(_("the signature will be removed in the replacement commit!"));
410 check_mergetags(commit, argc, argv);
412 if (write_sha1_file(buf.buf, buf.len, commit_type, new.hash))
413 die(_("could not write replacement commit for: '%s'"), old_ref);
415 strbuf_release(&buf);
417 if (!oidcmp(&old, &new))
418 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old));
420 return replace_object_oid(old_ref, &old, "replacement", &new, force);
423 int cmd_replace(int argc, const char **argv, const char *prefix)
427 const char *format = NULL;
429 MODE_UNSPECIFIED = 0,
435 } cmdmode = MODE_UNSPECIFIED;
436 struct option options[] = {
437 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
438 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
439 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
440 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
441 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
442 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
443 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
447 check_replace_refs = 0;
448 git_config(git_default_config, NULL);
450 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
453 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
455 if (format && cmdmode != MODE_LIST)
456 usage_msg_opt("--format cannot be used when not listing",
457 git_replace_usage, options);
460 cmdmode != MODE_REPLACE &&
461 cmdmode != MODE_EDIT &&
462 cmdmode != MODE_GRAFT)
463 usage_msg_opt("-f only makes sense when writing a replacement",
464 git_replace_usage, options);
466 if (raw && cmdmode != MODE_EDIT)
467 usage_msg_opt("--raw only makes sense with --edit",
468 git_replace_usage, options);
473 usage_msg_opt("-d needs at least one argument",
474 git_replace_usage, options);
475 return for_each_replace_name(argv, delete_replace_ref);
479 usage_msg_opt("bad number of arguments",
480 git_replace_usage, options);
481 return replace_object(argv[0], argv[1], force);
485 usage_msg_opt("-e needs exactly one argument",
486 git_replace_usage, options);
487 return edit_and_replace(argv[0], force, raw);
491 usage_msg_opt("-g needs at least one argument",
492 git_replace_usage, options);
493 return create_graft(argc, argv, force);
497 usage_msg_opt("only one pattern can be given with -l",
498 git_replace_usage, options);
499 return list_replace_refs(argv[0], format);
502 die("BUG: invalid cmdmode %d", (int)cmdmode);