update-ref: read commands in a line-wise fashion
[git] / builtin / update-ref.c
1 #include "cache.h"
2 #include "config.h"
3 #include "refs.h"
4 #include "builtin.h"
5 #include "parse-options.h"
6 #include "quote.h"
7 #include "argv-array.h"
8
9 static const char * const git_update_ref_usage[] = {
10         N_("git update-ref [<options>] -d <refname> [<old-val>]"),
11         N_("git update-ref [<options>]    <refname> <new-val> [<old-val>]"),
12         N_("git update-ref [<options>] --stdin [-z]"),
13         NULL
14 };
15
16 static char line_termination = '\n';
17 static unsigned int update_flags;
18 static unsigned int default_flags;
19 static unsigned create_reflog_flag;
20 static const char *msg;
21
22 /*
23  * Parse one whitespace- or NUL-terminated, possibly C-quoted argument
24  * and append the result to arg.  Return a pointer to the terminator.
25  * Die if there is an error in how the argument is C-quoted.  This
26  * function is only used if not -z.
27  */
28 static const char *parse_arg(const char *next, struct strbuf *arg)
29 {
30         if (*next == '"') {
31                 const char *orig = next;
32
33                 if (unquote_c_style(arg, next, &next))
34                         die("badly quoted argument: %s", orig);
35                 if (*next && !isspace(*next))
36                         die("unexpected character after quoted argument: %s", orig);
37         } else {
38                 while (*next && !isspace(*next))
39                         strbuf_addch(arg, *next++);
40         }
41
42         return next;
43 }
44
45 /*
46  * Parse the reference name immediately after "command SP".  If not
47  * -z, then handle C-quoting.  Return a pointer to a newly allocated
48  * string containing the name of the reference, or NULL if there was
49  * an error.  Update *next to point at the character that terminates
50  * the argument.  Die if C-quoting is malformed or the reference name
51  * is invalid.
52  */
53 static char *parse_refname(const char **next)
54 {
55         struct strbuf ref = STRBUF_INIT;
56
57         if (line_termination) {
58                 /* Without -z, use the next argument */
59                 *next = parse_arg(*next, &ref);
60         } else {
61                 /* With -z, use everything up to the next NUL */
62                 strbuf_addstr(&ref, *next);
63                 *next += ref.len;
64         }
65
66         if (!ref.len) {
67                 strbuf_release(&ref);
68                 return NULL;
69         }
70
71         if (check_refname_format(ref.buf, REFNAME_ALLOW_ONELEVEL))
72                 die("invalid ref format: %s", ref.buf);
73
74         return strbuf_detach(&ref, NULL);
75 }
76
77 /*
78  * The value being parsed is <oldvalue> (as opposed to <newvalue>; the
79  * difference affects which error messages are generated):
80  */
81 #define PARSE_SHA1_OLD 0x01
82
83 /*
84  * For backwards compatibility, accept an empty string for update's
85  * <newvalue> in binary mode to be equivalent to specifying zeros.
86  */
87 #define PARSE_SHA1_ALLOW_EMPTY 0x02
88
89 /*
90  * Parse an argument separator followed by the next argument, if any.
91  * If there is an argument, convert it to a SHA-1, write it to sha1,
92  * set *next to point at the character terminating the argument, and
93  * return 0.  If there is no argument at all (not even the empty
94  * string), return 1 and leave *next unchanged.  If the value is
95  * provided but cannot be converted to a SHA-1, die.  flags can
96  * include PARSE_SHA1_OLD and/or PARSE_SHA1_ALLOW_EMPTY.
97  */
98 static int parse_next_oid(const char **next, const char *end,
99                           struct object_id *oid,
100                           const char *command, const char *refname,
101                           int flags)
102 {
103         struct strbuf arg = STRBUF_INIT;
104         int ret = 0;
105
106         if (*next == end)
107                 goto eof;
108
109         if (line_termination) {
110                 /* Without -z, consume SP and use next argument */
111                 if (!**next || **next == line_termination)
112                         return 1;
113                 if (**next != ' ')
114                         die("%s %s: expected SP but got: %s",
115                             command, refname, *next);
116                 (*next)++;
117                 *next = parse_arg(*next, &arg);
118                 if (arg.len) {
119                         if (get_oid(arg.buf, oid))
120                                 goto invalid;
121                 } else {
122                         /* Without -z, an empty value means all zeros: */
123                         oidclr(oid);
124                 }
125         } else {
126                 /* With -z, read the next NUL-terminated line */
127                 if (**next)
128                         die("%s %s: expected NUL but got: %s",
129                             command, refname, *next);
130                 (*next)++;
131                 if (*next == end)
132                         goto eof;
133                 strbuf_addstr(&arg, *next);
134                 *next += arg.len;
135
136                 if (arg.len) {
137                         if (get_oid(arg.buf, oid))
138                                 goto invalid;
139                 } else if (flags & PARSE_SHA1_ALLOW_EMPTY) {
140                         /* With -z, treat an empty value as all zeros: */
141                         warning("%s %s: missing <newvalue>, treating as zero",
142                                 command, refname);
143                         oidclr(oid);
144                 } else {
145                         /*
146                          * With -z, an empty non-required value means
147                          * unspecified:
148                          */
149                         ret = 1;
150                 }
151         }
152
153         strbuf_release(&arg);
154
155         return ret;
156
157  invalid:
158         die(flags & PARSE_SHA1_OLD ?
159             "%s %s: invalid <oldvalue>: %s" :
160             "%s %s: invalid <newvalue>: %s",
161             command, refname, arg.buf);
162
163  eof:
164         die(flags & PARSE_SHA1_OLD ?
165             "%s %s: unexpected end of input when reading <oldvalue>" :
166             "%s %s: unexpected end of input when reading <newvalue>",
167             command, refname);
168 }
169
170
171 /*
172  * The following five parse_cmd_*() functions parse the corresponding
173  * command.  In each case, next points at the character following the
174  * command name and the following space.  They each return a pointer
175  * to the character terminating the command, and die with an
176  * explanatory message if there are any parsing problems.  All of
177  * these functions handle either text or binary format input,
178  * depending on how line_termination is set.
179  */
180
181 static void parse_cmd_update(struct ref_transaction *transaction,
182                              const char *next, const char *end)
183 {
184         struct strbuf err = STRBUF_INIT;
185         char *refname;
186         struct object_id new_oid, old_oid;
187         int have_old;
188
189         refname = parse_refname(&next);
190         if (!refname)
191                 die("update: missing <ref>");
192
193         if (parse_next_oid(&next, end, &new_oid, "update", refname,
194                            PARSE_SHA1_ALLOW_EMPTY))
195                 die("update %s: missing <newvalue>", refname);
196
197         have_old = !parse_next_oid(&next, end, &old_oid, "update", refname,
198                                    PARSE_SHA1_OLD);
199
200         if (*next != line_termination)
201                 die("update %s: extra input: %s", refname, next);
202
203         if (ref_transaction_update(transaction, refname,
204                                    &new_oid, have_old ? &old_oid : NULL,
205                                    update_flags | create_reflog_flag,
206                                    msg, &err))
207                 die("%s", err.buf);
208
209         update_flags = default_flags;
210         free(refname);
211         strbuf_release(&err);
212 }
213
214 static void parse_cmd_create(struct ref_transaction *transaction,
215                              const char *next, const char *end)
216 {
217         struct strbuf err = STRBUF_INIT;
218         char *refname;
219         struct object_id new_oid;
220
221         refname = parse_refname(&next);
222         if (!refname)
223                 die("create: missing <ref>");
224
225         if (parse_next_oid(&next, end, &new_oid, "create", refname, 0))
226                 die("create %s: missing <newvalue>", refname);
227
228         if (is_null_oid(&new_oid))
229                 die("create %s: zero <newvalue>", refname);
230
231         if (*next != line_termination)
232                 die("create %s: extra input: %s", refname, next);
233
234         if (ref_transaction_create(transaction, refname, &new_oid,
235                                    update_flags | create_reflog_flag,
236                                    msg, &err))
237                 die("%s", err.buf);
238
239         update_flags = default_flags;
240         free(refname);
241         strbuf_release(&err);
242 }
243
244 static void parse_cmd_delete(struct ref_transaction *transaction,
245                              const char *next, const char *end)
246 {
247         struct strbuf err = STRBUF_INIT;
248         char *refname;
249         struct object_id old_oid;
250         int have_old;
251
252         refname = parse_refname(&next);
253         if (!refname)
254                 die("delete: missing <ref>");
255
256         if (parse_next_oid(&next, end, &old_oid, "delete", refname,
257                            PARSE_SHA1_OLD)) {
258                 have_old = 0;
259         } else {
260                 if (is_null_oid(&old_oid))
261                         die("delete %s: zero <oldvalue>", refname);
262                 have_old = 1;
263         }
264
265         if (*next != line_termination)
266                 die("delete %s: extra input: %s", refname, next);
267
268         if (ref_transaction_delete(transaction, refname,
269                                    have_old ? &old_oid : NULL,
270                                    update_flags, msg, &err))
271                 die("%s", err.buf);
272
273         update_flags = default_flags;
274         free(refname);
275         strbuf_release(&err);
276 }
277
278 static void parse_cmd_verify(struct ref_transaction *transaction,
279                              const char *next, const char *end)
280 {
281         struct strbuf err = STRBUF_INIT;
282         char *refname;
283         struct object_id old_oid;
284
285         refname = parse_refname(&next);
286         if (!refname)
287                 die("verify: missing <ref>");
288
289         if (parse_next_oid(&next, end, &old_oid, "verify", refname,
290                            PARSE_SHA1_OLD))
291                 oidclr(&old_oid);
292
293         if (*next != line_termination)
294                 die("verify %s: extra input: %s", refname, next);
295
296         if (ref_transaction_verify(transaction, refname, &old_oid,
297                                    update_flags, &err))
298                 die("%s", err.buf);
299
300         update_flags = default_flags;
301         free(refname);
302         strbuf_release(&err);
303 }
304
305 static void parse_cmd_option(struct ref_transaction *transaction,
306                              const char *next, const char *end)
307 {
308         const char *rest;
309         if (skip_prefix(next, "no-deref", &rest) && *rest == line_termination)
310                 update_flags |= REF_NO_DEREF;
311         else
312                 die("option unknown: %s", next);
313 }
314
315 static const struct parse_cmd {
316         const char *prefix;
317         void (*fn)(struct ref_transaction *, const char *, const char *);
318         unsigned args;
319 } command[] = {
320         { "update", parse_cmd_update, 3 },
321         { "create", parse_cmd_create, 2 },
322         { "delete", parse_cmd_delete, 2 },
323         { "verify", parse_cmd_verify, 2 },
324         { "option", parse_cmd_option, 1 },
325 };
326
327 static void update_refs_stdin(void)
328 {
329         struct strbuf input = STRBUF_INIT, err = STRBUF_INIT;
330         struct ref_transaction *transaction;
331         int i, j;
332
333         transaction = ref_transaction_begin(&err);
334         if (!transaction)
335                 die("%s", err.buf);
336
337         /* Read each line dispatch its command */
338         while (!strbuf_getwholeline(&input, stdin, line_termination)) {
339                 const struct parse_cmd *cmd = NULL;
340
341                 if (*input.buf == line_termination)
342                         die("empty command in input");
343                 else if (isspace(*input.buf))
344                         die("whitespace before command: %s", input.buf);
345
346                 for (i = 0; i < ARRAY_SIZE(command); i++) {
347                         const char *prefix = command[i].prefix;
348                         char c;
349
350                         if (!starts_with(input.buf, prefix))
351                                 continue;
352
353                         /*
354                          * If the command has arguments, verify that it's
355                          * followed by a space. Otherwise, it shall be followed
356                          * by a line terminator.
357                          */
358                         c = command[i].args ? ' ' : line_termination;
359                         if (input.buf[strlen(prefix)] != c)
360                                 continue;
361
362                         cmd = &command[i];
363                         break;
364                 }
365                 if (!cmd)
366                         die("unknown command: %s", input.buf);
367
368                 /*
369                  * Read additional arguments if NUL-terminated. Do not raise an
370                  * error in case there is an early EOF to let the command
371                  * handle missing arguments with a proper error message.
372                  */
373                 for (j = 1; line_termination == '\0' && j < cmd->args; j++)
374                         if (strbuf_appendwholeline(&input, stdin, line_termination))
375                                 break;
376
377                 cmd->fn(transaction, input.buf + strlen(cmd->prefix) + !!cmd->args,
378                         input.buf + input.len);
379         }
380
381         if (ref_transaction_commit(transaction, &err))
382                 die("%s", err.buf);
383
384         ref_transaction_free(transaction);
385         strbuf_release(&err);
386         strbuf_release(&input);
387 }
388
389 int cmd_update_ref(int argc, const char **argv, const char *prefix)
390 {
391         const char *refname, *oldval;
392         struct object_id oid, oldoid;
393         int delete = 0, no_deref = 0, read_stdin = 0, end_null = 0;
394         int create_reflog = 0;
395         struct option options[] = {
396                 OPT_STRING( 'm', NULL, &msg, N_("reason"), N_("reason of the update")),
397                 OPT_BOOL('d', NULL, &delete, N_("delete the reference")),
398                 OPT_BOOL( 0 , "no-deref", &no_deref,
399                                         N_("update <refname> not the one it points to")),
400                 OPT_BOOL('z', NULL, &end_null, N_("stdin has NUL-terminated arguments")),
401                 OPT_BOOL( 0 , "stdin", &read_stdin, N_("read updates from stdin")),
402                 OPT_BOOL( 0 , "create-reflog", &create_reflog, N_("create a reflog")),
403                 OPT_END(),
404         };
405
406         git_config(git_default_config, NULL);
407         argc = parse_options(argc, argv, prefix, options, git_update_ref_usage,
408                              0);
409         if (msg && !*msg)
410                 die("Refusing to perform update with empty message.");
411
412         create_reflog_flag = create_reflog ? REF_FORCE_CREATE_REFLOG : 0;
413
414         if (no_deref) {
415                 default_flags = REF_NO_DEREF;
416                 update_flags = default_flags;
417         }
418
419         if (read_stdin) {
420                 if (delete || argc > 0)
421                         usage_with_options(git_update_ref_usage, options);
422                 if (end_null)
423                         line_termination = '\0';
424                 update_refs_stdin();
425                 return 0;
426         }
427
428         if (end_null)
429                 usage_with_options(git_update_ref_usage, options);
430
431         if (delete) {
432                 if (argc < 1 || argc > 2)
433                         usage_with_options(git_update_ref_usage, options);
434                 refname = argv[0];
435                 oldval = argv[1];
436         } else {
437                 const char *value;
438                 if (argc < 2 || argc > 3)
439                         usage_with_options(git_update_ref_usage, options);
440                 refname = argv[0];
441                 value = argv[1];
442                 oldval = argv[2];
443                 if (get_oid(value, &oid))
444                         die("%s: not a valid SHA1", value);
445         }
446
447         if (oldval) {
448                 if (!*oldval)
449                         /*
450                          * The empty string implies that the reference
451                          * must not already exist:
452                          */
453                         oidclr(&oldoid);
454                 else if (get_oid(oldval, &oldoid))
455                         die("%s: not a valid old SHA1", oldval);
456         }
457
458         if (delete)
459                 /*
460                  * For purposes of backwards compatibility, we treat
461                  * NULL_SHA1 as "don't care" here:
462                  */
463                 return delete_ref(msg, refname,
464                                   (oldval && !is_null_oid(&oldoid)) ? &oldoid : NULL,
465                                   default_flags);
466         else
467                 return update_ref(msg, refname, &oid, oldval ? &oldoid : NULL,
468                                   default_flags | create_reflog_flag,
469                                   UPDATE_REFS_DIE_ON_ERR);
470 }