git

Форк
0
/
mv.c 
587 строк · 16.4 Кб
1
/*
2
 * "git mv" builtin command
3
 *
4
 * Copyright (C) 2006 Johannes Schindelin
5
 */
6

7
#include "builtin.h"
8
#include "abspath.h"
9
#include "advice.h"
10
#include "config.h"
11
#include "environment.h"
12
#include "gettext.h"
13
#include "name-hash.h"
14
#include "object-file.h"
15
#include "pathspec.h"
16
#include "lockfile.h"
17
#include "dir.h"
18
#include "string-list.h"
19
#include "parse-options.h"
20
#include "read-cache-ll.h"
21
#include "repository.h"
22
#include "setup.h"
23
#include "strvec.h"
24
#include "submodule.h"
25
#include "entry.h"
26

27
static const char * const builtin_mv_usage[] = {
28
	N_("git mv [<options>] <source>... <destination>"),
29
	NULL
30
};
31

32
enum update_mode {
33
	WORKING_DIRECTORY = (1 << 1),
34
	INDEX = (1 << 2),
35
	SPARSE = (1 << 3),
36
	SKIP_WORKTREE_DIR = (1 << 4),
37
};
38

39
#define DUP_BASENAME 1
40
#define KEEP_TRAILING_SLASH 2
41

42
static void internal_prefix_pathspec(struct strvec *out,
43
				     const char *prefix,
44
				     const char **pathspec,
45
				     int count, unsigned flags)
46
{
47
	int prefixlen = prefix ? strlen(prefix) : 0;
48

49
	/* Create an intermediate copy of the pathspec based on the flags */
50
	for (int i = 0; i < count; i++) {
51
		size_t length = strlen(pathspec[i]);
52
		size_t to_copy = length;
53
		const char *maybe_basename;
54
		char *trimmed, *prefixed_path;
55

56
		while (!(flags & KEEP_TRAILING_SLASH) &&
57
		       to_copy > 0 && is_dir_sep(pathspec[i][to_copy - 1]))
58
			to_copy--;
59

60
		trimmed = xmemdupz(pathspec[i], to_copy);
61
		maybe_basename = (flags & DUP_BASENAME) ? basename(trimmed) : trimmed;
62
		prefixed_path = prefix_path(prefix, prefixlen, maybe_basename);
63
		strvec_push(out, prefixed_path);
64

65
		free(prefixed_path);
66
		free(trimmed);
67
	}
68
}
69

70
static char *add_slash(const char *path)
71
{
72
	size_t len = strlen(path);
73
	if (len && path[len - 1] != '/') {
74
		char *with_slash = xmalloc(st_add(len, 2));
75
		memcpy(with_slash, path, len);
76
		with_slash[len++] = '/';
77
		with_slash[len] = 0;
78
		return with_slash;
79
	}
80
	return xstrdup(path);
81
}
82

83
#define SUBMODULE_WITH_GITDIR ((const char *)1)
84

85
static const char *submodule_gitfile_path(const char *src, int first)
86
{
87
	struct strbuf submodule_dotgit = STRBUF_INIT;
88
	const char *path;
89

90
	if (!S_ISGITLINK(the_repository->index->cache[first]->ce_mode))
91
		die(_("Directory %s is in index and no submodule?"), src);
92
	if (!is_staging_gitmodules_ok(the_repository->index))
93
		die(_("Please stage your changes to .gitmodules or stash them to proceed"));
94

95
	strbuf_addf(&submodule_dotgit, "%s/.git", src);
96

97
	path = read_gitfile(submodule_dotgit.buf);
98
	strbuf_release(&submodule_dotgit);
99
	if (path)
100
		return path;
101
	return SUBMODULE_WITH_GITDIR;
102
}
103

104
static int index_range_of_same_dir(const char *src, int length,
105
				   int *first_p, int *last_p)
