replace: peel tag when passing a tag as parent to --graft
[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 "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"
20
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
29 };
30
31 enum replace_format {
32         REPLACE_FORMAT_SHORT,
33         REPLACE_FORMAT_MEDIUM,
34         REPLACE_FORMAT_LONG
35 };
36
37 struct show_data {
38         const char *pattern;
39         enum replace_format format;
40 };
41
42 static int show_reference(struct repository *r, const char *refname,
43                           const struct object_id *oid,
44                           int flag, void *cb_data)
45 {
46         struct show_data *data = cb_data;
47
48         if (!wildmatch(data->pattern, refname, 0)) {
49                 if (data->format == REPLACE_FORMAT_SHORT)
50                         printf("%s\n", refname);
51                 else if (data->format == REPLACE_FORMAT_MEDIUM)
52                         printf("%s -> %s\n", refname, oid_to_hex(oid));
53                 else { /* data->format == REPLACE_FORMAT_LONG */
54                         struct object_id object;
55                         enum object_type obj_type, repl_type;
56
57                         if (get_oid(refname, &object))
58                                 return error(_("failed to resolve '%s' as a valid ref"), refname);
59
60                         obj_type = oid_object_info(r, &object, NULL);
61                         repl_type = oid_object_info(r, oid, NULL);
62
63                         printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
64                                oid_to_hex(oid), type_name(repl_type));
65                 }
66         }
67
68         return 0;
69 }
70
71 static int list_replace_refs(const char *pattern, const char *format)
72 {
73         struct show_data data;
74
75         if (pattern == NULL)
76                 pattern = "*";
77         data.pattern = pattern;
78
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);
89
90         for_each_replace_ref(the_repository, show_reference, (void *)&data);
91
92         return 0;
93 }
94
95 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
96                                     const struct object_id *oid);
97
98 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
99 {
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;
105
106         strbuf_addstr(&ref, git_replace_ref_base);
107         base_len = ref.len;
108
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;
114                 }
115
116                 strbuf_setlen(&ref, base_len);
117                 strbuf_addstr(&ref, oid_to_hex(&oid));
118                 full_hex = ref.buf + base_len;
119
120                 if (read_ref(ref.buf, &oid)) {
121                         error(_("replace ref '%s' not found"), full_hex);
122                         had_error = 1;
123                         continue;
124                 }
125                 if (fn(full_hex, ref.buf, &oid))
126                         had_error = 1;
127         }
128         strbuf_release(&ref);
129         return had_error;
130 }
131
132 static int delete_replace_ref(const char *name, const char *ref,
133                               const struct object_id *oid)
134 {
135         if (delete_ref(NULL, ref, oid, 0))
136                 return 1;
137         printf_ln(_("Deleted replace ref '%s'"), name);
138         return 0;
139 }
140
141 static int check_ref_valid(struct object_id *object,
142                             struct object_id *prev,
143                             struct strbuf *ref,
144                             int force)
145 {
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);
150
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;
156 }
157
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)
163 {
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;
170
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));
180
181         if (check_ref_valid(object, &prev, &ref, force)) {
182                 strbuf_release(&ref);
183                 return -1;
184         }
185
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);
192
193         ref_transaction_free(transaction);
194         strbuf_release(&ref);
195         return res;
196 }
197
198 static int replace_object(const char *object_ref, const char *replace_ref, int force)
199 {
200         struct object_id object, repl;
201
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);
208
209         return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
210 }
211
212 /*
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.
216  */
217 static int export_object(const struct object_id *oid, enum object_type type,
218                           int raw, const char *filename)
219 {
220         struct child_process cmd = CHILD_PROCESS_INIT;
221         int fd;
222
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);
226
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;
236
237         if (run_command(&cmd))
238                 return error(_("cat-file reported failure"));
239         return 0;
240 }
241
242 /*
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.
246  */
247 static int import_object(struct object_id *oid, enum object_type type,
248                           int raw, const char *filename)
249 {
250         int fd;
251
252         fd = open(filename, O_RDONLY);
253         if (fd < 0)
254                 return error_errno(_("unable to open %s for reading"), filename);
255
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;
260
261                 cmd.argv = argv;
262                 cmd.git_cmd = 1;
263                 cmd.in = fd;
264                 cmd.out = -1;
265
266                 if (start_command(&cmd)) {
267                         close(fd);
268                         return error(_("unable to spawn mktree"));
269                 }
270
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;
276                 }
277                 close(cmd.out);
278
279                 if (finish_command(&cmd)) {
280                         strbuf_release(&result);
281                         return error(_("mktree reported failure"));
282                 }
283                 if (get_oid_hex(result.buf, oid) < 0) {
284                         strbuf_release(&result);
285                         return error(_("mktree did not return an object name"));
286                 }
287
288                 strbuf_release(&result);
289         } else {
290                 struct stat st;
291                 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
292
293                 if (fstat(fd, &st) < 0) {
294                         error_errno(_("unable to fstat %s"), filename);
295                         close(fd);
296                         return -1;
297                 }
298                 if (index_fd(the_repository->index, oid, fd, &st, type, NULL, flags) < 0)
299                         return error(_("unable to write object to database"));
300                 /* index_fd close()s fd for us */
301         }
302
303         /*
304          * No need to close(fd) here; both run-command and index-fd
305          * will have done it for us.
306          */
307         return 0;
308 }
309
310 static int edit_and_replace(const char *object_ref, int force, int raw)
311 {
312         char *tmpfile;
313         enum object_type type;
314         struct object_id old_oid, new_oid, prev;
315         struct strbuf ref = STRBUF_INIT;
316
317         if (get_oid(object_ref, &old_oid) < 0)
318                 return error(_("not a valid object name: '%s'"), object_ref);
319
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));
324
325         if (check_ref_valid(&old_oid, &prev, &ref, force)) {
326                 strbuf_release(&ref);
327                 return -1;
328         }
329         strbuf_release(&ref);
330
331         tmpfile = git_pathdup("REPLACE_EDITOBJ");
332         if (export_object(&old_oid, type, raw, tmpfile)) {
333                 free(tmpfile);
334                 return -1;
335         }
336         if (launch_editor(tmpfile, NULL, NULL) < 0) {
337                 free(tmpfile);
338                 return error(_("editing object file failed"));
339         }
340         if (import_object(&new_oid, type, raw, tmpfile)) {
341                 free(tmpfile);
342                 return -1;
343         }
344         free(tmpfile);
345
346         if (oideq(&old_oid, &new_oid))
347                 return error(_("new object is the same as the old one: '%s'"), oid_to_hex(&old_oid));
348
349         return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
350 }
351
352 static int replace_parents(struct strbuf *buf, int argc, const char **argv)
353 {
354         struct strbuf new_parents = STRBUF_INIT;
355         const char *parent_start, *parent_end;
356         int i;
357
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;
362
363         while (starts_with(parent_end, "parent "))
364                 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
365
366         /* prepare new parents */
367         for (i = 0; i < argc; i++) {
368                 struct object_id oid;
369                 struct commit *commit;
370
371                 if (get_oid(argv[i], &oid) < 0) {
372                         strbuf_release(&new_parents);
373                         return error(_("not a valid object name: '%s'"),
374                                      argv[i]);
375                 }
376                 commit = lookup_commit_reference(the_repository, &oid);
377                 if (!commit) {
378                         strbuf_release(&new_parents);
379                         return error(_("could not parse %s as a commit"), argv[i]);
380                 }
381                 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&commit->object.oid));
382         }
383
384         /* replace existing parents with new ones */
385         strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
386                       new_parents.buf, new_parents.len);
387
388         strbuf_release(&new_parents);
389         return 0;
390 }
391
392 struct check_mergetag_data {
393         int argc;
394         const char **argv;
395 };
396
397 static int check_one_mergetag(struct commit *commit,
398                                struct commit_extra_header *extra,
399                                void *data)
400 {
401         struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
402         const char *ref = mergetag_data->argv[0];
403         struct object_id tag_oid;
404         struct tag *tag;
405         int i;
406
407         hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
408         tag = lookup_tag(the_repository, &tag_oid);
409         if (!tag)
410                 return error(_("bad mergetag in commit '%s'"), ref);
411         if (parse_tag_buffer(the_repository, tag, extra->value, extra->len))
412                 return error(_("malformed mergetag in commit '%s'"), ref);
413
414         /* iterate over new parents */
415         for (i = 1; i < mergetag_data->argc; i++) {
416                 struct object_id oid;
417                 if (get_oid(mergetag_data->argv[i], &oid) < 0)
418                         return error(_("not a valid object name: '%s'"),
419                                      mergetag_data->argv[i]);
420                 if (oideq(&tag->tagged->oid, &oid))
421                         return 0; /* found */
422         }
423
424         return error(_("original commit '%s' contains mergetag '%s' that is "
425                        "discarded; use --edit instead of --graft"), ref,
426                      oid_to_hex(&tag_oid));
427 }
428
429 static int check_mergetags(struct commit *commit, int argc, const char **argv)
430 {
431         struct check_mergetag_data mergetag_data;
432
433         mergetag_data.argc = argc;
434         mergetag_data.argv = argv;
435         return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
436 }
437
438 static int create_graft(int argc, const char **argv, int force, int gentle)
439 {
440         struct object_id old_oid, new_oid;
441         const char *old_ref = argv[0];
442         struct commit *commit;
443         struct strbuf buf = STRBUF_INIT;
444         const char *buffer;
445         unsigned long size;
446
447         if (get_oid(old_ref, &old_oid) < 0)
448                 return error(_("not a valid object name: '%s'"), old_ref);
449         commit = lookup_commit_reference(the_repository, &old_oid);
450         if (!commit)
451                 return error(_("could not parse %s"), old_ref);
452
453         buffer = get_commit_buffer(commit, &size);
454         strbuf_add(&buf, buffer, size);
455         unuse_commit_buffer(commit, buffer);
456
457         if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
458                 strbuf_release(&buf);
459                 return -1;
460         }
461
462         if (remove_signature(&buf)) {
463                 warning(_("the original commit '%s' has a gpg signature"), old_ref);
464                 warning(_("the signature will be removed in the replacement commit!"));
465         }
466
467         if (check_mergetags(commit, argc, argv)) {
468                 strbuf_release(&buf);
469                 return -1;
470         }
471
472         if (write_object_file(buf.buf, buf.len, commit_type, &new_oid)) {
473                 strbuf_release(&buf);
474                 return error(_("could not write replacement commit for: '%s'"),
475                              old_ref);
476         }
477
478         strbuf_release(&buf);
479
480         if (oideq(&old_oid, &new_oid)) {
481                 if (gentle) {
482                         warning(_("graft for '%s' unnecessary"), oid_to_hex(&old_oid));
483                         return 0;
484                 }
485                 return error(_("new commit is the same as the old one: '%s'"), oid_to_hex(&old_oid));
486         }
487
488         return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
489 }
490
491 static int convert_graft_file(int force)
492 {
493         const char *graft_file = get_graft_file(the_repository);
494         FILE *fp = fopen_or_warn(graft_file, "r");
495         struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
496         struct argv_array args = ARGV_ARRAY_INIT;
497
498         if (!fp)
499                 return -1;
500
501         advice_graft_file_deprecated = 0;
502         while (strbuf_getline(&buf, fp) != EOF) {
503                 if (*buf.buf == '#')
504                         continue;
505
506                 argv_array_split(&args, buf.buf);
507                 if (args.argc && create_graft(args.argc, args.argv, force, 1))
508                         strbuf_addf(&err, "\n\t%s", buf.buf);
509                 argv_array_clear(&args);
510         }
511         fclose(fp);
512
513         strbuf_release(&buf);
514
515         if (!err.len)
516                 return unlink_or_warn(graft_file);
517
518         warning(_("could not convert the following graft(s):\n%s"), err.buf);
519         strbuf_release(&err);
520
521         return -1;
522 }
523
524 int cmd_replace(int argc, const char **argv, const char *prefix)
525 {
526         int force = 0;
527         int raw = 0;
528         const char *format = NULL;
529         enum {
530                 MODE_UNSPECIFIED = 0,
531                 MODE_LIST,
532                 MODE_DELETE,
533                 MODE_EDIT,
534                 MODE_GRAFT,
535                 MODE_CONVERT_GRAFT_FILE,
536                 MODE_REPLACE
537         } cmdmode = MODE_UNSPECIFIED;
538         struct option options[] = {
539                 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
540                 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
541                 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
542                 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
543                 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
544                 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
545                            PARSE_OPT_NOCOMPLETE),
546                 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
547                 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
548                 OPT_END()
549         };
550
551         read_replace_refs = 0;
552         git_config(git_default_config, NULL);
553
554         argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
555
556         if (!cmdmode)
557                 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
558
559         if (format && cmdmode != MODE_LIST)
560                 usage_msg_opt(_("--format cannot be used when not listing"),
561                               git_replace_usage, options);
562
563         if (force &&
564             cmdmode != MODE_REPLACE &&
565             cmdmode != MODE_EDIT &&
566             cmdmode != MODE_GRAFT &&
567             cmdmode != MODE_CONVERT_GRAFT_FILE)
568                 usage_msg_opt(_("-f only makes sense when writing a replacement"),
569                               git_replace_usage, options);
570
571         if (raw && cmdmode != MODE_EDIT)
572                 usage_msg_opt(_("--raw only makes sense with --edit"),
573                               git_replace_usage, options);
574
575         switch (cmdmode) {
576         case MODE_DELETE:
577                 if (argc < 1)
578                         usage_msg_opt(_("-d needs at least one argument"),
579                                       git_replace_usage, options);
580                 return for_each_replace_name(argv, delete_replace_ref);
581
582         case MODE_REPLACE:
583                 if (argc != 2)
584                         usage_msg_opt(_("bad number of arguments"),
585                                       git_replace_usage, options);
586                 return replace_object(argv[0], argv[1], force);
587
588         case MODE_EDIT:
589                 if (argc != 1)
590                         usage_msg_opt(_("-e needs exactly one argument"),
591                                       git_replace_usage, options);
592                 return edit_and_replace(argv[0], force, raw);
593
594         case MODE_GRAFT:
595                 if (argc < 1)
596                         usage_msg_opt(_("-g needs at least one argument"),
597                                       git_replace_usage, options);
598                 return create_graft(argc, argv, force, 0);
599
600         case MODE_CONVERT_GRAFT_FILE:
601                 if (argc != 0)
602                         usage_msg_opt(_("--convert-graft-file takes no argument"),
603                                       git_replace_usage, options);
604                 return !!convert_graft_file(force);
605
606         case MODE_LIST:
607                 if (argc > 1)
608                         usage_msg_opt(_("only one pattern can be given with -l"),
609                                       git_replace_usage, options);
610                 return list_replace_refs(argv[0], format);
611
612         default:
613                 BUG("invalid cmdmode %d", (int)cmdmode);
614         }
615 }