builtin-update-ref.con commit Merge branch 'ml/trace' (d3ba675)
   1#include "cache.h"
   2#include "refs.h"
   3#include "builtin.h"
   4
   5static const char git_update_ref_usage[] =
   6"git-update-ref <refname> <value> [<oldval>] [-m <reason>]";
   7
   8int cmd_update_ref(int argc, const char **argv, char **envp)
   9{
  10        const char *refname=NULL, *value=NULL, *oldval=NULL, *msg=NULL;
  11        struct ref_lock *lock;
  12        unsigned char sha1[20], oldsha1[20];
  13        int i;
  14
  15        setup_ident();
  16        setup_git_directory();
  17        git_config(git_default_config);
  18
  19        for (i = 1; i < argc; i++) {
  20                if (!strcmp("-m", argv[i])) {
  21                        if (i+1 >= argc)
  22                                usage(git_update_ref_usage);
  23                        msg = argv[++i];
  24                        if (!*msg)
  25                                die("Refusing to perform update with empty message.");
  26                        if (strchr(msg, '\n'))
  27                                die("Refusing to perform update with \\n in message.");
  28                        continue;
  29                }
  30                if (!refname) {
  31                        refname = argv[i];
  32                        continue;
  33                }
  34                if (!value) {
  35                        value = argv[i];
  36                        continue;
  37                }
  38                if (!oldval) {
  39                        oldval = argv[i];
  40                        continue;
  41                }
  42        }
  43        if (!refname || !value)
  44                usage(git_update_ref_usage);
  45
  46        if (get_sha1(value, sha1))
  47                die("%s: not a valid SHA1", value);
  48        memset(oldsha1, 0, 20);
  49        if (oldval && get_sha1(oldval, oldsha1))
  50                die("%s: not a valid old SHA1", oldval);
  51
  52        lock = lock_any_ref_for_update(refname, oldval ? oldsha1 : NULL, 0);
  53        if (!lock)
  54                return 1;
  55        if (write_ref_sha1(lock, sha1, msg) < 0)
  56                return 1;
  57
  58        /* write_ref_sha1 always unlocks the ref, no need to do it explicitly */
  59        return 0;
  60}