106
{
107
	char *src_w_slash = add_slash(src);
108
	int first, last, len_w_slash = length + 1;
109

110
	first = index_name_pos(the_repository->index, src_w_slash, len_w_slash);
111
	if (first >= 0)
112
		die(_("%.*s is in index"), len_w_slash, src_w_slash);
113

114
	first = -1 - first;
115
	for (last = first; last < the_repository->index->cache_nr; last++) {
116
		const char *path = the_repository->index->cache[last]->name;
117
		if (strncmp(path, src_w_slash, len_w_slash))
118
			break;
119
	}
120

121
	free(src_w_slash);
122
	*first_p = first;
123
	*last_p = last;
124
	return last - first;
125
}
126

127
/*
128
 * Given the path of a directory that does not exist on-disk, check whether the
129
 * directory contains any entries in the index with the SKIP_WORKTREE flag
130
 * enabled.
131
 * Return 1 if such index entries exist.
132
 * Return 0 otherwise.
133
 */
134
static int empty_dir_has_sparse_contents(const char *name)
135
{
136
	int ret = 0;
137
	char *with_slash = add_slash(name);
138
	int length = strlen(with_slash);
139

140
	int pos = index_name_pos(the_repository->index, with_slash, length);
141
	const struct cache_entry *ce;
142

143
	if (pos < 0) {
144
		pos = -pos - 1;
145
		if (pos >= the_repository->index->cache_nr)
146
			goto free_return;
147
		ce = the_repository->index->cache[pos];
148
		if (strncmp(with_slash, ce->name, length))
149
			goto free_return;
150
		if (ce_skip_worktree(ce))
151
			ret = 1;
152
	}
153

154
free_return:
155
	free(with_slash);
156
	return ret;
157
}
158

159
static void remove_empty_src_dirs(const char **src_dir, size_t src_dir_nr)
160
{
161
	size_t i;
162
	struct strbuf a_src_dir = STRBUF_INIT;
163

164
	for (i = 0; i < src_dir_nr; i++) {
165
		int dummy;
166
		strbuf_addstr(&a_src_dir, src_dir[i]);
167
		/*
168
		 * if entries under a_src_dir are all moved away,
169
		 * recursively remove a_src_dir to cleanup
170
		 */
171
		if (index_range_of_same_dir(a_src_dir.buf, a_src_dir.len,
172
					    &dummy, &dummy) < 1) {
173
			remove_dir_recursively(&a_src_dir, 0);
174
		}
175
		strbuf_reset(&a_src_dir);
176
	}
177

178
	strbuf_release(&a_src_dir);
179
}
180

