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