Raw
1 /*
2 * Builtin "git replace"
3 *
4 * Copyright (c) 2008 Christian Couder <chriscool@tuxfamily.org>
5 *
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 */
10 #define USE_THE_REPOSITORY_VARIABLE
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 "odb.h"
24 #include "replace-object.h"
25 #include "tag.h"
26 #include "wildmatch.h"
27
28 static const char * const git_replace_usage[] = {
29 N_("git replace [-f] <object> <replacement>"),
30 N_("git replace [-f] --edit <object>"),
31 N_("git replace [-f] --graft <commit> [<parent>...]"),
32 "git replace [-f] --convert-graft-file",
33 N_("git replace -d <object>..."),
34 N_("git replace [--format=<format>] [-l [<pattern>]]"),
35 NULL
36 };
37
38 enum replace_format {
39 REPLACE_FORMAT_SHORT,
40 REPLACE_FORMAT_MEDIUM,
41 REPLACE_FORMAT_LONG
42 };
43
44 struct show_data {
45 struct repository *repo;
46 const char *pattern;
47 enum replace_format format;
48 };
49
50 static int show_reference(const struct reference *ref, void *cb_data)
51 {
52 struct show_data *data = cb_data;
53
54 if (!wildmatch(data->pattern, ref->name, 0)) {
55 if (data->format == REPLACE_FORMAT_SHORT)
56 printf("%s\n", ref->name);
57 else if (data->format == REPLACE_FORMAT_MEDIUM)
58 printf("%s -> %s\n", ref->name, oid_to_hex(ref->oid));
59 else { /* data->format == REPLACE_FORMAT_LONG */
60 struct object_id object;
61 enum object_type obj_type, repl_type;
62
63 if (repo_get_oid(data->repo, ref->name, &object))
64 return error(_("failed to resolve '%s' as a valid ref"), ref->name);
65
66 obj_type = odb_read_object_info(data->repo->objects, &object, NULL);
67 repl_type = odb_read_object_info(data->repo->objects, ref->oid, NULL);
68
69 printf("%s (%s) -> %s (%s)\n", ref->name, type_name(obj_type),
70 oid_to_hex(ref->oid), type_name(repl_type));
71 }
72 }
73
74 return 0;
75 }
76
77 static int list_replace_refs(const char *pattern, const char *format)
78 {
79 struct show_data data;
80
81 data.repo = the_repository;
82 if (!pattern)
83 pattern = "*";
84 data.pattern = pattern;
85
86 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
87 data.format = REPLACE_FORMAT_SHORT;
88 else if (!strcmp(format, "medium"))
89 data.format = REPLACE_FORMAT_MEDIUM;
90 else if (!strcmp(format, "long"))
91 data.format = REPLACE_FORMAT_LONG;
92 /*
93 * Please update _git_replace() in git-completion.bash when
94 * you add new format
95 */
96 else
97 return error(_("invalid replace format '%s'\n"
98 "valid formats are 'short', 'medium' and 'long'"),
99 format);
100
101 refs_for_each_replace_ref(get_main_ref_store(the_repository),
102 show_reference, (void *)&data);
103
104 return 0;
105 }
106
107 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
108 const struct object_id *oid);
109
110 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
111 {
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;
118
119 strbuf_addstr(&ref, git_replace_ref_base);
120 base_len = ref.len;
121
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;
127 }
128
129 strbuf_setlen(&ref, base_len);
130 strbuf_add_oid_hex(&ref, &oid);
131 full_hex = ref.buf + base_len;
132
133 if (refs_read_ref(get_main_ref_store(the_repository), ref.buf, &oid)) {
134 error(_("replace ref '%s' not found"), full_hex);
135 had_error = 1;
136 continue;
137 }
138 if (fn(full_hex, ref.buf, &oid))
139 had_error = 1;
140 }
141 strbuf_release(&ref);
142 return had_error;
143 }
144
145 static int delete_replace_ref(const char *name, const char *ref,
146 const struct object_id *oid)
147 {
148 if (refs_delete_ref(get_main_ref_store(the_repository), NULL, ref, oid, 0))
149 return 1;
150 printf_ln(_("Deleted replace ref '%s'"), name);
151 return 0;
152 }
153
154 static int check_ref_valid(struct object_id *object,
155 struct object_id *prev,
156 struct strbuf *ref,
157 int force)
158 {
159 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
160
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);
165
166 if (refs_read_ref(get_main_ref_store(the_repository), ref->buf, prev))
167 oidclr(prev, the_repository->hash_algo);
168 else if (!force)
169 return error(_("replace ref '%s' already exists"), ref->buf);
170 return 0;
171 }
172
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)
178 {
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;
185
186 obj_type = odb_read_object_info(the_repository->objects, object, NULL);
187 repl_type = odb_read_object_info(the_repository->objects, 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));
195
196 if (check_ref_valid(object, &prev, &ref, force)) {
197 strbuf_release(&ref);
198 return -1;
199 }
200
201 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
202 0, &err);
203 if (!transaction ||
204 ref_transaction_update(transaction, ref.buf, repl, &prev,
205 NULL, NULL, 0, NULL, &err) ||
206 ref_transaction_commit(transaction, &err))
207 res = error("%s", err.buf);
208
209 ref_transaction_free(transaction);
210 strbuf_release(&ref);
211 return res;
212 }
213
214 static int replace_object(const char *object_ref, const char *replace_ref, int force)
215 {
216 struct object_id object, repl;
217
218 if (repo_get_oid(the_repository, object_ref, &object))
219 return error(_("failed to resolve '%s' as a valid ref"),
220 object_ref);
221 if (repo_get_oid(the_repository, replace_ref, &repl))
222 return error(_("failed to resolve '%s' as a valid ref"),
223 replace_ref);
224
225 return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
226 }
227
228 /*
229 * Write the contents of the object named by "sha1" to the file "filename".
230 * If "raw" is true, then the object's raw contents are printed according to
231 * "type". Otherwise, we pretty-print the contents for human editing.
232 */
233 static int export_object(const struct object_id *oid, enum object_type type,
234 int raw, const char *filename)
235 {
236 struct child_process cmd = CHILD_PROCESS_INIT;
237 int fd;
238
239 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
240 if (fd < 0)
241 return error_errno(_("unable to open %s for writing"), filename);
242
243 strvec_push(&cmd.args, "--no-replace-objects");
244 strvec_push(&cmd.args, "cat-file");
245 if (raw)
246 strvec_push(&cmd.args, type_name(type));
247 else
248 strvec_push(&cmd.args, "-p");
249 strvec_push(&cmd.args, oid_to_hex(oid));
250 cmd.git_cmd = 1;
251 cmd.out = fd;
252
253 if (run_command(&cmd))
254 return error(_("cat-file reported failure"));
255 return 0;
256 }
257
258 /*
259 * Read a previously-exported (and possibly edited) object back from "filename",
260 * interpreting it as "type", and writing the result to the object database.
261 * The sha1 of the written object is returned via sha1.
262 */
263 static int import_object(struct object_id *oid, enum object_type type,
264 int raw, const char *filename)
265 {
266 int fd;
267
268 fd = open(filename, O_RDONLY);
269 if (fd < 0)
270 return error_errno(_("unable to open %s for reading"), filename);
271
272 if (!raw && type == OBJ_TREE) {
273 struct child_process cmd = CHILD_PROCESS_INIT;
274 struct strbuf result = STRBUF_INIT;
275
276 strvec_push(&cmd.args, "mktree");
277 cmd.git_cmd = 1;
278 cmd.in = fd;
279 cmd.out = -1;
280
281 if (start_command(&cmd)) {
282 close(fd);
283 return error(_("unable to spawn mktree"));
284 }
285
286 if (strbuf_read(&result, cmd.out, the_hash_algo->hexsz + 1) < 0) {
287 error_errno(_("unable to read from mktree"));
288 close(fd);
289 close(cmd.out);
290 return -1;
291 }
292 close(cmd.out);
293
294 if (finish_command(&cmd)) {
295 strbuf_release(&result);
296 return error(_("mktree reported failure"));
297 }
298 if (get_oid_hex(result.buf, oid) < 0) {
299 strbuf_release(&result);
300 return error(_("mktree did not return an object name"));
301 }
302
303 strbuf_release(&result);
304 } else {
305 struct stat st;
306 int flags = INDEX_FORMAT_CHECK | INDEX_WRITE_OBJECT;
307
308 if (fstat(fd, &st) < 0) {
309 error_errno(_("unable to fstat %s"), filename);
310 close(fd);
311 return -1;
312 }
313 if (index_fd(the_repository->index, oid, fd, &st, type, NULL, flags) < 0)
314 return error(_("unable to write object to database"));
315 /* index_fd close()s fd for us */
316 }
317
318 /*
319 * No need to close(fd) here; both run-command and index-fd
320 * will have done it for us.
321 */
322 return 0;
323 }
324
325 static int edit_and_replace(const char *object_ref, int force, int raw)
326 {
327 char *tmpfile;
328 enum object_type type;
329 struct object_id old_oid, new_oid, prev;
330 struct strbuf ref = STRBUF_INIT;
331
332 if (repo_get_oid(the_repository, object_ref, &old_oid) < 0)
333 return error(_("not a valid object name: '%s'"), object_ref);
334
335 type = odb_read_object_info(the_repository->objects, &old_oid, NULL);
336 if (type < 0)
337 return error(_("unable to get object type for %s"),
338 oid_to_hex(&old_oid));
339
340 if (check_ref_valid(&old_oid, &prev, &ref, force)) {
341 strbuf_release(&ref);
342 return -1;
343 }
344 strbuf_release(&ref);
345
346 tmpfile = repo_git_path(the_repository, "REPLACE_EDITOBJ");
347 if (export_object(&old_oid, type, raw, tmpfile)) {
348 free(tmpfile);
349 return -1;
350 }
351 if (launch_editor(tmpfile, NULL, NULL) < 0) {
352 free(tmpfile);
353 return error(_("editing object file failed"));
354 }
355 if (import_object(&new_oid, type, raw, tmpfile)) {
356 free(tmpfile);
357 return -1;
358 }
359 free(tmpfile);
360
361 if (oideq(&old_oid, &new_oid))
362 return error(_("new object is the same as the old one: '%s'"), oid_to_hex(&old_oid));
363
364 return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
365 }
366
367 static int replace_parents(struct strbuf *buf, int argc, const char **argv)
368 {
369 struct strbuf new_parents = STRBUF_INIT;
370 const char *parent_start, *parent_end;
371 int i;
372 const unsigned hexsz = the_hash_algo->hexsz;
373
374 /* find existing parents */
375 parent_start = buf->buf;
376 parent_start += hexsz + 6; /* "tree " + "hex sha1" + "\n" */
377 parent_end = parent_start;
378
379 while (starts_with(parent_end, "parent "))
380 parent_end += hexsz + 8; /* "parent " + "hex sha1" + "\n" */
381
382 /* prepare new parents */
383 for (i = 0; i < argc; i++) {
384 struct object_id oid;
385 struct commit *commit;
386
387 if (repo_get_oid(the_repository, argv[i], &oid) < 0) {
388 strbuf_release(&new_parents);
389 return error(_("not a valid object name: '%s'"),
390 argv[i]);
391 }
392 commit = lookup_commit_reference(the_repository, &oid);
393 if (!commit) {
394 strbuf_release(&new_parents);
395 return error(_("could not parse %s as a commit"), argv[i]);
396 }
397 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&commit->object.oid));
398 }
399
400 /* replace existing parents with new ones */
401 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
402 new_parents.buf, new_parents.len);
403
404 strbuf_release(&new_parents);
405 return 0;
406 }
407
408 struct check_mergetag_data {
409 int argc;
410 const char **argv;
411 };
412
413 static int check_one_mergetag(struct commit *commit UNUSED,
414 struct commit_extra_header *extra,
415 void *data)
416 {
417 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
418 const char *ref = mergetag_data->argv[0];
419 struct object_id tag_oid;
420 struct tag *tag;
421 int i;
422
423 hash_object_file(the_hash_algo, extra->value, extra->len,
424 OBJ_TAG, &tag_oid);
425 tag = lookup_tag(the_repository, &tag_oid);
426 if (!tag)
427 return error(_("bad mergetag in commit '%s'"), ref);
428 if (parse_tag_buffer(the_repository, tag, extra->value, extra->len))
429 return error(_("malformed mergetag in commit '%s'"), ref);
430
431 /* iterate over new parents */
432 for (i = 1; i < mergetag_data->argc; i++) {
433 struct object_id oid;
434 if (repo_get_oid(the_repository, mergetag_data->argv[i], &oid) < 0)
435 return error(_("not a valid object name: '%s'"),
436 mergetag_data->argv[i]);
437 if (oideq(get_tagged_oid(tag), &oid))
438 return 0; /* found */
439 }
440
441 return error(_("original commit '%s' contains mergetag '%s' that is "
442 "discarded; use --edit instead of --graft"), ref,
443 oid_to_hex(&tag_oid));
444 }
445
446 static int check_mergetags(struct commit *commit, int argc, const char **argv)
447 {
448 struct check_mergetag_data mergetag_data;
449
450 mergetag_data.argc = argc;
451 mergetag_data.argv = argv;
452 return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
453 }
454
455 static int create_graft(int argc, const char **argv, int force, int gentle)
456 {
457 struct object_id old_oid, new_oid;
458 const char *old_ref = argv[0];
459 struct commit *commit;
460 struct strbuf buf = STRBUF_INIT;
461 const char *buffer;
462 unsigned long size;
463
464 if (repo_get_oid(the_repository, old_ref, &old_oid) < 0)
465 return error(_("not a valid object name: '%s'"), old_ref);
466 commit = lookup_commit_reference(the_repository, &old_oid);
467 if (!commit)
468 return error(_("could not parse %s"), old_ref);
469
470 buffer = repo_get_commit_buffer(the_repository, commit, &size);
471 strbuf_add(&buf, buffer, size);
472 repo_unuse_commit_buffer(the_repository, commit, buffer);
473
474 if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
475 strbuf_release(&buf);
476 return -1;
477 }
478
479 if (remove_signature(&buf)) {
480 warning(_("the original commit '%s' has a gpg signature"), old_ref);
481 warning(_("the signature will be removed in the replacement commit!"));
482 }
483
484 if (check_mergetags(commit, argc, argv)) {
485 strbuf_release(&buf);
486 return -1;
487 }
488
489 if (odb_write_object(the_repository->objects, buf.buf,
490 buf.len, OBJ_COMMIT, &new_oid)) {
491 strbuf_release(&buf);
492 return error(_("could not write replacement commit for: '%s'"),
493 old_ref);
494 }
495
496 strbuf_release(&buf);
497
498 if (oideq(&commit->object.oid, &new_oid)) {
499 if (gentle) {
500 warning(_("graft for '%s' unnecessary"),
501 oid_to_hex(&commit->object.oid));
502 return 0;
503 }
504 return error(_("new commit is the same as the old one: '%s'"),
505 oid_to_hex(&commit->object.oid));
506 }
507
508 return replace_object_oid(old_ref, &commit->object.oid,
509 "replacement", &new_oid, force);
510 }
511
512 static int convert_graft_file(int force)
513 {
514 const char *graft_file = repo_get_graft_file(the_repository);
515 FILE *fp = fopen_or_warn(graft_file, "r");
516 struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
517 struct strvec args = STRVEC_INIT;
518
519 if (!fp)
520 return -1;
521
522 no_graft_file_deprecated_advice = 1;
523 while (strbuf_getline(&buf, fp) != EOF) {
524 if (*buf.buf == '#')
525 continue;
526
527 strvec_split(&args, buf.buf);
528 if (args.nr && create_graft(args.nr, args.v, force, 1))
529 strbuf_addf(&err, "\n\t%s", buf.buf);
530 strvec_clear(&args);
531 }
532 fclose(fp);
533
534 strbuf_release(&buf);
535
536 if (!err.len)
537 return unlink_or_warn(graft_file);
538
539 warning(_("could not convert the following graft(s):\n%s"), err.buf);
540 strbuf_release(&err);
541
542 return -1;
543 }
544
545 int cmd_replace(int argc,
546 const char **argv,
547 const char *prefix,
548 struct repository *repo UNUSED)
549 {
550 int force = 0;
551 int raw = 0;
552 const char *format = NULL;
553 enum {
554 MODE_UNSPECIFIED = 0,
555 MODE_LIST,
556 MODE_DELETE,
557 MODE_EDIT,
558 MODE_GRAFT,
559 MODE_CONVERT_GRAFT_FILE,
560 MODE_REPLACE
561 } cmdmode = MODE_UNSPECIFIED;
562 struct option options[] = {
563 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
564 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
565 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
566 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
567 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
568 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
569 PARSE_OPT_NOCOMPLETE),
570 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
571 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
572 OPT_END()
573 };
574
575 disable_replace_refs();
576 repo_config(the_repository, git_default_config, NULL);
577
578 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
579
580 if (!cmdmode)
581 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
582
583 if (format && cmdmode != MODE_LIST)
584 usage_msg_opt(_("--format cannot be used when not listing"),
585 git_replace_usage, options);
586
587 if (force &&
588 cmdmode != MODE_REPLACE &&
589 cmdmode != MODE_EDIT &&
590 cmdmode != MODE_GRAFT &&
591 cmdmode != MODE_CONVERT_GRAFT_FILE)
592 usage_msg_opt(_("-f only makes sense when writing a replacement"),
593 git_replace_usage, options);
594
595 if (raw && cmdmode != MODE_EDIT)
596 usage_msg_opt(_("--raw only makes sense with --edit"),
597 git_replace_usage, options);
598
599 switch (cmdmode) {
600 case MODE_DELETE:
601 if (argc < 1)
602 usage_msg_opt(_("-d needs at least one argument"),
603 git_replace_usage, options);
604 return for_each_replace_name(argv, delete_replace_ref);
605
606 case MODE_REPLACE:
607 if (argc != 2)
608 usage_msg_opt(_("bad number of arguments"),
609 git_replace_usage, options);
610 return replace_object(argv[0], argv[1], force);
611
612 case MODE_EDIT:
613 if (argc != 1)
614 usage_msg_opt(_("-e needs exactly one argument"),
615 git_replace_usage, options);
616 return edit_and_replace(argv[0], force, raw);
617
618 case MODE_GRAFT:
619 if (argc < 1)
620 usage_msg_opt(_("-g needs at least one argument"),
621 git_replace_usage, options);
622 return create_graft(argc, argv, force, 0);
623
624 case MODE_CONVERT_GRAFT_FILE:
625 if (argc != 0)
626 usage_msg_opt(_("--convert-graft-file takes no argument"),
627 git_replace_usage, options);
628 return !!convert_graft_file(force);
629
630 case MODE_LIST:
631 if (argc > 1)
632 usage_msg_opt(_("only one pattern can be given with -l"),
633 git_replace_usage, options);
634 return list_replace_refs(argv[0], format);
635
636 default:
637 BUG("invalid cmdmode %d", (int)cmdmode);
638 }
639 }