Merge branch 'tz/cred-netrc-cleanup'
[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(const char *refname, const struct object_id *oid,
43                           int flag, void *cb_data)
44 {
45         struct show_data *data = cb_data;
46
47         if (!wildmatch(data->pattern, refname, 0)) {
48                 if (data->format == REPLACE_FORMAT_SHORT)
49                         printf("%s\n", refname);
50                 else if (data->format == REPLACE_FORMAT_MEDIUM)
51                         printf("%s -> %s\n", refname, oid_to_hex(oid));
52                 else { /* data->format == REPLACE_FORMAT_LONG */
53                         struct object_id object;
54                         enum object_type obj_type, repl_type;
55
56                         if (get_oid(refname, &object))
57                                 return error("Failed to resolve '%s' as a valid ref.", refname);
58
59                         obj_type = oid_object_info(the_repository, &object,
60                                                    NULL);
61                         repl_type = oid_object_info(the_repository, 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'\n",
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("Deleted replace ref '%s'\n", 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(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 (!oidcmp(&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                 if (get_oid(argv[i], &oid) < 0) {
370                         strbuf_release(&new_parents);
371                         return error(_("Not a valid object name: '%s'"),
372                                      argv[i]);
373                 }
374                 if (!lookup_commit_reference(&oid)) {
375                         strbuf_release(&new_parents);
376                         return error(_("could not parse %s"), argv[i]);
377                 }
378                 strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
379         }
380
381         /* replace existing parents with new ones */
382         strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
383                       new_parents.buf, new_parents.len);
384
385         strbuf_release(&new_parents);
386         return 0;
387 }
388
389 struct check_mergetag_data {
390         int argc;
391         const char **argv;
392 };
393
394 static int check_one_mergetag(struct commit *commit,
395                                struct commit_extra_header *extra,
396                                void *data)
397 {
398         struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
399         const char *ref = mergetag_data->argv[0];
400         struct object_id tag_oid;
401         struct tag *tag;
402         int i;
403
404         hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
405         tag = lookup_tag(&tag_oid);
406         if (!tag)
407                 return error(_("bad mergetag in commit '%s'"), ref);
408         if (parse_tag_buffer(tag, extra->value, extra->len))
409                 return error(_("malformed mergetag in commit '%s'"), ref);
410
411         /* iterate over new parents */
412         for (i = 1; i < mergetag_data->argc; i++) {
413                 struct object_id oid;
414                 if (get_oid(mergetag_data->argv[i], &oid) < 0)
415                         return error(_("Not a valid object name: '%s'"),
416                                      mergetag_data->argv[i]);
417                 if (!oidcmp(&tag->tagged->oid, &oid))
418                         return 0; /* found */
419         }
420
421         return error(_("original commit '%s' contains mergetag '%s' that is "
422                        "discarded; use --edit instead of --graft"), ref,
423                      oid_to_hex(&tag_oid));
424 }
425
426 static int check_mergetags(struct commit *commit, int argc, const char **argv)
427 {
428         struct check_mergetag_data mergetag_data;
429
430         mergetag_data.argc = argc;
431         mergetag_data.argv = argv;
432         return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
433 }
434
435 static int create_graft(int argc, const char **argv, int force, int gentle)
436 {
437         struct object_id old_oid, new_oid;
438         const char *old_ref = argv[0];
439         struct commit *commit;
440         struct strbuf buf = STRBUF_INIT;
441         const char *buffer;
442         unsigned long size;
443
444         if (get_oid(old_ref, &old_oid) < 0)
445                 return error(_("Not a valid object name: '%s'"), old_ref);
446         commit = lookup_commit_reference(&old_oid);
447         if (!commit)
448                 return error(_("could not parse %s"), old_ref);
449
450         buffer = get_commit_buffer(commit, &size);
451         strbuf_add(&buf, buffer, size);
452         unuse_commit_buffer(commit, buffer);
453
454         if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
455                 strbuf_release(&buf);
456                 return -1;
457         }
458
459         if (remove_signature(&buf)) {
460                 warning(_("the original commit '%s' has a gpg signature."), old_ref);
461                 warning(_("the signature will be removed in the replacement commit!"));
462         }
463
464         if (check_mergetags(commit, argc, argv)) {
465                 strbuf_release(&buf);
466                 return -1;
467         }
468
469         if (write_object_file(buf.buf, buf.len, commit_type, &new_oid)) {
470                 strbuf_release(&buf);
471                 return error(_("could not write replacement commit for: '%s'"),
472                              old_ref);
473         }
474
475         strbuf_release(&buf);
476
477         if (!oidcmp(&old_oid, &new_oid)) {
478                 if (gentle) {
479                         warning("graft for '%s' unnecessary", oid_to_hex(&old_oid));
480                         return 0;
481                 }
482                 return error("new commit is the same as the old one: '%s'", oid_to_hex(&old_oid));
483         }
484
485         return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
486 }
487
488 static int convert_graft_file(int force)
489 {
490         const char *graft_file = get_graft_file();
491         FILE *fp = fopen_or_warn(graft_file, "r");
492         struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
493         struct argv_array args = ARGV_ARRAY_INIT;
494
495         if (!fp)
496                 return -1;
497
498         while (strbuf_getline(&buf, fp) != EOF) {
499                 if (*buf.buf == '#')
500                         continue;
501
502                 argv_array_split(&args, buf.buf);
503                 if (args.argc && create_graft(args.argc, args.argv, force, 1))
504                         strbuf_addf(&err, "\n\t%s", buf.buf);
505                 argv_array_clear(&args);
506         }
507         fclose(fp);
508
509         strbuf_release(&buf);
510
511         if (!err.len)
512                 return unlink_or_warn(graft_file);
513
514         warning(_("could not convert the following graft(s):\n%s"), err.buf);
515         strbuf_release(&err);
516
517         return -1;
518 }
519
520 int cmd_replace(int argc, const char **argv, const char *prefix)
521 {
522         int force = 0;
523         int raw = 0;
524         const char *format = NULL;
525         enum {
526                 MODE_UNSPECIFIED = 0,
527                 MODE_LIST,
528                 MODE_DELETE,
529                 MODE_EDIT,
530                 MODE_GRAFT,
531                 MODE_CONVERT_GRAFT_FILE,
532                 MODE_REPLACE
533         } cmdmode = MODE_UNSPECIFIED;
534         struct option options[] = {
535                 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
536                 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
537                 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
538                 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
539                 OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
540                 OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
541                            PARSE_OPT_NOCOMPLETE),
542                 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
543                 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
544                 OPT_END()
545         };
546
547         check_replace_refs = 0;
548         git_config(git_default_config, NULL);
549
550         argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
551
552         if (!cmdmode)
553                 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
554
555         if (format && cmdmode != MODE_LIST)
556                 usage_msg_opt("--format cannot be used when not listing",
557                               git_replace_usage, options);
558
559         if (force &&
560             cmdmode != MODE_REPLACE &&
561             cmdmode != MODE_EDIT &&
562             cmdmode != MODE_GRAFT &&
563             cmdmode != MODE_CONVERT_GRAFT_FILE)
564                 usage_msg_opt("-f only makes sense when writing a replacement",
565                               git_replace_usage, options);
566
567         if (raw && cmdmode != MODE_EDIT)
568                 usage_msg_opt("--raw only makes sense with --edit",
569                               git_replace_usage, options);
570
571         switch (cmdmode) {
572         case MODE_DELETE:
573                 if (argc < 1)
574                         usage_msg_opt("-d needs at least one argument",
575                                       git_replace_usage, options);
576                 return for_each_replace_name(argv, delete_replace_ref);
577
578         case MODE_REPLACE:
579                 if (argc != 2)
580                         usage_msg_opt("bad number of arguments",
581                                       git_replace_usage, options);
582                 return replace_object(argv[0], argv[1], force);
583
584         case MODE_EDIT:
585                 if (argc != 1)
586                         usage_msg_opt("-e needs exactly one argument",
587                                       git_replace_usage, options);
588                 return edit_and_replace(argv[0], force, raw);
589
590         case MODE_GRAFT:
591                 if (argc < 1)
592                         usage_msg_opt("-g needs at least one argument",
593                                       git_replace_usage, options);
594                 return create_graft(argc, argv, force, 0);
595
596         case MODE_CONVERT_GRAFT_FILE:
597                 if (argc != 0)
598                         usage_msg_opt("--convert-graft-file takes no argument",
599                                       git_replace_usage, options);
600                 return !!convert_graft_file(force);
601
602         case MODE_LIST:
603                 if (argc > 1)
604                         usage_msg_opt("only one pattern can be given with -l",
605                                       git_replace_usage, options);
606                 return list_replace_refs(argv[0], format);
607
608         default:
609                 BUG("invalid cmdmode %d", (int)cmdmode);
610         }
611 }