git

Форк
0
/
reset.c 
528 строк · 15.6 Кб
1
/*
2
 * "git reset" builtin command
3
 *
4
 * Copyright (c) 2007 Carlos Rica
5
 *
6
 * Based on git-reset.sh, which is
7
 *
8
 * Copyright (c) 2005, 2006 Linus Torvalds and Junio C Hamano
9
 */
10

11
#include "builtin.h"
12
#include "advice.h"
13
#include "config.h"
14
#include "environment.h"
15
#include "gettext.h"
16
#include "hash.h"
17
#include "hex.h"
18
#include "lockfile.h"
19
#include "object.h"
20
#include "pretty.h"
21
#include "refs.h"
22
#include "diff.h"
23
#include "diffcore.h"
24
#include "tree.h"
25
#include "branch.h"
26
#include "object-name.h"
27
#include "parse-options.h"
28
#include "path.h"
29
#include "unpack-trees.h"
30
#include "cache-tree.h"
31
#include "setup.h"
32
#include "sparse-index.h"
33
#include "submodule.h"
34
#include "trace.h"
35
#include "trace2.h"
36
#include "dir.h"
37
#include "add-interactive.h"
38

39
#define REFRESH_INDEX_DELAY_WARNING_IN_MS (2 * 1000)
40

41
static const char * const git_reset_usage[] = {
42
	N_("git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]"),
43
	N_("git reset [-q] [<tree-ish>] [--] <pathspec>..."),
44
	N_("git reset [-q] [--pathspec-from-file [--pathspec-file-nul]] [<tree-ish>]"),
45
	N_("git reset --patch [<tree-ish>] [--] [<pathspec>...]"),
46
	NULL
47
};
48

49
enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
50
static const char *reset_type_names[] = {
51
	N_("mixed"), N_("soft"), N_("hard"), N_("merge"), N_("keep"), NULL
52
};
53

54
static inline int is_merge(void)
55
{
56
	return !access(git_path_merge_head(the_repository), F_OK);
57
}
58

59
static int reset_index(const char *ref, const struct object_id *oid, int reset_type, int quiet)
60
{
61
	int i, nr = 0;
62
	struct tree_desc desc[2];
63
	struct tree *tree;
64
	struct unpack_trees_options opts;
65
	int ret = -1;
66

67
	memset(&opts, 0, sizeof(opts));
68
	opts.head_idx = 1;
69
	opts.src_index = the_repository->index;
70
	opts.dst_index = the_repository->index;
71
	opts.fn = oneway_merge;
72
	opts.merge = 1;
73
	init_checkout_metadata(&opts.meta, ref, oid, NULL);
74
	if (!quiet)
75
		opts.verbose_update = 1;
76
	switch (reset_type) {
77
	case KEEP:
78
	case MERGE:
79
		opts.update = 1;
80
		opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
81
		break;
82
	case HARD:
83
		opts.update = 1;
84
		opts.reset = UNPACK_RESET_OVERWRITE_UNTRACKED;
85
		opts.skip_cache_tree_update = 1;
86
		break;
87
	case MIXED:
88
		opts.reset = UNPACK_RESET_PROTECT_UNTRACKED;
89
		opts.skip_cache_tree_update = 1;
90
		/* but opts.update=0, so working tree not updated */
91
		break;
92
	default:
93
		BUG("invalid reset_type passed to reset_index");
94
	}
95

96
	repo_read_index_unmerged(the_repository);
97

98
	if (reset_type == KEEP) {
99
		struct object_id head_oid;
100
		if (repo_get_oid(the_repository, "HEAD", &head_oid))
101
			return error(_("You do not have a valid HEAD."));
102
		if (!fill_tree_descriptor(the_repository, desc + nr, &head_oid))
103
			return error(_("Failed to find tree of HEAD."));
104
		nr++;
105
		opts.fn = twoway_merge;
106
	}
107

108
	if (!fill_tree_descriptor(the_repository, desc + nr, oid)) {
109
		error(_("Failed to find tree of %s."), oid_to_hex(oid));
110
		goto out;
111
	}
112
	nr++;
113

114
	if (unpack_trees(nr, desc, &opts))
115
		goto out;
116

117
	if (reset_type == MIXED || reset_type == HARD) {
118
		tree = parse_tree_indirect(oid);
119
		if (!tree) {
120
			error(_("unable to read tree (%s)"), oid_to_hex(oid));
121
			goto out;
122
		}
123
		prime_cache_tree(the_repository, the_repository->index, tree);
124
	}
125

126
	ret = 0;
127

128
out:
129
	for (i = 0; i < nr; i++)
130
		free((void *)desc[i].buffer);
131
	return ret;
132
}
133

