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