Merge branch 'pw/add-p-recount'
[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 = sha1_object_info(object.hash, NULL);
57                         repl_type = sha1_object_info(oid->hash, 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                 die("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 void 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                 die("'%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                 die("replace ref '%s' already exists", ref->buf);
151 }
152
153 static int replace_object_oid(const char *object_ref,
154                                struct object_id *object,
155                                const char *replace_ref,
156                                struct object_id *repl,
157                                int force)
158 {
159         struct object_id prev;
160         enum object_type obj_type, repl_type;
161         struct strbuf ref = STRBUF_INIT;
162         struct ref_transaction *transaction;
163         struct strbuf err = STRBUF_INIT;
164
165         obj_type = sha1_object_info(object->hash, NULL);
166         repl_type = sha1_object_info(repl->hash, NULL);
167         if (!force && obj_type != repl_type)
168                 die("Objects must be of the same type.\n"
169                     "'%s' points to a replaced object of type '%s'\n"
170                     "while '%s' points to a replacement object of type '%s'.",
171                     object_ref, type_name(obj_type),
172                     replace_ref, type_name(repl_type));
173
174         check_ref_valid(object, &prev, &ref, force);
175
176         transaction = ref_transaction_begin(&err);
177         if (!transaction ||
178             ref_transaction_update(transaction, ref.buf, repl, &prev,
179                                    0, NULL, &err) ||
180             ref_transaction_commit(transaction, &err))
181                 die("%s", err.buf);
182
183         ref_transaction_free(transaction);
184         strbuf_release(&ref);
185         return 0;
186 }
187
188 static int replace_object(const char *object_ref, const char *replace_ref, int force)
189 {
190         struct object_id object, repl;
191
192         if (get_oid(object_ref, &object))
193                 die("Failed to resolve '%s' as a valid ref.", object_ref);
194         if (get_oid(replace_ref, &repl))
195                 die("Failed to resolve '%s' as a valid ref.", replace_ref);
196
197         return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
198 }
199
200 /*
201  * Write the contents of the object named by "sha1" to the file "filename".
202  * If "raw" is true, then the object's raw contents are printed according to
203  * "type". Otherwise, we pretty-print the contents for human editing.
204  */
205 static void export_object(const struct object_id *oid, enum object_type type,
206                           int raw, const char *filename)
207 {
208         struct child_process cmd = CHILD_PROCESS_INIT;
209         int fd;
210
211         fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
212         if (fd < 0)
213                 die_errno("unable to open %s for writing", filename);
214
215         argv_array_push(&cmd.args, "--no-replace-objects");
216         argv_array_push(&cmd.args, "cat-file");
217         if (raw)
218                 argv_array_push(&cmd.args, type_name(type));
219         else
220                 argv_array_push(&cmd.args, "-p");
221         argv_array_push(&cmd.args, oid_to_hex(oid));
222         cmd.git_cmd = 1;
223         cmd.out = fd;
224
225         if (run_command(&cmd))
226                 die("cat-file reported failure");
227 }
228
229 /*
230  * Read a previously-exported (and possibly edited) object back from "filename",
231  * interpreting it as "type", and writing the result to the object database.
232  * The sha1 of the written object is returned via sha1.
233  */
234 static void import_object(struct object_id *oid, enum object_type type,
235                           int raw, const char *filename)
236 {
237         int fd;
238
239         fd = open(filename, O_RDONLY);
240         if (fd < 0)
241                 die_errno("unable to open %s for reading", filename);
242
243         if (!raw && type == OBJ_TREE) {
244                 const char *argv[] = { "mktree", NULL };
245                 struct child_process cmd = CHILD_PROCESS_INIT;
246                 struct strbuf result = STRBUF_INIT;
247
248                 cmd.argv = argv;
249                 cmd.git_cmd = 1;
250                 cmd.in = fd;
251                 cmd.out = -1;
252
253                 if (start_command(&cmd))
254                         die("unable to spawn mktree");
255
256                 if (strbuf_read(&result, cmd.out, 41) < 0)
257                         die_errno("unable to read from mktree");
258                 close(cmd.out);
259
260                 if (finish_command(&cmd))
261                         die("mktree reported failure");
262                 if (get_oid_hex(result.buf, oid) < 0)
263                         die("mktree did not return an object name");
264
265                 strbuf_release(&result);
266         } else {
267                 struct stat st;
268                 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
269
270                 if (fstat(fd, &st) < 0)
271                         die_errno("unable to fstat %s", filename);
272                 if (index_fd(oid, fd, &st, type, NULL, flags) < 0)
273                         die("unable to write object to database");
274                 /* index_fd close()s fd for us */
275         }
276
277         /*
278          * No need to close(fd) here; both run-command and index-fd
279          * will have done it for us.
280          */
281 }
282
283 static int edit_and_replace(const char *object_ref, int force, int raw)
284 {
285         char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
286         enum object_type type;
287         struct object_id old_oid, new_oid, prev;
288         struct strbuf ref = STRBUF_INIT;
289
290         if (get_oid(object_ref, &old_oid) < 0)
291                 die("Not a valid object name: '%s'", object_ref);
292
293         type = sha1_object_info(old_oid.hash, NULL);
294         if (type < 0)
295                 die("unable to get object type for %s", oid_to_hex(&old_oid));
296
297         check_ref_valid(&old_oid, &prev, &ref, force);
298         strbuf_release(&ref);
299
300         export_object(&old_oid, type, raw, tmpfile);
301         if (launch_editor(tmpfile, NULL, NULL) < 0)
302                 die("editing object file failed");
303         import_object(&new_oid, type, raw, tmpfile);
304
305         free(tmpfile);
306
307         if (!oidcmp(&old_oid, &new_oid))
308                 return error("new object is the same as the old one: '%s'", oid_to_hex(&old_oid));
309
310         return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
311 }
312
313 static void replace_parents(struct strbuf *buf, int argc, const char **argv)
314 {
315         struct strbuf new_parents = STRBUF_INIT;
316         const char *parent_start, *parent_end;
317         int i;
318
319         /* find existing parents */
320         parent_start = buf->buf;
321         parent_start += GIT_SHA1_HEXSZ + 6; /* "tree " + "hex sha1" + "\n" */
322         parent_end = parent_start;
323
324         while (starts_with(parent_end, "parent "))
325                 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
326
327         /* prepare new parents */
328         for (i = 0; i < argc; i++) {
329                 struct object_id oid;
330                 if (get_oid(argv[i], &oid) < 0)
331                         die(_("Not a valid object name: '%s'"), argv[i]);
332                 lookup_commit_or_die(&oid, argv[i]);
333                 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
334         }
335
336         /* replace existing parents with new ones */
337         strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
338                       new_parents.buf, new_parents.len);
339
340         strbuf_release(&new_parents);
341 }
342
343 struct check_mergetag_data {
344         int argc;
345         const char **argv;
346 };
347
348 static void check_one_mergetag(struct commit *commit,
349                                struct commit_extra_header *extra,
350                                void *data)
351 {
352         struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
353         const char *ref = mergetag_data->argv[0];
354         struct object_id tag_oid;
355         struct tag *tag;
356         int i;
357
358         hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
359         tag = lookup_tag(&tag_oid);
360         if (!tag)
361                 die(_("bad mergetag in commit '%s'"), ref);
362         if (parse_tag_buffer(tag, extra->value, extra->len))
363                 die(_("malformed mergetag in commit '%s'"), ref);
364
365         /* iterate over new parents */
366         for (i = 1; i < mergetag_data->argc; i++) {
367                 struct object_id oid;
368                 if (get_oid(mergetag_data->argv[i], &oid) < 0)
369                         die(_("Not a valid object name: '%s'"), mergetag_data->argv[i]);
370                 if (!oidcmp(&tag->tagged->oid, &oid))
371                         return; /* found */
372         }
373
374         die(_("original commit '%s' contains mergetag '%s' that is discarded; "
375               "use --edit instead of --graft"), ref, oid_to_hex(&tag_oid));
376 }
377
378 static void check_mergetags(struct commit *commit, int argc, const char **argv)
379 {
380         struct check_mergetag_data mergetag_data;
381
382         mergetag_data.argc = argc;
383         mergetag_data.argv = argv;
384         for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
385 }
386
387 static int create_graft(int argc, const char **argv, int force)
388 {
389         struct object_id old_oid, new_oid;
390         const char *old_ref = argv[0];
391         struct commit *commit;
392         struct strbuf buf = STRBUF_INIT;
393         const char *buffer;
394         unsigned long size;
395
396         if (get_oid(old_ref, &old_oid) < 0)
397                 die(_("Not a valid object name: '%s'"), old_ref);
398         commit = lookup_commit_or_die(&old_oid, old_ref);
399
400         buffer = get_commit_buffer(commit, &size);
401         strbuf_add(&buf, buffer, size);
402         unuse_commit_buffer(commit, buffer);
403
404         replace_parents(&buf, argc - 1, &argv[1]);
405
406         if (remove_signature(&buf)) {
407                 warning(_("the original commit '%s' has a gpg signature."), old_ref);
408                 warning(_("the signature will be removed in the replacement commit!"));
409         }
410
411         check_mergetags(commit, argc, argv);
412
413         if (write_object_file(buf.buf, buf.len, commit_type, &new_oid))
414                 die(_("could not write replacement commit for: '%s'"), old_ref);
415
416         strbuf_release(&buf);
417
418         if (!oidcmp(&old_oid, &new_oid))
419                 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old_oid));
420
421         return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
422 }
423
424 int cmd_replace(int argc, const char **argv, const char *prefix)
425 {
426         int force = 0;
427         int raw = 0;
428         const char *format = NULL;
429         enum {
430                 MODE_UNSPECIFIED = 0,
431                 MODE_LIST,
432                 MODE_DELETE,
433                 MODE_EDIT,
434                 MODE_GRAFT,
435                 MODE_REPLACE
436         } cmdmode = MODE_UNSPECIFIED;
437         struct option options[] = {
438                 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
439                 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
440                 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
441                 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
442                 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
443                 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
444                 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
445                 OPT_END()
446         };
447
448         check_replace_refs = 0;
449         git_config(git_default_config, NULL);
450
451         argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
452
453         if (!cmdmode)
454                 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
455
456         if (format && cmdmode != MODE_LIST)
457                 usage_msg_opt("--format cannot be used when not listing",
458                               git_replace_usage, options);
459
460         if (force &&
461             cmdmode != MODE_REPLACE &&
462             cmdmode != MODE_EDIT &&
463             cmdmode != MODE_GRAFT)
464                 usage_msg_opt("-f only makes sense when writing a replacement",
465                               git_replace_usage, options);
466
467         if (raw && cmdmode != MODE_EDIT)
468                 usage_msg_opt("--raw only makes sense with --edit",
469                               git_replace_usage, options);
470
471         switch (cmdmode) {
472         case MODE_DELETE:
473                 if (argc < 1)
474                         usage_msg_opt("-d needs at least one argument",
475                                       git_replace_usage, options);
476                 return for_each_replace_name(argv, delete_replace_ref);
477
478         case MODE_REPLACE:
479                 if (argc != 2)
480                         usage_msg_opt("bad number of arguments",
481                                       git_replace_usage, options);
482                 return replace_object(argv[0], argv[1], force);
483
484         case MODE_EDIT:
485                 if (argc != 1)
486                         usage_msg_opt("-e needs exactly one argument",
487                                       git_replace_usage, options);
488                 return edit_and_replace(argv[0], force, raw);
489
490         case MODE_GRAFT:
491                 if (argc < 1)
492                         usage_msg_opt("-g needs at least one argument",
493                                       git_replace_usage, options);
494                 return create_graft(argc, argv, force);
495
496         case MODE_LIST:
497                 if (argc > 1)
498                         usage_msg_opt("only one pattern can be given with -l",
499                                       git_replace_usage, options);
500                 return list_replace_refs(argv[0], format);
501
502         default:
503                 die("BUG: invalid cmdmode %d", (int)cmdmode);
504         }
505 }