commit-graph: reduce initial oid allocation
[git/gitster.git] / builtin / replace.c
blob4f05791f3e895f78ba511dd6571bd09abab9269c
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 "cache.h"
12 #include "config.h"
13 #include "builtin.h"
14 #include "refs.h"
15 #include "parse-options.h"
16 #include "run-command.h"
17 #include "object-store.h"
18 #include "repository.h"
19 #include "tag.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>]]"),
28 NULL
31 enum replace_format {
32 REPLACE_FORMAT_SHORT,
33 REPLACE_FORMAT_MEDIUM,
34 REPLACE_FORMAT_LONG
37 struct show_data {
38 const char *pattern;
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,
60 NULL);
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));
68 return 0;
71 static int list_replace_refs(const char *pattern, const char *format)
73 struct show_data data;
75 if (pattern == NULL)
76 pattern = "*";
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;
85 else
86 return error(_("invalid replace format '%s'\n"
87 "valid formats are 'short', 'medium' and 'long'"),
88 format);
90 for_each_replace_ref(the_repository, show_reference, (void *)&data);
92 return 0;
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;
102 size_t base_len;
103 int had_error = 0;
104 struct object_id oid;
106 strbuf_addstr(&ref, git_replace_ref_base);
107 base_len = ref.len;
109 for (p = argv; *p; p++) {
110 if (get_oid(*p, &oid)) {
111 error("failed to resolve '%s' as a valid ref", *p);
112 had_error = 1;
113 continue;
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);
122 had_error = 1;
123 continue;
125 if (fn(full_hex, ref.buf, &oid))
126 had_error = 1;
128 strbuf_release(&ref);
129 return had_error;
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))
136 return 1;
137 printf_ln(_("Deleted replace ref '%s'"), name);
138 return 0;
141 static int check_ref_valid(struct object_id *object,
142 struct object_id *prev,
143 struct strbuf *ref,
144 int force)
146 strbuf_reset(ref);
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))
152 oidclr(prev);
153 else if (!force)
154 return error(_("replace ref '%s' already exists"), ref->buf);
155 return 0;
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,
162 int force)
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;
169 int res = 0;
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 "
177 "type '%s'."),
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);
183 return -1;
186 transaction = ref_transaction_begin(&err);
187 if (!transaction ||
188 ref_transaction_update(transaction, ref.buf, repl, &prev,
189 0, NULL, &err) ||
190 ref_transaction_commit(transaction, &err))
191 res = error("%s", err.buf);
193 ref_transaction_free(transaction);
194 strbuf_release(&ref);
195 return res;
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"),
204 object_ref);
205 if (get_oid(replace_ref, &repl))
206 return error(_("failed to resolve '%s' as a valid ref"),
207 replace_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;
221 int fd;
223 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
224 if (fd < 0)
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");
229 if (raw)
230 argv_array_push(&cmd.args, type_name(type));
231 else
232 argv_array_push(&cmd.args, "-p");
233 argv_array_push(&cmd.args, oid_to_hex(oid));
234 cmd.git_cmd = 1;
235 cmd.out = fd;
237 if (run_command(&cmd))
238 return error(_("cat-file reported failure"));
239 return 0;
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)
250 int fd;
252 fd = open(filename, O_RDONLY);
253 if (fd < 0)
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;
261 cmd.argv = argv;
262 cmd.git_cmd = 1;
263 cmd.in = fd;
264 cmd.out = -1;
266 if (start_command(&cmd)) {
267 close(fd);
268 return error(_("unable to spawn mktree"));
271 if (strbuf_read(&result, cmd.out, 41) < 0) {
272 error_errno(_("unable to read from mktree"));
273 close(fd);
274 close(cmd.out);
275 return -1;
277 close(cmd.out);
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);
289 } else {
290 struct stat st;
291 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
293 if (fstat(fd, &st) < 0) {
294 error_errno(_("unable to fstat %s"), filename);
295 close(fd);
296 return -1;
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.
307 return 0;
310 static int edit_and_replace(const char *object_ref, int force, int raw)
312 char *tmpfile;
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);
321 if (type < 0)
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);
327 return -1;
329 strbuf_release(&ref);
331 tmpfile = git_pathdup("REPLACE_EDITOBJ");
332 if (export_object(&old_oid, type, raw, tmpfile)) {
333 free(tmpfile);
334 return -1;
336 if (launch_editor(tmpfile, NULL, NULL) < 0) {
337 free(tmpfile);
338 return error(_("editing object file failed"));
340 if (import_object(&new_oid, type, raw, tmpfile)) {
341 free(tmpfile);
342 return -1;
344 free(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;
356 int i;
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'"),
372 argv[i]);
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);
386 return 0;
389 struct check_mergetag_data {
390 int argc;
391 const char **argv;
394 static int check_one_mergetag(struct commit *commit,
395 struct commit_extra_header *extra,
396 void *data)
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;
401 struct tag *tag;
402 int i;
404 hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
405 tag = lookup_tag(the_repository, &tag_oid);
406 if (!tag)
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;
441 const char *buffer;
442 unsigned long size;
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);
447 if (!commit)
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);
456 return -1;
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);
466 return -1;
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'"),
472 old_ref);
475 strbuf_release(&buf);
477 if (!oidcmp(&old_oid, &new_oid)) {
478 if (gentle) {
479 warning(_("graft for '%s' unnecessary"), oid_to_hex(&old_oid));
480 return 0;
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;
495 if (!fp)
496 return -1;
498 while (strbuf_getline(&buf, fp) != EOF) {
499 if (*buf.buf == '#')
500 continue;
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);
507 fclose(fp);
509 strbuf_release(&buf);
511 if (!err.len)
512 return unlink_or_warn(graft_file);
514 warning(_("could not convert the following graft(s):\n%s"), err.buf);
515 strbuf_release(&err);
517 return -1;
520 int cmd_replace(int argc, const char **argv, const char *prefix)
522 int force = 0;
523 int raw = 0;
524 const char *format = NULL;
525 enum {
526 MODE_UNSPECIFIED = 0,
527 MODE_LIST,
528 MODE_DELETE,
529 MODE_EDIT,
530 MODE_GRAFT,
531 MODE_CONVERT_GRAFT_FILE,
532 MODE_REPLACE
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")),
544 OPT_END()
547 read_replace_refs = 0;
548 git_config(git_default_config, NULL);
550 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
552 if (!cmdmode)
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);
559 if (force &&
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);
571 switch (cmdmode) {
572 case MODE_DELETE:
573 if (argc < 1)
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);
578 case MODE_REPLACE:
579 if (argc != 2)
580 usage_msg_opt(_("bad number of arguments"),
581 git_replace_usage, options);
582 return replace_object(argv[0], argv[1], force);
584 case MODE_EDIT:
585 if (argc != 1)
586 usage_msg_opt(_("-e needs exactly one argument"),
587 git_replace_usage, options);
588 return edit_and_replace(argv[0], force, raw);
590 case MODE_GRAFT:
591 if (argc < 1)
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:
597 if (argc != 0)
598 usage_msg_opt(_("--convert-graft-file takes no argument"),
599 git_replace_usage, options);
600 return !!convert_graft_file(force);
602 case MODE_LIST:
603 if (argc > 1)
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);
608 default:
609 BUG("invalid cmdmode %d", (int)cmdmode);