181
int cmd_mv(int argc, const char **argv, const char *prefix)
182
{
183
	int i, flags, gitmodules_modified = 0;
184
	int verbose = 0, show_only = 0, force = 0, ignore_errors = 0, ignore_sparse = 0;
185
	struct option builtin_mv_options[] = {
186
		OPT__VERBOSE(&verbose, N_("be verbose")),
187
		OPT__DRY_RUN(&show_only, N_("dry run")),
188
		OPT__FORCE(&force, N_("force move/rename even if target exists"),
189
			   PARSE_OPT_NOCOMPLETE),
190
		OPT_BOOL('k', NULL, &ignore_errors, N_("skip move/rename errors")),
191
		OPT_BOOL(0, "sparse", &ignore_sparse, N_("allow updating entries outside of the sparse-checkout cone")),
192
		OPT_END(),
193
	};
194
	struct strvec sources = STRVEC_INIT;
195
	struct strvec dest_paths = STRVEC_INIT;
196
	struct strvec destinations = STRVEC_INIT;
197
	struct strvec submodule_gitfiles_to_free = STRVEC_INIT;
198
	const char **submodule_gitfiles;
199
	char *dst_w_slash = NULL;
200
	struct strvec src_dir = STRVEC_INIT;
201
	enum update_mode *modes, dst_mode = 0;
202
	struct stat st, dest_st;
203
	struct string_list src_for_dst = STRING_LIST_INIT_DUP;
204
	struct lock_file lock_file = LOCK_INIT;
205
	struct cache_entry *ce;
206
	struct string_list only_match_skip_worktree = STRING_LIST_INIT_DUP;
207
	struct string_list dirty_paths = STRING_LIST_INIT_DUP;
208
	int ret;
209

210
	git_config(git_default_config, NULL);
211

212
	argc = parse_options(argc, argv, prefix, builtin_mv_options,
213
			     builtin_mv_usage, 0);
214
	if (--argc < 1)
215
		usage_with_options(builtin_mv_usage, builtin_mv_options);
216

217
	repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
218
	if (repo_read_index(the_repository) < 0)
219
		die(_("index file corrupt"));
220

221
	internal_prefix_pathspec(&sources, prefix, argv, argc, 0);
222
	CALLOC_ARRAY(modes, argc);
223

224
	/*
225
	 * Keep trailing slash, needed to let
226
	 * "git mv file no-such-dir/" error out, except in the case
227
	 * "git mv directory no-such-dir/".
228
	 */
229
	flags = KEEP_TRAILING_SLASH;
230
	if (argc == 1 && is_directory(argv[0]) && !is_directory(argv[1]))
231
		flags = 0;
232
	internal_prefix_pathspec(&dest_paths, prefix, argv + argc, 1, flags);
233
	dst_w_slash = add_slash(dest_paths.v[0]);
234
	submodule_gitfiles = xcalloc(argc, sizeof(char *));
235

236
	if (dest_paths.v[0][0] == '\0')
237
		/* special case: "." was normalized to "" */
238
		internal_prefix_pathspec(&destinations, dest_paths.v[0], argv, argc, DUP_BASENAME);
239
	else if (!lstat(dest_paths.v[0], &st) && S_ISDIR(st.st_mode)) {
240
		internal_prefix_pathspec(&destinations, dst_w_slash, argv, argc, DUP_BASENAME);
241
	} else if (!path_in_sparse_checkout(dst_w_slash, the_repository->index) &&
242
		   empty_dir_has_sparse_contents(dst_w_slash)) {
243
		internal_prefix_pathspec(&destinations, dst_w_slash, argv, argc, DUP_BASENAME);
244
		dst_mode = SKIP_WORKTREE_DIR;
245
	} else if (argc != 1) {
246
		die(_("destination '%s' is not a directory"), dest_paths.v[0]);
247
	} else {
248
		strvec_pushv(&destinations, dest_paths.v);
249

250
		/*
251
		 * <destination> is a file outside of sparse-checkout
252
		 * cone. Insist on cone mode here for backward
253
		 * compatibility. We don't want dst_mode to be assigned
254
		 * for a file when the repo is using no-cone mode (which
255
		 * is deprecated at this point) sparse-checkout. As
256
		 * SPARSE here is only considering cone-mode situation.
257
		 */
258
		if (!path_in_cone_mode_sparse_checkout(destinations.v[0], the_repository->index))
259
			dst_mode = SPARSE;
260
	}
261

262
	/* Checking */
263
	for (i = 0; i < argc; i++) {
264
		const char *src = sources.v[i], *dst = destinations.v[i];
265
		int length;
266
		const char *bad = NULL;
267
		int skip_sparse = 0;
268

269
		if (show_only)
270
			printf(_("Checking rename of '%s' to '%s'\n"), src, dst);
271

272
		length = strlen(src);
273
		if (lstat(src, &st) < 0) {
274
			int pos;
275
			const struct cache_entry *ce;
276

277
			pos = index_name_pos(the_repository->index, src, length);
278
			if (pos < 0) {
279
				char *src_w_slash = add_slash(src);
280
				if (!path_in_sparse_checkout(src_w_slash, the_repository->index) &&
281
				    empty_dir_has_sparse_contents(src)) {
282
					free(src_w_slash);
283
					modes[i] |= SKIP_WORKTREE_DIR;
284
					goto dir_check;
285
				}
286
				free(src_w_slash);
287
				/* only error if existence is expected. */
288
				if (!(modes[i] & SPARSE))
289
					bad = _("bad source");
290
				goto act_on_entry;
291
			}
292
			ce = the_repository->index->cache[pos];
293
			if (!ce_skip_worktree(ce)) {
294
				bad = _("bad source");
295
				goto act_on_entry;
296
			}
297
			if (!ignore_sparse) {
298
				string_list_append(&only_match_skip_worktree, src);
299
				goto act_on_entry;
300
			}
301
			/* Check if dst exists in index */
302
			if (index_name_pos(the_repository->index, dst, strlen(dst)) < 0) {
303
				modes[i] |= SPARSE;
304
				goto act_on_entry;
305
			}
306
			if (!force) {
307
				bad = _("destination exists");
308
				goto act_on_entry;
309
			}
310
			modes[i] |= SPARSE;
311
			goto act_on_entry;
312
		}
313
		if (!strncmp(src, dst, length) &&
314
		    (dst[length] == 0 || dst[length] == '/')) {
315
			bad = _("can not move directory into itself");
316
			goto act_on_entry;
317
		}
318
		if (S_ISDIR(st.st_mode)
319
		    && lstat(dst, &dest_st) == 0) {
320
			bad = _("destination already exists");
321
			goto act_on_entry;
322
		}
323

324
dir_check:
325
		if (S_ISDIR(st.st_mode)) {
326
			char *dst_with_slash;
327
			size_t dst_with_slash_len;
328
			int j, n;
329
			int first = index_name_pos(the_repository->index, src, length), last;
330

331
			if (first >= 0) {
332
				const char *path = submodule_gitfile_path(src, first);
333
				if (path != SUBMODULE_WITH_GITDIR)
334
					path = strvec_push(&submodule_gitfiles_to_free, path);
335
				submodule_gitfiles[i] = path;
336
				goto act_on_entry;
337
			} else if (index_range_of_same_dir(src, length,
338
							   &first, &last) < 1) {
339
				bad = _("source directory is empty");
340
				goto act_on_entry;
341
			}
342

343
			/* last - first >= 1 */
344
			modes[i] |= WORKING_DIRECTORY;
345

346
			strvec_push(&src_dir, src);
347

348
			n = argc + last - first;
349
			REALLOC_ARRAY(modes, n);
350
			REALLOC_ARRAY(submodule_gitfiles, n);
351

352
			dst_with_slash = add_slash(dst);
353
			dst_with_slash_len = strlen(dst_with_slash);
354

355
			for (j = 0; j < last - first; j++) {
356
				const struct cache_entry *ce = the_repository->index->cache[first + j];
357
				const char *path = ce->name;
358
				char *prefixed_path = prefix_path(dst_with_slash, dst_with_slash_len, path + length + 1);
359

360
				strvec_push(&sources, path);
361
				strvec_push(&destinations, prefixed_path);
362

363
				memset(modes + argc + j, 0, sizeof(enum update_mode));
364
				modes[argc + j] |= ce_skip_worktree(ce) ? SPARSE : INDEX;
365
				submodule_gitfiles[argc + j] = NULL;
366

367
				free(prefixed_path);
368
			}
369

370
			free(dst_with_slash);
371
			argc += last - first;
372
			goto act_on_entry;
373
		}
374
		if (!(ce = index_file_exists(the_repository->index, src, length, 0))) {
375
			bad = _("not under version control");
376
			goto act_on_entry;
377
		}
378
		if (ce_stage(ce)) {
379
			bad = _("conflicted");
380
			goto act_on_entry;
381
		}
382
		if (lstat(dst, &st) == 0 &&
383
		    (!ignore_case || strcasecmp(src, dst))) {
384
			bad = _("destination exists");
385
			if (force) {
386
				/*
387
				 * only files can overwrite each other:
388
				 * check both source and destination
389
				 */
390
				if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
391
					if (verbose)
392
						warning(_("overwriting '%s'"), dst);
393
					bad = NULL;
394
				} else
395
					bad = _("Cannot overwrite");
396
			}
397
			goto act_on_entry;
398
		}
399
		if (string_list_has_string(&src_for_dst, dst)) {
400
			bad = _("multiple sources for the same target");
401
			goto act_on_entry;
402
		}
403
		if (is_dir_sep(dst[strlen(dst) - 1])) {
404
			bad = _("destination directory does not exist");
405
			goto act_on_entry;
406
		}
407

408
		if (ignore_sparse &&
409
		    (dst_mode & (SKIP_WORKTREE_DIR | SPARSE)) &&
410
		    index_entry_exists(the_repository->index, dst, strlen(dst))) {
411
			bad = _("destination exists in the index");
412
			if (force) {
413
				if (verbose)
414
					warning(_("overwriting '%s'"), dst);
415
				bad = NULL;
416
			} else {
417
				goto act_on_entry;
418
			}
419
		}
420
		/*
421
		 * We check if the paths are in the sparse-checkout
422
		 * definition as a very final check, since that
423
		 * allows us to point the user to the --sparse
424
		 * option as a way to have a successful run.
425
		 */
426
		if (!ignore_sparse &&
427
		    !path_in_sparse_checkout(src, the_repository->index)) {
428
			string_list_append(&only_match_skip_worktree, src);
429
			skip_sparse = 1;
430
		}
431
		if (!ignore_sparse &&
432
		    !path_in_sparse_checkout(dst, the_repository->index)) {
433
			string_list_append(&only_match_skip_worktree, dst);
434
			skip_sparse = 1;
435
		}
436

437
		if (skip_sparse)
438
			goto remove_entry;
439

440
		string_list_insert(&src_for_dst, dst);
441

442
act_on_entry:
443
		if (!bad)
444
			continue;
445
		if (!ignore_errors)
446
			die(_("%s, source=%s, destination=%s"),
447
			     bad, src, dst);
448
remove_entry:
449
		if (--argc > 0) {
450
			int n = argc - i;
451
			strvec_remove(&sources, i);
452
			strvec_remove(&destinations, i);
453
			MOVE_ARRAY(modes + i, modes + i + 1, n);
454
			MOVE_ARRAY(submodule_gitfiles + i,
455
				   submodule_gitfiles + i + 1, n);
456
			i--;
457
		}
458
	}
