Merge branch 'rj/add-i-leak-fix'
[git.git] / builtin / replace.c
blobda59600ad22fda16155a278a210478fb55d0d94e
1 /*
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.
9 */
11 #include "builtin.h"
12 #include "config.h"
13 #include "editor.h"
14 #include "environment.h"
15 #include "gettext.h"
16 #include "hex.h"
17 #include "refs.h"
18 #include "parse-options.h"
19 #include "path.h"
20 #include "run-command.h"
21 #include "object-file.h"
22 #include "object-name.h"
23 #include "object-store-ll.h"
24 #include "replace-object.h"
25 #include "repository.h"
26 #include "tag.h"
27 #include "wildmatch.h"
29 static const char * const git_replace_usage[] = {
30 N_("git replace [-f] <object> <replacement>"),
31 N_("git replace [-f] --edit <object>"),
32 N_("git replace [-f] --graft <commit> [<parent>...]"),
33 "git replace [-f] --convert-graft-file",
34 N_("git replace -d <object>..."),
35 N_("git replace [--format=<format>] [-l [<pattern>]]"),
36 NULL
39 enum replace_format {
40 REPLACE_FORMAT_SHORT,
41 REPLACE_FORMAT_MEDIUM,
42 REPLACE_FORMAT_LONG
45 struct show_data {
46 const char *pattern;
47 enum replace_format format;
50 static int show_reference(struct repository *r, const char *refname,
51 const struct object_id *oid,
52 int flag UNUSED, void *cb_data)
54 struct show_data *data = cb_data;
56 if (!wildmatch(data->pattern, refname, 0)) {
57 if (data->format == REPLACE_FORMAT_SHORT)
58 printf("%s\n", refname);
59 else if (data->format == REPLACE_FORMAT_MEDIUM)
60 printf("%s -> %s\n", refname, oid_to_hex(oid));
61 else { /* data->format == REPLACE_FORMAT_LONG */
62 struct object_id object;
63 enum object_type obj_type, repl_type;
65 if (repo_get_oid(r, refname, &object))
66 return error(_("failed to resolve '%s' as a valid ref"), refname);
68 obj_type = oid_object_info(r, &object, NULL);
69 repl_type = oid_object_info(r, oid, NULL);
71 printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
72 oid_to_hex(oid), type_name(repl_type));
76 return 0;
79 static int list_replace_refs(const char *pattern, const char *format)
81 struct show_data data;
83 if (!pattern)
84 pattern = "*";
85 data.pattern = pattern;
87 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
88 data.format = REPLACE_FORMAT_SHORT;
89 else if (!strcmp(format, "medium"))
90 data.format = REPLACE_FORMAT_MEDIUM;
91 else if (!strcmp(format, "long"))
92 data.format = REPLACE_FORMAT_LONG;
94 * Please update _git_replace() in git-completion.bash when
95 * you add new format
97 else
98 return error(_("invalid replace format '%s'\n"
99 "valid formats are 'short', 'medium' and 'long'"),
100 format);
102 for_each_replace_ref(the_repository, show_reference, (void *)&data);
104 return 0;
107 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
108 const struct object_id *oid);
110 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
112 const char **p, *full_hex;
113 struct strbuf ref = STRBUF_INIT;
114 size_t base_len;
115 int had_error = 0;
116 struct object_id oid;
117 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
119 strbuf_addstr(&ref, git_replace_ref_base);
120 base_len = ref.len;
122 for (p = argv; *p; p++) {
123 if (repo_get_oid(the_repository, *p, &oid)) {
124 error("failed to resolve '%s' as a valid ref", *p);
125 had_error = 1;
126 continue;
129 strbuf_setlen(&ref, base_len);
130 strbuf_addstr(&ref, oid_to_hex(&oid));
131 full_hex = ref.buf + base_len;
133 if (read_ref(ref.buf, &oid)) {
134 error(_("replace ref '%s' not found"), full_hex);
135 had_error = 1;
136 continue;
138 if (fn(full_hex, ref.buf, &oid))
139 had_error = 1;
141 strbuf_release(&ref);
142 return had_error;
145 static int delete_replace_ref(const char *name, const char *ref,
146 const struct object_id *oid)
148 if (delete_ref(NULL, ref, oid, 0))
149 return 1;
150 printf_ln(_("Deleted replace ref '%s'"), name);
151 return 0;
154 static int check_ref_valid(struct object_id *object,
155 struct object_id *prev,
156 struct strbuf *ref,
157 int force)
159 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
161 strbuf_reset(ref);
162 strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
163 if (check_refname_format(ref->buf, 0))
164 return error(_("'%s' is not a valid ref name"), ref->buf);
166 if (read_ref(ref->buf, prev))
167 oidclr(prev);
168 else if (!force)
169 return error(_("replace ref '%s' already exists"), ref->buf);
170 return 0;
173 static int replace_object_oid(const char *object_ref,
174 struct object_id *object,
175 const char *replace_ref,
176 struct object_id *repl,
177 int force)
179 struct object_id prev;
180 enum object_type obj_type, repl_type;
181 struct strbuf ref = STRBUF_INIT;
182 struct ref_transaction *transaction;
183 struct strbuf err = STRBUF_INIT;
184 int res = 0;
186 obj_type = oid_object_info(the_repository, object, NULL);
187 repl_type = oid_object_info(the_repository, repl, NULL);
188 if (!force && obj_type != repl_type)
189 return error(_("Objects must be of the same type.\n"
190 "'%s' points to a replaced object of type '%s'\n"
191 "while '%s' points to a replacement object of "
192 "type '%s'."),
193 object_ref, type_name(obj_type),
194 replace_ref, type_name(repl_type));
196 if (check_ref_valid(object, &prev, &ref, force)) {
197 strbuf_release(&ref);
198 return -1;
201 transaction = ref_transaction_begin(&err);
202 if (!transaction ||
203 ref_transaction_update(transaction, ref.buf, repl, &prev,
204 0, NULL, &err) ||
205 ref_transaction_commit(transaction, &err))
206 res = error("%s", err.buf);
208 ref_transaction_free(transaction);
209 strbuf_release(&ref);
210 return res;
213 static int replace_object(const char *object_ref, const char *replace_ref, int force)
215 struct object_id object, repl;
217 if (repo_get_oid(the_repository, object_ref, &object))
218 return error(_("failed to resolve '%s' as a valid ref"),
219 object_ref);
220 if (repo_get_oid(the_repository, replace_ref, &repl))
221 return error(_("failed to resolve '%s' as a valid ref"),
222 replace_ref);
224 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
228 * Write the contents of the object named by "sha1" to the file "filename".
229 * If "raw" is true, then the object's raw contents are printed according to
230 * "type". Otherwise, we pretty-print the contents for human editing.
232 static int export_object(const struct object_id *oid, enum object_type type,
233 int raw, const char *filename)
235 struct child_process cmd = CHILD_PROCESS_INIT;
236 int fd;
238 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
239 if (fd < 0)
240 return error_errno(_("unable to open %s for writing"), filename);
242 strvec_push(&cmd.args, "--no-replace-objects");
243 strvec_push(&cmd.args, "cat-file");
244 if (raw)
245 strvec_push(&cmd.args, type_name(type));
246 else
247 strvec_push(&cmd.args, "-p");
248 strvec_push(&cmd.args, oid_to_hex(oid));
249 cmd.git_cmd = 1;
250 cmd.out = fd;
252 if (run_command(&cmd))
253 return error(_("cat-file reported failure"));
254 return 0;
258 * Read a previously-exported (and possibly edited) object back from "filename",
259 * interpreting it as "type", and writing the result to the object database.
260 * The sha1 of the written object is returned via sha1.
262 static int import_object(struct object_id *oid, enum object_type type,
263 int raw, const char *filename)
265 int fd;
267 fd = open(filename, O_RDONLY);
268 if (fd < 0)
269 return error_errno(_("unable to open %s for reading"), filename);
271 if (!raw && type == OBJ_TREE) {
272 struct child_process cmd = CHILD_PROCESS_INIT;
273 struct strbuf result = STRBUF_INIT;
275 strvec_push(&cmd.args, "mktree");
276 cmd.git_cmd = 1;
277 cmd.in = fd;
278 cmd.out = -1;
280 if (start_command(&cmd)) {
281 close(fd);
282 return error(_("unable to spawn mktree"));
285 if (strbuf_read(&result, cmd.out, the_hash_algo->hexsz + 1) < 0) {
286 error_errno(_("unable to read from mktree"));
287 close(fd);
288 close(cmd.out);
289 return -1;
291 close(cmd.out);
293 if (finish_command(&cmd)) {
294 strbuf_release(&result);
295 return error(_("mktree reported failure"));
297 if (get_oid_hex(result.buf, oid) < 0) {
298 strbuf_release(&result);
299 return error(_("mktree did not return an object name"));
302 strbuf_release(&result);
303 } else {
304 struct stat st;
305 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
307 if (fstat(fd, &st) < 0) {
308 error_errno(_("unable to fstat %s"), filename);
309 close(fd);
310 return -1;
312 if (index_fd(the_repository->index, oid, fd, &st, type, NULL, flags) < 0)
313 return error(_("unable to write object to database"));
314 /* index_fd close()s fd for us */
318 * No need to close(fd) here; both run-command and index-fd
319 * will have done it for us.
321 return 0;
324 static int edit_and_replace(const char *object_ref, int force, int raw)
326 char *tmpfile;
327 enum object_type type;
328 struct object_id old_oid, new_oid, prev;
329 struct strbuf ref = STRBUF_INIT;
331 if (repo_get_oid(the_repository, object_ref, &old_oid) < 0)
332 return error(_("not a valid object name: '%s'"), object_ref);
334 type = oid_object_info(the_repository, &old_oid, NULL);
335 if (type < 0)
336 return error(_("unable to get object type for %s"),
337 oid_to_hex(&old_oid));
339 if (check_ref_valid(&old_oid, &prev, &ref, force)) {
340 strbuf_release(&ref);
341 return -1;
343 strbuf_release(&ref);
345 tmpfile = git_pathdup("REPLACE_EDITOBJ");
346 if (export_object(&old_oid, type, raw, tmpfile)) {
347 free(tmpfile);
348 return -1;
350 if (launch_editor(tmpfile, NULL, NULL) < 0) {
351 free(tmpfile);
352 return error(_("editing object file failed"));
354 if (import_object(&new_oid, type, raw, tmpfile)) {
355 free(tmpfile);
356 return -1;
358 free(tmpfile);
360 if (oideq(&old_oid, &new_oid))
361 return error(_("new object is the same as the old one: '%s'"), oid_to_hex(&old_oid));
363 return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
366 static int replace_parents(struct strbuf *buf, int argc, const char **argv)
368 struct strbuf new_parents = STRBUF_INIT;
369 const char *parent_start, *parent_end;
370 int i;
371 const unsigned hexsz = the_hash_algo->hexsz;
373 /* find existing parents */
374 parent_start = buf->buf;
375 parent_start += hexsz + 6; /* "tree " + "hex sha1" + "\n" */
376 parent_end = parent_start;
378 while (starts_with(parent_end, "parent "))
379 parent_end += hexsz + 8; /* "parent " + "hex sha1" + "\n" */
381 /* prepare new parents */
382 for (i = 0; i < argc; i++) {
383 struct object_id oid;
384 struct commit *commit;
386 if (repo_get_oid(the_repository, argv[i], &oid) < 0) {
387 strbuf_release(&new_parents);
388 return error(_("not a valid object name: '%s'"),
389 argv[i]);
391 commit = lookup_commit_reference(the_repository, &oid);
392 if (!commit) {
393 strbuf_release(&new_parents);
394 return error(_("could not parse %s as a commit"), argv[i]);
396 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&commit->object.oid));
399 /* replace existing parents with new ones */
400 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
401 new_parents.buf, new_parents.len);
403 strbuf_release(&new_parents);
404 return 0;
407 struct check_mergetag_data {
408 int argc;
409 const char **argv;
412 static int check_one_mergetag(struct commit *commit UNUSED,
413 struct commit_extra_header *extra,
414 void *data)
416 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
417 const char *ref = mergetag_data->argv[0];
418 struct object_id tag_oid;
419 struct tag *tag;
420 int i;
422 hash_object_file(the_hash_algo, extra->value, extra->len,
423 OBJ_TAG, &tag_oid);
424 tag = lookup_tag(the_repository, &tag_oid);
425 if (!tag)
426 return error(_("bad mergetag in commit '%s'"), ref);
427 if (parse_tag_buffer(the_repository, tag, extra->value, extra->len))
428 return error(_("malformed mergetag in commit '%s'"), ref);
430 /* iterate over new parents */
431 for (i = 1; i < mergetag_data->argc; i++) {
432 struct object_id oid;
433 if (repo_get_oid(the_repository, mergetag_data->argv[i], &oid) < 0)
434 return error(_("not a valid object name: '%s'"),
435 mergetag_data->argv[i]);
436 if (oideq(get_tagged_oid(tag), &oid))
437 return 0; /* found */
440 return error(_("original commit '%s' contains mergetag '%s' that is "
441 "discarded; use --edit instead of --graft"), ref,
442 oid_to_hex(&tag_oid));
445 static int check_mergetags(struct commit *commit, int argc, const char **argv)
447 struct check_mergetag_data mergetag_data;
449 mergetag_data.argc = argc;
450 mergetag_data.argv = argv;
451 return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
454 static int create_graft(int argc, const char **argv, int force, int gentle)
456 struct object_id old_oid, new_oid;
457 const char *old_ref = argv[0];
458 struct commit *commit;
459 struct strbuf buf = STRBUF_INIT;
460 const char *buffer;
461 unsigned long size;
463 if (repo_get_oid(the_repository, old_ref, &old_oid) < 0)
464 return error(_("not a valid object name: '%s'"), old_ref);
465 commit = lookup_commit_reference(the_repository, &old_oid);
466 if (!commit)
467 return error(_("could not parse %s"), old_ref);
469 buffer = repo_get_commit_buffer(the_repository, commit, &size);
470 strbuf_add(&buf, buffer, size);
471 repo_unuse_commit_buffer(the_repository, commit, buffer);
473 if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
474 strbuf_release(&buf);
475 return -1;
478 if (remove_signature(&buf)) {
479 warning(_("the original commit '%s' has a gpg signature"), old_ref);
480 warning(_("the signature will be removed in the replacement commit!"));
483 if (check_mergetags(commit, argc, argv)) {
484 strbuf_release(&buf);
485 return -1;
488 if (write_object_file(buf.buf, buf.len, OBJ_COMMIT, &new_oid)) {
489 strbuf_release(&buf);
490 return error(_("could not write replacement commit for: '%s'"),
491 old_ref);
494 strbuf_release(&buf);
496 if (oideq(&commit->object.oid, &new_oid)) {
497 if (gentle) {
498 warning(_("graft for '%s' unnecessary"),
499 oid_to_hex(&commit->object.oid));
500 return 0;
502 return error(_("new commit is the same as the old one: '%s'"),
503 oid_to_hex(&commit->object.oid));
506 return replace_object_oid(old_ref, &commit->object.oid,
507 "replacement", &new_oid, force);
510 static int convert_graft_file(int force)
512 const char *graft_file = get_graft_file(the_repository);
513 FILE *fp = fopen_or_warn(graft_file, "r");
514 struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
515 struct strvec args = STRVEC_INIT;
517 if (!fp)
518 return -1;
520 no_graft_file_deprecated_advice = 1;
521 while (strbuf_getline(&buf, fp) != EOF) {
522 if (*buf.buf == '#')
523 continue;
525 strvec_split(&args, buf.buf);
526 if (args.nr && create_graft(args.nr, args.v, force, 1))
527 strbuf_addf(&err, "\n\t%s", buf.buf);
528 strvec_clear(&args);
530 fclose(fp);
532 strbuf_release(&buf);
534 if (!err.len)
535 return unlink_or_warn(graft_file);
537 warning(_("could not convert the following graft(s):\n%s"), err.buf);
538 strbuf_release(&err);
540 return -1;
543 int cmd_replace(int argc, const char **argv, const char *prefix)
545 int force = 0;
546 int raw = 0;
547 const char *format = NULL;
548 enum {
549 MODE_UNSPECIFIED = 0,
550 MODE_LIST,
551 MODE_DELETE,
552 MODE_EDIT,
553 MODE_GRAFT,
554 MODE_CONVERT_GRAFT_FILE,
555 MODE_REPLACE
556 } cmdmode = MODE_UNSPECIFIED;
557 struct option options[] = {
558 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
559 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
560 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
561 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
562 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
563 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
564 PARSE_OPT_NOCOMPLETE),
565 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
566 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
567 OPT_END()
570 disable_replace_refs();
571 git_config(git_default_config, NULL);
573 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
575 if (!cmdmode)
576 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
578 if (format && cmdmode != MODE_LIST)
579 usage_msg_opt(_("--format cannot be used when not listing"),
580 git_replace_usage, options);
582 if (force &&
583 cmdmode != MODE_REPLACE &&
584 cmdmode != MODE_EDIT &&
585 cmdmode != MODE_GRAFT &&
586 cmdmode != MODE_CONVERT_GRAFT_FILE)
587 usage_msg_opt(_("-f only makes sense when writing a replacement"),
588 git_replace_usage, options);
590 if (raw && cmdmode != MODE_EDIT)
591 usage_msg_opt(_("--raw only makes sense with --edit"),
592 git_replace_usage, options);
594 switch (cmdmode) {
595 case MODE_DELETE:
596 if (argc < 1)
597 usage_msg_opt(_("-d needs at least one argument"),
598 git_replace_usage, options);
599 return for_each_replace_name(argv, delete_replace_ref);
601 case MODE_REPLACE:
602 if (argc != 2)
603 usage_msg_opt(_("bad number of arguments"),
604 git_replace_usage, options);
605 return replace_object(argv[0], argv[1], force);
607 case MODE_EDIT:
608 if (argc != 1)
609 usage_msg_opt(_("-e needs exactly one argument"),
610 git_replace_usage, options);
611 return edit_and_replace(argv[0], force, raw);
613 case MODE_GRAFT:
614 if (argc < 1)
615 usage_msg_opt(_("-g needs at least one argument"),
616 git_replace_usage, options);
617 return create_graft(argc, argv, force, 0);
619 case MODE_CONVERT_GRAFT_FILE:
620 if (argc != 0)
621 usage_msg_opt(_("--convert-graft-file takes no argument"),
622 git_replace_usage, options);
623 return !!convert_graft_file(force);
625 case MODE_LIST:
626 if (argc > 1)
627 usage_msg_opt(_("only one pattern can be given with -l"),
628 git_replace_usage, options);
629 return list_replace_refs(argv[0], format);
631 default:
632 BUG("invalid cmdmode %d", (int)cmdmode);