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