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