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