]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/replace.c
The seventh batch
[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 "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"
28
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
37 };
38
39 enum replace_format {
40 REPLACE_FORMAT_SHORT,
41 REPLACE_FORMAT_MEDIUM,
42 REPLACE_FORMAT_LONG
43 };
44
45 struct show_data {
46 const char *pattern;
47 enum replace_format format;
48 };
49
50 static int show_reference(struct repository *r, const char *refname,
51 const struct object_id *oid,
52 int flag UNUSED, void *cb_data)
53 {
54 struct show_data *data = cb_data;
55
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;
64
65 if (repo_get_oid(r, refname, &object))
66 return error(_("failed to resolve '%s' as a valid ref"), refname);
67
68 obj_type = oid_object_info(r, &object, NULL);
69 repl_type = oid_object_info(r, oid, NULL);
70
71 printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
72 oid_to_hex(oid), type_name(repl_type));
73 }
74 }
75
76 return 0;
77 }
78
79 static int list_replace_refs(const char *pattern, const char *format)
80 {
81 struct show_data data;
82
83 if (!pattern)
84 pattern = "*";
85 data.pattern = pattern;
86
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;
93 /*
94 * Please update _git_replace() in git-completion.bash when
95 * you add new format
96 */
97 else
98 return error(_("invalid replace format '%s'\n"
99 "valid formats are 'short', 'medium' and 'long'"),
100 format);
101
102 for_each_replace_ref(the_repository, 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_addstr(&ref, oid_to_hex(&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);
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 = 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));
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 &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 = HASH_FORMAT_CHECK | HASH_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 = oid_object_info(the_repository, &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 = git_pathdup("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 (write_object_file(buf.buf, buf.len, OBJ_COMMIT, &new_oid)) {
490 strbuf_release(&buf);
491 return error(_("could not write replacement commit for: '%s'"),
492 old_ref);
493 }
494
495 strbuf_release(&buf);
496
497 if (oideq(&commit->object.oid, &new_oid)) {
498 if (gentle) {
499 warning(_("graft for '%s' unnecessary"),
500 oid_to_hex(&commit->object.oid));
501 return 0;
502 }
503 return error(_("new commit is the same as the old one: '%s'"),
504 oid_to_hex(&commit->object.oid));
505 }
506
507 return replace_object_oid(old_ref, &commit->object.oid,
508 "replacement", &new_oid, force);
509 }
510
511 static int convert_graft_file(int force)
512 {
513 const char *graft_file = get_graft_file(the_repository);
514 FILE *fp = fopen_or_warn(graft_file, "r");
515 struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
516 struct strvec args = STRVEC_INIT;
517
518 if (!fp)
519 return -1;
520
521 no_graft_file_deprecated_advice = 1;
522 while (strbuf_getline(&buf, fp) != EOF) {
523 if (*buf.buf == '#')
524 continue;
525
526 strvec_split(&args, buf.buf);
527 if (args.nr && create_graft(args.nr, args.v, force, 1))
528 strbuf_addf(&err, "\n\t%s", buf.buf);
529 strvec_clear(&args);
530 }
531 fclose(fp);
532
533 strbuf_release(&buf);
534
535 if (!err.len)
536 return unlink_or_warn(graft_file);
537
538 warning(_("could not convert the following graft(s):\n%s"), err.buf);
539 strbuf_release(&err);
540
541 return -1;
542 }
543
544 int cmd_replace(int argc, const char **argv, const char *prefix)
545 {
546 int force = 0;
547 int raw = 0;
548 const char *format = NULL;
549 enum {
550 MODE_UNSPECIFIED = 0,
551 MODE_LIST,
552 MODE_DELETE,
553 MODE_EDIT,
554 MODE_GRAFT,
555 MODE_CONVERT_GRAFT_FILE,
556 MODE_REPLACE
557 } cmdmode = MODE_UNSPECIFIED;
558 struct option options[] = {
559 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
560 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
561 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
562 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
563 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
564 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
565 PARSE_OPT_NOCOMPLETE),
566 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
567 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
568 OPT_END()
569 };
570
571 disable_replace_refs();
572 git_config(git_default_config, NULL);
573
574 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
575
576 if (!cmdmode)
577 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
578
579 if (format && cmdmode != MODE_LIST)
580 usage_msg_opt(_("--format cannot be used when not listing"),
581 git_replace_usage, options);
582
583 if (force &&
584 cmdmode != MODE_REPLACE &&
585 cmdmode != MODE_EDIT &&
586 cmdmode != MODE_GRAFT &&
587 cmdmode != MODE_CONVERT_GRAFT_FILE)
588 usage_msg_opt(_("-f only makes sense when writing a replacement"),
589 git_replace_usage, options);
590
591 if (raw && cmdmode != MODE_EDIT)
592 usage_msg_opt(_("--raw only makes sense with --edit"),
593 git_replace_usage, options);
594
595 switch (cmdmode) {
596 case MODE_DELETE:
597 if (argc < 1)
598 usage_msg_opt(_("-d needs at least one argument"),
599 git_replace_usage, options);
600 return for_each_replace_name(argv, delete_replace_ref);
601
602 case MODE_REPLACE:
603 if (argc != 2)
604 usage_msg_opt(_("bad number of arguments"),
605 git_replace_usage, options);
606 return replace_object(argv[0], argv[1], force);
607
608 case MODE_EDIT:
609 if (argc != 1)
610 usage_msg_opt(_("-e needs exactly one argument"),
611 git_replace_usage, options);
612 return edit_and_replace(argv[0], force, raw);
613
614 case MODE_GRAFT:
615 if (argc < 1)
616 usage_msg_opt(_("-g needs at least one argument"),
617 git_replace_usage, options);
618 return create_graft(argc, argv, force, 0);
619
620 case MODE_CONVERT_GRAFT_FILE:
621 if (argc != 0)
622 usage_msg_opt(_("--convert-graft-file takes no argument"),
623 git_replace_usage, options);
624 return !!convert_graft_file(force);
625
626 case MODE_LIST:
627 if (argc > 1)
628 usage_msg_opt(_("only one pattern can be given with -l"),
629 git_replace_usage, options);
630 return list_replace_refs(argv[0], format);
631
632 default:
633 BUG("invalid cmdmode %d", (int)cmdmode);
634 }
635 }