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))
126 static int delete_replace_ref(const char *name, const char *ref,
127 const struct object_id *oid)
129 if (delete_ref(NULL, ref, oid->hash, 0))
131 printf("Deleted replace ref '%s'\n", name);
135 static void check_ref_valid(struct object_id *object,
136 struct object_id *prev,
141 strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
142 if (check_refname_format(ref->buf, 0))
143 die("'%s' is not a valid ref name.", ref->buf);
145 if (read_ref(ref->buf, prev->hash))
148 die("replace ref '%s' already exists", ref->buf);
151 static int replace_object_oid(const char *object_ref,
152 struct object_id *object,
153 const char *replace_ref,
154 struct object_id *repl,
157 struct object_id prev;
158 enum object_type obj_type, repl_type;
159 struct strbuf ref = STRBUF_INIT;
160 struct ref_transaction *transaction;
161 struct strbuf err = STRBUF_INIT;
163 obj_type = sha1_object_info(object->hash, NULL);
164 repl_type = sha1_object_info(repl->hash, NULL);
165 if (!force && obj_type != repl_type)
166 die("Objects must be of the same type.\n"
167 "'%s' points to a replaced object of type '%s'\n"
168 "while '%s' points to a replacement object of type '%s'.",
169 object_ref, typename(obj_type),
170 replace_ref, typename(repl_type));
172 check_ref_valid(object, &prev, &ref, force);
174 transaction = ref_transaction_begin(&err);
176 ref_transaction_update(transaction, ref.buf, repl->hash, prev.hash,
178 ref_transaction_commit(transaction, &err))
181 ref_transaction_free(transaction);
182 strbuf_release(&ref);
186 static int replace_object(const char *object_ref, const char *replace_ref, int force)
188 struct object_id object, repl;
190 if (get_oid(object_ref, &object))
191 die("Failed to resolve '%s' as a valid ref.", object_ref);
192 if (get_oid(replace_ref, &repl))
193 die("Failed to resolve '%s' as a valid ref.", replace_ref);
195 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
199 * Write the contents of the object named by "sha1" to the file "filename".
200 * If "raw" is true, then the object's raw contents are printed according to
201 * "type". Otherwise, we pretty-print the contents for human editing.
203 static void export_object(const struct object_id *oid, enum object_type type,
204 int raw, const char *filename)
206 struct child_process cmd = CHILD_PROCESS_INIT;
209 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
211 die_errno("unable to open %s for writing", filename);
213 argv_array_push(&cmd.args, "--no-replace-objects");
214 argv_array_push(&cmd.args, "cat-file");
216 argv_array_push(&cmd.args, typename(type));
218 argv_array_push(&cmd.args, "-p");
219 argv_array_push(&cmd.args, oid_to_hex(oid));
223 if (run_command(&cmd))
224 die("cat-file reported failure");
228 * Read a previously-exported (and possibly edited) object back from "filename",
229 * interpreting it as "type", and writing the result to the object database.
230 * The sha1 of the written object is returned via sha1.
232 static void import_object(struct object_id *oid, enum object_type type,
233 int raw, const char *filename)
237 fd = open(filename, O_RDONLY);
239 die_errno("unable to open %s for reading", filename);
241 if (!raw && type == OBJ_TREE) {
242 const char *argv[] = { "mktree", NULL };
243 struct child_process cmd = CHILD_PROCESS_INIT;
244 struct strbuf result = STRBUF_INIT;
251 if (start_command(&cmd))
252 die("unable to spawn mktree");
254 if (strbuf_read(&result, cmd.out, 41) < 0)
255 die_errno("unable to read from mktree");
258 if (finish_command(&cmd))
259 die("mktree reported failure");
260 if (get_oid_hex(result.buf, oid) < 0)
261 die("mktree did not return an object name");
263 strbuf_release(&result);
266 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
268 if (fstat(fd, &st) < 0)
269 die_errno("unable to fstat %s", filename);
270 if (index_fd(oid->hash, fd, &st, type, NULL, flags) < 0)
271 die("unable to write object to database");
272 /* index_fd close()s fd for us */
276 * No need to close(fd) here; both run-command and index-fd
277 * will have done it for us.
281 static int edit_and_replace(const char *object_ref, int force, int raw)
283 char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
284 enum object_type type;
285 struct object_id old, new, prev;
286 struct strbuf ref = STRBUF_INIT;
288 if (get_oid(object_ref, &old) < 0)
289 die("Not a valid object name: '%s'", object_ref);
291 type = sha1_object_info(old.hash, NULL);
293 die("unable to get object type for %s", oid_to_hex(&old));
295 check_ref_valid(&old, &prev, &ref, force);
296 strbuf_release(&ref);
298 export_object(&old, type, raw, tmpfile);
299 if (launch_editor(tmpfile, NULL, NULL) < 0)
300 die("editing object file failed");
301 import_object(&new, type, raw, tmpfile);
305 if (!oidcmp(&old, &new))
306 return error("new object is the same as the old one: '%s'", oid_to_hex(&old));
308 return replace_object_oid(object_ref, &old, "replacement", &new, force);
311 static void replace_parents(struct strbuf *buf, int argc, const char **argv)
313 struct strbuf new_parents = STRBUF_INIT;
314 const char *parent_start, *parent_end;
317 /* find existing parents */
318 parent_start = buf->buf;
319 parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
320 parent_end = parent_start;
322 while (starts_with(parent_end, "parent "))
323 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
325 /* prepare new parents */
326 for (i = 0; i < argc; i++) {
327 struct object_id oid;
328 if (get_oid(argv[i], &oid) < 0)
329 die(_("Not a valid object name: '%s'"), argv[i]);
330 lookup_commit_or_die(oid.hash, argv[i]);
331 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
334 /* replace existing parents with new ones */
335 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
336 new_parents.buf, new_parents.len);
338 strbuf_release(&new_parents);
341 struct check_mergetag_data {
346 static void check_one_mergetag(struct commit *commit,
347 struct commit_extra_header *extra,
350 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
351 const char *ref = mergetag_data->argv[0];
352 struct object_id tag_oid;
356 hash_sha1_file(extra->value, extra->len, typename(OBJ_TAG), tag_oid.hash);
357 tag = lookup_tag(tag_oid.hash);
359 die(_("bad mergetag in commit '%s'"), ref);
360 if (parse_tag_buffer(tag, extra->value, extra->len))
361 die(_("malformed mergetag in commit '%s'"), ref);
363 /* iterate over new parents */
364 for (i = 1; i < mergetag_data->argc; i++) {
365 struct object_id oid;
366 if (get_sha1(mergetag_data->argv[i], oid.hash) < 0)
367 die(_("Not a valid object name: '%s'"), mergetag_data->argv[i]);
368 if (!oidcmp(&tag->tagged->oid, &oid))
372 die(_("original commit '%s' contains mergetag '%s' that is discarded; "
373 "use --edit instead of --graft"), ref, oid_to_hex(&tag_oid));
376 static void check_mergetags(struct commit *commit, int argc, const char **argv)
378 struct check_mergetag_data mergetag_data;
380 mergetag_data.argc = argc;
381 mergetag_data.argv = argv;
382 for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
385 static int create_graft(int argc, const char **argv, int force)
387 struct object_id old, new;
388 const char *old_ref = argv[0];
389 struct commit *commit;
390 struct strbuf buf = STRBUF_INIT;
394 if (get_oid(old_ref, &old) < 0)
395 die(_("Not a valid object name: '%s'"), old_ref);
396 commit = lookup_commit_or_die(old.hash, old_ref);
398 buffer = get_commit_buffer(commit, &size);
399 strbuf_add(&buf, buffer, size);
400 unuse_commit_buffer(commit, buffer);
402 replace_parents(&buf, argc - 1, &argv[1]);
404 if (remove_signature(&buf)) {
405 warning(_("the original commit '%s' has a gpg signature."), old_ref);
406 warning(_("the signature will be removed in the replacement commit!"));
409 check_mergetags(commit, argc, argv);
411 if (write_sha1_file(buf.buf, buf.len, commit_type, new.hash))
412 die(_("could not write replacement commit for: '%s'"), old_ref);
414 strbuf_release(&buf);
416 if (!oidcmp(&old, &new))
417 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old));
419 return replace_object_oid(old_ref, &old, "replacement", &new, force);
422 int cmd_replace(int argc, const char **argv, const char *prefix)
426 const char *format = NULL;
428 MODE_UNSPECIFIED = 0,
434 } cmdmode = MODE_UNSPECIFIED;
435 struct option options[] = {
436 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
437 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
438 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
439 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
440 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
441 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
442 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
446 check_replace_refs = 0;
447 git_config(git_default_config, NULL);
449 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
452 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
454 if (format && cmdmode != MODE_LIST)
455 usage_msg_opt("--format cannot be used when not listing",
456 git_replace_usage, options);
459 cmdmode != MODE_REPLACE &&
460 cmdmode != MODE_EDIT &&
461 cmdmode != MODE_GRAFT)
462 usage_msg_opt("-f only makes sense when writing a replacement",
463 git_replace_usage, options);
465 if (raw && cmdmode != MODE_EDIT)
466 usage_msg_opt("--raw only makes sense with --edit",
467 git_replace_usage, options);
472 usage_msg_opt("-d needs at least one argument",
473 git_replace_usage, options);
474 return for_each_replace_name(argv, delete_replace_ref);
478 usage_msg_opt("bad number of arguments",
479 git_replace_usage, options);
480 return replace_object(argv[0], argv[1], force);
484 usage_msg_opt("-e needs exactly one argument",
485 git_replace_usage, options);
486 return edit_and_replace(argv[0], force, raw);
490 usage_msg_opt("-g needs at least one argument",
491 git_replace_usage, options);
492 return create_graft(argc, argv, force);
496 usage_msg_opt("only one pattern can be given with -l",
497 git_replace_usage, options);
498 return list_replace_refs(argv[0], format);
501 die("BUG: invalid cmdmode %d", (int)cmdmode);