Raw
1 /*
2 * "git mv" builtin command
3 *
4 * Copyright (C) 2006 Johannes Schindelin
5 */
6
7 #define USE_THE_REPOSITORY_VARIABLE
8 #define DISABLE_SIGN_COMPARE_WARNINGS
9
10 #include "builtin.h"
11 #include "abspath.h"
12 #include "advice.h"
13 #include "config.h"
14 #include "environment.h"
15 #include "gettext.h"
16 #include "name-hash.h"
17 #include "object-file.h"
18 #include "path.h"
19 #include "pathspec.h"
20 #include "lockfile.h"
21 #include "dir.h"
22 #include "string-list.h"
23 #include "parse-options.h"
24 #include "read-cache-ll.h"
25
26 #include "setup.h"
27 #include "strvec.h"
28 #include "submodule.h"
29 #include "entry.h"
30
31 static const char * const builtin_mv_usage[] = {
32 N_("git mv [-v] [-f] [-n] [-k] <source> <destination>"),
33 N_("git mv [-v] [-f] [-n] [-k] <source>... <destination-directory>"),
34 NULL
35 };
36
37 enum update_mode {
38 WORKING_DIRECTORY = (1 << 1),
39 INDEX = (1 << 2),
40 SPARSE = (1 << 3),
41 SKIP_WORKTREE_DIR = (1 << 4),
42 /*
43 * A file gets moved implicitly via a move of one of its parent
44 * directories. This flag causes us to skip the check that we don't try
45 * to move a file and any of its parent directories at the same point
46 * in time.
47 */
48 MOVE_VIA_PARENT_DIR = (1 << 5),
49 };
50
51 #define DUP_BASENAME 1
52 #define KEEP_TRAILING_SLASH 2
53
54 static void internal_prefix_pathspec(struct strvec *out,
55 const char *prefix,
56 const char **pathspec,
57 int count, unsigned flags)
58 {
59 int prefixlen = prefix ? strlen(prefix) : 0;
60
61 /* Create an intermediate copy of the pathspec based on the flags */
62 for (int i = 0; i < count; i++) {
63 size_t length = strlen(pathspec[i]);
64 size_t to_copy = length;
65 const char *maybe_basename;
66 char *trimmed, *prefixed_path;
67
68 while (!(flags & KEEP_TRAILING_SLASH) &&
69 to_copy > 0 && is_dir_sep(pathspec[i][to_copy - 1]))
70 to_copy--;
71
72 trimmed = xmemdupz(pathspec[i], to_copy);
73 maybe_basename = (flags & DUP_BASENAME) ? basename(trimmed) : trimmed;
74 prefixed_path = prefix_path(the_repository, prefix, prefixlen, maybe_basename);
75 strvec_push(out, prefixed_path);
76
77 free(prefixed_path);
78 free(trimmed);
79 }
80 }
81
82 static char *add_slash(const char *path)
83 {
84 size_t len = strlen(path);
85 if (len && path[len - 1] != '/') {
86 char *with_slash = xmalloc(st_add(len, 2));
87 memcpy(with_slash, path, len);
88 with_slash[len++] = '/';
89 with_slash[len] = 0;
90 return with_slash;
91 }
92 return xstrdup(path);
93 }
94
95 #define SUBMODULE_WITH_GITDIR ((const char *)1)
96
97 static const char *submodule_gitfile_path(const char *src, int first)
98 {
99 struct strbuf submodule_dotgit = STRBUF_INIT;
100 const char *path;
101
102 if (!S_ISGITLINK(the_repository->index->cache[first]->ce_mode))
103 die(_("Directory %s is in index and no submodule?"), src);
104 if (!is_staging_gitmodules_ok(the_repository->index))
105 die(_("Please stage your changes to .gitmodules or stash them to proceed"));
106
107 strbuf_addf(&submodule_dotgit, "%s/.git", src);
108
109 path = read_gitfile(submodule_dotgit.buf);
110 strbuf_release(&submodule_dotgit);
111 if (path)
112 return path;
113 return SUBMODULE_WITH_GITDIR;
114 }
115
116 static int index_range_of_same_dir(const char *src, int length,
117 int *first_p, int *last_p)
118 {
119 char *src_w_slash = add_slash(src);
120 int first, last, len_w_slash = length + 1;
121
122 first = index_name_pos(the_repository->index, src_w_slash, len_w_slash);
123 if (first >= 0)
124 die(_("%.*s is in index"), len_w_slash, src_w_slash);
125
126 first = -1 - first;
127 for (last = first; last < the_repository->index->cache_nr; last++) {
128 const char *path = the_repository->index->cache[last]->name;
129 if (strncmp(path, src_w_slash, len_w_slash))
130 break;
131 }
132
133 free(src_w_slash);
134 *first_p = first;
135 *last_p = last;
136 return last - first;
137 }
138
139 /*
140 * Given the path of a directory that does not exist on-disk, check whether the
141 * directory contains any entries in the index with the SKIP_WORKTREE flag
142 * enabled.
143 * Return 1 if such index entries exist.
144 * Return 0 otherwise.
145 */
146 static int empty_dir_has_sparse_contents(const char *name)
147 {
148 int ret = 0;
149 char *with_slash = add_slash(name);
150 int length = strlen(with_slash);
151
152 int pos = index_name_pos(the_repository->index, with_slash, length);
153 const struct cache_entry *ce;
154
155 if (pos < 0) {
156 pos = -pos - 1;
157 if (pos >= the_repository->index->cache_nr)
158 goto free_return;
159 ce = the_repository->index->cache[pos];
160 if (strncmp(with_slash, ce->name, length))
161 goto free_return;
162 if (ce_skip_worktree(ce))
163 ret = 1;
164 }
165
166 free_return:
167 free(with_slash);
168 return ret;
169 }
170
171 static void remove_empty_src_dirs(const char **src_dir, size_t src_dir_nr)
172 {
173 size_t i;
174 struct strbuf a_src_dir = STRBUF_INIT;
175
176 for (i = 0; i < src_dir_nr; i++) {
177 int dummy;
178 strbuf_addstr(&a_src_dir, src_dir[i]);
179 /*
180 * if entries under a_src_dir are all moved away,
181 * recursively remove a_src_dir to cleanup
182 */
183 if (index_range_of_same_dir(a_src_dir.buf, a_src_dir.len,
184 &dummy, &dummy) < 1) {
185 remove_dir_recursively(&a_src_dir, 0);
186 }
187 strbuf_reset(&a_src_dir);
188 }
189
190 strbuf_release(&a_src_dir);
191 }
192
193 struct pathmap_entry {
194 struct hashmap_entry ent;
195 const char *path;
196 };
197
198 static int pathmap_cmp(const void *cmp_data UNUSED,
199 const struct hashmap_entry *a,
200 const struct hashmap_entry *b,
201 const void *key UNUSED)
202 {
203 const struct pathmap_entry *e1 = container_of(a, struct pathmap_entry, ent);
204 const struct pathmap_entry *e2 = container_of(b, struct pathmap_entry, ent);
205 return fspathcmp(e1->path, e2->path);
206 }
207
208 int cmd_mv(int argc,
209 const char **argv,
210 const char *prefix,
211 struct repository *repo UNUSED)
212 {
213 int i, flags, gitmodules_modified = 0;
214 int verbose = 0, show_only = 0, force = 0, ignore_errors = 0, ignore_sparse = 0;
215 struct option builtin_mv_options[] = {
216 OPT__VERBOSE(&verbose, N_("be verbose")),
217 OPT__DRY_RUN(&show_only, N_("dry run")),
218 OPT__FORCE(&force, N_("force move/rename even if target exists"),
219 PARSE_OPT_NOCOMPLETE),
220 OPT_BOOL('k', NULL, &ignore_errors, N_("skip move/rename errors")),
221 OPT_BOOL(0, "sparse", &ignore_sparse, N_("allow updating entries outside of the sparse-checkout cone")),
222 OPT_END(),
223 };
224 struct strvec sources = STRVEC_INIT;
225 struct strvec dest_paths = STRVEC_INIT;
226 struct strvec destinations = STRVEC_INIT;
227 struct strvec submodule_gitfiles_to_free = STRVEC_INIT;
228 const char **submodule_gitfiles;
229 char *dst_w_slash = NULL;
230 struct strvec src_dir = STRVEC_INIT;
231 enum update_mode *modes, dst_mode = 0;
232 struct stat st, dest_st;
233 struct string_list src_for_dst = STRING_LIST_INIT_DUP;
234 struct lock_file lock_file = LOCK_INIT;
235 struct cache_entry *ce;
236 struct string_list only_match_skip_worktree = STRING_LIST_INIT_DUP;
237 struct string_list dirty_paths = STRING_LIST_INIT_DUP;
238 struct hashmap moved_dirs = HASHMAP_INIT(pathmap_cmp, NULL);
239 struct strbuf pathbuf = STRBUF_INIT;
240 int ret;
241 struct repo_config_values *cfg = repo_config_values(the_repository);
242
243 repo_config(the_repository, git_default_config, NULL);
244
245 argc = parse_options(argc, argv, prefix, builtin_mv_options,
246 builtin_mv_usage, 0);
247 if (--argc < 1)
248 usage_with_options(builtin_mv_usage, builtin_mv_options);
249
250 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
251 if (repo_read_index(the_repository) < 0)
252 die(_("index file corrupt"));
253
254 internal_prefix_pathspec(&sources, prefix, argv, argc, 0);
255 CALLOC_ARRAY(modes, argc);
256
257 /*
258 * Keep trailing slash, needed to let
259 * "git mv file no-such-dir/" error out, except in the case
260 * "git mv directory no-such-dir/".
261 */
262 flags = KEEP_TRAILING_SLASH;
263 if (argc == 1 && is_directory(argv[0]) && !is_directory(argv[1]))
264 flags = 0;
265 internal_prefix_pathspec(&dest_paths, prefix, argv + argc, 1, flags);
266 dst_w_slash = add_slash(dest_paths.v[0]);
267 submodule_gitfiles = xcalloc(argc, sizeof(char *));
268
269 if (dest_paths.v[0][0] == '\0')
270 /* special case: "." was normalized to "" */
271 internal_prefix_pathspec(&destinations, dest_paths.v[0], argv, argc, DUP_BASENAME);
272 else if (!lstat(dest_paths.v[0], &st) && S_ISDIR(st.st_mode)) {
273 internal_prefix_pathspec(&destinations, dst_w_slash, argv, argc, DUP_BASENAME);
274 } else if (!path_in_sparse_checkout(dst_w_slash, the_repository->index) &&
275 empty_dir_has_sparse_contents(dst_w_slash)) {
276 internal_prefix_pathspec(&destinations, dst_w_slash, argv, argc, DUP_BASENAME);
277 dst_mode = SKIP_WORKTREE_DIR;
278 } else if (argc != 1) {
279 die(_("destination '%s' is not a directory"), dest_paths.v[0]);
280 } else {
281 strvec_pushv(&destinations, dest_paths.v);
282
283 /*
284 * <destination> is a file outside of sparse-checkout
285 * cone. Insist on cone mode here for backward
286 * compatibility. We don't want dst_mode to be assigned
287 * for a file when the repo is using no-cone mode (which
288 * is deprecated at this point) sparse-checkout. As
289 * SPARSE here is only considering cone-mode situation.
290 */
291 if (!path_in_cone_mode_sparse_checkout(destinations.v[0], the_repository->index))
292 dst_mode = SPARSE;
293 }
294
295 /* Checking */
296 for (i = 0; i < argc; i++) {
297 const char *src = sources.v[i], *dst = destinations.v[i];
298 int length;
299 const char *bad = NULL;
300 int skip_sparse = 0;
301
302 if (show_only)
303 printf(_("Checking rename of '%s' to '%s'\n"), src, dst);
304
305 length = strlen(src);
306 if (lstat(src, &st) < 0) {
307 int pos;
308 const struct cache_entry *ce;
309
310 pos = index_name_pos(the_repository->index, src, length);
311 if (pos < 0) {
312 char *src_w_slash = add_slash(src);
313 if (!path_in_sparse_checkout(src_w_slash, the_repository->index) &&
314 empty_dir_has_sparse_contents(src)) {
315 free(src_w_slash);
316 modes[i] |= SKIP_WORKTREE_DIR;
317 goto dir_check;
318 }
319 free(src_w_slash);
320 /* only error if existence is expected. */
321 if (!(modes[i] & SPARSE))
322 bad = _("bad source");
323 goto act_on_entry;
324 }
325 ce = the_repository->index->cache[pos];
326 if (!ce_skip_worktree(ce)) {
327 bad = _("bad source");
328 goto act_on_entry;
329 }
330 if (!ignore_sparse) {
331 string_list_append(&only_match_skip_worktree, src);
332 goto act_on_entry;
333 }
334 /* Check if dst exists in index */
335 if (index_name_pos(the_repository->index, dst, strlen(dst)) < 0) {
336 modes[i] |= SPARSE;
337 goto act_on_entry;
338 }
339 if (!force) {
340 bad = _("destination exists");
341 goto act_on_entry;
342 }
343 modes[i] |= SPARSE;
344 goto act_on_entry;
345 }
346 if (!strncmp(src, dst, length) &&
347 (dst[length] == 0 || dst[length] == '/')) {
348 bad = _("can not move directory into itself");
349 goto act_on_entry;
350 }
351 if (S_ISDIR(st.st_mode)
352 && lstat(dst, &dest_st) == 0) {
353 bad = _("destination already exists");
354 goto act_on_entry;
355 }
356
357 dir_check:
358 if (S_ISDIR(st.st_mode)) {
359 struct pathmap_entry *entry;
360 char *dst_with_slash;
361 size_t dst_with_slash_len;
362 int j, n;
363 int first = index_name_pos(the_repository->index, src, length), last;
364
365 if (first >= 0) {
366 const char *path = submodule_gitfile_path(src, first);
367 if (path != SUBMODULE_WITH_GITDIR)
368 path = strvec_push(&submodule_gitfiles_to_free, path);
369 submodule_gitfiles[i] = path;
370 goto act_on_entry;
371 } else if (index_range_of_same_dir(src, length,
372 &first, &last) < 1) {
373 bad = _("source directory is empty");
374 goto act_on_entry;
375 }
376
377 entry = xmalloc(sizeof(*entry));
378 entry->path = src;
379 hashmap_entry_init(&entry->ent, fspathhash(src));
380 hashmap_add(&moved_dirs, &entry->ent);
381
382 /* last - first >= 1 */
383 modes[i] |= WORKING_DIRECTORY;
384
385 strvec_push(&src_dir, src);
386
387 n = argc + last - first;
388 REALLOC_ARRAY(modes, n);
389 REALLOC_ARRAY(submodule_gitfiles, n);
390
391 dst_with_slash = add_slash(dst);
392 dst_with_slash_len = strlen(dst_with_slash);
393
394 for (j = 0; j < last - first; j++) {
395 const struct cache_entry *ce = the_repository->index->cache[first + j];
396 const char *path = ce->name;
397 char *prefixed_path = prefix_path(the_repository, dst_with_slash,
398 dst_with_slash_len, path + length + 1);
399
400 strvec_push(&sources, path);
401 strvec_push(&destinations, prefixed_path);
402
403 modes[argc + j] = MOVE_VIA_PARENT_DIR | (ce_skip_worktree(ce) ? SPARSE : INDEX);
404 submodule_gitfiles[argc + j] = NULL;
405
406 free(prefixed_path);
407 }
408
409 free(dst_with_slash);
410 argc += last - first;
411 goto act_on_entry;
412 }
413 if (!(ce = index_file_exists(the_repository->index, src, length, 0))) {
414 bad = _("not under version control");
415 goto act_on_entry;
416 }
417 if (ce_stage(ce)) {
418 bad = _("conflicted");
419 goto act_on_entry;
420 }
421 if (lstat(dst, &st) == 0 &&
422 (!ignore_case || strcasecmp(src, dst))) {
423 bad = _("destination exists");
424 if (force) {
425 /*
426 * only files can overwrite each other:
427 * check both source and destination
428 */
429 if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
430 if (verbose)
431 warning(_("overwriting '%s'"), dst);
432 bad = NULL;
433 } else
434 bad = _("Cannot overwrite");
435 }
436 goto act_on_entry;
437 }
438 if (string_list_has_string(&src_for_dst, dst)) {
439 bad = _("multiple sources for the same target");
440 goto act_on_entry;
441 }
442 if (is_dir_sep(dst[strlen(dst) - 1])) {
443 bad = _("destination directory does not exist");
444 goto act_on_entry;
445 }
446
447 if (ignore_sparse &&
448 (dst_mode & (SKIP_WORKTREE_DIR | SPARSE)) &&
449 index_entry_exists(the_repository->index, dst, strlen(dst))) {
450 bad = _("destination exists in the index");
451 if (force) {
452 if (verbose)
453 warning(_("overwriting '%s'"), dst);
454 bad = NULL;
455 } else {
456 goto act_on_entry;
457 }
458 }
459 /*
460 * We check if the paths are in the sparse-checkout
461 * definition as a very final check, since that
462 * allows us to point the user to the --sparse
463 * option as a way to have a successful run.
464 */
465 if (!ignore_sparse &&
466 !path_in_sparse_checkout(src, the_repository->index)) {
467 string_list_append(&only_match_skip_worktree, src);
468 skip_sparse = 1;
469 }
470 if (!ignore_sparse &&
471 !path_in_sparse_checkout(dst, the_repository->index)) {
472 string_list_append(&only_match_skip_worktree, dst);
473 skip_sparse = 1;
474 }
475
476 if (skip_sparse)
477 goto remove_entry;
478
479 string_list_insert(&src_for_dst, dst);
480
481 act_on_entry:
482 if (!bad)
483 continue;
484 if (!ignore_errors)
485 die(_("%s, source=%s, destination=%s"),
486 bad, src, dst);
487 remove_entry:
488 if (--argc > 0) {
489 int n = argc - i;
490 strvec_remove(&sources, i);
491 strvec_remove(&destinations, i);
492 MOVE_ARRAY(modes + i, modes + i + 1, n);
493 MOVE_ARRAY(submodule_gitfiles + i,
494 submodule_gitfiles + i + 1, n);
495 i--;
496 }
497 }
498
499 for (i = 0; i < argc; i++) {
500 const char *slash_pos;
501
502 if (modes[i] & MOVE_VIA_PARENT_DIR)
503 continue;
504
505 strbuf_reset(&pathbuf);
506 strbuf_addstr(&pathbuf, sources.v[i]);
507
508 slash_pos = strrchr(pathbuf.buf, '/');
509 while (slash_pos > pathbuf.buf) {
510 struct pathmap_entry needle;
511
512 strbuf_setlen(&pathbuf, slash_pos - pathbuf.buf);
513
514 needle.path = pathbuf.buf;
515 hashmap_entry_init(&needle.ent, fspathhash(pathbuf.buf));
516
517 if (hashmap_get_entry(&moved_dirs, &needle, ent, NULL))
518 die(_("cannot move both '%s' and its parent directory '%s'"),
519 sources.v[i], pathbuf.buf);
520
521 slash_pos = strrchr(pathbuf.buf, '/');
522 }
523 }
524
525 if (only_match_skip_worktree.nr) {
526 advise_on_updating_sparse_paths(&only_match_skip_worktree);
527 if (!ignore_errors) {
528 ret = 1;
529 goto out;
530 }
531 }
532
533 for (i = 0; i < argc; i++) {
534 const char *src = sources.v[i], *dst = destinations.v[i];
535 enum update_mode mode = modes[i];
536 int pos;
537 int sparse_and_dirty = 0;
538 struct checkout state = CHECKOUT_INIT;
539 state.istate = the_repository->index;
540
541 if (force)
542 state.force = 1;
543 if (show_only || verbose)
544 printf(_("Renaming %s to %s\n"), src, dst);
545 if (show_only)
546 continue;
547 if (!(mode & (INDEX | SPARSE | SKIP_WORKTREE_DIR)) &&
548 !(dst_mode & (SKIP_WORKTREE_DIR | SPARSE)) &&
549 rename(src, dst) < 0) {
550 if (ignore_errors)
551 continue;
552 die_errno(_("renaming '%s' failed"), src);
553 }
554 if (submodule_gitfiles[i]) {
555 if (!update_path_in_gitmodules(src, dst))
556 gitmodules_modified = 1;
557 if (submodule_gitfiles[i] != SUBMODULE_WITH_GITDIR)
558 connect_work_tree_and_git_dir(dst,
559 submodule_gitfiles[i],
560 1);
561 }
562
563 if (mode & (WORKING_DIRECTORY | SKIP_WORKTREE_DIR))
564 continue;
565
566 pos = index_name_pos(the_repository->index, src, strlen(src));
567 if (pos < 0)
568 BUG("could not find source in index: '%s'", src);
569 if (!(mode & SPARSE) && !lstat(src, &st))
570 sparse_and_dirty = ie_modified(the_repository->index,
571 the_repository->index->cache[pos],
572 &st,
573 0);
574 rename_index_entry_at(the_repository->index, pos, dst);
575
576 if (ignore_sparse &&
577 cfg->apply_sparse_checkout &&
578 cfg->core_sparse_checkout_cone) {
579 /*
580 * NEEDSWORK: we are *not* paying attention to
581 * "out-to-out" move (<source> is out-of-cone and
582 * <destination> is out-of-cone) at this point. It
583 * should be added in a future patch.
584 */
585 if ((mode & SPARSE) &&
586 path_in_sparse_checkout(dst, the_repository->index)) {
587 /* from out-of-cone to in-cone */
588 int dst_pos = index_name_pos(the_repository->index, dst,
589 strlen(dst));
590 struct cache_entry *dst_ce = the_repository->index->cache[dst_pos];
591
592 dst_ce->ce_flags &= ~CE_SKIP_WORKTREE;
593
594 if (checkout_entry(dst_ce, &state, NULL, NULL))
595 die(_("cannot checkout %s"), dst_ce->name);
596 } else if ((dst_mode & (SKIP_WORKTREE_DIR | SPARSE)) &&
597 !(mode & SPARSE) &&
598 !path_in_sparse_checkout(dst, the_repository->index)) {
599 /* from in-cone to out-of-cone */
600 int dst_pos = index_name_pos(the_repository->index, dst,
601 strlen(dst));
602 struct cache_entry *dst_ce = the_repository->index->cache[dst_pos];
603
604 /*
605 * if src is clean, it will suffice to remove it
606 */
607 if (!sparse_and_dirty) {
608 dst_ce->ce_flags |= CE_SKIP_WORKTREE;
609 unlink_or_warn(src);
610 } else {
611 /*
612 * if src is dirty, move it to the
613 * destination and create leading
614 * dirs if necessary
615 */
616 char *dst_dup = xstrdup(dst);
617 string_list_append(&dirty_paths, dst);
618 safe_create_leading_directories(the_repository, dst_dup);
619 FREE_AND_NULL(dst_dup);
620 rename(src, dst);
621 }
622 }
623 }
624 }
625
626 remove_empty_src_dirs(src_dir.v, src_dir.nr);
627
628 if (dirty_paths.nr)
629 advise_on_moving_dirty_path(&dirty_paths);
630
631 if (gitmodules_modified)
632 stage_updated_gitmodules(the_repository->index);
633
634 if (write_locked_index(the_repository->index, &lock_file,
635 COMMIT_LOCK | SKIP_IF_UNCHANGED))
636 die(_("Unable to write new index file"));
637
638 ret = 0;
639
640 out:
641 strvec_clear(&src_dir);
642 free(dst_w_slash);
643 string_list_clear(&src_for_dst, 0);
644 string_list_clear(&dirty_paths, 0);
645 string_list_clear(&only_match_skip_worktree, 0);
646 strvec_clear(&sources);
647 strvec_clear(&dest_paths);
648 strvec_clear(&destinations);
649 strvec_clear(&submodule_gitfiles_to_free);
650 hashmap_clear_and_free(&moved_dirs, struct pathmap_entry, ent);
651 strbuf_release(&pathbuf);
652 free(submodule_gitfiles);
653 free(modes);
654 return ret;
655 }