134
static void print_new_head_line(struct commit *commit)
135
{
136
	struct strbuf buf = STRBUF_INIT;
137

138
	printf(_("HEAD is now at %s"),
139
		repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
140

141
	pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
142
	if (buf.len > 0)
143
		printf(" %s", buf.buf);
144
	putchar('\n');
145
	strbuf_release(&buf);
146
}
147

148
static void update_index_from_diff(struct diff_queue_struct *q,
149
				   struct diff_options *opt UNUSED,
150
				   void *data)
151
{
152
	int i;
153
	int intent_to_add = *(int *)data;
154

155
	for (i = 0; i < q->nr; i++) {
156
		int pos;
157
		struct diff_filespec *one = q->queue[i]->one;
158
		int is_in_reset_tree = one->mode && !is_null_oid(&one->oid);
159
		struct cache_entry *ce;
160

161
		if (!is_in_reset_tree && !intent_to_add) {
162
			remove_file_from_index(the_repository->index, one->path);
163
			continue;
164
		}
165

166
		ce = make_cache_entry(the_repository->index, one->mode, &one->oid, one->path,
167
				      0, 0);
168

169
		/*
170
		 * If the file 1) corresponds to an existing index entry with
171
		 * skip-worktree set, or 2) does not exist in the index but is
172
		 * outside the sparse checkout definition, add a skip-worktree bit
173
		 * to the new index entry. Note that a sparse index will be expanded
174
		 * if this entry is outside the sparse cone - this is necessary
175
		 * to properly construct the reset sparse directory.
176
		 */
177
		pos = index_name_pos(the_repository->index, one->path, strlen(one->path));
178
		if ((pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) ||
179
		    (pos < 0 && !path_in_sparse_checkout(one->path, the_repository->index)))
180
			ce->ce_flags |= CE_SKIP_WORKTREE;
181

182
		if (!ce)
183
			die(_("make_cache_entry failed for path '%s'"),
184
			    one->path);
185
		if (!is_in_reset_tree) {
186
			ce->ce_flags |= CE_INTENT_TO_ADD;
187
			set_object_name_for_intent_to_add_entry(ce);
188
		}
189
		add_index_entry(the_repository->index, ce,
190
				ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
191
	}
192
}
193

194
static int read_from_tree(const struct pathspec *pathspec,
195
			  struct object_id *tree_oid,
196
			  int intent_to_add)
197
{
198
	struct diff_options opt;
199

200
	memset(&opt, 0, sizeof(opt));
201
	copy_pathspec(&opt.pathspec, pathspec);
202
	opt.output_format = DIFF_FORMAT_CALLBACK;
203
	opt.format_callback = update_index_from_diff;
204
	opt.format_callback_data = &intent_to_add;
205
	opt.flags.override_submodule_config = 1;
206
	opt.flags.recursive = 1;
207
	opt.repo = the_repository;
208
	opt.change = diff_change;
209
	opt.add_remove = diff_addremove;
210

211
	if (pathspec->nr && pathspec_needs_expanded_index(the_repository->index, pathspec))
212
		ensure_full_index(the_repository->index);
213

214
	if (do_diff_cache(tree_oid, &opt))
215
		return 1;
216
	diffcore_std(&opt);
217
	diff_flush(&opt);
218

219
	return 0;
220
}
221

222
static void set_reflog_message(struct strbuf *sb, const char *action,
223
			       const char *rev)
224
{
225
	const char *rla = getenv("GIT_REFLOG_ACTION");
226

227
	strbuf_reset(sb);
228
	if (rla)
229
		strbuf_addf(sb, "%s: %s", rla, action);
230
	else if (rev)
231
		strbuf_addf(sb, "reset: moving to %s", rev);
232
	else
233
		strbuf_addf(sb, "reset: %s", action);
234
}
235

236
static void die_if_unmerged_cache(int reset_type)
237
{
238
	if (is_merge() || unmerged_index(the_repository->index))
239
		die(_("Cannot do a %s reset in the middle of a merge."),
240
		    _(reset_type_names[reset_type]));
241

242
}
243

244
static void parse_args(struct pathspec *pathspec,
245
		       const char **argv, const char *prefix,
246
		       int patch_mode,
247
		       const char **rev_ret)
248
{
249
	const char *rev = "HEAD";
250
	struct object_id unused;
251
	/*
252
	 * Possible arguments are:
253
	 *
254
	 * git reset [-opts] [<rev>]
255
	 * git reset [-opts] <tree> [<paths>...]
256
	 * git reset [-opts] <tree> -- [<paths>...]
257
	 * git reset [-opts] -- [<paths>...]
258
	 * git reset [-opts] <paths>...
259
	 *
260
	 * At this point, argv points immediately after [-opts].
261
	 */
262

263
	if (argv[0]) {
264
		if (!strcmp(argv[0], "--")) {
265
			argv++; /* reset to HEAD, possibly with paths */
266
		} else if (argv[1] && !strcmp(argv[1], "--")) {
267
			rev = argv[0];
268
			argv += 2;
269
		}
270
		/*
271
		 * Otherwise, argv[0] could be either <rev> or <paths> and
272
		 * has to be unambiguous. If there is a single argument, it
273
		 * can not be a tree
274
		 */
275
		else if ((!argv[1] && !repo_get_oid_committish(the_repository, argv[0], &unused)) ||
276
			 (argv[1] && !repo_get_oid_treeish(the_repository, argv[0], &unused))) {
277
			/*
278
			 * Ok, argv[0] looks like a commit/tree; it should not
279
			 * be a filename.
280
			 */
281
			verify_non_filename(prefix, argv[0]);
282
			rev = *argv++;
283
		} else {
284
			/* Otherwise we treat this as a filename */
285
			verify_filename(prefix, argv[0], 1);
286
		}
287
	}
288

289
	/* treat '@' as a shortcut for 'HEAD' */
290
	*rev_ret = !strcmp("@", rev) ? "HEAD" : rev;
291

292
	parse_pathspec(pathspec, 0,
293
		       PATHSPEC_PREFER_FULL |
294
		       (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
295
		       prefix, argv);
296
}
297

298
static int reset_refs(const char *rev, const struct object_id *oid)
299
{
300
	int update_ref_status;
301
	struct strbuf msg = STRBUF_INIT;
302
	struct object_id *orig = NULL, oid_orig,
303
		*old_orig = NULL, oid_old_orig;
304

305
	if (!repo_get_oid(the_repository, "ORIG_HEAD", &oid_old_orig))
306
		old_orig = &oid_old_orig;
307
	if (!repo_get_oid(the_repository, "HEAD", &oid_orig)) {
308
		orig = &oid_orig;
309
		set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
310
		refs_update_ref(get_main_ref_store(the_repository), msg.buf,
311
				"ORIG_HEAD", orig, old_orig, 0,
312
				UPDATE_REFS_MSG_ON_ERR);
313
	} else if (old_orig)
314
		refs_delete_ref(get_main_ref_store(the_repository), NULL,
315
				"ORIG_HEAD", old_orig, 0);
316
	set_reflog_message(&msg, "updating HEAD", rev);
317
	update_ref_status = refs_update_ref(get_main_ref_store(the_repository),
318
					    msg.buf, "HEAD", oid, orig, 0,
319
					    UPDATE_REFS_MSG_ON_ERR);
320
	strbuf_release(&msg);
321
	return update_ref_status;
322
}
323

324
static int git_reset_config(const char *var, const char *value,
325
			    const struct config_context *ctx, void *cb)
326
{
327
	if (!strcmp(var, "submodule.recurse"))
328
		return git_default_submodule_config(var, value, cb);
329

330
	return git_default_config(var, value, ctx, cb);
331
}
332

333
int cmd_reset(int argc, const char **argv, const char *prefix)
334
{
335
	int reset_type = NONE, update_ref_status = 0, quiet = 0;
336
	int no_refresh = 0;
337
	int patch_mode = 0, pathspec_file_nul = 0, unborn;
338
	const char *rev;
339
	char *pathspec_from_file = NULL;
340
	struct object_id oid;
341
	struct pathspec pathspec;
342
	int intent_to_add = 0;
343
	const struct option options[] = {
344
		OPT__QUIET(&quiet, N_("be quiet, only report errors")),
345
		OPT_BOOL(0, "no-refresh", &no_refresh,
346
				N_("skip refreshing the index after reset")),
347
		OPT_SET_INT_F(0, "mixed", &reset_type,
348
			      N_("reset HEAD and index"),
349
			      MIXED, PARSE_OPT_NONEG),
350
		OPT_SET_INT_F(0, "soft", &reset_type,
351
			      N_("reset only HEAD"),
352
			      SOFT, PARSE_OPT_NONEG),
353
		OPT_SET_INT_F(0, "hard", &reset_type,
354
			      N_("reset HEAD, index and working tree"),
355
			      HARD, PARSE_OPT_NONEG),
356
		OPT_SET_INT_F(0, "merge", &reset_type,
357
			      N_("reset HEAD, index and working tree"),
358
			      MERGE, PARSE_OPT_NONEG),
359
		OPT_SET_INT_F(0, "keep", &reset_type,
360
			      N_("reset HEAD but keep local changes"),
361
			      KEEP, PARSE_OPT_NONEG),
362
		OPT_CALLBACK_F(0, "recurse-submodules", NULL,
363
			       "reset", "control recursive updating of submodules",
364
			       PARSE_OPT_OPTARG,
365
			       option_parse_recurse_submodules_worktree_updater),
366
		OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
367
		OPT_BOOL('N', "intent-to-add", &intent_to_add,
368
				N_("record only the fact that removed paths will be added later")),
369
		OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
370
		OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
371
		OPT_END()
372
	};
373

374
	git_config(git_reset_config, NULL);
375

376
	argc = parse_options(argc, argv, prefix, options, git_reset_usage,
377
						PARSE_OPT_KEEP_DASHDASH);
378
	parse_args(&pathspec, argv, prefix, patch_mode, &rev);
379

380
	if (pathspec_from_file) {
381
		if (patch_mode)
382
			die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
383

384
		if (pathspec.nr)
385
			die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
386

387
		parse_pathspec_file(&pathspec, 0,
388
				    PATHSPEC_PREFER_FULL,
389
				    prefix, pathspec_from_file, pathspec_file_nul);
390
	} else if (pathspec_file_nul) {
391
		die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
392
	}
393

394
	unborn = !strcmp(rev, "HEAD") && repo_get_oid(the_repository, "HEAD",
395
						      &oid);
396
	if (unborn) {
397
		/* reset on unborn branch: treat as reset to empty tree */
398
		oidcpy(&oid, the_hash_algo->empty_tree);
399
	} else if (!pathspec.nr && !patch_mode) {
400
		struct commit *commit;
401
		if (repo_get_oid_committish(the_repository, rev, &oid))
402
			die(_("Failed to resolve '%s' as a valid revision."), rev);
403
		commit = lookup_commit_reference(the_repository, &oid);
404
		if (!commit)
405
			die(_("Could not parse object '%s'."), rev);
406
		oidcpy(&oid, &commit->object.oid);
407
	} else {
408
		struct tree *tree;
409
		if (repo_get_oid_treeish(the_repository, rev, &oid))
410
			die(_("Failed to resolve '%s' as a valid tree."), rev);
411
		tree = parse_tree_indirect(&oid);
412
		if (!tree)
413
			die(_("Could not parse object '%s'."), rev);
414
		oidcpy(&oid, &tree->object.oid);
415
	}
416

417
	if (patch_mode) {
418
		if (reset_type != NONE)
419
			die(_("options '%s' and '%s' cannot be used together"), "--patch", "--{hard,mixed,soft}");
420
		trace2_cmd_mode("patch-interactive");
421
		update_ref_status = !!run_add_p(the_repository, ADD_P_RESET, rev,
422
				   &pathspec);
423
		goto cleanup;
424
	}
425

426
	/* git reset tree [--] paths... can be used to
427
	 * load chosen paths from the tree into the index without
428
	 * affecting the working tree nor HEAD. */
429
	if (pathspec.nr) {
430
		if (reset_type == MIXED)
431
			warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
432
		else if (reset_type != NONE)
433
			die(_("Cannot do %s reset with paths."),
434
					_(reset_type_names[reset_type]));
435
	}
436
	if (reset_type == NONE)
437
		reset_type = MIXED; /* by default */
438

439
	if (pathspec.nr)
440
		trace2_cmd_mode("path");
441
	else
442
		trace2_cmd_mode(reset_type_names[reset_type]);
443

444
	if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
445
		setup_work_tree();
446

447
	if (reset_type == MIXED && is_bare_repository())
448
		die(_("%s reset is not allowed in a bare repository"),
449
		    _(reset_type_names[reset_type]));
450

451
	if (intent_to_add && reset_type != MIXED)
452
		die(_("the option '%s' requires '%s'"), "-N", "--mixed");
453

454
	prepare_repo_settings(the_repository);
455
	the_repository->settings.command_requires_full_index = 0;
456

457
	if (repo_read_index(the_repository) < 0)
458
		die(_("index file corrupt"));
459

460
	/* Soft reset does not touch the index file nor the working tree
461
	 * at all, but requires them in a good order.  Other resets reset
462
	 * the index file to the tree object we are switching to. */
463
	if (reset_type == SOFT || reset_type == KEEP)
464
		die_if_unmerged_cache(reset_type);
465

466
	if (reset_type != SOFT) {
467
		struct lock_file lock = LOCK_INIT;
468
		repo_hold_locked_index(the_repository, &lock,
469
				       LOCK_DIE_ON_ERROR);
470
		if (reset_type == MIXED) {
471
			int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
472
			if (read_from_tree(&pathspec, &oid, intent_to_add)) {
473
				update_ref_status = 1;
474
				goto cleanup;
475
			}
476
			the_repository->index->updated_skipworktree = 1;
477
			if (!no_refresh && get_git_work_tree()) {
478
				uint64_t t_begin, t_delta_in_ms;
479

480
				t_begin = getnanotime();
481
				refresh_index(the_repository->index, flags, NULL, NULL,
482
					      _("Unstaged changes after reset:"));
483
				t_delta_in_ms = (getnanotime() - t_begin) / 1000000;
484
				if (!quiet && advice_enabled(ADVICE_RESET_NO_REFRESH_WARNING) && t_delta_in_ms > REFRESH_INDEX_DELAY_WARNING_IN_MS) {
485
					advise(_("It took %.2f seconds to refresh the index after reset.  You can use\n"
486
						 "'--no-refresh' to avoid this."), t_delta_in_ms / 1000.0);
487
				}
488
			}
489
		} else {
490
			struct object_id dummy;
491
			char *ref = NULL;
492
			int err;
493

494
			repo_dwim_ref(the_repository, rev, strlen(rev),
495
				      &dummy, &ref, 0);
496
			if (ref && !starts_with(ref, "refs/"))
497
				FREE_AND_NULL(ref);
498

499
			err = reset_index(ref, &oid, reset_type, quiet);
500
			if (reset_type == KEEP && !err)
501
				err = reset_index(ref, &oid, MIXED, quiet);
502
			if (err)
503
				die(_("Could not reset index file to revision '%s'."), rev);
504
			free(ref);
505
		}
506

507
		if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK))
508
			die(_("Could not write new index file."));
509
	}
510

511
	if (!pathspec.nr && !unborn) {
512
		/* Any resets without paths update HEAD to the head being
513
		 * switched to, saving the previous head in ORIG_HEAD before. */
514
		update_ref_status = reset_refs(rev, &oid);
515

516
		if (reset_type == HARD && !update_ref_status && !quiet)
517
			print_new_head_line(lookup_commit_reference(the_repository, &oid));
518
	}
519
	if (!pathspec.nr)
520
		remove_branch_state(the_repository, 0);
521

522
	discard_index(the_repository->index);
523

524
cleanup:
525
	clear_pathspec(&pathspec);
526
	free(pathspec_from_file);
527
	return update_ref_status;
528
}
529

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

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

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

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