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