replace.c: use the ref transaction functions for updates
[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 "builtin.h"
13 #include "refs.h"
14 #include "parse-options.h"
15 #include "run-command.h"
16
17 static const char * const git_replace_usage[] = {
18         N_("git replace [-f] <object> <replacement>"),
19         N_("git replace [-f] --edit <object>"),
20         N_("git replace -d <object>..."),
21         N_("git replace [--format=<format>] [-l [<pattern>]]"),
22         NULL
23 };
24
25 enum replace_format {
26       REPLACE_FORMAT_SHORT,
27       REPLACE_FORMAT_MEDIUM,
28       REPLACE_FORMAT_LONG
29 };
30
31 struct show_data {
32         const char *pattern;
33         enum replace_format format;
34 };
35
36 static int show_reference(const char *refname, const unsigned char *sha1,
37                           int flag, void *cb_data)
38 {
39         struct show_data *data = cb_data;
40
41         if (!wildmatch(data->pattern, refname, 0, NULL)) {
42                 if (data->format == REPLACE_FORMAT_SHORT)
43                         printf("%s\n", refname);
44                 else if (data->format == REPLACE_FORMAT_MEDIUM)
45                         printf("%s -> %s\n", refname, sha1_to_hex(sha1));
46                 else { /* data->format == REPLACE_FORMAT_LONG */
47                         unsigned char object[20];
48                         enum object_type obj_type, repl_type;
49
50                         if (get_sha1(refname, object))
51                                 return error("Failed to resolve '%s' as a valid ref.", refname);
52
53                         obj_type = sha1_object_info(object, NULL);
54                         repl_type = sha1_object_info(sha1, NULL);
55
56                         printf("%s (%s) -> %s (%s)\n", refname, typename(obj_type),
57                                sha1_to_hex(sha1), typename(repl_type));
58                 }
59         }
60
61         return 0;
62 }
63
64 static int list_replace_refs(const char *pattern, const char *format)
65 {
66         struct show_data data;
67
68         if (pattern == NULL)
69                 pattern = "*";
70         data.pattern = pattern;
71
72         if (format == NULL || *format == '\0' || !strcmp(format, "short"))
73                 data.format = REPLACE_FORMAT_SHORT;
74         else if (!strcmp(format, "medium"))
75                 data.format = REPLACE_FORMAT_MEDIUM;
76         else if (!strcmp(format, "long"))
77                 data.format = REPLACE_FORMAT_LONG;
78         else
79                 die("invalid replace format '%s'\n"
80                     "valid formats are 'short', 'medium' and 'long'\n",
81                     format);
82
83         for_each_replace_ref(show_reference, (void *) &data);
84
85         return 0;
86 }
87
88 typedef int (*each_replace_name_fn)(const char *name, const char *ref,
89                                     const unsigned char *sha1);
90
91 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
92 {
93         const char **p, *full_hex;
94         char ref[PATH_MAX];
95         int had_error = 0;
96         unsigned char sha1[20];
97
98         for (p = argv; *p; p++) {
99                 if (get_sha1(*p, sha1)) {
100                         error("Failed to resolve '%s' as a valid ref.", *p);
101                         had_error = 1;
102                         continue;
103                 }
104                 full_hex = sha1_to_hex(sha1);
105                 snprintf(ref, sizeof(ref), "refs/replace/%s", full_hex);
106                 /* read_ref() may reuse the buffer */
107                 full_hex = ref + strlen("refs/replace/");
108                 if (read_ref(ref, sha1)) {
109                         error("replace ref '%s' not found.", full_hex);
110                         had_error = 1;
111                         continue;
112                 }
113                 if (fn(full_hex, ref, sha1))
114                         had_error = 1;
115         }
116         return had_error;
117 }
118
119 static int delete_replace_ref(const char *name, const char *ref,
120                               const unsigned char *sha1)
121 {
122         if (delete_ref(ref, sha1, 0))
123                 return 1;
124         printf("Deleted replace ref '%s'\n", name);
125         return 0;
126 }
127
128 static void check_ref_valid(unsigned char object[20],
129                             unsigned char prev[20],
130                             char *ref,
131                             int ref_size,
132                             int force)
133 {
134         if (snprintf(ref, ref_size,
135                      "refs/replace/%s",
136                      sha1_to_hex(object)) > ref_size - 1)
137                 die("replace ref name too long: %.*s...", 50, ref);
138         if (check_refname_format(ref, 0))
139                 die("'%s' is not a valid ref name.", ref);
140
141         if (read_ref(ref, prev))
142                 hashclr(prev);
143         else if (!force)
144                 die("replace ref '%s' already exists", ref);
145 }
146
147 static int replace_object_sha1(const char *object_ref,
148                                unsigned char object[20],
149                                const char *replace_ref,
150                                unsigned char repl[20],
151                                int force)
152 {
153         unsigned char prev[20];
154         enum object_type obj_type, repl_type;
155         char ref[PATH_MAX];
156         struct ref_transaction *transaction;
157         struct strbuf err = STRBUF_INIT;
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         transaction = ref_transaction_begin(&err);
171         if (!transaction ||
172             ref_transaction_update(transaction, ref, repl, prev, 0, 1, &err) ||
173             ref_transaction_commit(transaction, NULL, &err))
174                 die("%s", err.buf);
175
176         ref_transaction_free(transaction);
177         return 0;
178 }
179
180 static int replace_object(const char *object_ref, const char *replace_ref, int force)
181 {
182         unsigned char object[20], repl[20];
183
184         if (get_sha1(object_ref, object))
185                 die("Failed to resolve '%s' as a valid ref.", object_ref);
186         if (get_sha1(replace_ref, repl))
187                 die("Failed to resolve '%s' as a valid ref.", replace_ref);
188
189         return replace_object_sha1(object_ref, object, replace_ref, repl, force);
190 }
191
192 /*
193  * Write the contents of the object named by "sha1" to the file "filename",
194  * pretty-printed for human editing based on its type.
195  */
196 static void export_object(const unsigned char *sha1, const char *filename)
197 {
198         const char *argv[] = { "--no-replace-objects", "cat-file", "-p", NULL, NULL };
199         struct child_process cmd = { argv };
200         int fd;
201
202         fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
203         if (fd < 0)
204                 die_errno("unable to open %s for writing", filename);
205
206         argv[3] = sha1_to_hex(sha1);
207         cmd.git_cmd = 1;
208         cmd.out = fd;
209
210         if (run_command(&cmd))
211                 die("cat-file reported failure");
212
213         close(fd);
214 }
215
216 /*
217  * Read a previously-exported (and possibly edited) object back from "filename",
218  * interpreting it as "type", and writing the result to the object database.
219  * The sha1 of the written object is returned via sha1.
220  */
221 static void import_object(unsigned char *sha1, enum object_type type,
222                           const char *filename)
223 {
224         int fd;
225
226         fd = open(filename, O_RDONLY);
227         if (fd < 0)
228                 die_errno("unable to open %s for reading", filename);
229
230         if (type == OBJ_TREE) {
231                 const char *argv[] = { "mktree", NULL };
232                 struct child_process cmd = { argv };
233                 struct strbuf result = STRBUF_INIT;
234
235                 cmd.argv = argv;
236                 cmd.git_cmd = 1;
237                 cmd.in = fd;
238                 cmd.out = -1;
239
240                 if (start_command(&cmd))
241                         die("unable to spawn mktree");
242
243                 if (strbuf_read(&result, cmd.out, 41) < 0)
244                         die_errno("unable to read from mktree");
245                 close(cmd.out);
246
247                 if (finish_command(&cmd))
248                         die("mktree reported failure");
249                 if (get_sha1_hex(result.buf, sha1) < 0)
250                         die("mktree did not return an object name");
251
252                 strbuf_release(&result);
253         } else {
254                 struct stat st;
255                 int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
256
257                 if (fstat(fd, &st) < 0)
258                         die_errno("unable to fstat %s", filename);
259                 if (index_fd(sha1, fd, &st, type, NULL, flags) < 0)
260                         die("unable to write object to database");
261                 /* index_fd close()s fd for us */
262         }
263
264         /*
265          * No need to close(fd) here; both run-command and index-fd
266          * will have done it for us.
267          */
268 }
269
270 static int edit_and_replace(const char *object_ref, int force)
271 {
272         char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
273         enum object_type type;
274         unsigned char old[20], new[20], prev[20];
275         char ref[PATH_MAX];
276
277         if (get_sha1(object_ref, old) < 0)
278                 die("Not a valid object name: '%s'", object_ref);
279
280         type = sha1_object_info(old, NULL);
281         if (type < 0)
282                 die("unable to get object type for %s", sha1_to_hex(old));
283
284         check_ref_valid(old, prev, ref, sizeof(ref), force);
285
286         export_object(old, tmpfile);
287         if (launch_editor(tmpfile, NULL, NULL) < 0)
288                 die("editing object file failed");
289         import_object(new, type, tmpfile);
290
291         free(tmpfile);
292
293         if (!hashcmp(old, new))
294                 return error("new object is the same as the old one: '%s'", sha1_to_hex(old));
295
296         return replace_object_sha1(object_ref, old, "replacement", new, force);
297 }
298
299 int cmd_replace(int argc, const char **argv, const char *prefix)
300 {
301         int force = 0;
302         const char *format = NULL;
303         enum {
304                 MODE_UNSPECIFIED = 0,
305                 MODE_LIST,
306                 MODE_DELETE,
307                 MODE_EDIT,
308                 MODE_REPLACE
309         } cmdmode = MODE_UNSPECIFIED;
310         struct option options[] = {
311                 OPT_CMDMODE('l', "list", &cmdmode, N_("list replace refs"), MODE_LIST),
312                 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
313                 OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
314                 OPT_BOOL('f', "force", &force, N_("replace the ref if it exists")),
315                 OPT_STRING(0, "format", &format, N_("format"), N_("use this format")),
316                 OPT_END()
317         };
318
319         check_replace_refs = 0;
320
321         argc = parse_options(argc, argv, prefix, options, git_replace_usage, 0);
322
323         if (!cmdmode)
324                 cmdmode = argc ? MODE_REPLACE : MODE_LIST;
325
326         if (format && cmdmode != MODE_LIST)
327                 usage_msg_opt("--format cannot be used when not listing",
328                               git_replace_usage, options);
329
330         if (force && cmdmode != MODE_REPLACE && cmdmode != MODE_EDIT)
331                 usage_msg_opt("-f only makes sense when writing a replacement",
332                               git_replace_usage, options);
333
334         switch (cmdmode) {
335         case MODE_DELETE:
336                 if (argc < 1)
337                         usage_msg_opt("-d needs at least one argument",
338                                       git_replace_usage, options);
339                 return for_each_replace_name(argv, delete_replace_ref);
340
341         case MODE_REPLACE:
342                 if (argc != 2)
343                         usage_msg_opt("bad number of arguments",
344                                       git_replace_usage, options);
345                 return replace_object(argv[0], argv[1], force);
346
347         case MODE_EDIT:
348                 if (argc != 1)
349                         usage_msg_opt("-e needs exactly one argument",
350                                       git_replace_usage, options);
351                 return edit_and_replace(argv[0], force);
352
353         case MODE_LIST:
354                 if (argc > 1)
355                         usage_msg_opt("only one pattern can be given with -l",
356                                       git_replace_usage, options);
357                 return list_replace_refs(argv[0], format);
358
359         default:
360                 die("BUG: invalid cmdmode %d", (int)cmdmode);
361         }
362 }