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
17static const char * const git_replace_usage[] = {
18 N_("git replace [-f] <object> <replacement>"),
19 N_("git replace [-f] --edit <object>"),
20 N_("git replace [-f] --graft <commit> [<parent>...]"),
21 N_("git replace -d <object>..."),
22 N_("git replace [--format=<format>] [-l [<pattern>]]"),
23 NULL
24};
25
26enum replace_format {
27 REPLACE_FORMAT_SHORT,
28 REPLACE_FORMAT_MEDIUM,
29 REPLACE_FORMAT_LONG
30};
31
32struct show_data {
33 const char *pattern;
34 enum replace_format format;
35};
36
37static int show_reference(const char *refname, const unsigned char *sha1,
38 int flag, void *cb_data)
39{
40 struct show_data *data = cb_data;
41
42 if (!wildmatch(data->pattern, refname, 0, NULL)) {
43 if (data->format == REPLACE_FORMAT_SHORT)
44 printf("%s\n", refname);
45 else if (data->format == REPLACE_FORMAT_MEDIUM)
46 printf("%s -> %s\n", refname, sha1_to_hex(sha1));
47 else { /* data->format == REPLACE_FORMAT_LONG */
48 unsigned char object[20];
49 enum object_type obj_type, repl_type;
50
51 if (get_sha1(refname, object))
52 return error("Failed to resolve '%s' as a valid ref.", refname);
53
54 obj_type = sha1_object_info(object, NULL);
55 repl_type = sha1_object_info(sha1, NULL);
56
57 printf("%s (%s) -> %s (%s)\n", refname, typename(obj_type),
58 sha1_to_hex(sha1), typename(repl_type));
59 }
60 }
61
62 return 0;
63}
64
65static int list_replace_refs(const char *pattern, const char *format)
66{
67 struct show_data data;
68
69 if (pattern == NULL)
70 pattern = "*";
71 data.pattern = pattern;
72
73 if (format == NULL || *format == '\0' || !strcmp(format, "short"))
74 data.format = REPLACE_FORMAT_SHORT;
75 else if (!strcmp(format, "medium"))
76 data.format = REPLACE_FORMAT_MEDIUM;
77 else if (!strcmp(format, "long"))
78 data.format = REPLACE_FORMAT_LONG;
79 else
80 die("invalid replace format '%s'\n"
81 "valid formats are 'short', 'medium' and 'long'\n",
82 format);
83
84 for_each_replace_ref(show_reference, (void *) &data);
85
86 return 0;
87}
88
89typedef int (*each_replace_name_fn)(const char *name, const char *ref,
90 const unsigned char *sha1);
91
92static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
93{
94 const char **p, *full_hex;
95 char ref[PATH_MAX];
96 int had_error = 0;
97 unsigned char sha1[20];
98
99 for (p = argv; *p; p++) {
100 if (get_sha1(*p, sha1)) {
101 error("Failed to resolve '%s' as a valid ref.", *p);
102 had_error = 1;
103 continue;
104 }
105 full_hex = sha1_to_hex(sha1);
106 snprintf(ref, sizeof(ref), "refs/replace/%s", full_hex);
107 /* read_ref() may reuse the buffer */
108 full_hex = ref + strlen("refs/replace/");
109 if (read_ref(ref, sha1)) {
110 error("replace ref '%s' not found.", full_hex);
111 had_error = 1;
112 continue;
113 }
114 if (fn(full_hex, ref, sha1))
115 had_error = 1;
116 }
117 return had_error;
118}
119
120static int delete_replace_ref(const char *name, const char *ref,
121 const unsigned char *sha1)
122{
123 if (delete_ref(ref, sha1, 0))
124 return 1;
125 printf("Deleted replace ref '%s'\n", name);
126 return 0;
127}
128
129static void check_ref_valid(unsigned char object[20],
130 unsigned char prev[20],
131 char *ref,
132 int ref_size,
133 int force)
134{
135 if (snprintf(ref, ref_size,
136 "refs/replace/%s",
137 sha1_to_hex(object)) > ref_size - 1)
138 die("replace ref name too long: %.*s...", 50, ref);
139 if (check_refname_format(ref, 0))
140 die("'%s' is not a valid ref name.", ref);
141
142 if (read_ref(ref, prev))
143 hashclr(prev);
144 else if (!force)
145 die("replace ref '%s' already exists", ref);
146}
147
148static int replace_object_sha1(const char *object_ref,
149 unsigned char object[20],
150 const char *replace_ref,
151 unsigned char repl[20],
152 int force)
153{
154 unsigned char prev[20];
155 enum object_type obj_type, repl_type;
156 char ref[PATH_MAX];
157 struct ref_lock *lock;
158
159 obj_type = sha1_object_info(object, NULL);
160 repl_type = sha1_object_info(repl, NULL);
161 if (!force && obj_type != repl_type)
162 die("Objects must be of the same type.\n"
163 "'%s' points to a replaced object of type '%s'\n"
164 "while '%s' points to a replacement object of type '%s'.",
165 object_ref, typename(obj_type),
166 replace_ref, typename(repl_type));
167
168 check_ref_valid(object, prev, ref, sizeof(ref), force);
169
170 lock = lock_any_ref_for_update(ref, prev, 0, NULL);
171 if (!lock)
172 die("%s: cannot lock the ref", ref);
173 if (write_ref_sha1(lock, repl, NULL) < 0)
174 die("%s: cannot update the ref", ref);
175
176 return 0;
177}
178
179static int replace_object(const char *object_ref, const char *replace_ref, int force)
180{
181 unsigned char object[20], repl[20];
182
183 if (get_sha1(object_ref, object))
184 die("Failed to resolve '%s' as a valid ref.", object_ref);
185 if (get_sha1(replace_ref, repl))
186 die("Failed to resolve '%s' as a valid ref.", replace_ref);
187
188 return replace_object_sha1(object_ref, object, replace_ref, repl, force);
189}
190
191/*
192 * Write the contents of the object named by "sha1" to the file "filename",
193 * pretty-printed for human editing based on its type.
194 */
195static void export_object(const unsigned char *sha1, const char *filename)
196{
197 const char *argv[] = { "--no-replace-objects", "cat-file", "-p", NULL, NULL };
198 struct child_process cmd = { argv };
199 int fd;
200
201 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
202 if (fd < 0)
203 die_errno("unable to open %s for writing", filename);
204
205 argv[3] = sha1_to_hex(sha1);
206 cmd.git_cmd = 1;
207 cmd.out = fd;
208
209 if (run_command(&cmd))
210 die("cat-file reported failure");
211
212 close(fd);
213}
214
215/*
216 * Read a previously-exported (and possibly edited) object back from "filename",
217 * interpreting it as "type", and writing the result to the object database.
218 * The sha1 of the written object is returned via sha1.
219 */
220static void import_object(unsigned char *sha1, enum object_type type,
221 const char *filename)
222{
223 int fd;
224
225 fd = open(filename, O_RDONLY);
226 if (fd < 0)
227 die_errno("unable to open %s for reading", filename);
228
229 if (type == OBJ_TREE) {
230 const char *argv[] = { "mktree", NULL };
231 struct child_process cmd = { argv };
232 struct strbuf result = STRBUF_INIT;
233
234 cmd.argv = argv;
235 cmd.git_cmd = 1;
236 cmd.in = fd;
237 cmd.out = -1;
238
239 if (start_command(&cmd))
240 die("unable to spawn mktree");
241
242 if (strbuf_read(&result, cmd.out, 41) < 0)
243 die_errno("unable to read from mktree");
244 close(cmd.out);
245
246 if (finish_command(&cmd))
247 die("mktree reported failure");
248 if (get_sha1_hex(result.buf, sha1) < 0)
249 die("mktree did not return an object name");
250
251 strbuf_release(&result);
252 } else {
253 struct stat st;
254 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
255
256 if (fstat(fd, &st) < 0)
257 die_errno("unable to fstat %s", filename);
258 if (index_fd(sha1, fd, &st, type, NULL, flags) < 0)
259 die("unable to write object to database");
260 /* index_fd close()s fd for us */
261 }
262
263 /*
264 * No need to close(fd) here; both run-command and index-fd
265 * will have done it for us.
266 */
267}
268
269static int edit_and_replace(const char *object_ref, int force)
270{
271 char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
272 enum object_type type;
273 unsigned char old[20], new[20], prev[20];
274 char ref[PATH_MAX];
275
276 if (get_sha1(object_ref, old) < 0)
277 die("Not a valid object name: '%s'", object_ref);
278
279 type = sha1_object_info(old, NULL);
280 if (type < 0)
281 die("unable to get object type for %s", sha1_to_hex(old));
282
283 check_ref_valid(old, prev, ref, sizeof(ref), force);
284
285 export_object(old, tmpfile);
286 if (launch_editor(tmpfile, NULL, NULL) < 0)
287 die("editing object file failed");
288 import_object(new, type, tmpfile);
289
290 free(tmpfile);
291
292 if (!hashcmp(old, new))
293 return error("new object is the same as the old one: '%s'", sha1_to_hex(old));
294
295 return replace_object_sha1(object_ref, old, "replacement", new, force);
296}
297
298static void replace_parents(struct strbuf *buf, int argc, const char **argv)
299{
300 struct strbuf new_parents = STRBUF_INIT;
301 const char *parent_start, *parent_end;
302 int i;
303
304 /* find existing parents */
305 parent_start = buf->buf;
306 parent_start += 46; /* "tree " + "hex sha1" + "\n" */
307 parent_end = parent_start;
308
309 while (starts_with(parent_end, "parent "))
310 parent_end += 48; /* "parent " + "hex sha1" + "\n" */
311
312 /* prepare new parents */
313 for (i = 0; i < argc; i++) {
314 unsigned char sha1[20];
315 if (get_sha1(argv[i], sha1) < 0)
316 die(_("Not a valid object name: '%s'"), argv[i]);
317 lookup_commit_or_die(sha1, argv[i]);
318 strbuf_addf(&new_parents, "parent %s\n", sha1_to_hex(sha1));
319 }
320
321 /* replace existing parents with new ones */
322 strbuf_splice(buf, parent_start - buf->buf, parent_end - parent_start,
323 new_parents.buf, new_parents.len);
324
325 strbuf_release(&new_parents);
326}
327
328static int create_graft(int argc, const char **argv, int force)
329{
330 unsigned char old[20], new[20];
331 const char *old_ref = argv[0];
332 struct commit *commit;
333 struct strbuf buf = STRBUF_INIT;
334 const char *buffer;
335 unsigned long size;
336
337 if (get_sha1(old_ref, old) < 0)
338 die(_("Not a valid object name: '%s'"), old_ref);
339 commit = lookup_commit_or_die(old, old_ref);
340
341 buffer = get_commit_buffer(commit, &size);
342 strbuf_add(&buf, buffer, size);
343 unuse_commit_buffer(commit, buffer);
344
345 replace_parents(&buf, argc - 1, &argv[1]);
346
347 if (remove_signature(&buf)) {
348 warning(_("the original commit '%s' has a gpg signature."), old_ref);
349 warning(_("the signature will be removed in the replacement commit!"));
350 }
351
352 if (write_sha1_file(buf.buf, buf.len, commit_type, new))
353 die(_("could not write replacement commit for: '%s'"), old_ref);
354
355 strbuf_release(&buf);
356
357 if (!hashcmp(old, new))
358 return error("new commit is the same as the old one: '%s'", sha1_to_hex(old));
359
360 return replace_object_sha1(old_ref, old, "replacement", new, force);
361}
362
363int cmd_replace(int argc, const char **argv, const char *prefix)
364{
365 int force = 0;
366 const char *format = NULL;
367 enum {
368 MODE_UNSPECIFIED = 0,
369 MODE_LIST,
370 MODE_DELETE,
371 MODE_EDIT,
372 MODE_GRAFT,
373 MODE_REPLACE
374 } cmdmode = MODE_UNSPECIFIED;
375 struct option options[] = {
376 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
377 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
378 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
379 OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
380 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
381 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
382 OPT_END()
383 };
384
385 check_replace_refs = 0;
386
387 argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
388
389 if (!cmdmode)
390 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
391
392 if (format && cmdmode != MODE_LIST)
393 usage_msg_opt("--format cannot be used when not listing",
394 git_replace_usage, options);
395
396 if (force &&
397 cmdmode != MODE_REPLACE &&
398 cmdmode != MODE_EDIT &&
399 cmdmode != MODE_GRAFT)
400 usage_msg_opt("-f only makes sense when writing a replacement",
401 git_replace_usage, options);
402
403 switch (cmdmode) {
404 case MODE_DELETE:
405 if (argc < 1)
406 usage_msg_opt("-d needs at least one argument",
407 git_replace_usage, options);
408 return for_each_replace_name(argv, delete_replace_ref);
409
410 case MODE_REPLACE:
411 if (argc != 2)
412 usage_msg_opt("bad number of arguments",
413 git_replace_usage, options);
414 return replace_object(argv[0], argv[1], force);
415
416 case MODE_EDIT:
417 if (argc != 1)
418 usage_msg_opt("-e needs exactly one argument",
419 git_replace_usage, options);
420 return edit_and_replace(argv[0], force);
421
422 case MODE_GRAFT:
423 if (argc < 1)
424 usage_msg_opt("-g needs at least one argument",
425 git_replace_usage, options);
426 return create_graft(argc, argv, force);
427
428 case MODE_LIST:
429 if (argc > 1)
430 usage_msg_opt("only one pattern can be given with -l",
431 git_replace_usage, options);
432 return list_replace_refs(argv[0], format);
433
434 default:
435 die("BUG: invalid cmdmode %d", (int)cmdmode);
436 }
437}