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