459

460
	if (only_match_skip_worktree.nr) {
461
		advise_on_updating_sparse_paths(&only_match_skip_worktree);
462
		if (!ignore_errors) {
463
			ret = 1;
464
			goto out;
465
		}
466
	}
467

468
	for (i = 0; i < argc; i++) {
469
		const char *src = sources.v[i], *dst = destinations.v[i];
470
		enum update_mode mode = modes[i];
471
		int pos;
472
		int sparse_and_dirty = 0;
473
		struct checkout state = CHECKOUT_INIT;
474
		state.istate = the_repository->index;
475

476
		if (force)
477
			state.force = 1;
478
		if (show_only || verbose)
479
			printf(_("Renaming %s to %s\n"), src, dst);
480
		if (show_only)
481
			continue;
482
		if (!(mode & (INDEX | SPARSE | SKIP_WORKTREE_DIR)) &&
483
		    !(dst_mode & (SKIP_WORKTREE_DIR | SPARSE)) &&
484
		    rename(src, dst) < 0) {
485
			if (ignore_errors)
486
				continue;
487
			die_errno(_("renaming '%s' failed"), src);
488
		}
489
		if (submodule_gitfiles[i]) {
490
			if (!update_path_in_gitmodules(src, dst))
491
				gitmodules_modified = 1;
492
			if (submodule_gitfiles[i] != SUBMODULE_WITH_GITDIR)
493
				connect_work_tree_and_git_dir(dst,
494
							      submodule_gitfiles[i],
495
							      1);
496
		}
497

498
		if (mode & (WORKING_DIRECTORY | SKIP_WORKTREE_DIR))
499
			continue;
500

501
		pos = index_name_pos(the_repository->index, src, strlen(src));
502
		assert(pos >= 0);
503
		if (!(mode & SPARSE) && !lstat(src, &st))
504
			sparse_and_dirty = ie_modified(the_repository->index,
505
						       the_repository->index->cache[pos],
506
						       &st,
507
						       0);
508
		rename_index_entry_at(the_repository->index, pos, dst);
509

510
		if (ignore_sparse &&
511
		    core_apply_sparse_checkout &&
512
		    core_sparse_checkout_cone) {
513
			/*
514
			 * NEEDSWORK: we are *not* paying attention to
515
			 * "out-to-out" move (<source> is out-of-cone and
516
			 * <destination> is out-of-cone) at this point. It
517
			 * should be added in a future patch.
518
			 */
519
			if ((mode & SPARSE) &&
520
			    path_in_sparse_checkout(dst, the_repository->index)) {
521
				/* from out-of-cone to in-cone */
522
				int dst_pos = index_name_pos(the_repository->index, dst,
523
							     strlen(dst));
524
				struct cache_entry *dst_ce = the_repository->index->cache[dst_pos];
525

526
				dst_ce->ce_flags &= ~CE_SKIP_WORKTREE;
527

528
				if (checkout_entry(dst_ce, &state, NULL, NULL))
529
					die(_("cannot checkout %s"), dst_ce->name);
530
			} else if ((dst_mode & (SKIP_WORKTREE_DIR | SPARSE)) &&
531
				   !(mode & SPARSE) &&
532
				   !path_in_sparse_checkout(dst, the_repository->index)) {
533
				/* from in-cone to out-of-cone */
534
				int dst_pos = index_name_pos(the_repository->index, dst,
535
							     strlen(dst));
536
				struct cache_entry *dst_ce = the_repository->index->cache[dst_pos];
537

538
				/*
539
				 * if src is clean, it will suffice to remove it
540
				 */
541
				if (!sparse_and_dirty) {
542
					dst_ce->ce_flags |= CE_SKIP_WORKTREE;
543
					unlink_or_warn(src);
544
				} else {
545
					/*
546
					 * if src is dirty, move it to the
547
					 * destination and create leading
548
					 * dirs if necessary
549
					 */
550
					char *dst_dup = xstrdup(dst);
551
					string_list_append(&dirty_paths, dst);
552
					safe_create_leading_directories(dst_dup);
553
					FREE_AND_NULL(dst_dup);
554
					rename(src, dst);
555
				}
556
			}
557
		}
558
	}
559

560
	remove_empty_src_dirs(src_dir.v, src_dir.nr);
561

562
	if (dirty_paths.nr)
563
		advise_on_moving_dirty_path(&dirty_paths);
564

565
	if (gitmodules_modified)
566
		stage_updated_gitmodules(the_repository->index);
567

568
	if (write_locked_index(the_repository->index, &lock_file,
569
			       COMMIT_LOCK | SKIP_IF_UNCHANGED))
570
		die(_("Unable to write new index file"));
571

572
	ret = 0;
573

574
out:
575
	strvec_clear(&src_dir);
576
	free(dst_w_slash);
577
	string_list_clear(&src_for_dst, 0);
578
	string_list_clear(&dirty_paths, 0);
579
	string_list_clear(&only_match_skip_worktree, 0);
580
	strvec_clear(&sources);
581
	strvec_clear(&dest_paths);
582
	strvec_clear(&destinations);
583
	strvec_clear(&submodule_gitfiles_to_free);
584
	free(submodule_gitfiles);
585
	free(modes);
586
	return ret;
587
}
588

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.