each_ref_fn: change to take an object_id parameter
[git.git] / builtin / replace.c
blobbcf1508c088fd2a7eb5105a1ce05423b87088c62
1 /*
2 * Builtin "git replace"
4 * Copyright (c) 2008 Christian Couder <chriscool@tuxfamily.org>
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 */
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"
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
27 enum replace_format {
28 REPLACE_FORMAT_SHORT,
29 REPLACE_FORMAT_MEDIUM,
30 REPLACE_FORMAT_LONG
33 struct show_data {
34 const char *pattern;
35 enum replace_format format;
38 static int show_reference(const char *refname, const unsigned char *sha1,
39 int flag, void *cb_data)
41 struct show_data *data = cb_data;
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;
52 if (get_sha1(refname, object))
53 return error("Failed to resolve '%s' as a valid ref.", refname);
55 obj_type = sha1_object_info(object, NULL);
56 repl_type = sha1_object_info(sha1, NULL);
58 printf("%s (%s) -> %s (%s)\n", refname, typename(obj_type),
59 sha1_to_hex(sha1), typename(repl_type));
63 return 0;
66 static int list_replace_refs(const char *pattern, const char *format)
68 struct show_data data;
69 struct each_ref_fn_sha1_adapter wrapped_show_reference =
70 {show_reference, (void *) &data};
72 if (pattern == NULL)
73 pattern = "*";
74 data.pattern = pattern;
76 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
77 data.format = REPLACE_FORMAT_SHORT;
78 else if (!strcmp(format, "medium"))
79 data.format = REPLACE_FORMAT_MEDIUM;
80 else if (!strcmp(format, "long"))
81 data.format = REPLACE_FORMAT_LONG;
82 else
83 die("invalid replace format '%s'\n"
84 "valid formats are 'short', 'medium' and 'long'\n",
85 format);
87 for_each_replace_ref(each_ref_fn_adapter, &wrapped_show_reference);
89 return 0;
92 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
93 const unsigned char *sha1);
95 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
97 const char **p, *full_hex;
98 char ref[PATH_MAX];
99 int had_error = 0;
100 unsigned char sha1[20];
102 for (p = argv; *p; p++) {
103 if (get_sha1(*p, sha1)) {
104 error("Failed to resolve '%s' as a valid ref.", *p);
105 had_error = 1;
106 continue;
108 full_hex = sha1_to_hex(sha1);
109 snprintf(ref, sizeof(ref), "refs/replace/%s", full_hex);
110 /* read_ref() may reuse the buffer */
111 full_hex = ref + strlen("refs/replace/");
112 if (read_ref(ref, sha1)) {
113 error("replace ref '%s' not found.", full_hex);
114 had_error = 1;
115 continue;
117 if (fn(full_hex, ref, sha1))
118 had_error = 1;
120 return had_error;
123 static int delete_replace_ref(const char *name, const char *ref,
124 const unsigned char *sha1)
126 if (delete_ref(ref, sha1, 0))
127 return 1;
128 printf("Deleted replace ref '%s'\n", name);
129 return 0;
132 static void check_ref_valid(unsigned char object[20],
133 unsigned char prev[20],
134 char *ref,
135 int ref_size,
136 int force)
138 if (snprintf(ref, ref_size,
139 "refs/replace/%s",
140 sha1_to_hex(object)) > ref_size - 1)
141 die("replace ref name too long: %.*s...", 50, ref);
142 if (check_refname_format(ref, 0))
143 die("'%s' is not a valid ref name.", ref);
145 if (read_ref(ref, prev))
146 hashclr(prev);
147 else if (!force)
148 die("replace ref '%s' already exists", ref);
151 static int replace_object_sha1(const char *object_ref,
152 unsigned char object[20],
153 const char *replace_ref,
154 unsigned char repl[20],
155 int force)
157 unsigned char prev[20];
158 enum object_type obj_type, repl_type;
159 char ref[PATH_MAX];
160 struct ref_transaction *transaction;
161 struct strbuf err = STRBUF_INIT;
163 obj_type = sha1_object_info(object, NULL);
164 repl_type = sha1_object_info(repl, 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));
172 check_ref_valid(object, prev, ref, sizeof(ref), force);
174 transaction = ref_transaction_begin(&err);
175 if (!transaction ||
176 ref_transaction_update(transaction, ref, repl, prev,
177 0, NULL, &err) ||
178 ref_transaction_commit(transaction, &err))
179 die("%s", err.buf);
181 ref_transaction_free(transaction);
182 return 0;
185 static int replace_object(const char *object_ref, const char *replace_ref, int force)
187 unsigned char object[20], repl[20];
189 if (get_sha1(object_ref, object))
190 die("Failed to resolve '%s' as a valid ref.", object_ref);
191 if (get_sha1(replace_ref, repl))
192 die("Failed to resolve '%s' as a valid ref.", replace_ref);
194 return replace_object_sha1(object_ref, object, replace_ref, repl, force);
198 * Write the contents of the object named by "sha1" to the file "filename".
199 * If "raw" is true, then the object's raw contents are printed according to
200 * "type". Otherwise, we pretty-print the contents for human editing.
202 static void export_object(const unsigned char *sha1, enum object_type type,
203 int raw, const char *filename)
205 struct child_process cmd = CHILD_PROCESS_INIT;
206 int fd;
208 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
209 if (fd < 0)
210 die_errno("unable to open %s for writing", filename);
212 argv_array_push(&cmd.args, "--no-replace-objects");
213 argv_array_push(&cmd.args, "cat-file");
214 if (raw)
215 argv_array_push(&cmd.args, typename(type));
216 else
217 argv_array_push(&cmd.args, "-p");
218 argv_array_push(&cmd.args, sha1_to_hex(sha1));
219 cmd.git_cmd = 1;
220 cmd.out = fd;
222 if (run_command(&cmd))
223 die("cat-file reported failure");
227 * Read a previously-exported (and possibly edited) object back from "filename",
228 * interpreting it as "type", and writing the result to the object database.
229 * The sha1 of the written object is returned via sha1.
231 static void import_object(unsigned char *sha1, enum object_type type,
232 int raw, const char *filename)
234 int fd;
236 fd = open(filename, O_RDONLY);
237 if (fd < 0)
238 die_errno("unable to open %s for reading", filename);
240 if (!raw && type == OBJ_TREE) {
241 const char *argv[] = { "mktree", NULL };
242 struct child_process cmd = CHILD_PROCESS_INIT;
243 struct strbuf result = STRBUF_INIT;
245 cmd.argv = argv;
246 cmd.git_cmd = 1;
247 cmd.in = fd;
248 cmd.out = -1;
250 if (start_command(&cmd))
251 die("unable to spawn mktree");
253 if (strbuf_read(&result, cmd.out, 41) < 0)
254 die_errno("unable to read from mktree");
255 close(cmd.out);
257 if (finish_command(&cmd))
258 die("mktree reported failure");
259 if (get_sha1_hex(result.buf, sha1) < 0)
260 die("mktree did not return an object name");
262 strbuf_release(&result);
263 } else {
264 struct stat st;
265 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
267 if (fstat(fd, &st) < 0)
268 die_errno("unable to fstat %s", filename);
269 if (index_fd(sha1, fd, &st, type, NULL, flags) < 0)
270 die("unable to write object to database");
271 /* index_fd close()s fd for us */
275 * No need to close(fd) here; both run-command and index-fd
276 * will have done it for us.
280 static int edit_and_replace(const char *object_ref, int force, int raw)
282 char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
283 enum object_type type;
284 unsigned char old[20], new[20], prev[20];
285 char ref[PATH_MAX];
287 if (get_sha1(object_ref, old) < 0)
288 die("Not a valid object name: '%s'", object_ref);
290 type = sha1_object_info(old, NULL);
291 if (type < 0)
292 die("unable to get object type for %s", sha1_to_hex(old));
294 check_ref_valid(old, prev, ref, sizeof(ref), force);
296 export_object(old, type, raw, tmpfile);
297 if (launch_editor(tmpfile, NULL, NULL) < 0)
298 die("editing object file failed");
299 import_object(new, type, raw, tmpfile);
301 free(tmpfile);
303 if (!hashcmp(old, new))
304 return error("new object is the same as the old one: '%s'", sha1_to_hex(old));
306 return replace_object_sha1(object_ref, old, "replacement", new, force);
309 static void replace_parents(struct strbuf *buf, int argc, const char **argv)
311 struct strbuf new_parents = STRBUF_INIT;
312 const char *parent_start, *parent_end;
313 int i;
315 /* find existing parents */
316 parent_start = buf->buf;
317 parent_start += 46; /* "tree " + "hex sha1" + "\n" */
318 parent_end = parent_start;
320 while (starts_with(parent_end, "parent "))
321 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
323 /* prepare new parents */
324 for (i = 0; i < argc; i++) {
325 unsigned char sha1[20];
326 if (get_sha1(argv[i], sha1) < 0)
327 die(_("Not a valid object name: '%s'"), argv[i]);
328 lookup_commit_or_die(sha1, argv[i]);
329 strbuf_addf(&new_parents, "parent %s\n", sha1_to_hex(sha1));
332 /* replace existing parents with new ones */
333 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
334 new_parents.buf, new_parents.len);
336 strbuf_release(&new_parents);
339 struct check_mergetag_data {
340 int argc;
341 const char **argv;
344 static void check_one_mergetag(struct commit *commit,
345 struct commit_extra_header *extra,
346 void *data)
348 struct check_mergetag_data *mergetag_data = (struct check_mergetag_data *)data;
349 const char *ref = mergetag_data->argv[0];
350 unsigned char tag_sha1[20];
351 struct tag *tag;
352 int i;
354 hash_sha1_file(extra->value, extra->len, typename(OBJ_TAG), tag_sha1);
355 tag = lookup_tag(tag_sha1);
356 if (!tag)
357 die(_("bad mergetag in commit '%s'"), ref);
358 if (parse_tag_buffer(tag, extra->value, extra->len))
359 die(_("malformed mergetag in commit '%s'"), ref);
361 /* iterate over new parents */
362 for (i = 1; i < mergetag_data->argc; i++) {
363 unsigned char sha1[20];
364 if (get_sha1(mergetag_data->argv[i], sha1) < 0)
365 die(_("Not a valid object name: '%s'"), mergetag_data->argv[i]);
366 if (!hashcmp(tag->tagged->sha1, sha1))
367 return; /* found */
370 die(_("original commit '%s' contains mergetag '%s' that is discarded; "
371 "use --edit instead of --graft"), ref, sha1_to_hex(tag_sha1));
374 static void check_mergetags(struct commit *commit, int argc, const char **argv)
376 struct check_mergetag_data mergetag_data;
378 mergetag_data.argc = argc;
379 mergetag_data.argv = argv;
380 for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
383 static int create_graft(int argc, const char **argv, int force)
385 unsigned char old[20], new[20];
386 const char *old_ref = argv[0];
387 struct commit *commit;
388 struct strbuf buf = STRBUF_INIT;
389 const char *buffer;
390 unsigned long size;
392 if (get_sha1(old_ref, old) < 0)
393 die(_("Not a valid object name: '%s'"), old_ref);
394 commit = lookup_commit_or_die(old, old_ref);
396 buffer = get_commit_buffer(commit, &size);
397 strbuf_add(&buf, buffer, size);
398 unuse_commit_buffer(commit, buffer);
400 replace_parents(&buf, argc - 1, &argv[1]);
402 if (remove_signature(&buf)) {
403 warning(_("the original commit '%s' has a gpg signature."), old_ref);
404 warning(_("the signature will be removed in the replacement commit!"));
407 check_mergetags(commit, argc, argv);
409 if (write_sha1_file(buf.buf, buf.len, commit_type, new))
410 die(_("could not write replacement commit for: '%s'"), old_ref);
412 strbuf_release(&buf);
414 if (!hashcmp(old, new))
415 return error("new commit is the same as the old one: '%s'", sha1_to_hex(old));
417 return replace_object_sha1(old_ref, old, "replacement", new, force);
420 int cmd_replace(int argc, const char **argv, const char *prefix)
422 int force = 0;
423 int raw = 0;
424 const char *format = NULL;
425 enum {
426 MODE_UNSPECIFIED = 0,
427 MODE_LIST,
428 MODE_DELETE,
429 MODE_EDIT,
430 MODE_GRAFT,
431 MODE_REPLACE
432 } cmdmode = MODE_UNSPECIFIED;
433 struct option options[] = {
434 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
435 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
436 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
437 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
438 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
439 OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
440 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
441 OPT_END()
444 check_replace_refs = 0;
446 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
448 if (!cmdmode)
449 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
451 if (format && cmdmode != MODE_LIST)
452 usage_msg_opt("--format cannot be used when not listing",
453 git_replace_usage, options);
455 if (force &&
456 cmdmode != MODE_REPLACE &&
457 cmdmode != MODE_EDIT &&
458 cmdmode != MODE_GRAFT)
459 usage_msg_opt("-f only makes sense when writing a replacement",
460 git_replace_usage, options);
462 if (raw && cmdmode != MODE_EDIT)
463 usage_msg_opt("--raw only makes sense with --edit",
464 git_replace_usage, options);
466 switch (cmdmode) {
467 case MODE_DELETE:
468 if (argc < 1)
469 usage_msg_opt("-d needs at least one argument",
470 git_replace_usage, options);
471 return for_each_replace_name(argv, delete_replace_ref);
473 case MODE_REPLACE:
474 if (argc != 2)
475 usage_msg_opt("bad number of arguments",
476 git_replace_usage, options);
477 return replace_object(argv[0], argv[1], force);
479 case MODE_EDIT:
480 if (argc != 1)
481 usage_msg_opt("-e needs exactly one argument",
482 git_replace_usage, options);
483 return edit_and_replace(argv[0], force, raw);
485 case MODE_GRAFT:
486 if (argc < 1)
487 usage_msg_opt("-g needs at least one argument",
488 git_replace_usage, options);
489 return create_graft(argc, argv, force);
491 case MODE_LIST:
492 if (argc > 1)
493 usage_msg_opt("only one pattern can be given with -l",
494 git_replace_usage, options);
495 return list_replace_refs(argv[0], format);
497 default:
498 die("BUG: invalid cmdmode %d", (int)cmdmode);